main.c 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345
  1. /*
  2. * Copyright 2011 Con Kolivas
  3. * Copyright 2010 Jeff Garzik
  4. *
  5. * This program is free software; you can redistribute it and/or modify it
  6. * under the terms of the GNU General Public License as published by the Free
  7. * Software Foundation; either version 2 of the License, or (at your option)
  8. * any later version. See COPYING for more details.
  9. */
  10. #include "config.h"
  11. #include <curses.h>
  12. #include <stdio.h>
  13. #include <stdlib.h>
  14. #include <string.h>
  15. #include <stdbool.h>
  16. #include <stdint.h>
  17. #include <unistd.h>
  18. #include <sys/time.h>
  19. #include <time.h>
  20. #include <math.h>
  21. #include <stdarg.h>
  22. #include <assert.h>
  23. #include <signal.h>
  24. #ifndef WIN32
  25. #include <sys/resource.h>
  26. #endif
  27. #include <ccan/opt/opt.h>
  28. #include <jansson.h>
  29. #include <curl/curl.h>
  30. #include "compat.h"
  31. #include "miner.h"
  32. #include "findnonce.h"
  33. #include "ocl.h"
  34. #define PROGRAM_NAME "cgminer"
  35. #define DEF_RPC_URL "http://127.0.0.1:8332/"
  36. #define DEF_RPC_USERNAME "rpcuser"
  37. #define DEF_RPC_PASSWORD "rpcpass"
  38. #define DEF_RPC_USERPASS DEF_RPC_USERNAME ":" DEF_RPC_PASSWORD
  39. #ifdef __linux /* Linux specific policy and affinity management */
  40. #include <sched.h>
  41. static inline void drop_policy(void)
  42. {
  43. struct sched_param param;
  44. #ifdef SCHED_BATCH
  45. #ifdef SCHED_IDLE
  46. if (unlikely(sched_setscheduler(0, SCHED_IDLE, &param) == -1))
  47. #endif
  48. sched_setscheduler(0, SCHED_BATCH, &param);
  49. #endif
  50. }
  51. static inline void affine_to_cpu(int id, int cpu)
  52. {
  53. cpu_set_t set;
  54. CPU_ZERO(&set);
  55. CPU_SET(cpu, &set);
  56. sched_setaffinity(0, sizeof(&set), &set);
  57. applog(LOG_INFO, "Binding cpu mining thread %d to cpu %d", id, cpu);
  58. }
  59. #else
  60. static inline void drop_policy(void)
  61. {
  62. }
  63. static inline void affine_to_cpu(int id, int cpu)
  64. {
  65. }
  66. #endif
  67. enum workio_commands {
  68. WC_GET_WORK,
  69. WC_SUBMIT_WORK,
  70. WC_DIE,
  71. };
  72. struct workio_cmd {
  73. enum workio_commands cmd;
  74. struct thr_info *thr;
  75. union {
  76. struct work *work;
  77. } u;
  78. };
  79. enum sha256_algos {
  80. ALGO_C, /* plain C */
  81. ALGO_4WAY, /* parallel SSE2 */
  82. ALGO_VIA, /* VIA padlock */
  83. ALGO_CRYPTOPP, /* Crypto++ (C) */
  84. ALGO_CRYPTOPP_ASM32, /* Crypto++ 32-bit assembly */
  85. ALGO_SSE2_64, /* SSE2 for x86_64 */
  86. };
  87. static const char *algo_names[] = {
  88. [ALGO_C] = "c",
  89. #ifdef WANT_SSE2_4WAY
  90. [ALGO_4WAY] = "4way",
  91. #endif
  92. #ifdef WANT_VIA_PADLOCK
  93. [ALGO_VIA] = "via",
  94. #endif
  95. [ALGO_CRYPTOPP] = "cryptopp",
  96. #ifdef WANT_CRYPTOPP_ASM32
  97. [ALGO_CRYPTOPP_ASM32] = "cryptopp_asm32",
  98. #endif
  99. #ifdef WANT_X8664_SSE2
  100. [ALGO_SSE2_64] = "sse2_64",
  101. #endif
  102. };
  103. bool opt_debug = false;
  104. bool opt_protocol = false;
  105. bool want_longpoll = true;
  106. bool have_longpoll = false;
  107. bool use_syslog = false;
  108. static bool opt_quiet = false;
  109. static int opt_retries = -1;
  110. static int opt_fail_pause = 5;
  111. static int opt_log_interval = 5;
  112. bool opt_log_output = false;
  113. static bool opt_dynamic = true;
  114. static int opt_queue = 1;
  115. int opt_vectors;
  116. int opt_worksize;
  117. int opt_scantime = 60;
  118. static const bool opt_time = true;
  119. #ifdef WANT_X8664_SSE2
  120. static enum sha256_algos opt_algo = ALGO_SSE2_64;
  121. #else
  122. static enum sha256_algos opt_algo = ALGO_C;
  123. #endif
  124. static int nDevs;
  125. static int opt_g_threads = 2;
  126. static int opt_device;
  127. static int total_devices;
  128. static bool gpu_devices[16];
  129. static int gpu_threads;
  130. static bool forced_n_threads;
  131. static int opt_n_threads;
  132. static int mining_threads;
  133. static int num_processors;
  134. static int scan_intensity;
  135. static bool use_curses = true;
  136. static char *rpc_url;
  137. static char *rpc_userpass;
  138. static char *rpc_user, *rpc_pass;
  139. struct thr_info *thr_info;
  140. static int work_thr_id;
  141. int longpoll_thr_id;
  142. static int stage_thr_id;
  143. static int watchdog_thr_id;
  144. struct work_restart *work_restart = NULL;
  145. static pthread_mutex_t hash_lock;
  146. static pthread_mutex_t qd_lock;
  147. static pthread_mutex_t stgd_lock;
  148. static pthread_mutex_t curses_lock;
  149. static double total_mhashes_done;
  150. static struct timeval total_tv_start, total_tv_end;
  151. static int accepted, rejected;
  152. int hw_errors;
  153. static int total_queued, total_staged, lp_staged;
  154. static bool localgen = false;
  155. static unsigned int getwork_requested;
  156. static unsigned int stale_shares;
  157. static unsigned int discarded_work;
  158. static unsigned int new_blocks;
  159. static unsigned int local_work;
  160. static unsigned int localgen_occasions;
  161. static unsigned int remotefail_occasions;
  162. static char current_block[37];
  163. static char longpoll_block[37];
  164. static char blank[37];
  165. static char datestamp[40];
  166. static void applog_and_exit(const char *fmt, ...)
  167. {
  168. va_list ap;
  169. va_start(ap, fmt);
  170. vapplog(LOG_ERR, fmt, ap);
  171. va_end(ap);
  172. exit(1);
  173. }
  174. /* FIXME: Use asprintf for better errors. */
  175. static char *set_algo(const char *arg, enum sha256_algos *algo)
  176. {
  177. enum sha256_algos i;
  178. for (i = 0; i < ARRAY_SIZE(algo_names); i++) {
  179. if (algo_names[i] && !strcmp(arg, algo_names[i])) {
  180. *algo = i;
  181. return NULL;
  182. }
  183. }
  184. return "Unknown algorithm";
  185. }
  186. static void show_algo(char buf[OPT_SHOW_LEN], const enum sha256_algos *algo)
  187. {
  188. strncpy(buf, algo_names[*algo], OPT_SHOW_LEN);
  189. }
  190. static char *set_int_range(const char *arg, int *i, int min, int max)
  191. {
  192. char *err = opt_set_intval(arg, i);
  193. if (err)
  194. return err;
  195. if (*i < min || *i > max)
  196. return "Value out of range";
  197. return NULL;
  198. }
  199. static char *set_int_0_to_9999(const char *arg, int *i)
  200. {
  201. return set_int_range(arg, i, 0, 9999);
  202. }
  203. static char *forced_int_0_to_14(const char *arg, int *i)
  204. {
  205. opt_dynamic = false;
  206. return set_int_range(arg, i, 0, 14);
  207. }
  208. static char *force_nthreads_int(const char *arg, int *i)
  209. {
  210. forced_n_threads = true;
  211. return set_int_range(arg, i, 0, 9999);
  212. }
  213. static char *set_int_0_to_10(const char *arg, int *i)
  214. {
  215. return set_int_range(arg, i, 0, 10);
  216. }
  217. static char *set_int_1_to_10(const char *arg, int *i)
  218. {
  219. return set_int_range(arg, i, 1, 10);
  220. }
  221. static char *set_devices(const char *arg, int *i)
  222. {
  223. char *err = opt_set_intval(arg, i);
  224. if (err)
  225. return err;
  226. if (*i < 0 || *i > 15)
  227. return "Invalid GPU device number";
  228. total_devices++;
  229. gpu_devices[*i] = true;
  230. return NULL;
  231. }
  232. static char *set_url(const char *arg, char **p)
  233. {
  234. opt_set_charp(arg, p);
  235. if (strncmp(arg, "http://", 7) &&
  236. strncmp(arg, "https://", 8))
  237. return "URL must start with http:// or https://";
  238. return NULL;
  239. }
  240. static char *set_vector(const char *arg, int *i)
  241. {
  242. char *err = opt_set_intval(arg, i);
  243. if (err)
  244. return err;
  245. if (*i != 1 && *i != 2 && *i != 4)
  246. return "Valid vectors are 1, 2 or 4";
  247. return NULL;
  248. }
  249. static char *enable_debug(bool *flag)
  250. {
  251. *flag = true;
  252. /* Turn out verbose output, too. */
  253. opt_log_output = true;
  254. return NULL;
  255. }
  256. /* These options are available from config file or commandline */
  257. static struct opt_table opt_config_table[] = {
  258. OPT_WITH_ARG("--algo|-a",
  259. set_algo, show_algo, &opt_algo,
  260. "Specify sha256 implementation:\n"
  261. "\tc\t\tLinux kernel sha256, implemented in C"
  262. #ifdef WANT_SSE2_4WAY
  263. "\n\t4way\t\ttcatm's 4-way SSE2 implementation"
  264. #endif
  265. #ifdef WANT_VIA_PADLOCK
  266. "\n\tvia\t\tVIA padlock implementation"
  267. #endif
  268. "\n\tcryptopp\tCrypto++ C/C++ implementation"
  269. #ifdef WANT_CRYPTOPP_ASM32
  270. "\n\tcryptopp_asm32\tCrypto++ 32-bit assembler implementation"
  271. #endif
  272. #ifdef WANT_X8664_SSE2
  273. "\n\tsse2_64\t\tSSE2 implementation for x86_64 machines"
  274. #endif
  275. ),
  276. OPT_WITH_ARG("--cpu-threads|-t",
  277. force_nthreads_int, opt_show_intval, &opt_n_threads,
  278. "Number of miner CPU threads"),
  279. OPT_WITHOUT_ARG("--debug|-D",
  280. enable_debug, &opt_debug,
  281. "Enable debug output"),
  282. #ifdef HAVE_OPENCL
  283. OPT_WITH_ARG("--device|-d",
  284. set_devices, NULL, &opt_device,
  285. "Select device to use, (Use repeat -d for multiple devices, default: all)"),
  286. OPT_WITH_ARG("--gpu-threads|-g",
  287. set_int_0_to_10, opt_show_intval, &opt_g_threads,
  288. "Number of threads per GPU (0 - 10)"),
  289. OPT_WITH_ARG("--intensity|-I",
  290. forced_int_0_to_14, opt_show_intval, &scan_intensity,
  291. "Intensity of GPU scanning (0 - 14, default: dynamic to maintain desktop interactivity)"),
  292. #endif
  293. OPT_WITH_ARG("--log|-l",
  294. set_int_0_to_9999, opt_show_intval, &opt_log_interval,
  295. "Interval in seconds between log output"),
  296. OPT_WITHOUT_ARG("--no-longpoll",
  297. opt_set_invbool, &want_longpoll,
  298. "Disable X-Long-Polling support"),
  299. OPT_WITH_ARG("--pass|-p",
  300. opt_set_charp, NULL, &rpc_pass,
  301. "Password for bitcoin JSON-RPC server"),
  302. OPT_WITHOUT_ARG("--protocol-dump|-P",
  303. opt_set_bool, &opt_protocol,
  304. "Verbose dump of protocol-level activities"),
  305. OPT_WITH_ARG("--queue|-Q",
  306. set_int_1_to_10, opt_show_intval, &opt_queue,
  307. "Number of extra work items to queue (1 - 10)"),
  308. OPT_WITHOUT_ARG("--quiet|-q",
  309. opt_set_bool, &opt_quiet,
  310. "Disable per-thread hashmeter output"),
  311. OPT_WITH_ARG("--retries|-r",
  312. opt_set_intval, opt_show_intval, &opt_retries,
  313. "Number of times to retry before giving up, if JSON-RPC call fails (-1 means never)"),
  314. OPT_WITH_ARG("--retry-pause|-R",
  315. set_int_0_to_9999, opt_show_intval, &opt_fail_pause,
  316. "Number of seconds to pause, between retries"),
  317. OPT_WITH_ARG("--scan-time|-s",
  318. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  319. "Upper bound on time spent scanning current work, in seconds"),
  320. #ifdef HAVE_SYSLOG_H
  321. OPT_WITHOUT_ARG("--syslog",
  322. opt_set_bool, &use_syslog,
  323. "Use system log for output messages (default: standard error)"),
  324. #endif
  325. OPT_WITHOUT_ARG("--text-only|-T",
  326. opt_set_invbool, &use_curses,
  327. "Disable ncurses formatted screen output"),
  328. OPT_WITH_ARG("--url|-o",
  329. set_url, opt_show_charp, &rpc_url,
  330. "URL for bitcoin JSON-RPC server"),
  331. OPT_WITH_ARG("--user|-u",
  332. opt_set_charp, NULL, &rpc_user,
  333. "Username for bitcoin JSON-RPC server"),
  334. #ifdef HAVE_OPENCL
  335. OPT_WITH_ARG("--vectors|-v",
  336. set_vector, NULL, &opt_vectors,
  337. "Override detected optimal vector width (1, 2 or 4)"),
  338. #endif
  339. OPT_WITHOUT_ARG("--verbose",
  340. opt_set_bool, &opt_log_output,
  341. "Log verbose output to stderr as well as status output"),
  342. #ifdef HAVE_OPENCL
  343. OPT_WITH_ARG("--worksize|-w",
  344. set_int_0_to_9999, opt_show_intval, &opt_worksize,
  345. "Override detected optimal worksize"),
  346. #endif
  347. OPT_WITH_ARG("--userpass|-O",
  348. opt_set_charp, NULL, &rpc_userpass,
  349. "Username:Password pair for bitcoin JSON-RPC server"),
  350. OPT_ENDTABLE
  351. };
  352. static char *parse_config(json_t *config)
  353. {
  354. static char err_buf[200];
  355. json_t *val;
  356. struct opt_table *opt;
  357. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  358. char *p, *name;
  359. /* We don't handle subtables. */
  360. assert(!(opt->type & OPT_SUBTABLE));
  361. /* Pull apart the option name(s). */
  362. name = strdup(opt->names);
  363. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  364. char *err;
  365. /* Ignore short options. */
  366. if (p[1] != '-')
  367. continue;
  368. val = json_object_get(config, p+2);
  369. if (!val)
  370. continue;
  371. if ((opt->type & OPT_HASARG) && json_is_string(val)) {
  372. err = opt->cb_arg(json_string_value(val),
  373. opt->u.arg);
  374. } else if ((opt->type&OPT_NOARG) && json_is_true(val)) {
  375. err = opt->cb(opt->u.arg);
  376. } else {
  377. err = "Invalid value";
  378. }
  379. if (err) {
  380. sprintf(err_buf, "Parsing JSON option %s: %s",
  381. p, err);
  382. return err_buf;
  383. }
  384. }
  385. free(name);
  386. }
  387. return NULL;
  388. }
  389. static char *load_config(const char *arg, void *unused)
  390. {
  391. json_error_t err;
  392. json_t *config;
  393. config = json_load_file(arg, 0, &err);
  394. if (!json_is_object(config))
  395. return "JSON decode of file failed";
  396. /* Parse the config now, so we can override it. That can keep pointers
  397. * so don't free config object. */
  398. return parse_config(config);
  399. }
  400. static char *print_ndevs_and_exit(int *ndevs)
  401. {
  402. printf("%i GPU devices detected", *ndevs);
  403. exit(*ndevs);
  404. }
  405. /* These options are available from commandline only */
  406. static struct opt_table opt_cmdline_table[] = {
  407. OPT_WITH_ARG("--config|-c",
  408. load_config, NULL, NULL,
  409. "Load a JSON-format configuration file\n"
  410. "See example-cfg.json for an example configuration."),
  411. OPT_WITHOUT_ARG("--help|-h",
  412. opt_usage_and_exit,
  413. #ifdef HAVE_OPENCL
  414. "\nBuilt with CPU and GPU mining support.\n\n",
  415. #else
  416. "\nBuilt with CPU mining support only.\n\n",
  417. #endif
  418. "Print this message"),
  419. OPT_WITHOUT_ARG("--ndevs|-n",
  420. print_ndevs_and_exit, &nDevs,
  421. "Enumerate number of detected GPUs and exit"),
  422. OPT_ENDTABLE
  423. };
  424. static bool jobj_binary(const json_t *obj, const char *key,
  425. void *buf, size_t buflen)
  426. {
  427. const char *hexstr;
  428. json_t *tmp;
  429. tmp = json_object_get(obj, key);
  430. if (unlikely(!tmp)) {
  431. applog(LOG_ERR, "JSON key '%s' not found", key);
  432. return false;
  433. }
  434. hexstr = json_string_value(tmp);
  435. if (unlikely(!hexstr)) {
  436. applog(LOG_ERR, "JSON key '%s' is not a string", key);
  437. return false;
  438. }
  439. if (!hex2bin(buf, hexstr, buflen))
  440. return false;
  441. return true;
  442. }
  443. static bool work_decode(const json_t *val, struct work *work)
  444. {
  445. if (unlikely(!jobj_binary(val, "midstate",
  446. work->midstate, sizeof(work->midstate)))) {
  447. applog(LOG_ERR, "JSON inval midstate");
  448. goto err_out;
  449. }
  450. if (unlikely(!jobj_binary(val, "data", work->data, sizeof(work->data)))) {
  451. applog(LOG_ERR, "JSON inval data");
  452. goto err_out;
  453. }
  454. if (unlikely(!jobj_binary(val, "hash1", work->hash1, sizeof(work->hash1)))) {
  455. applog(LOG_ERR, "JSON inval hash1");
  456. goto err_out;
  457. }
  458. if (unlikely(!jobj_binary(val, "target", work->target, sizeof(work->target)))) {
  459. applog(LOG_ERR, "JSON inval target");
  460. goto err_out;
  461. }
  462. memset(work->hash, 0, sizeof(work->hash));
  463. return true;
  464. err_out:
  465. return false;
  466. }
  467. static inline int gpu_from_thr_id(int thr_id)
  468. {
  469. return thr_id % nDevs;
  470. }
  471. static inline int cpu_from_thr_id(int thr_id)
  472. {
  473. return (thr_id - gpu_threads) % num_processors;
  474. }
  475. static WINDOW *mainwin, *statuswin, *logwin;
  476. static double total_secs = 0.1;
  477. static char statusline[256];
  478. static int cpucursor, gpucursor, logstart, logcursor;
  479. static bool curses_active = false;
  480. static struct cgpu_info *gpus, *cpus;
  481. static void text_print_status(int thr_id)
  482. {
  483. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  484. printf(" %sPU %d: [%.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]\n",
  485. cgpu->is_gpu ? "G" : "C", cgpu->cpu_gpu, cgpu->total_mhashes / total_secs,
  486. cgpu->getworks, cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  487. cgpu->efficiency, cgpu->utility);
  488. }
  489. /* Must be called with curses mutex lock held and curses_active */
  490. static void curses_print_status(int thr_id)
  491. {
  492. wmove(statuswin, 0, 0);
  493. wattron(statuswin, A_BOLD);
  494. wprintw(statuswin, " " PROGRAM_NAME " version " VERSION " - Started: %s", datestamp);
  495. wattroff(statuswin, A_BOLD);
  496. wmove(statuswin, 1, 0);
  497. whline(statuswin, '-', 80);
  498. wmove(statuswin, 2,0);
  499. wprintw(statuswin, " %s", statusline);
  500. wclrtoeol(statuswin);
  501. wmove(statuswin, 3, 0);
  502. whline(statuswin, '-', 80);
  503. wmove(statuswin, logstart - 1, 0);
  504. whline(statuswin, '-', 80);
  505. if (thr_id >= 0 && thr_id < gpu_threads) {
  506. int gpu = gpu_from_thr_id(thr_id);
  507. struct cgpu_info *cgpu = &gpus[gpu];
  508. wmove(statuswin, gpucursor + gpu, 0);
  509. wprintw(statuswin, " GPU %d: [%.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]",
  510. gpu, cgpu->total_mhashes / total_secs,
  511. cgpu->getworks, cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  512. cgpu->efficiency, cgpu->utility);
  513. wclrtoeol(statuswin);
  514. } else if (thr_id >= gpu_threads) {
  515. int cpu = cpu_from_thr_id(thr_id);
  516. struct cgpu_info *cgpu = &cpus[cpu];
  517. wmove(statuswin, cpucursor + cpu, 0);
  518. wprintw(statuswin, " CPU %d: [%.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]",
  519. cpu, cgpu->total_mhashes / total_secs,
  520. cgpu->getworks, cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  521. cgpu->efficiency, cgpu->utility);
  522. wclrtoeol(statuswin);
  523. }
  524. }
  525. static void print_status(int thr_id)
  526. {
  527. if (!curses_active)
  528. text_print_status(thr_id);
  529. else {
  530. pthread_mutex_lock(&curses_lock);
  531. curses_print_status(thr_id);
  532. wrefresh(statuswin);
  533. pthread_mutex_unlock(&curses_lock);
  534. }
  535. }
  536. void log_curses(const char *f, va_list ap)
  537. {
  538. if (curses_active) {
  539. pthread_mutex_lock(&curses_lock);
  540. vw_printw(logwin, f, ap);
  541. wrefresh(logwin);
  542. pthread_mutex_unlock(&curses_lock);
  543. } else
  544. vprintf(f, ap);
  545. }
  546. static bool submit_fail = false;
  547. static bool submit_upstream_work(const struct work *work)
  548. {
  549. char *hexstr = NULL;
  550. json_t *val, *res;
  551. char s[345];
  552. bool rc = false;
  553. int thr_id = work->thr_id;
  554. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  555. CURL *curl = curl_easy_init();
  556. if (unlikely(!curl)) {
  557. applog(LOG_ERR, "CURL initialisation failed");
  558. return rc;
  559. }
  560. /* build hex string */
  561. hexstr = bin2hex(work->data, sizeof(work->data));
  562. if (unlikely(!hexstr)) {
  563. applog(LOG_ERR, "submit_upstream_work OOM");
  564. goto out_nofree;
  565. }
  566. /* build JSON-RPC request */
  567. sprintf(s,
  568. "{\"method\": \"getwork\", \"params\": [ \"%s\" ], \"id\":1}\r\n",
  569. hexstr);
  570. if (opt_debug)
  571. applog(LOG_DEBUG, "DBG: sending RPC call: %s", s);
  572. /* issue JSON-RPC request */
  573. val = json_rpc_call(curl, rpc_url, rpc_userpass, s, false, false);
  574. if (unlikely(!val)) {
  575. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  576. if (!submit_fail) {
  577. submit_fail = true;
  578. remotefail_occasions++;
  579. applog(LOG_WARNING, "Upstream communication failure, caching submissions");
  580. }
  581. goto out;
  582. } else if (submit_fail) {
  583. submit_fail = false;
  584. applog(LOG_WARNING, "Upstream communication resumed, submitting work");
  585. }
  586. res = json_object_get(val, "result");
  587. /* Theoretically threads could race when modifying accepted and
  588. * rejected values but the chance of two submits completing at the
  589. * same time is zero so there is no point adding extra locking */
  590. if (json_is_true(res)) {
  591. cgpu->accepted++;
  592. accepted++;
  593. if (opt_debug)
  594. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  595. if (!opt_quiet)
  596. applog(LOG_WARNING, "Share accepted from %sPU %d thread %d",
  597. cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, thr_id);
  598. } else {
  599. cgpu->rejected++;
  600. rejected++;
  601. if (opt_debug)
  602. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  603. if (!opt_quiet)
  604. applog(LOG_WARNING, "Share rejected from %sPU %d thread %d",
  605. cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, thr_id);
  606. }
  607. cgpu->utility = cgpu->accepted / ( total_secs ? total_secs : 1 ) * 60;
  608. cgpu->efficiency = cgpu->getworks ? cgpu->accepted * 100.0 / cgpu->getworks : 0.0;
  609. if (!opt_quiet)
  610. print_status(thr_id);
  611. applog(LOG_INFO, "%sPU %d Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m",
  612. cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, cgpu->getworks, cgpu->accepted,
  613. cgpu->rejected, cgpu->hw_errors, cgpu->efficiency, cgpu->utility);
  614. json_decref(val);
  615. rc = true;
  616. out:
  617. free(hexstr);
  618. out_nofree:
  619. curl_easy_cleanup(curl);
  620. return rc;
  621. }
  622. static const char *rpc_req =
  623. "{\"method\": \"getwork\", \"params\": [], \"id\":0}\r\n";
  624. static bool get_upstream_work(struct work *work)
  625. {
  626. json_t *val;
  627. bool rc = false;
  628. CURL *curl = curl_easy_init();
  629. if (unlikely(!curl)) {
  630. applog(LOG_ERR, "CURL initialisation failed");
  631. return rc;
  632. }
  633. val = json_rpc_call(curl, rpc_url, rpc_userpass, rpc_req,
  634. want_longpoll, false);
  635. if (unlikely(!val)) {
  636. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  637. goto out;
  638. }
  639. rc = work_decode(json_object_get(val, "result"), work);
  640. json_decref(val);
  641. out:
  642. curl_easy_cleanup(curl);
  643. return rc;
  644. }
  645. static void workio_cmd_free(struct workio_cmd *wc)
  646. {
  647. if (!wc)
  648. return;
  649. switch (wc->cmd) {
  650. case WC_SUBMIT_WORK:
  651. free(wc->u.work);
  652. break;
  653. default: /* do nothing */
  654. break;
  655. }
  656. memset(wc, 0, sizeof(*wc)); /* poison */
  657. free(wc);
  658. }
  659. static void kill_work(void)
  660. {
  661. struct workio_cmd *wc;
  662. struct thr_info *thr;
  663. unsigned int i;
  664. applog(LOG_INFO, "Received kill message");
  665. /* Kill the watchdog thread */
  666. thr = &thr_info[watchdog_thr_id];
  667. pthread_cancel(thr->pth);
  668. /* Stop the mining threads*/
  669. for (i = 0; i < mining_threads; i++) {
  670. thr = &thr_info[i];
  671. tq_freeze(thr->q);
  672. /* No need to check if this succeeds or not */
  673. pthread_cancel(thr->pth);
  674. }
  675. /* Stop the others */
  676. thr = &thr_info[stage_thr_id];
  677. pthread_cancel(thr->pth);
  678. thr = &thr_info[longpoll_thr_id];
  679. pthread_cancel(thr->pth);
  680. wc = calloc(1, sizeof(*wc));
  681. if (unlikely(!wc)) {
  682. applog(LOG_ERR, "Failed to calloc wc in kill_work");
  683. /* We're just trying to die anyway, so forget graceful */
  684. exit (1);
  685. }
  686. wc->cmd = WC_DIE;
  687. wc->thr = 0;
  688. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  689. applog(LOG_ERR, "Failed to tq_push work in kill_work");
  690. exit (1);
  691. }
  692. }
  693. static void disable_curses(void)
  694. {
  695. if (curses_active) {
  696. curses_active = false;
  697. delwin(logwin);
  698. delwin(statuswin);
  699. delwin(mainwin);
  700. endwin();
  701. refresh();
  702. }
  703. }
  704. static void sighandler(int sig)
  705. {
  706. kill_work();
  707. }
  708. static void *get_work_thread(void *userdata)
  709. {
  710. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  711. struct work *ret_work;
  712. int failures = 0;
  713. pthread_detach(pthread_self());
  714. ret_work = calloc(1, sizeof(*ret_work));
  715. if (unlikely(!ret_work)) {
  716. applog(LOG_ERR, "Failed to calloc ret_work in workio_get_work");
  717. kill_work();
  718. goto out;
  719. }
  720. /* obtain new work from bitcoin via JSON-RPC */
  721. while (!get_upstream_work(ret_work)) {
  722. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  723. applog(LOG_ERR, "json_rpc_call failed, terminating workio thread");
  724. free(ret_work);
  725. kill_work();
  726. goto out;
  727. }
  728. /* pause, then restart work-request loop */
  729. applog(LOG_DEBUG, "json_rpc_call failed on get work, retry after %d seconds",
  730. opt_fail_pause);
  731. sleep(opt_fail_pause);
  732. }
  733. /* send work to requesting thread */
  734. if (unlikely(!tq_push(thr_info[stage_thr_id].q, ret_work))) {
  735. applog(LOG_ERR, "Failed to tq_push work in workio_get_work");
  736. kill_work();
  737. free(ret_work);
  738. }
  739. out:
  740. workio_cmd_free(wc);
  741. return NULL;
  742. }
  743. static bool workio_get_work(struct workio_cmd *wc)
  744. {
  745. pthread_t get_thread;
  746. if (unlikely(pthread_create(&get_thread, NULL, get_work_thread, (void *)wc))) {
  747. applog(LOG_ERR, "Failed to create get_work_thread");
  748. return false;
  749. }
  750. return true;
  751. }
  752. static void *submit_work_thread(void *userdata)
  753. {
  754. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  755. int failures = 0;
  756. char *hexstr;
  757. pthread_detach(pthread_self());
  758. hexstr = bin2hex(wc->u.work->data, 36);
  759. if (unlikely(!hexstr)) {
  760. applog(LOG_ERR, "submit_work_thread OOM");
  761. goto out;
  762. }
  763. if (unlikely(strncmp(hexstr, current_block, 36))) {
  764. applog(LOG_WARNING, "Stale work detected, discarding");
  765. stale_shares++;
  766. goto out_free;
  767. }
  768. /* submit solution to bitcoin via JSON-RPC */
  769. while (!submit_upstream_work(wc->u.work)) {
  770. if (unlikely(strncmp(hexstr, current_block, 36))) {
  771. applog(LOG_WARNING, "Stale work detected, discarding");
  772. stale_shares++;
  773. goto out_free;
  774. }
  775. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  776. applog(LOG_ERR, "Failed %d retries ...terminating workio thread", opt_retries);
  777. kill_work();
  778. goto out_free;
  779. }
  780. /* pause, then restart work-request loop */
  781. applog(LOG_INFO, "json_rpc_call failed on submit_work, retry after %d seconds",
  782. opt_fail_pause);
  783. sleep(opt_fail_pause);
  784. }
  785. out_free:
  786. free(hexstr);
  787. out:
  788. workio_cmd_free(wc);
  789. return NULL;
  790. }
  791. static bool workio_submit_work(struct workio_cmd *wc)
  792. {
  793. pthread_t submit_thread;
  794. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, (void *)wc))) {
  795. applog(LOG_ERR, "Failed to create submit_work_thread");
  796. return false;
  797. }
  798. return true;
  799. }
  800. static void inc_staged(int inc, bool lp)
  801. {
  802. pthread_mutex_lock(&stgd_lock);
  803. if (lp) {
  804. lp_staged += inc;
  805. total_staged += inc;
  806. } else if (lp_staged)
  807. lp_staged--;
  808. else
  809. total_staged += inc;
  810. pthread_mutex_unlock(&stgd_lock);
  811. }
  812. static void dec_staged(int inc)
  813. {
  814. pthread_mutex_lock(&stgd_lock);
  815. if (lp_staged)
  816. lp_staged -= inc;
  817. total_staged -= inc;
  818. pthread_mutex_unlock(&stgd_lock);
  819. }
  820. static int requests_staged(void)
  821. {
  822. int ret;
  823. pthread_mutex_lock(&stgd_lock);
  824. ret = total_staged;
  825. pthread_mutex_unlock(&stgd_lock);
  826. return ret;
  827. }
  828. static void *stage_thread(void *userdata)
  829. {
  830. struct thr_info *mythr = userdata;
  831. bool ok = true;
  832. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  833. while (ok) {
  834. struct work *work = NULL;
  835. char *hexstr;
  836. work = tq_pop(mythr->q, NULL);
  837. if (unlikely(!work)) {
  838. applog(LOG_ERR, "Failed to tq_pop in stage_thread");
  839. ok = false;
  840. break;
  841. }
  842. hexstr = bin2hex(work->data, 36);
  843. if (unlikely(!hexstr)) {
  844. applog(LOG_ERR, "stage_thread OOM");
  845. break;
  846. }
  847. /* current_block is blanked out on successful longpoll */
  848. if (likely(strncmp(current_block, blank, 36))) {
  849. if (unlikely(strncmp(hexstr, current_block, 36))) {
  850. new_blocks++;
  851. if (want_longpoll)
  852. applog(LOG_WARNING, "New block detected on network before receiving longpoll, flushing work queue");
  853. else
  854. applog(LOG_WARNING, "New block detected on network, flushing work queue");
  855. /* As we can't flush the work from here, signal
  856. * the wakeup thread to restart all the
  857. * threads */
  858. work_restart[stage_thr_id].restart = 1;
  859. }
  860. } else
  861. memcpy(longpoll_block, hexstr, 36);
  862. memcpy(current_block, hexstr, 36);
  863. free(hexstr);
  864. if (unlikely(!tq_push(thr_info[0].q, work))) {
  865. applog(LOG_ERR, "Failed to tq_push work in stage_thread");
  866. ok = false;
  867. break;
  868. }
  869. inc_staged(1, false);
  870. }
  871. tq_freeze(mythr->q);
  872. return NULL;
  873. }
  874. static void *workio_thread(void *userdata)
  875. {
  876. struct thr_info *mythr = userdata;
  877. bool ok = true;
  878. while (ok) {
  879. struct workio_cmd *wc;
  880. /* wait for workio_cmd sent to us, on our queue */
  881. wc = tq_pop(mythr->q, NULL);
  882. if (unlikely(!wc)) {
  883. applog(LOG_ERR, "Failed to tq_pop in workio_thread");
  884. ok = false;
  885. break;
  886. }
  887. /* process workio_cmd */
  888. switch (wc->cmd) {
  889. case WC_GET_WORK:
  890. ok = workio_get_work(wc);
  891. break;
  892. case WC_SUBMIT_WORK:
  893. ok = workio_submit_work(wc);
  894. break;
  895. case WC_DIE:
  896. default:
  897. ok = false;
  898. break;
  899. }
  900. }
  901. tq_freeze(mythr->q);
  902. return NULL;
  903. }
  904. static void hashmeter(int thr_id, struct timeval *diff,
  905. unsigned long hashes_done)
  906. {
  907. struct timeval temp_tv_end, total_diff;
  908. double khashes, secs;
  909. double local_secs;
  910. double utility, efficiency = 0.0;
  911. static double local_mhashes_done = 0;
  912. static double rolling_local = 0;
  913. double local_mhashes = (double)hashes_done / 1000000.0;
  914. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  915. /* Update the last time this thread reported in */
  916. if (thr_id >= 0)
  917. gettimeofday(&thr_info[thr_id].last, NULL);
  918. /* Don't bother calculating anything if we're not displaying it */
  919. if (opt_quiet || !opt_log_interval)
  920. return;
  921. khashes = hashes_done / 1000.0;
  922. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  923. if (thr_id >= 0 && secs) {
  924. /* So we can call hashmeter from a non worker thread */
  925. if (opt_debug)
  926. applog(LOG_DEBUG, "[thread %d: %lu hashes, %.0f khash/sec]",
  927. thr_id, hashes_done, hashes_done / secs);
  928. cgpu->local_mhashes += local_mhashes;
  929. cgpu->total_mhashes += local_mhashes;
  930. }
  931. /* Totals are updated by all threads so can race without locking */
  932. pthread_mutex_lock(&hash_lock);
  933. gettimeofday(&temp_tv_end, NULL);
  934. timeval_subtract(&total_diff, &temp_tv_end, &total_tv_end);
  935. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  936. total_mhashes_done += local_mhashes;
  937. local_mhashes_done += local_mhashes;
  938. if (total_diff.tv_sec < opt_log_interval)
  939. /* Only update the total every opt_log_interval seconds */
  940. goto out_unlock;
  941. gettimeofday(&total_tv_end, NULL);
  942. /* Use a rolling average by faking an exponential decay over 5 * log */
  943. rolling_local = ((rolling_local * 0.9) + local_mhashes_done) / 1.9;
  944. timeval_subtract(&total_diff, &total_tv_end, &total_tv_start);
  945. total_secs = (double)total_diff.tv_sec +
  946. ((double)total_diff.tv_usec / 1000000.0);
  947. utility = accepted / ( total_secs ? total_secs : 1 ) * 60;
  948. efficiency = getwork_requested ? accepted * 100.0 / getwork_requested : 0.0;
  949. sprintf(statusline, "[(%ds):%.1f (avg):%.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]",
  950. opt_log_interval, rolling_local / local_secs, total_mhashes_done / total_secs,
  951. getwork_requested, accepted, rejected, hw_errors, efficiency, utility);
  952. if (!curses_active) {
  953. printf("%s \r", statusline);
  954. fflush(stdout);
  955. } else
  956. applog(LOG_INFO, "%s", statusline);
  957. local_mhashes_done = 0;
  958. out_unlock:
  959. pthread_mutex_unlock(&hash_lock);
  960. }
  961. /* This is overkill, but at least we'll know accurately how much work is
  962. * queued to prevent ever being left without work */
  963. static void inc_queued(void)
  964. {
  965. pthread_mutex_lock(&qd_lock);
  966. total_queued++;
  967. pthread_mutex_unlock(&qd_lock);
  968. }
  969. static void dec_queued(void)
  970. {
  971. pthread_mutex_lock(&qd_lock);
  972. total_queued--;
  973. pthread_mutex_unlock(&qd_lock);
  974. dec_staged(1);
  975. }
  976. static int requests_queued(void)
  977. {
  978. int ret;
  979. pthread_mutex_lock(&qd_lock);
  980. ret = total_queued;
  981. pthread_mutex_unlock(&qd_lock);
  982. return ret;
  983. }
  984. /* All work is queued flagged as being for thread 0 and then the mining thread
  985. * flags it as its own */
  986. static bool queue_request(void)
  987. {
  988. struct thr_info *thr = &thr_info[0];
  989. struct workio_cmd *wc;
  990. /* fill out work request message */
  991. wc = calloc(1, sizeof(*wc));
  992. if (unlikely(!wc)) {
  993. applog(LOG_ERR, "Failed to tq_pop in queue_request");
  994. return false;
  995. }
  996. wc->cmd = WC_GET_WORK;
  997. wc->thr = thr;
  998. /* send work request to workio thread */
  999. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  1000. applog(LOG_ERR, "Failed to tq_push in queue_request");
  1001. workio_cmd_free(wc);
  1002. return false;
  1003. }
  1004. inc_queued();
  1005. return true;
  1006. }
  1007. static bool discard_request(void)
  1008. {
  1009. struct thr_info *thr = &thr_info[0];
  1010. struct work *work_heap;
  1011. /* Just in case we fell in a hole and missed a queue filling */
  1012. if (unlikely(!requests_queued())) {
  1013. applog(LOG_WARNING, "Tried to discard_request with nil queued");
  1014. return true;
  1015. }
  1016. work_heap = tq_pop(thr->q, NULL);
  1017. if (unlikely(!work_heap)) {
  1018. applog(LOG_ERR, "Failed to tq_pop in discard_request");
  1019. return false;
  1020. }
  1021. free(work_heap);
  1022. dec_queued();
  1023. discarded_work++;
  1024. return true;
  1025. }
  1026. static void flush_requests(bool longpoll)
  1027. {
  1028. int i, extra;
  1029. extra = requests_queued();
  1030. /* When flushing from longpoll, we don't know the new work yet. When
  1031. * not flushing from longpoll, the first work item is valid so do not
  1032. * discard it */
  1033. if (longpoll)
  1034. memcpy(current_block, blank, 36);
  1035. else
  1036. extra--;
  1037. /* Temporarily increase the staged count so that get_work thinks there
  1038. * is work available instead of making threads reuse existing work */
  1039. if (extra >= mining_threads)
  1040. inc_staged(mining_threads, true);
  1041. else
  1042. inc_staged(extra, true);
  1043. for (i = 0; i < extra; i++) {
  1044. /* Queue a whole batch of new requests */
  1045. if (unlikely(!queue_request())) {
  1046. applog(LOG_ERR, "Failed to queue requests in flush_requests");
  1047. kill_work();
  1048. break;
  1049. }
  1050. /* Pop off the old requests. Cancelling the requests would be better
  1051. * but is tricky */
  1052. if (unlikely(!discard_request())) {
  1053. applog(LOG_ERR, "Failed to discard requests in flush_requests");
  1054. kill_work();
  1055. break;
  1056. }
  1057. }
  1058. }
  1059. static bool get_work(struct work *work, bool queued)
  1060. {
  1061. struct timeval now;
  1062. struct timespec abstime = {};
  1063. struct thr_info *thr = &thr_info[0];
  1064. struct work *work_heap;
  1065. bool ret = false;
  1066. int failures = 0;
  1067. getwork_requested++;
  1068. retry:
  1069. gettimeofday(&now, NULL);
  1070. abstime.tv_sec = now.tv_sec + 60;
  1071. if (unlikely(!queued && !queue_request())) {
  1072. applog(LOG_WARNING, "Failed to queue_request in get_work");
  1073. goto out;
  1074. }
  1075. if (!requests_staged()) {
  1076. uint32_t *work_ntime;
  1077. uint32_t ntime;
  1078. /* Only print this message once each time we shift to localgen */
  1079. if (!localgen) {
  1080. applog(LOG_WARNING, "Server not providing work fast enough, generating work locally");
  1081. localgen = true;
  1082. localgen_occasions++;
  1083. }
  1084. work_ntime = (uint32_t *)(work->data + 68);
  1085. ntime = be32toh(*work_ntime);
  1086. ntime++;
  1087. *work_ntime = htobe32(ntime);
  1088. ret = true;
  1089. local_work++;
  1090. goto out;
  1091. } else if (localgen) {
  1092. localgen = false;
  1093. applog(LOG_WARNING, "Resumed retrieving work from server");
  1094. }
  1095. /* Wait for 1st response, or get cached response. We really should
  1096. * never time out on the pop request but something might go amiss :/
  1097. */
  1098. work_heap = tq_pop(thr->q, &abstime);
  1099. if (unlikely(!work_heap)) {
  1100. applog(LOG_INFO, "Failed to tq_pop in get_work");
  1101. goto out;
  1102. }
  1103. dec_queued();
  1104. memcpy(work, work_heap, sizeof(*work));
  1105. ret = true;
  1106. free(work_heap);
  1107. out:
  1108. if (unlikely(ret == false)) {
  1109. if ((opt_retries >= 0) && (++failures > opt_retries)) {
  1110. applog(LOG_ERR, "Failed %d times to get_work");
  1111. return ret;
  1112. }
  1113. applog(LOG_DEBUG, "Retrying after %d seconds", opt_fail_pause);
  1114. sleep(opt_fail_pause);
  1115. goto retry;
  1116. }
  1117. return ret;
  1118. }
  1119. static bool submit_work_sync(struct thr_info *thr, const struct work *work_in)
  1120. {
  1121. struct workio_cmd *wc;
  1122. /* fill out work request message */
  1123. wc = calloc(1, sizeof(*wc));
  1124. if (unlikely(!wc)) {
  1125. applog(LOG_ERR, "Failed to calloc wc in submit_work_sync");
  1126. return false;
  1127. }
  1128. wc->u.work = malloc(sizeof(*work_in));
  1129. if (unlikely(!wc->u.work)) {
  1130. applog(LOG_ERR, "Failed to calloc work in submit_work_sync");
  1131. goto err_out;
  1132. }
  1133. wc->cmd = WC_SUBMIT_WORK;
  1134. wc->thr = thr;
  1135. memcpy(wc->u.work, work_in, sizeof(*work_in));
  1136. /* send solution to workio thread */
  1137. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  1138. applog(LOG_ERR, "Failed to tq_push work in submit_work_sync");
  1139. goto err_out;
  1140. }
  1141. return true;
  1142. err_out:
  1143. workio_cmd_free(wc);
  1144. return false;
  1145. }
  1146. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  1147. {
  1148. work->data[64+12+0] = (nonce>>0) & 0xff;
  1149. work->data[64+12+1] = (nonce>>8) & 0xff;
  1150. work->data[64+12+2] = (nonce>>16) & 0xff;
  1151. work->data[64+12+3] = (nonce>>24) & 0xff;
  1152. return submit_work_sync(thr, work);
  1153. }
  1154. static void *miner_thread(void *userdata)
  1155. {
  1156. struct thr_info *mythr = userdata;
  1157. const int thr_id = mythr->id;
  1158. uint32_t max_nonce = 0xffffff;
  1159. unsigned long hashes_done = max_nonce;
  1160. bool needs_work = true;
  1161. /* Try to cycle approximately 5 times before each log update */
  1162. const unsigned long cycle = opt_log_interval / 5 ? : 1;
  1163. /* Request the next work item at 2/3 of the scantime */
  1164. unsigned const int request_interval = opt_scantime * 2 / 3 ? : 1;
  1165. unsigned const long request_nonce = MAXTHREADS / 3 * 2;
  1166. bool requested = true;
  1167. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  1168. /* Set worker threads to nice 19 and then preferentially to SCHED_IDLE
  1169. * and if that fails, then SCHED_BATCH. No need for this to be an
  1170. * error if it fails */
  1171. setpriority(PRIO_PROCESS, 0, 19);
  1172. drop_policy();
  1173. /* Cpu affinity only makes sense if the number of threads is a multiple
  1174. * of the number of CPUs */
  1175. if (!(opt_n_threads % num_processors))
  1176. affine_to_cpu(thr_id - gpu_threads, cpu_from_thr_id(thr_id));
  1177. while (1) {
  1178. struct work work __attribute__((aligned(128)));
  1179. struct timeval tv_workstart, tv_start, tv_end, diff;
  1180. uint64_t max64;
  1181. bool rc;
  1182. if (needs_work) {
  1183. gettimeofday(&tv_workstart, NULL);
  1184. /* obtain new work from internal workio thread */
  1185. if (unlikely(!get_work(&work, requested))) {
  1186. applog(LOG_ERR, "work retrieval failed, exiting "
  1187. "mining thread %d", thr_id);
  1188. goto out;
  1189. }
  1190. mythr->cgpu->getworks++;
  1191. work.thr_id = thr_id;
  1192. needs_work = requested = false;
  1193. work.blk.nonce = 0;
  1194. max_nonce = hashes_done;
  1195. }
  1196. hashes_done = 0;
  1197. gettimeofday(&tv_start, NULL);
  1198. /* scan nonces for a proof-of-work hash */
  1199. switch (opt_algo) {
  1200. case ALGO_C:
  1201. rc = scanhash_c(thr_id, work.midstate, work.data + 64,
  1202. work.hash1, work.hash, work.target,
  1203. max_nonce, &hashes_done,
  1204. work.blk.nonce);
  1205. break;
  1206. #ifdef WANT_X8664_SSE2
  1207. case ALGO_SSE2_64: {
  1208. unsigned int rc5 =
  1209. scanhash_sse2_64(thr_id, work.midstate, work.data + 64,
  1210. work.hash1, work.hash,
  1211. work.target,
  1212. max_nonce, &hashes_done,
  1213. work.blk.nonce);
  1214. rc = (rc5 == -1) ? false : true;
  1215. }
  1216. break;
  1217. #endif
  1218. #ifdef WANT_SSE2_4WAY
  1219. case ALGO_4WAY: {
  1220. unsigned int rc4 =
  1221. ScanHash_4WaySSE2(thr_id, work.midstate, work.data + 64,
  1222. work.hash1, work.hash,
  1223. work.target,
  1224. max_nonce, &hashes_done,
  1225. work.blk.nonce);
  1226. rc = (rc4 == -1) ? false : true;
  1227. }
  1228. break;
  1229. #endif
  1230. #ifdef WANT_VIA_PADLOCK
  1231. case ALGO_VIA:
  1232. rc = scanhash_via(thr_id, work.data, work.target,
  1233. max_nonce, &hashes_done,
  1234. work.blk.nonce);
  1235. break;
  1236. #endif
  1237. case ALGO_CRYPTOPP:
  1238. rc = scanhash_cryptopp(thr_id, work.midstate, work.data + 64,
  1239. work.hash1, work.hash, work.target,
  1240. max_nonce, &hashes_done,
  1241. work.blk.nonce);
  1242. break;
  1243. #ifdef WANT_CRYPTOPP_ASM32
  1244. case ALGO_CRYPTOPP_ASM32:
  1245. rc = scanhash_asm32(thr_id, work.midstate, work.data + 64,
  1246. work.hash1, work.hash, work.target,
  1247. max_nonce, &hashes_done,
  1248. work.blk.nonce);
  1249. break;
  1250. #endif
  1251. default:
  1252. /* should never happen */
  1253. goto out;
  1254. }
  1255. /* record scanhash elapsed time */
  1256. gettimeofday(&tv_end, NULL);
  1257. timeval_subtract(&diff, &tv_end, &tv_start);
  1258. hashes_done -= work.blk.nonce;
  1259. hashmeter(thr_id, &diff, hashes_done);
  1260. work.blk.nonce += hashes_done;
  1261. /* adjust max_nonce to meet target cycle time */
  1262. if (diff.tv_usec > 500000)
  1263. diff.tv_sec++;
  1264. if (diff.tv_sec && diff.tv_sec != cycle) {
  1265. max64 = work.blk.nonce +
  1266. ((uint64_t)hashes_done * cycle) / diff.tv_sec;
  1267. } else
  1268. max64 = work.blk.nonce + hashes_done;
  1269. if (max64 > 0xfffffffaULL)
  1270. max64 = 0xfffffffaULL;
  1271. max_nonce = max64;
  1272. /* if nonce found, submit work */
  1273. if (unlikely(rc)) {
  1274. if (opt_debug)
  1275. applog(LOG_DEBUG, "CPU %d found something?", cpu_from_thr_id(thr_id));
  1276. if (unlikely(!submit_work_sync(mythr, &work))) {
  1277. applog(LOG_ERR, "Failed to submit_work_sync in miner_thread %d", thr_id);
  1278. break;
  1279. }
  1280. work.blk.nonce += 4;
  1281. }
  1282. timeval_subtract(&diff, &tv_end, &tv_workstart);
  1283. if (!requested && (diff.tv_sec > request_interval || work.blk.nonce > request_nonce)) {
  1284. if (unlikely(!queue_request())) {
  1285. applog(LOG_ERR, "Failed to queue_request in miner_thread %d", thr_id);
  1286. goto out;
  1287. }
  1288. requested = true;
  1289. }
  1290. if (diff.tv_sec > opt_scantime || work_restart[thr_id].restart ||
  1291. work.blk.nonce >= MAXTHREADS - hashes_done)
  1292. needs_work = true;
  1293. }
  1294. out:
  1295. tq_freeze(mythr->q);
  1296. return NULL;
  1297. }
  1298. enum {
  1299. STAT_SLEEP_INTERVAL = 1,
  1300. STAT_CTR_INTERVAL = 10000000,
  1301. FAILURE_INTERVAL = 30,
  1302. };
  1303. #ifdef HAVE_OPENCL
  1304. static _clState *clStates[16];
  1305. static inline cl_int queue_kernel_parameters(_clState *clState, dev_blk_ctx *blk)
  1306. {
  1307. cl_kernel *kernel = &clState->kernel;
  1308. cl_int status = 0;
  1309. int num = 0;
  1310. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_a);
  1311. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_b);
  1312. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_c);
  1313. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_d);
  1314. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_e);
  1315. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_f);
  1316. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_g);
  1317. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_h);
  1318. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_b);
  1319. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_c);
  1320. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_d);
  1321. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_f);
  1322. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_g);
  1323. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_h);
  1324. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->nonce);
  1325. if (clState->hasBitAlign == true) {
  1326. /* Parameters for phatk kernel */
  1327. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W2);
  1328. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W16);
  1329. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W17);
  1330. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreVal4);
  1331. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->T1);
  1332. } else {
  1333. /* Parameters for poclbm kernel */
  1334. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW0);
  1335. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW1);
  1336. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW2);
  1337. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW3);
  1338. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW15);
  1339. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW01r);
  1340. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e);
  1341. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e2);
  1342. }
  1343. status |= clSetKernelArg(*kernel, num++, sizeof(clState->outputBuffer),
  1344. (void *)&clState->outputBuffer);
  1345. return status;
  1346. }
  1347. static void set_threads_hashes(unsigned int vectors, unsigned int *threads,
  1348. unsigned int *hashes, size_t *globalThreads)
  1349. {
  1350. *globalThreads = *threads = 1 << (15 + scan_intensity);
  1351. *hashes = *threads * vectors;
  1352. }
  1353. static void *gpuminer_thread(void *userdata)
  1354. {
  1355. const unsigned long cycle = opt_log_interval / 5 ? : 1;
  1356. struct timeval tv_start, tv_end, diff, tv_workstart;
  1357. struct thr_info *mythr = userdata;
  1358. const int thr_id = mythr->id;
  1359. uint32_t *res, *blank_res;
  1360. double gpu_ms_average = 7;
  1361. size_t globalThreads[1];
  1362. size_t localThreads[1];
  1363. cl_int status;
  1364. _clState *clState = clStates[thr_id];
  1365. const cl_kernel *kernel = &clState->kernel;
  1366. struct work *work = malloc(sizeof(struct work));
  1367. unsigned int threads = 1 << (15 + scan_intensity);
  1368. unsigned const int vectors = clState->preferred_vwidth;
  1369. unsigned int hashes = threads * vectors;
  1370. unsigned int hashes_done = 0;
  1371. /* Request the next work item at 2/3 of the scantime */
  1372. unsigned const int request_interval = opt_scantime * 2 / 3 ? : 1;
  1373. unsigned const long request_nonce = MAXTHREADS / 3 * 2;
  1374. bool requested = true;
  1375. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  1376. res = calloc(BUFFERSIZE, 1);
  1377. blank_res = calloc(BUFFERSIZE, 1);
  1378. if (!res || !blank_res) {
  1379. applog(LOG_ERR, "Failed to calloc in gpuminer_thread");
  1380. goto out;
  1381. }
  1382. gettimeofday(&tv_start, NULL);
  1383. globalThreads[0] = threads;
  1384. localThreads[0] = clState->work_size;
  1385. diff.tv_sec = 0;
  1386. gettimeofday(&tv_end, NULL);
  1387. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_TRUE, 0,
  1388. BUFFERSIZE, blank_res, 0, NULL, NULL);
  1389. if (unlikely(status != CL_SUCCESS))
  1390. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  1391. gettimeofday(&tv_workstart, NULL);
  1392. /* obtain new work from internal workio thread */
  1393. if (unlikely(!get_work(work, requested))) {
  1394. applog(LOG_ERR, "work retrieval failed, exiting "
  1395. "gpu mining thread %d", mythr->id);
  1396. goto out;
  1397. }
  1398. mythr->cgpu->getworks++;
  1399. work->thr_id = thr_id;
  1400. requested = false;
  1401. precalc_hash(&work->blk, (uint32_t *)(work->midstate), (uint32_t *)(work->data + 64));
  1402. work->blk.nonce = 0;
  1403. while (1) {
  1404. struct timeval tv_gpustart, tv_gpuend;
  1405. suseconds_t gpu_us;
  1406. gettimeofday(&tv_gpustart, NULL);
  1407. timeval_subtract(&diff, &tv_gpustart, &tv_gpuend);
  1408. /* This finish flushes the readbuffer set with CL_FALSE later */
  1409. clFinish(clState->commandQueue);
  1410. gettimeofday(&tv_gpuend, NULL);
  1411. timeval_subtract(&diff, &tv_gpuend, &tv_gpustart);
  1412. gpu_us = diff.tv_sec * 1000000 + diff.tv_usec;
  1413. gpu_ms_average = ((gpu_us / 1000) + gpu_ms_average * 0.9) / 1.9;
  1414. if (opt_dynamic) {
  1415. /* Try to not let the GPU be out for longer than 6ms, but
  1416. * increase intensity when the system is idle, unless
  1417. * dynamic is disabled. */
  1418. if (gpu_ms_average > 7) {
  1419. if (scan_intensity > 0)
  1420. scan_intensity--;
  1421. set_threads_hashes(vectors, &threads, &hashes, globalThreads);
  1422. } else if (gpu_ms_average < 3) {
  1423. if (scan_intensity < 14)
  1424. scan_intensity++;
  1425. set_threads_hashes(vectors, &threads, &hashes, globalThreads);
  1426. }
  1427. }
  1428. if (diff.tv_sec > opt_scantime || work->blk.nonce >= MAXTHREADS - hashes || work_restart[thr_id].restart) {
  1429. /* Ignore any reads since we're getting new work and queue a clean buffer */
  1430. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  1431. BUFFERSIZE, blank_res, 0, NULL, NULL);
  1432. if (unlikely(status != CL_SUCCESS))
  1433. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  1434. memset(res, 0, BUFFERSIZE);
  1435. gettimeofday(&tv_workstart, NULL);
  1436. /* obtain new work from internal workio thread */
  1437. if (unlikely(!get_work(work, requested))) {
  1438. applog(LOG_ERR, "work retrieval failed, exiting "
  1439. "gpu mining thread %d", mythr->id);
  1440. goto out;
  1441. }
  1442. mythr->cgpu->getworks++;
  1443. work->thr_id = thr_id;
  1444. requested = false;
  1445. precalc_hash(&work->blk, (uint32_t *)(work->midstate), (uint32_t *)(work->data + 64));
  1446. work->blk.nonce = 0;
  1447. work_restart[thr_id].restart = 0;
  1448. if (opt_debug)
  1449. applog(LOG_DEBUG, "getwork thread %d", thr_id);
  1450. /* Flushes the writebuffer set with CL_FALSE above */
  1451. clFinish(clState->commandQueue);
  1452. }
  1453. status = queue_kernel_parameters(clState, &work->blk);
  1454. if (unlikely(status != CL_SUCCESS))
  1455. { applog(LOG_ERR, "Error: clSetKernelArg of all params failed."); goto out; }
  1456. /* MAXBUFFERS entry is used as a flag to say nonces exist */
  1457. if (res[MAXBUFFERS]) {
  1458. /* Clear the buffer again */
  1459. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  1460. BUFFERSIZE, blank_res, 0, NULL, NULL);
  1461. if (unlikely(status != CL_SUCCESS))
  1462. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  1463. if (opt_debug)
  1464. applog(LOG_DEBUG, "GPU %d found something?", gpu_from_thr_id(thr_id));
  1465. postcalc_hash_async(mythr, work, res);
  1466. memset(res, 0, BUFFERSIZE);
  1467. clFinish(clState->commandQueue);
  1468. }
  1469. status = clEnqueueNDRangeKernel(clState->commandQueue, *kernel, 1, NULL,
  1470. globalThreads, localThreads, 0, NULL, NULL);
  1471. if (unlikely(status != CL_SUCCESS))
  1472. { applog(LOG_ERR, "Error: Enqueueing kernel onto command queue. (clEnqueueNDRangeKernel)"); goto out; }
  1473. status = clEnqueueReadBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  1474. BUFFERSIZE, res, 0, NULL, NULL);
  1475. if (unlikely(status != CL_SUCCESS))
  1476. { applog(LOG_ERR, "Error: clEnqueueReadBuffer failed. (clEnqueueReadBuffer)"); goto out;}
  1477. gettimeofday(&tv_end, NULL);
  1478. timeval_subtract(&diff, &tv_end, &tv_start);
  1479. hashes_done += hashes;
  1480. work->blk.nonce += hashes;
  1481. if (diff.tv_usec > 500000)
  1482. diff.tv_sec++;
  1483. if (diff.tv_sec >= cycle) {
  1484. hashmeter(thr_id, &diff, hashes_done);
  1485. gettimeofday(&tv_start, NULL);
  1486. hashes_done = 0;
  1487. }
  1488. timeval_subtract(&diff, &tv_end, &tv_workstart);
  1489. if (!requested && (diff.tv_sec > request_interval || work->blk.nonce > request_nonce)) {
  1490. if (unlikely(!queue_request())) {
  1491. applog(LOG_ERR, "Failed to queue_request in gpuminer_thread %d", thr_id);
  1492. goto out;
  1493. }
  1494. requested = true;
  1495. }
  1496. }
  1497. out:
  1498. tq_freeze(mythr->q);
  1499. return NULL;
  1500. }
  1501. #endif /* HAVE_OPENCL */
  1502. static void restart_threads(bool longpoll)
  1503. {
  1504. int i;
  1505. /* Discard old queued requests and get new ones */
  1506. flush_requests(longpoll);
  1507. for (i = 0; i < mining_threads; i++)
  1508. work_restart[i].restart = 1;
  1509. }
  1510. static void *longpoll_thread(void *userdata)
  1511. {
  1512. struct thr_info *mythr = userdata;
  1513. CURL *curl = NULL;
  1514. char *copy_start, *hdr_path, *lp_url = NULL;
  1515. bool need_slash = false;
  1516. int failures = 0;
  1517. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  1518. hdr_path = tq_pop(mythr->q, NULL);
  1519. if (!hdr_path)
  1520. goto out;
  1521. /* full URL */
  1522. if (strstr(hdr_path, "://")) {
  1523. lp_url = hdr_path;
  1524. hdr_path = NULL;
  1525. }
  1526. /* absolute path, on current server */
  1527. else {
  1528. copy_start = (*hdr_path == '/') ? (hdr_path + 1) : hdr_path;
  1529. if (rpc_url[strlen(rpc_url) - 1] != '/')
  1530. need_slash = true;
  1531. lp_url = malloc(strlen(rpc_url) + strlen(copy_start) + 2);
  1532. if (!lp_url)
  1533. goto out;
  1534. sprintf(lp_url, "%s%s%s", rpc_url, need_slash ? "/" : "", copy_start);
  1535. }
  1536. applog(LOG_INFO, "Long-polling activated for %s", lp_url);
  1537. curl = curl_easy_init();
  1538. if (unlikely(!curl)) {
  1539. applog(LOG_ERR, "CURL initialisation failed");
  1540. goto out;
  1541. }
  1542. while (1) {
  1543. struct timeval start, end;
  1544. json_t *val;
  1545. gettimeofday(&start, NULL);
  1546. val = json_rpc_call(curl, lp_url, rpc_userpass, rpc_req,
  1547. false, true);
  1548. if (likely(val)) {
  1549. failures = 0;
  1550. json_decref(val);
  1551. /* Keep track of who ordered a restart_threads to make
  1552. * sure it's only done once per new block */
  1553. if (likely(!strncmp(longpoll_block, blank, 36) ||
  1554. !strncmp(longpoll_block, current_block, 36))) {
  1555. new_blocks++;
  1556. applog(LOG_WARNING, "LONGPOLL detected new block on network, flushing work queue");
  1557. restart_threads(true);
  1558. } else
  1559. applog(LOG_WARNING, "LONGPOLL received after new block already detected");
  1560. } else {
  1561. /* Some pools regularly drop the longpoll request so
  1562. * only see this as longpoll failure if it happens
  1563. * immediately and just restart it the rest of the
  1564. * time. */
  1565. gettimeofday(&end, NULL);
  1566. if (end.tv_sec - start.tv_sec > 30)
  1567. continue;
  1568. if (failures++ < 10) {
  1569. sleep(30);
  1570. applog(LOG_WARNING,
  1571. "longpoll failed, sleeping for 30s");
  1572. } else {
  1573. applog(LOG_ERR,
  1574. "longpoll failed, ending thread");
  1575. goto out;
  1576. }
  1577. }
  1578. memcpy(longpoll_block, current_block, 36);
  1579. }
  1580. out:
  1581. free(hdr_path);
  1582. free(lp_url);
  1583. tq_freeze(mythr->q);
  1584. if (curl)
  1585. curl_easy_cleanup(curl);
  1586. return NULL;
  1587. }
  1588. static void reinit_cputhread(int thr_id)
  1589. {
  1590. struct thr_info *thr = &thr_info[thr_id];
  1591. tq_freeze(thr->q);
  1592. if (unlikely(pthread_cancel(thr->pth))) {
  1593. applog(LOG_ERR, "Failed to pthread_cancel in reinit_gputhread");
  1594. goto failed_out;
  1595. }
  1596. if (unlikely(pthread_join(thr->pth, NULL))) {
  1597. applog(LOG_ERR, "Failed to pthread_join in reinit_gputhread");
  1598. goto failed_out;
  1599. }
  1600. applog(LOG_INFO, "Reinit CPU thread %d", thr_id);
  1601. tq_thaw(thr->q);
  1602. gettimeofday(&thr->last, NULL);
  1603. if (unlikely(pthread_create(&thr->pth, NULL, miner_thread, thr))) {
  1604. applog(LOG_ERR, "thread %d create failed", thr_id);
  1605. goto failed_out;
  1606. }
  1607. return;
  1608. failed_out:
  1609. kill_work();
  1610. }
  1611. #ifdef HAVE_OPENCL
  1612. static void reinit_gputhread(int thr_id)
  1613. {
  1614. int gpu = gpu_from_thr_id(thr_id);
  1615. struct thr_info *thr = &thr_info[thr_id];
  1616. char name[256];
  1617. tq_freeze(thr->q);
  1618. if (unlikely(pthread_cancel(thr->pth))) {
  1619. applog(LOG_ERR, "Failed to pthread_cancel in reinit_gputhread");
  1620. goto failed_out;
  1621. }
  1622. if (unlikely(pthread_join(thr->pth, NULL))) {
  1623. applog(LOG_ERR, "Failed to pthread_join in reinit_gputhread");
  1624. goto failed_out;
  1625. }
  1626. free(clStates[thr_id]);
  1627. applog(LOG_INFO, "Reinit GPU thread %d", thr_id);
  1628. tq_thaw(thr->q);
  1629. clStates[thr_id] = initCl(gpu, name, sizeof(name));
  1630. if (!clStates[thr_id]) {
  1631. applog(LOG_ERR, "Failed to reinit GPU thread %d", thr_id);
  1632. goto failed_out;
  1633. }
  1634. applog(LOG_INFO, "initCl() finished. Found %s", name);
  1635. gettimeofday(&thr->last, NULL);
  1636. if (unlikely(pthread_create(&thr->pth, NULL, gpuminer_thread, thr))) {
  1637. applog(LOG_ERR, "thread %d create failed", thr_id);
  1638. goto failed_out;
  1639. }
  1640. return;
  1641. failed_out:
  1642. kill_work();
  1643. }
  1644. static void reinit_thread(int thr_id)
  1645. {
  1646. if (thr_id < gpu_threads)
  1647. reinit_gputhread(thr_id);
  1648. else
  1649. reinit_cputhread(thr_id);
  1650. }
  1651. #else
  1652. static void reinit_thread(int thr_id)
  1653. {
  1654. reinit_cputhread(thr_id);
  1655. }
  1656. #endif
  1657. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  1658. * the screen at regular intervals, and restarts threads if they appear to have
  1659. * died. */
  1660. static void *watchdog_thread(void *userdata)
  1661. {
  1662. const unsigned int interval = opt_log_interval / 2 ? : 1;
  1663. struct timeval zero_tv;
  1664. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  1665. memset(&zero_tv, 0, sizeof(struct timeval));
  1666. while (1) {
  1667. int x, y, logx, logy, i;
  1668. struct timeval now;
  1669. sleep(interval);
  1670. if (requests_queued() < opt_queue)
  1671. queue_request();
  1672. hashmeter(-1, &zero_tv, 0);
  1673. if (curses_active) {
  1674. pthread_mutex_lock(&curses_lock);
  1675. getmaxyx(mainwin, y, x);
  1676. getmaxyx(logwin, logy, logx);
  1677. y -= logcursor;
  1678. /* Detect screen size change */
  1679. if (x != logx || y != logy)
  1680. wresize(logwin, y, x);
  1681. for (i = 0; i < mining_threads; i++)
  1682. curses_print_status(i);
  1683. redrawwin(logwin);
  1684. redrawwin(statuswin);
  1685. pthread_mutex_unlock(&curses_lock);
  1686. }
  1687. if (unlikely(work_restart[stage_thr_id].restart)) {
  1688. restart_threads(false);
  1689. work_restart[stage_thr_id].restart = 0;
  1690. }
  1691. gettimeofday(&now, NULL);
  1692. for (i = 0; i < mining_threads; i++) {
  1693. struct thr_info *thr = &thr_info[i];
  1694. /* Do not kill threads waiting on longpoll staged work */
  1695. if (now.tv_sec - thr->last.tv_sec > 60 && !lp_staged) {
  1696. applog(LOG_ERR, "Attempting to restart thread %d, idle for more than 60 seconds", i);
  1697. /* Create one mandatory work item */
  1698. inc_staged(1, true);
  1699. if (unlikely(!queue_request())) {
  1700. applog(LOG_ERR, "Failed to queue_request in watchdog_thread");
  1701. kill_work();
  1702. break;
  1703. }
  1704. reinit_thread(i);
  1705. applog(LOG_WARNING, "Thread %d restarted", i);
  1706. }
  1707. }
  1708. }
  1709. return NULL;
  1710. }
  1711. static void print_summary(void)
  1712. {
  1713. struct timeval diff;
  1714. int hours, mins, secs, i, cpu_gpu = -1;
  1715. double utility, efficiency = 0.0;
  1716. timeval_subtract(&diff, &total_tv_end, &total_tv_start);
  1717. hours = diff.tv_sec / 3600;
  1718. mins = (diff.tv_sec % 3600) / 60;
  1719. secs = diff.tv_sec % 60;
  1720. utility = accepted / ( total_secs ? total_secs : 1 ) * 60;
  1721. efficiency = getwork_requested ? accepted * 100.0 / getwork_requested : 0.0;
  1722. printf("\nSummary of runtime statistics:\n\n");
  1723. printf("Started at %s\n", datestamp);
  1724. printf("Runtime: %d hrs : %d mins : %d secs\n", hours, mins, secs);
  1725. printf("Average hashrate: %.1f Megahash/s\n", total_mhashes_done / total_secs);
  1726. printf("Queued work requests: %d\n", getwork_requested);
  1727. printf("Share submissions: %d\n", accepted + rejected);
  1728. printf("Accepted shares: %d\n", accepted);
  1729. printf("Rejected shares: %d\n", rejected);
  1730. printf("Reject ratio: %.1f\n", (double)(rejected * 100) / (double)(accepted + rejected));
  1731. printf("Hardware errors: %d\n", hw_errors);
  1732. printf("Efficiency (accepted / queued): %.0f%%\n", efficiency);
  1733. printf("Utility (accepted shares / min): %.2f/min\n\n", utility);
  1734. printf("Discarded work due to new blocks: %d\n", discarded_work);
  1735. printf("Stale submissions discarded due to new blocks: %d\n", stale_shares);
  1736. printf("Unable to get work from server occasions: %d\n", localgen_occasions);
  1737. printf("Work items generated locally: %d\n", local_work);
  1738. printf("Submitting work remotely delay occasions: %d\n", remotefail_occasions);
  1739. printf("New blocks detected on network: %d\n\n", new_blocks);
  1740. printf("Summary of per device statistics:\n\n");
  1741. for (i = 0; i < mining_threads; i++) {
  1742. if (thr_info[i].cgpu->cpu_gpu != cpu_gpu) {
  1743. cpu_gpu = thr_info[i].cgpu->cpu_gpu;
  1744. text_print_status(i);
  1745. }
  1746. }
  1747. printf("\n");
  1748. }
  1749. int main (int argc, char *argv[])
  1750. {
  1751. unsigned int i, j = 0, x, y;
  1752. struct sigaction handler;
  1753. struct thr_info *thr;
  1754. char name[256];
  1755. struct tm tm;
  1756. if (unlikely(pthread_mutex_init(&hash_lock, NULL)))
  1757. return 1;
  1758. if (unlikely(pthread_mutex_init(&qd_lock, NULL)))
  1759. return 1;
  1760. if (unlikely(pthread_mutex_init(&stgd_lock, NULL)))
  1761. return 1;
  1762. if (unlikely(pthread_mutex_init(&curses_lock, NULL)))
  1763. return 1;
  1764. handler.sa_handler = &sighandler;
  1765. sigaction(SIGTERM, &handler, 0);
  1766. sigaction(SIGINT, &handler, 0);
  1767. gettimeofday(&total_tv_start, NULL);
  1768. gettimeofday(&total_tv_end, NULL);
  1769. localtime_r(&total_tv_start.tv_sec, &tm);
  1770. sprintf(datestamp, "[%d-%02d-%02d %02d:%02d:%02d]",
  1771. tm.tm_year + 1900,
  1772. tm.tm_mon + 1,
  1773. tm.tm_mday,
  1774. tm.tm_hour,
  1775. tm.tm_min,
  1776. tm.tm_sec);
  1777. for (i = 0; i < 36; i++) {
  1778. strcat(blank, "0");
  1779. strcat(current_block, "0");
  1780. strcat(longpoll_block, "0");
  1781. }
  1782. #ifdef WIN32
  1783. opt_n_threads = num_processors = 1;
  1784. #else
  1785. num_processors = sysconf(_SC_NPROCESSORS_ONLN);
  1786. opt_n_threads = num_processors;
  1787. #endif /* !WIN32 */
  1788. #ifdef HAVE_OPENCL
  1789. for (i = 0; i < 16; i++)
  1790. gpu_devices[i] = false;
  1791. nDevs = clDevicesNum();
  1792. if (nDevs < 0)
  1793. return 1;
  1794. #endif
  1795. if (nDevs)
  1796. opt_n_threads = 0;
  1797. rpc_url = strdup(DEF_RPC_URL);
  1798. /* parse command line */
  1799. opt_register_table(opt_config_table,
  1800. "Options for both config file and command line");
  1801. opt_register_table(opt_cmdline_table,
  1802. "Options for command line only");
  1803. opt_parse(&argc, argv, applog_and_exit);
  1804. if (argc != 1) {
  1805. applog(LOG_ERR, "Unexpected extra commandline arguments");
  1806. return 1;
  1807. }
  1808. if (total_devices) {
  1809. if (total_devices > nDevs) {
  1810. applog(LOG_ERR, "More devices specified than exist");
  1811. return 1;
  1812. }
  1813. for (i = 0; i < 16; i++)
  1814. if (gpu_devices[i] && i + 1 > nDevs) {
  1815. applog(LOG_ERR, "Command line options set a device that doesn't exist");
  1816. return 1;
  1817. }
  1818. gpu_threads = total_devices * opt_g_threads;
  1819. } else {
  1820. gpu_threads = nDevs * opt_g_threads;
  1821. for (i = 0; i < nDevs; i++)
  1822. gpu_devices[i] = true;
  1823. }
  1824. if (!gpu_threads && !forced_n_threads) {
  1825. /* Maybe they turned GPU off; restore default CPU threads. */
  1826. opt_n_threads = num_processors;
  1827. }
  1828. logcursor = 4;
  1829. mining_threads = opt_n_threads + gpu_threads;
  1830. gpucursor = logcursor;
  1831. cpucursor = gpucursor + nDevs;
  1832. logstart = cpucursor + (opt_n_threads ? num_processors : 0) + 1;
  1833. logcursor = logstart + 1;
  1834. if (!rpc_userpass) {
  1835. if (!rpc_user || !rpc_pass) {
  1836. applog(LOG_ERR, "No login credentials supplied");
  1837. return 1;
  1838. }
  1839. rpc_userpass = malloc(strlen(rpc_user) + strlen(rpc_pass) + 2);
  1840. if (!rpc_userpass)
  1841. return 1;
  1842. sprintf(rpc_userpass, "%s:%s", rpc_user, rpc_pass);
  1843. }
  1844. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  1845. return 1;
  1846. #ifdef HAVE_SYSLOG_H
  1847. if (use_syslog)
  1848. openlog("cpuminer", LOG_PID, LOG_USER);
  1849. #endif
  1850. work_restart = calloc(mining_threads + 4, sizeof(*work_restart));
  1851. if (!work_restart)
  1852. return 1;
  1853. thr_info = calloc(mining_threads + 4, sizeof(*thr));
  1854. if (!thr_info)
  1855. return 1;
  1856. /* init workio thread info */
  1857. work_thr_id = mining_threads;
  1858. thr = &thr_info[work_thr_id];
  1859. thr->id = work_thr_id;
  1860. thr->q = tq_new();
  1861. if (!thr->q)
  1862. return 1;
  1863. /* start work I/O thread */
  1864. if (pthread_create(&thr->pth, NULL, workio_thread, thr)) {
  1865. applog(LOG_ERR, "workio thread create failed");
  1866. return 1;
  1867. }
  1868. /* init longpoll thread info */
  1869. if (want_longpoll) {
  1870. longpoll_thr_id = mining_threads + 1;
  1871. thr = &thr_info[longpoll_thr_id];
  1872. thr->id = longpoll_thr_id;
  1873. thr->q = tq_new();
  1874. if (!thr->q)
  1875. return 1;
  1876. /* start longpoll thread */
  1877. if (unlikely(pthread_create(&thr->pth, NULL, longpoll_thread, thr))) {
  1878. applog(LOG_ERR, "longpoll thread create failed");
  1879. return 1;
  1880. }
  1881. pthread_detach(thr->pth);
  1882. } else
  1883. longpoll_thr_id = -1;
  1884. if (opt_n_threads ) {
  1885. cpus = calloc(num_processors, sizeof(struct cgpu_info));
  1886. if (unlikely(!cpus)) {
  1887. applog(LOG_ERR, "Failed to calloc cpus");
  1888. return 1;
  1889. }
  1890. }
  1891. if (gpu_threads) {
  1892. gpus = calloc(nDevs, sizeof(struct cgpu_info));
  1893. if (unlikely(!gpus)) {
  1894. applog(LOG_ERR, "Failed to calloc gpus");
  1895. return 1;
  1896. }
  1897. }
  1898. stage_thr_id = mining_threads + 3;
  1899. thr = &thr_info[stage_thr_id];
  1900. thr->q = tq_new();
  1901. if (!thr->q)
  1902. return 1;
  1903. /* start stage thread */
  1904. if (pthread_create(&thr->pth, NULL, stage_thread, thr)) {
  1905. applog(LOG_ERR, "stage thread create failed");
  1906. return 1;
  1907. }
  1908. /* Flag the work as ready forcing the mining threads to wait till we
  1909. * actually put something into the queue */
  1910. inc_staged(mining_threads, true);
  1911. #ifdef HAVE_OPENCL
  1912. i = 0;
  1913. /* start GPU mining threads */
  1914. for (j = 0; j < nDevs * opt_g_threads; j++) {
  1915. int gpu = gpu_from_thr_id(j);
  1916. /* Skip devices not set to work */
  1917. if (!gpu_devices[gpu])
  1918. continue;
  1919. thr = &thr_info[i];
  1920. thr->id = i;
  1921. gpus[gpu].is_gpu = 1;
  1922. gpus[gpu].cpu_gpu = gpu;
  1923. thr->cgpu = &gpus[gpu];
  1924. thr->q = tq_new();
  1925. if (!thr->q) {
  1926. applog(LOG_ERR, "tq_new failed in starting gpu mining threads");
  1927. return 1;
  1928. }
  1929. applog(LOG_INFO, "Init GPU thread %i", i);
  1930. clStates[i] = initCl(gpu, name, sizeof(name));
  1931. if (!clStates[i]) {
  1932. applog(LOG_ERR, "Failed to init GPU thread %d", i);
  1933. continue;
  1934. }
  1935. applog(LOG_INFO, "initCl() finished. Found %s", name);
  1936. gettimeofday(&thr->last, NULL);
  1937. if (unlikely(pthread_create(&thr->pth, NULL, gpuminer_thread, thr))) {
  1938. applog(LOG_ERR, "thread %d create failed", i);
  1939. return 1;
  1940. }
  1941. i++;
  1942. }
  1943. applog(LOG_INFO, "%d gpu miner threads started", gpu_threads);
  1944. #endif
  1945. /* start CPU mining threads */
  1946. for (i = gpu_threads; i < mining_threads; i++) {
  1947. int cpu = cpu_from_thr_id(i);
  1948. thr = &thr_info[i];
  1949. thr->id = i;
  1950. cpus[cpu].cpu_gpu = cpu;
  1951. thr->cgpu = &cpus[cpu];
  1952. thr->q = tq_new();
  1953. if (!thr->q) {
  1954. applog(LOG_ERR, "tq_new failed in starting cpu mining threads");
  1955. return 1;
  1956. }
  1957. gettimeofday(&thr->last, NULL);
  1958. if (unlikely(pthread_create(&thr->pth, NULL, miner_thread, thr))) {
  1959. applog(LOG_ERR, "thread %d create failed", i);
  1960. return 1;
  1961. }
  1962. }
  1963. applog(LOG_INFO, "%d cpu miner threads started, "
  1964. "using SHA256 '%s' algorithm.",
  1965. opt_n_threads,
  1966. algo_names[opt_algo]);
  1967. watchdog_thr_id = mining_threads + 2;
  1968. thr = &thr_info[watchdog_thr_id];
  1969. /* start wakeup thread */
  1970. if (pthread_create(&thr->pth, NULL, watchdog_thread, NULL)) {
  1971. applog(LOG_ERR, "wakeup thread create failed");
  1972. return 1;
  1973. }
  1974. /* Restart count as it will be wrong till all threads are started */
  1975. pthread_mutex_lock(&hash_lock);
  1976. gettimeofday(&total_tv_start, NULL);
  1977. gettimeofday(&total_tv_end, NULL);
  1978. total_mhashes_done = 0;
  1979. pthread_mutex_unlock(&hash_lock);
  1980. /* Set up the ncurses interface */
  1981. if (!opt_quiet && use_curses) {
  1982. mainwin = initscr();
  1983. getmaxyx(mainwin, y, x);
  1984. statuswin = newwin(logstart, x, 0, 0);
  1985. logwin = newwin(y - logcursor, 0, logcursor, 0);
  1986. idlok(logwin, true);
  1987. scrollok(logwin, true);
  1988. leaveok(logwin, true);
  1989. leaveok(statuswin, true);
  1990. curses_active = true;
  1991. for (i = 0; i < mining_threads; i++)
  1992. print_status(i);
  1993. }
  1994. /* Now that everything's ready put enough work in the queue */
  1995. for (i = 0; i < opt_queue + mining_threads; i++) {
  1996. if (unlikely(!queue_request())) {
  1997. applog(LOG_ERR, "Failed to queue_request in main");
  1998. return 1;
  1999. }
  2000. }
  2001. /* main loop - simply wait for workio thread to exit */
  2002. pthread_join(thr_info[work_thr_id].pth, NULL);
  2003. applog(LOG_INFO, "workio thread dead, exiting.");
  2004. gettimeofday(&total_tv_end, NULL);
  2005. curl_global_cleanup();
  2006. disable_curses();
  2007. if (!opt_quiet)
  2008. print_summary();
  2009. if (gpu_threads)
  2010. free(gpus);
  2011. if (opt_n_threads)
  2012. free(cpus);
  2013. return 0;
  2014. }