main.c 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439
  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;
  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 bool idlenet = false;
  156. static unsigned int getwork_requested;
  157. static unsigned int stale_shares;
  158. static unsigned int discarded_work;
  159. static unsigned int new_blocks;
  160. static unsigned int local_work;
  161. static unsigned int localgen_occasions;
  162. static unsigned int remotefail_occasions;
  163. static char current_block[37];
  164. static char longpoll_block[37];
  165. static char blank[37];
  166. static char datestamp[40];
  167. static char blockdate[40];
  168. struct sigaction termhandler, inthandler;
  169. struct thread_q *getq;
  170. static void applog_and_exit(const char *fmt, ...)
  171. {
  172. va_list ap;
  173. va_start(ap, fmt);
  174. vapplog(LOG_ERR, fmt, ap);
  175. va_end(ap);
  176. exit(1);
  177. }
  178. /* FIXME: Use asprintf for better errors. */
  179. static char *set_algo(const char *arg, enum sha256_algos *algo)
  180. {
  181. enum sha256_algos i;
  182. for (i = 0; i < ARRAY_SIZE(algo_names); i++) {
  183. if (algo_names[i] && !strcmp(arg, algo_names[i])) {
  184. *algo = i;
  185. return NULL;
  186. }
  187. }
  188. return "Unknown algorithm";
  189. }
  190. static void show_algo(char buf[OPT_SHOW_LEN], const enum sha256_algos *algo)
  191. {
  192. strncpy(buf, algo_names[*algo], OPT_SHOW_LEN);
  193. }
  194. static char *set_int_range(const char *arg, int *i, int min, int max)
  195. {
  196. char *err = opt_set_intval(arg, i);
  197. if (err)
  198. return err;
  199. if (*i < min || *i > max)
  200. return "Value out of range";
  201. return NULL;
  202. }
  203. static char *set_int_0_to_9999(const char *arg, int *i)
  204. {
  205. return set_int_range(arg, i, 0, 9999);
  206. }
  207. static char *forced_int_0_to_14(const char *arg, int *i)
  208. {
  209. opt_dynamic = false;
  210. return set_int_range(arg, i, 0, 14);
  211. }
  212. static char *force_nthreads_int(const char *arg, int *i)
  213. {
  214. forced_n_threads = true;
  215. return set_int_range(arg, i, 0, 9999);
  216. }
  217. static char *set_int_0_to_10(const char *arg, int *i)
  218. {
  219. return set_int_range(arg, i, 0, 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_0_to_10, opt_show_intval, &opt_queue,
  307. "Number of extra work items to queue (0 - 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\n", *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 dev_from_id(int thr_id)
  468. {
  469. return thr_info[thr_id].cgpu->cpu_gpu;
  470. }
  471. static WINDOW *mainwin, *statuswin, *logwin;
  472. static double total_secs = 0.1;
  473. static char statusline[256];
  474. static int cpucursor, gpucursor, logstart, logcursor;
  475. static bool curses_active = false;
  476. static struct cgpu_info *gpus, *cpus;
  477. static void text_print_status(int thr_id)
  478. {
  479. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  480. printf(" %sPU %d: [%.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]\n",
  481. cgpu->is_gpu ? "G" : "C", cgpu->cpu_gpu, cgpu->total_mhashes / total_secs,
  482. cgpu->getworks, cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  483. cgpu->efficiency, cgpu->utility);
  484. }
  485. /* Must be called with curses mutex lock held and curses_active */
  486. static void curses_print_status(int thr_id)
  487. {
  488. wmove(statuswin, 0, 0);
  489. wattron(statuswin, A_BOLD);
  490. wprintw(statuswin, " " PROGRAM_NAME " version " VERSION " - Started: %s", datestamp);
  491. wattroff(statuswin, A_BOLD);
  492. wmove(statuswin, 1, 0);
  493. whline(statuswin, '-', 80);
  494. wmove(statuswin, 2,0);
  495. wprintw(statuswin, " %s", statusline);
  496. wclrtoeol(statuswin);
  497. wmove(statuswin, 3,0);
  498. wprintw(statuswin, " TQ: %d ST: %d LS: %d SS: %d DW: %d NB: %d LW: %d LO: %d RF: %d I: %d",
  499. total_queued, total_staged, lp_staged, stale_shares, discarded_work, new_blocks,
  500. local_work, localgen_occasions, remotefail_occasions, scan_intensity);
  501. wclrtoeol(statuswin);
  502. wmove(statuswin, 4, 0);
  503. wprintw(statuswin, " Connected to %s as user %s", rpc_url, rpc_user);
  504. wmove(statuswin, 5, 0);
  505. wprintw(statuswin, " Block %s started: %s", current_block + 4, blockdate);
  506. wmove(statuswin, 6, 0);
  507. whline(statuswin, '-', 80);
  508. wmove(statuswin, logstart - 1, 0);
  509. whline(statuswin, '-', 80);
  510. if (thr_id >= 0 && thr_id < gpu_threads) {
  511. int gpu = dev_from_id(thr_id);
  512. struct cgpu_info *cgpu = &gpus[gpu];
  513. wmove(statuswin, gpucursor + gpu, 0);
  514. wprintw(statuswin, " GPU %d: [%.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]",
  515. gpu, cgpu->total_mhashes / total_secs,
  516. cgpu->getworks, cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  517. cgpu->efficiency, cgpu->utility);
  518. wclrtoeol(statuswin);
  519. } else if (thr_id >= gpu_threads) {
  520. int cpu = dev_from_id(thr_id);
  521. struct cgpu_info *cgpu = &cpus[cpu];
  522. wmove(statuswin, cpucursor + cpu, 0);
  523. wprintw(statuswin, " CPU %d: [%.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]",
  524. cpu, cgpu->total_mhashes / total_secs,
  525. cgpu->getworks, cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  526. cgpu->efficiency, cgpu->utility);
  527. wclrtoeol(statuswin);
  528. }
  529. wrefresh(statuswin);
  530. }
  531. static void print_status(int thr_id)
  532. {
  533. if (!curses_active)
  534. text_print_status(thr_id);
  535. else {
  536. pthread_mutex_lock(&curses_lock);
  537. curses_print_status(thr_id);
  538. wrefresh(statuswin);
  539. pthread_mutex_unlock(&curses_lock);
  540. }
  541. }
  542. void log_curses(const char *f, va_list ap)
  543. {
  544. if (curses_active) {
  545. pthread_mutex_lock(&curses_lock);
  546. vw_printw(logwin, f, ap);
  547. wrefresh(logwin);
  548. pthread_mutex_unlock(&curses_lock);
  549. } else
  550. vprintf(f, ap);
  551. }
  552. static bool submit_fail = false;
  553. static bool submit_upstream_work(const struct work *work)
  554. {
  555. char *hexstr = NULL;
  556. json_t *val, *res;
  557. char s[345];
  558. bool rc = false;
  559. int thr_id = work->thr_id;
  560. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  561. CURL *curl = curl_easy_init();
  562. if (unlikely(!curl)) {
  563. applog(LOG_ERR, "CURL initialisation failed");
  564. return rc;
  565. }
  566. /* build hex string */
  567. hexstr = bin2hex(work->data, sizeof(work->data));
  568. if (unlikely(!hexstr)) {
  569. applog(LOG_ERR, "submit_upstream_work OOM");
  570. goto out_nofree;
  571. }
  572. /* build JSON-RPC request */
  573. sprintf(s,
  574. "{\"method\": \"getwork\", \"params\": [ \"%s\" ], \"id\":1}\r\n",
  575. hexstr);
  576. if (opt_debug)
  577. applog(LOG_DEBUG, "DBG: sending RPC call: %s", s);
  578. /* issue JSON-RPC request */
  579. val = json_rpc_call(curl, rpc_url, rpc_userpass, s, false, false);
  580. if (unlikely(!val)) {
  581. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  582. if (!submit_fail) {
  583. submit_fail = true;
  584. remotefail_occasions++;
  585. applog(LOG_WARNING, "Upstream communication failure, caching submissions");
  586. }
  587. goto out;
  588. } else if (submit_fail) {
  589. submit_fail = false;
  590. applog(LOG_WARNING, "Upstream communication resumed, submitting work");
  591. }
  592. res = json_object_get(val, "result");
  593. /* Theoretically threads could race when modifying accepted and
  594. * rejected values but the chance of two submits completing at the
  595. * same time is zero so there is no point adding extra locking */
  596. if (json_is_true(res)) {
  597. cgpu->accepted++;
  598. accepted++;
  599. if (opt_debug)
  600. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  601. if (!opt_quiet)
  602. applog(LOG_WARNING, "Share %.8s accepted from %sPU %d thread %d",
  603. hexstr + 152, cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, thr_id);
  604. } else {
  605. cgpu->rejected++;
  606. rejected++;
  607. if (opt_debug)
  608. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  609. if (!opt_quiet)
  610. applog(LOG_WARNING, "Share %.8s rejected from %sPU %d thread %d",
  611. hexstr + 152, cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, thr_id);
  612. }
  613. cgpu->utility = cgpu->accepted / ( total_secs ? total_secs : 1 ) * 60;
  614. cgpu->efficiency = cgpu->getworks ? cgpu->accepted * 100.0 / cgpu->getworks : 0.0;
  615. if (!opt_quiet)
  616. print_status(thr_id);
  617. applog(LOG_INFO, "%sPU %d Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m",
  618. cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, cgpu->getworks, cgpu->accepted,
  619. cgpu->rejected, cgpu->hw_errors, cgpu->efficiency, cgpu->utility);
  620. json_decref(val);
  621. rc = true;
  622. out:
  623. free(hexstr);
  624. out_nofree:
  625. curl_easy_cleanup(curl);
  626. return rc;
  627. }
  628. static const char *rpc_req =
  629. "{\"method\": \"getwork\", \"params\": [], \"id\":0}\r\n";
  630. static bool get_upstream_work(struct work *work)
  631. {
  632. json_t *val;
  633. bool rc = false;
  634. CURL *curl = curl_easy_init();
  635. if (unlikely(!curl)) {
  636. applog(LOG_ERR, "CURL initialisation failed");
  637. return rc;
  638. }
  639. val = json_rpc_call(curl, rpc_url, rpc_userpass, rpc_req,
  640. want_longpoll, false);
  641. if (unlikely(!val)) {
  642. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  643. goto out;
  644. }
  645. rc = work_decode(json_object_get(val, "result"), work);
  646. json_decref(val);
  647. out:
  648. curl_easy_cleanup(curl);
  649. return rc;
  650. }
  651. static void workio_cmd_free(struct workio_cmd *wc)
  652. {
  653. if (!wc)
  654. return;
  655. switch (wc->cmd) {
  656. case WC_SUBMIT_WORK:
  657. free(wc->u.work);
  658. break;
  659. default: /* do nothing */
  660. break;
  661. }
  662. memset(wc, 0, sizeof(*wc)); /* poison */
  663. free(wc);
  664. }
  665. static void disable_curses(void)
  666. {
  667. if (curses_active) {
  668. curses_active = false;
  669. delwin(logwin);
  670. delwin(statuswin);
  671. delwin(mainwin);
  672. endwin();
  673. refresh();
  674. }
  675. }
  676. void kill_work(void)
  677. {
  678. struct workio_cmd *wc;
  679. struct thr_info *thr;
  680. unsigned int i;
  681. disable_curses();
  682. applog(LOG_INFO, "Received kill message");
  683. /* Kill the watchdog thread */
  684. thr = &thr_info[watchdog_thr_id];
  685. pthread_cancel(thr->pth);
  686. /* Stop the mining threads*/
  687. for (i = 0; i < mining_threads; i++) {
  688. thr = &thr_info[i];
  689. tq_freeze(thr->q);
  690. /* No need to check if this succeeds or not */
  691. pthread_cancel(thr->pth);
  692. }
  693. /* Stop the others */
  694. thr = &thr_info[stage_thr_id];
  695. pthread_cancel(thr->pth);
  696. thr = &thr_info[longpoll_thr_id];
  697. pthread_cancel(thr->pth);
  698. wc = calloc(1, sizeof(*wc));
  699. if (unlikely(!wc)) {
  700. applog(LOG_ERR, "Failed to calloc wc in kill_work");
  701. /* We're just trying to die anyway, so forget graceful */
  702. exit (1);
  703. }
  704. wc->cmd = WC_DIE;
  705. wc->thr = 0;
  706. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  707. applog(LOG_ERR, "Failed to tq_push work in kill_work");
  708. exit (1);
  709. }
  710. }
  711. static void sighandler(int sig)
  712. {
  713. /* Restore signal handlers so we can still quit if kill_work fails */
  714. sigaction(SIGTERM, &termhandler, NULL);
  715. sigaction(SIGINT, &inthandler, NULL);
  716. kill_work();
  717. }
  718. static void *get_work_thread(void *userdata)
  719. {
  720. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  721. struct work *ret_work;
  722. int failures = 0;
  723. pthread_detach(pthread_self());
  724. ret_work = calloc(1, sizeof(*ret_work));
  725. if (unlikely(!ret_work)) {
  726. applog(LOG_ERR, "Failed to calloc ret_work in workio_get_work");
  727. kill_work();
  728. goto out;
  729. }
  730. /* obtain new work from bitcoin via JSON-RPC */
  731. while (!get_upstream_work(ret_work)) {
  732. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  733. applog(LOG_ERR, "json_rpc_call failed, terminating workio thread");
  734. free(ret_work);
  735. kill_work();
  736. goto out;
  737. }
  738. /* pause, then restart work-request loop */
  739. applog(LOG_DEBUG, "json_rpc_call failed on get work, retry after %d seconds",
  740. opt_fail_pause);
  741. sleep(opt_fail_pause);
  742. }
  743. /* send work to requesting thread */
  744. if (unlikely(!tq_push(thr_info[stage_thr_id].q, ret_work))) {
  745. applog(LOG_ERR, "Failed to tq_push work in workio_get_work");
  746. kill_work();
  747. free(ret_work);
  748. }
  749. out:
  750. workio_cmd_free(wc);
  751. return NULL;
  752. }
  753. static bool workio_get_work(struct workio_cmd *wc)
  754. {
  755. pthread_t get_thread;
  756. if (unlikely(pthread_create(&get_thread, NULL, get_work_thread, (void *)wc))) {
  757. applog(LOG_ERR, "Failed to create get_work_thread");
  758. return false;
  759. }
  760. return true;
  761. }
  762. static bool stale_work(struct work *work)
  763. {
  764. bool ret = false;
  765. char *hexstr;
  766. if (!strncmp(blank, current_block, 36))
  767. return ret;
  768. hexstr = bin2hex(work->data, 36);
  769. if (unlikely(!hexstr)) {
  770. applog(LOG_ERR, "submit_work_thread OOM");
  771. return ret;
  772. }
  773. if (strncmp(hexstr, current_block, 36))
  774. ret = true;
  775. free(hexstr);
  776. return ret;
  777. }
  778. static void *submit_work_thread(void *userdata)
  779. {
  780. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  781. int failures = 0;
  782. pthread_detach(pthread_self());
  783. if (stale_work(wc->u.work)) {
  784. applog(LOG_WARNING, "Stale share detected, discarding");
  785. stale_shares++;
  786. goto out;
  787. }
  788. /* submit solution to bitcoin via JSON-RPC */
  789. while (!submit_upstream_work(wc->u.work)) {
  790. if (stale_work(wc->u.work)) {
  791. applog(LOG_WARNING, "Stale share detected, discarding");
  792. stale_shares++;
  793. break;
  794. }
  795. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  796. applog(LOG_ERR, "Failed %d retries ...terminating workio thread", opt_retries);
  797. kill_work();
  798. break;
  799. }
  800. /* pause, then restart work-request loop */
  801. applog(LOG_INFO, "json_rpc_call failed on submit_work, retry after %d seconds",
  802. opt_fail_pause);
  803. sleep(opt_fail_pause);
  804. }
  805. out:
  806. workio_cmd_free(wc);
  807. return NULL;
  808. }
  809. static bool workio_submit_work(struct workio_cmd *wc)
  810. {
  811. pthread_t submit_thread;
  812. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, (void *)wc))) {
  813. applog(LOG_ERR, "Failed to create submit_work_thread");
  814. return false;
  815. }
  816. return true;
  817. }
  818. static void inc_staged(int inc, bool lp)
  819. {
  820. pthread_mutex_lock(&stgd_lock);
  821. if (lp) {
  822. lp_staged += inc;
  823. total_staged += inc;
  824. idlenet = true;
  825. } else if (lp_staged) {
  826. if (!--lp_staged) {
  827. unsigned int i;
  828. /* Make sure the watchdog thread doesn't kill the mining
  829. * threads once we unset the idlenet flag */
  830. for (i = 0; i < mining_threads; i++)
  831. gettimeofday(&thr_info[i].last, NULL);
  832. idlenet = false;
  833. }
  834. } else
  835. total_staged += inc;
  836. pthread_mutex_unlock(&stgd_lock);
  837. }
  838. static void dec_staged(int inc)
  839. {
  840. pthread_mutex_lock(&stgd_lock);
  841. total_staged -= inc;
  842. pthread_mutex_unlock(&stgd_lock);
  843. }
  844. static int requests_staged(void)
  845. {
  846. int ret;
  847. pthread_mutex_lock(&stgd_lock);
  848. ret = total_staged;
  849. pthread_mutex_unlock(&stgd_lock);
  850. return ret;
  851. }
  852. static void set_curblock(char *hexstr)
  853. {
  854. struct timeval tv_now;
  855. struct tm tm;
  856. memcpy(current_block, hexstr, 36);
  857. gettimeofday(&tv_now, NULL);
  858. localtime_r(&tv_now.tv_sec, &tm);
  859. sprintf(blockdate, "[%d-%02d-%02d %02d:%02d:%02d]",
  860. tm.tm_year + 1900,
  861. tm.tm_mon + 1,
  862. tm.tm_mday,
  863. tm.tm_hour,
  864. tm.tm_min,
  865. tm.tm_sec);
  866. }
  867. static void *stage_thread(void *userdata)
  868. {
  869. struct thr_info *mythr = userdata;
  870. bool ok = true;
  871. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  872. while (ok) {
  873. struct work *work = NULL;
  874. char *hexstr;
  875. work = tq_pop(mythr->q, NULL);
  876. if (unlikely(!work)) {
  877. applog(LOG_ERR, "Failed to tq_pop in stage_thread");
  878. ok = false;
  879. break;
  880. }
  881. hexstr = bin2hex(work->data, 36);
  882. if (unlikely(!hexstr)) {
  883. applog(LOG_ERR, "stage_thread OOM");
  884. break;
  885. }
  886. /* current_block is blanked out on successful longpoll */
  887. if (likely(strncmp(current_block, blank, 36))) {
  888. if (unlikely(strncmp(hexstr, current_block, 36))) {
  889. new_blocks++;
  890. if (have_longpoll)
  891. applog(LOG_WARNING, "New block detected on network before longpoll, waiting on fresh work");
  892. else
  893. applog(LOG_WARNING, "New block detected on network, waiting on fresh work");
  894. /* As we can't flush the work from here, signal
  895. * the wakeup thread to restart all the
  896. * threads */
  897. work_restart[watchdog_thr_id].restart = 1;
  898. set_curblock(hexstr);
  899. }
  900. } else {
  901. set_curblock(hexstr);
  902. memcpy(longpoll_block, hexstr, 36);
  903. }
  904. free(hexstr);
  905. if (unlikely(!tq_push(getq, work))) {
  906. applog(LOG_ERR, "Failed to tq_push work in stage_thread");
  907. ok = false;
  908. break;
  909. }
  910. inc_staged(1, false);
  911. }
  912. tq_freeze(mythr->q);
  913. return NULL;
  914. }
  915. static void *workio_thread(void *userdata)
  916. {
  917. struct thr_info *mythr = userdata;
  918. bool ok = true;
  919. while (ok) {
  920. struct workio_cmd *wc;
  921. /* wait for workio_cmd sent to us, on our queue */
  922. wc = tq_pop(mythr->q, NULL);
  923. if (unlikely(!wc)) {
  924. applog(LOG_ERR, "Failed to tq_pop in workio_thread");
  925. ok = false;
  926. break;
  927. }
  928. /* process workio_cmd */
  929. switch (wc->cmd) {
  930. case WC_GET_WORK:
  931. ok = workio_get_work(wc);
  932. break;
  933. case WC_SUBMIT_WORK:
  934. ok = workio_submit_work(wc);
  935. break;
  936. case WC_DIE:
  937. default:
  938. ok = false;
  939. break;
  940. }
  941. }
  942. tq_freeze(mythr->q);
  943. return NULL;
  944. }
  945. static void hashmeter(int thr_id, struct timeval *diff,
  946. unsigned long hashes_done)
  947. {
  948. struct timeval temp_tv_end, total_diff;
  949. double khashes, secs;
  950. double local_secs;
  951. double utility, efficiency = 0.0;
  952. static double local_mhashes_done = 0;
  953. static double rolling_local = 0;
  954. double local_mhashes = (double)hashes_done / 1000000.0;
  955. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  956. /* Update the last time this thread reported in */
  957. if (thr_id >= 0)
  958. gettimeofday(&thr_info[thr_id].last, NULL);
  959. /* Don't bother calculating anything if we're not displaying it */
  960. if (opt_quiet || !opt_log_interval)
  961. return;
  962. khashes = hashes_done / 1000.0;
  963. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  964. if (thr_id >= 0 && secs) {
  965. /* So we can call hashmeter from a non worker thread */
  966. if (opt_debug)
  967. applog(LOG_DEBUG, "[thread %d: %lu hashes, %.0f khash/sec]",
  968. thr_id, hashes_done, hashes_done / secs);
  969. cgpu->local_mhashes += local_mhashes;
  970. cgpu->total_mhashes += local_mhashes;
  971. }
  972. /* Totals are updated by all threads so can race without locking */
  973. pthread_mutex_lock(&hash_lock);
  974. gettimeofday(&temp_tv_end, NULL);
  975. timeval_subtract(&total_diff, &temp_tv_end, &total_tv_end);
  976. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  977. total_mhashes_done += local_mhashes;
  978. local_mhashes_done += local_mhashes;
  979. if (total_diff.tv_sec < opt_log_interval)
  980. /* Only update the total every opt_log_interval seconds */
  981. goto out_unlock;
  982. gettimeofday(&total_tv_end, NULL);
  983. /* Use a rolling average by faking an exponential decay over 5 * log */
  984. rolling_local = ((rolling_local * 0.9) + local_mhashes_done) / 1.9;
  985. timeval_subtract(&total_diff, &total_tv_end, &total_tv_start);
  986. total_secs = (double)total_diff.tv_sec +
  987. ((double)total_diff.tv_usec / 1000000.0);
  988. utility = accepted / ( total_secs ? total_secs : 1 ) * 60;
  989. efficiency = getwork_requested ? accepted * 100.0 / getwork_requested : 0.0;
  990. sprintf(statusline, "[(%ds):%.1f (avg):%.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]",
  991. opt_log_interval, rolling_local / local_secs, total_mhashes_done / total_secs,
  992. getwork_requested, accepted, rejected, hw_errors, efficiency, utility);
  993. if (!curses_active) {
  994. printf("%s \r", statusline);
  995. fflush(stdout);
  996. } else
  997. applog(LOG_INFO, "%s", statusline);
  998. local_mhashes_done = 0;
  999. out_unlock:
  1000. pthread_mutex_unlock(&hash_lock);
  1001. }
  1002. /* This is overkill, but at least we'll know accurately how much work is
  1003. * queued to prevent ever being left without work */
  1004. static void inc_queued(void)
  1005. {
  1006. pthread_mutex_lock(&qd_lock);
  1007. total_queued++;
  1008. pthread_mutex_unlock(&qd_lock);
  1009. }
  1010. static void dec_queued(void)
  1011. {
  1012. pthread_mutex_lock(&qd_lock);
  1013. total_queued--;
  1014. pthread_mutex_unlock(&qd_lock);
  1015. dec_staged(1);
  1016. }
  1017. static int requests_queued(void)
  1018. {
  1019. int ret;
  1020. pthread_mutex_lock(&qd_lock);
  1021. ret = total_queued;
  1022. pthread_mutex_unlock(&qd_lock);
  1023. return ret;
  1024. }
  1025. static bool queue_request(void)
  1026. {
  1027. struct workio_cmd *wc;
  1028. /* If we've been generating lots of local work we may already have
  1029. * enough in the queue */
  1030. if (requests_queued() >= opt_queue + mining_threads)
  1031. return true;
  1032. /* fill out work request message */
  1033. wc = calloc(1, sizeof(*wc));
  1034. if (unlikely(!wc)) {
  1035. applog(LOG_ERR, "Failed to tq_pop in queue_request");
  1036. return false;
  1037. }
  1038. wc->cmd = WC_GET_WORK;
  1039. /* The get work does not belong to any thread */
  1040. wc->thr = NULL;
  1041. /* send work request to workio thread */
  1042. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  1043. applog(LOG_ERR, "Failed to tq_push in queue_request");
  1044. workio_cmd_free(wc);
  1045. return false;
  1046. }
  1047. getwork_requested++;
  1048. inc_queued();
  1049. return true;
  1050. }
  1051. static bool discard_request(void)
  1052. {
  1053. struct work *work_heap;
  1054. /* Just in case we fell in a hole and missed a queue filling */
  1055. if (unlikely(!requests_queued())) {
  1056. applog(LOG_WARNING, "Tried to discard_request with nil queued");
  1057. return true;
  1058. }
  1059. work_heap = tq_pop(getq, NULL);
  1060. if (unlikely(!work_heap)) {
  1061. applog(LOG_ERR, "Failed to tq_pop in discard_request");
  1062. return false;
  1063. }
  1064. free(work_heap);
  1065. dec_queued();
  1066. discarded_work++;
  1067. return true;
  1068. }
  1069. static void flush_requests(bool longpoll)
  1070. {
  1071. int i, extra;
  1072. extra = requests_queued();
  1073. /* When flushing from longpoll, we don't know the new work yet. When
  1074. * not flushing from longpoll, the first work item is valid so do not
  1075. * discard it */
  1076. if (longpoll)
  1077. memcpy(current_block, blank, 36);
  1078. else
  1079. extra--;
  1080. /* Temporarily increase the staged count so that get_work thinks there
  1081. * is work available instead of making threads reuse existing work */
  1082. inc_staged(mining_threads, true);
  1083. for (i = 0; i < extra; i++) {
  1084. /* Queue a whole batch of new requests */
  1085. if (unlikely(!queue_request())) {
  1086. applog(LOG_ERR, "Failed to queue requests in flush_requests");
  1087. kill_work();
  1088. break;
  1089. }
  1090. /* Pop off the old requests. Cancelling the requests would be better
  1091. * but is tricky */
  1092. if (unlikely(!discard_request())) {
  1093. applog(LOG_ERR, "Failed to discard requests in flush_requests");
  1094. kill_work();
  1095. break;
  1096. }
  1097. }
  1098. }
  1099. static bool get_work(struct work *work, bool queued)
  1100. {
  1101. static struct timeval tv_localgen = {};
  1102. struct work *work_heap;
  1103. bool ret = false;
  1104. int failures = 0;
  1105. retry:
  1106. if (unlikely(!queued && !queue_request())) {
  1107. applog(LOG_WARNING, "Failed to queue_request in get_work");
  1108. goto out;
  1109. }
  1110. if (!requests_staged() && !stale_work(work)) {
  1111. uint32_t *work_ntime;
  1112. uint32_t ntime;
  1113. /* Only print this message once each time we shift to localgen */
  1114. if (!localgen) {
  1115. localgen = true;
  1116. applog(LOG_WARNING, "Server not providing work fast enough, generating work locally");
  1117. localgen_occasions++;
  1118. gettimeofday(&tv_localgen, NULL);
  1119. } else {
  1120. struct timeval tv_now, diff;
  1121. gettimeofday(&tv_now, NULL);
  1122. timeval_subtract(&diff, &tv_now, &tv_localgen);
  1123. if (diff.tv_sec > 600) {
  1124. /* A new block appears on average every 10 mins */
  1125. applog(LOG_WARNING, "Prolonged outage. Going idle till network recovers.");
  1126. /* Force every thread to wait for new work */
  1127. inc_staged(mining_threads, true);
  1128. goto retry;
  1129. }
  1130. }
  1131. work_ntime = (uint32_t *)(work->data + 68);
  1132. ntime = be32toh(*work_ntime);
  1133. ntime++;
  1134. *work_ntime = htobe32(ntime);
  1135. ret = true;
  1136. local_work++;
  1137. goto out;
  1138. }
  1139. /* wait for 1st response, or get cached response */
  1140. work_heap = tq_pop(getq, NULL);
  1141. if (unlikely(!work_heap)) {
  1142. applog(LOG_WARNING, "Failed to tq_pop in get_work");
  1143. goto out;
  1144. }
  1145. /* If we make it here we have succeeded in getting fresh work */
  1146. if (localgen) {
  1147. localgen = false;
  1148. applog(LOG_WARNING, "Resuming with work from server");
  1149. }
  1150. dec_queued();
  1151. memcpy(work, work_heap, sizeof(*work));
  1152. ret = true;
  1153. free(work_heap);
  1154. out:
  1155. if (unlikely(ret == false)) {
  1156. if ((opt_retries >= 0) && (++failures > opt_retries)) {
  1157. applog(LOG_ERR, "Failed %d times to get_work");
  1158. return ret;
  1159. }
  1160. applog(LOG_DEBUG, "Retrying after %d seconds", opt_fail_pause);
  1161. sleep(opt_fail_pause);
  1162. goto retry;
  1163. }
  1164. return ret;
  1165. }
  1166. static bool submit_work_sync(struct thr_info *thr, const struct work *work_in)
  1167. {
  1168. struct workio_cmd *wc;
  1169. /* fill out work request message */
  1170. wc = calloc(1, sizeof(*wc));
  1171. if (unlikely(!wc)) {
  1172. applog(LOG_ERR, "Failed to calloc wc in submit_work_sync");
  1173. return false;
  1174. }
  1175. wc->u.work = malloc(sizeof(*work_in));
  1176. if (unlikely(!wc->u.work)) {
  1177. applog(LOG_ERR, "Failed to calloc work in submit_work_sync");
  1178. goto err_out;
  1179. }
  1180. wc->cmd = WC_SUBMIT_WORK;
  1181. wc->thr = thr;
  1182. memcpy(wc->u.work, work_in, sizeof(*work_in));
  1183. /* send solution to workio thread */
  1184. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  1185. applog(LOG_ERR, "Failed to tq_push work in submit_work_sync");
  1186. goto err_out;
  1187. }
  1188. return true;
  1189. err_out:
  1190. workio_cmd_free(wc);
  1191. return false;
  1192. }
  1193. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  1194. {
  1195. work->data[64+12+0] = (nonce>>0) & 0xff;
  1196. work->data[64+12+1] = (nonce>>8) & 0xff;
  1197. work->data[64+12+2] = (nonce>>16) & 0xff;
  1198. work->data[64+12+3] = (nonce>>24) & 0xff;
  1199. return submit_work_sync(thr, work);
  1200. }
  1201. static void *miner_thread(void *userdata)
  1202. {
  1203. struct thr_info *mythr = userdata;
  1204. const int thr_id = mythr->id;
  1205. uint32_t max_nonce = 0xffffff;
  1206. unsigned long hashes_done = max_nonce;
  1207. bool needs_work = true;
  1208. /* Try to cycle approximately 5 times before each log update */
  1209. const unsigned long cycle = opt_log_interval / 5 ? : 1;
  1210. /* Request the next work item at 2/3 of the scantime */
  1211. unsigned const int request_interval = opt_scantime * 2 / 3 ? : 1;
  1212. unsigned const long request_nonce = MAXTHREADS / 3 * 2;
  1213. bool requested = true;
  1214. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  1215. /* Set worker threads to nice 19 and then preferentially to SCHED_IDLE
  1216. * and if that fails, then SCHED_BATCH. No need for this to be an
  1217. * error if it fails */
  1218. setpriority(PRIO_PROCESS, 0, 19);
  1219. drop_policy();
  1220. /* Cpu affinity only makes sense if the number of threads is a multiple
  1221. * of the number of CPUs */
  1222. if (!(opt_n_threads % num_processors))
  1223. affine_to_cpu(thr_id - gpu_threads, dev_from_id(thr_id));
  1224. while (1) {
  1225. struct work work __attribute__((aligned(128)));
  1226. struct timeval tv_workstart, tv_start, tv_end, diff;
  1227. uint64_t max64;
  1228. bool rc;
  1229. if (needs_work) {
  1230. gettimeofday(&tv_workstart, NULL);
  1231. /* obtain new work from internal workio thread */
  1232. if (unlikely(!get_work(&work, requested))) {
  1233. applog(LOG_ERR, "work retrieval failed, exiting "
  1234. "mining thread %d", thr_id);
  1235. goto out;
  1236. }
  1237. mythr->cgpu->getworks++;
  1238. work.thr_id = thr_id;
  1239. needs_work = requested = false;
  1240. work.blk.nonce = 0;
  1241. max_nonce = hashes_done;
  1242. }
  1243. hashes_done = 0;
  1244. gettimeofday(&tv_start, NULL);
  1245. /* scan nonces for a proof-of-work hash */
  1246. switch (opt_algo) {
  1247. case ALGO_C:
  1248. rc = scanhash_c(thr_id, work.midstate, work.data + 64,
  1249. work.hash1, work.hash, work.target,
  1250. max_nonce, &hashes_done,
  1251. work.blk.nonce);
  1252. break;
  1253. #ifdef WANT_X8664_SSE2
  1254. case ALGO_SSE2_64: {
  1255. unsigned int rc5 =
  1256. scanhash_sse2_64(thr_id, work.midstate, work.data + 64,
  1257. work.hash1, work.hash,
  1258. work.target,
  1259. max_nonce, &hashes_done,
  1260. work.blk.nonce);
  1261. rc = (rc5 == -1) ? false : true;
  1262. }
  1263. break;
  1264. #endif
  1265. #ifdef WANT_SSE2_4WAY
  1266. case ALGO_4WAY: {
  1267. unsigned int rc4 =
  1268. ScanHash_4WaySSE2(thr_id, work.midstate, work.data + 64,
  1269. work.hash1, work.hash,
  1270. work.target,
  1271. max_nonce, &hashes_done,
  1272. work.blk.nonce);
  1273. rc = (rc4 == -1) ? false : true;
  1274. }
  1275. break;
  1276. #endif
  1277. #ifdef WANT_VIA_PADLOCK
  1278. case ALGO_VIA:
  1279. rc = scanhash_via(thr_id, work.data, work.target,
  1280. max_nonce, &hashes_done,
  1281. work.blk.nonce);
  1282. break;
  1283. #endif
  1284. case ALGO_CRYPTOPP:
  1285. rc = scanhash_cryptopp(thr_id, work.midstate, work.data + 64,
  1286. work.hash1, work.hash, work.target,
  1287. max_nonce, &hashes_done,
  1288. work.blk.nonce);
  1289. break;
  1290. #ifdef WANT_CRYPTOPP_ASM32
  1291. case ALGO_CRYPTOPP_ASM32:
  1292. rc = scanhash_asm32(thr_id, work.midstate, work.data + 64,
  1293. work.hash1, work.hash, work.target,
  1294. max_nonce, &hashes_done,
  1295. work.blk.nonce);
  1296. break;
  1297. #endif
  1298. default:
  1299. /* should never happen */
  1300. goto out;
  1301. }
  1302. /* record scanhash elapsed time */
  1303. gettimeofday(&tv_end, NULL);
  1304. timeval_subtract(&diff, &tv_end, &tv_start);
  1305. hashes_done -= work.blk.nonce;
  1306. hashmeter(thr_id, &diff, hashes_done);
  1307. work.blk.nonce += hashes_done;
  1308. /* adjust max_nonce to meet target cycle time */
  1309. if (diff.tv_usec > 500000)
  1310. diff.tv_sec++;
  1311. if (diff.tv_sec && diff.tv_sec != cycle) {
  1312. max64 = work.blk.nonce +
  1313. ((uint64_t)hashes_done * cycle) / diff.tv_sec;
  1314. } else
  1315. max64 = work.blk.nonce + hashes_done;
  1316. if (max64 > 0xfffffffaULL)
  1317. max64 = 0xfffffffaULL;
  1318. max_nonce = max64;
  1319. /* if nonce found, submit work */
  1320. if (unlikely(rc)) {
  1321. if (opt_debug)
  1322. applog(LOG_DEBUG, "CPU %d found something?", dev_from_id(thr_id));
  1323. if (unlikely(!submit_work_sync(mythr, &work))) {
  1324. applog(LOG_ERR, "Failed to submit_work_sync in miner_thread %d", thr_id);
  1325. break;
  1326. }
  1327. work.blk.nonce += 4;
  1328. }
  1329. timeval_subtract(&diff, &tv_end, &tv_workstart);
  1330. if (!requested && (diff.tv_sec > request_interval || work.blk.nonce > request_nonce)) {
  1331. if (unlikely(!queue_request())) {
  1332. applog(LOG_ERR, "Failed to queue_request in miner_thread %d", thr_id);
  1333. goto out;
  1334. }
  1335. requested = true;
  1336. }
  1337. if (diff.tv_sec > opt_scantime || work_restart[thr_id].restart ||
  1338. work.blk.nonce >= MAXTHREADS - hashes_done ||
  1339. stale_work(&work))
  1340. needs_work = true;
  1341. }
  1342. out:
  1343. tq_freeze(mythr->q);
  1344. return NULL;
  1345. }
  1346. enum {
  1347. STAT_SLEEP_INTERVAL = 1,
  1348. STAT_CTR_INTERVAL = 10000000,
  1349. FAILURE_INTERVAL = 30,
  1350. };
  1351. #ifdef HAVE_OPENCL
  1352. static _clState *clStates[16];
  1353. static inline cl_int queue_kernel_parameters(_clState *clState, dev_blk_ctx *blk)
  1354. {
  1355. cl_kernel *kernel = &clState->kernel;
  1356. cl_int status = 0;
  1357. int num = 0;
  1358. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_a);
  1359. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_b);
  1360. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_c);
  1361. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_d);
  1362. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_e);
  1363. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_f);
  1364. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_g);
  1365. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_h);
  1366. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_b);
  1367. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_c);
  1368. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_d);
  1369. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_f);
  1370. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_g);
  1371. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_h);
  1372. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->nonce);
  1373. if (clState->hasBitAlign == true) {
  1374. /* Parameters for phatk kernel */
  1375. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W2);
  1376. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W16);
  1377. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W17);
  1378. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreVal4);
  1379. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->T1);
  1380. } else {
  1381. /* Parameters for poclbm kernel */
  1382. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW0);
  1383. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW1);
  1384. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW2);
  1385. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW3);
  1386. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW15);
  1387. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW01r);
  1388. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e);
  1389. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e2);
  1390. }
  1391. status |= clSetKernelArg(*kernel, num++, sizeof(clState->outputBuffer),
  1392. (void *)&clState->outputBuffer);
  1393. return status;
  1394. }
  1395. static void set_threads_hashes(unsigned int vectors, unsigned int *threads,
  1396. unsigned int *hashes, size_t *globalThreads)
  1397. {
  1398. *globalThreads = *threads = 1 << (15 + scan_intensity);
  1399. *hashes = *threads * vectors;
  1400. }
  1401. static void *gpuminer_thread(void *userdata)
  1402. {
  1403. const unsigned long cycle = opt_log_interval / 5 ? : 1;
  1404. struct timeval tv_start, tv_end, diff, tv_workstart;
  1405. struct thr_info *mythr = userdata;
  1406. const int thr_id = mythr->id;
  1407. uint32_t *res, *blank_res;
  1408. double gpu_ms_average = 7;
  1409. size_t globalThreads[1];
  1410. size_t localThreads[1];
  1411. cl_int status;
  1412. _clState *clState = clStates[thr_id];
  1413. const cl_kernel *kernel = &clState->kernel;
  1414. struct work *work = malloc(sizeof(struct work));
  1415. unsigned int threads = 1 << (15 + scan_intensity);
  1416. unsigned const int vectors = clState->preferred_vwidth;
  1417. unsigned int hashes = threads * vectors;
  1418. unsigned int hashes_done = 0;
  1419. /* Request the next work item at 2/3 of the scantime */
  1420. unsigned const int request_interval = opt_scantime * 2 / 3 ? : 1;
  1421. unsigned const long request_nonce = MAXTHREADS / 3 * 2;
  1422. bool requested = true;
  1423. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  1424. res = calloc(BUFFERSIZE, 1);
  1425. blank_res = calloc(BUFFERSIZE, 1);
  1426. if (!res || !blank_res) {
  1427. applog(LOG_ERR, "Failed to calloc in gpuminer_thread");
  1428. goto out;
  1429. }
  1430. gettimeofday(&tv_start, NULL);
  1431. globalThreads[0] = threads;
  1432. localThreads[0] = clState->work_size;
  1433. diff.tv_sec = 0;
  1434. gettimeofday(&tv_end, NULL);
  1435. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_TRUE, 0,
  1436. BUFFERSIZE, blank_res, 0, NULL, NULL);
  1437. if (unlikely(status != CL_SUCCESS))
  1438. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  1439. gettimeofday(&tv_workstart, NULL);
  1440. /* obtain new work from internal workio thread */
  1441. if (unlikely(!get_work(work, requested))) {
  1442. applog(LOG_ERR, "work retrieval failed, exiting "
  1443. "gpu mining thread %d", mythr->id);
  1444. goto out;
  1445. }
  1446. mythr->best_g = ~0;
  1447. mythr->cgpu->getworks++;
  1448. work->thr_id = thr_id;
  1449. requested = false;
  1450. precalc_hash(&work->blk, (uint32_t *)(work->midstate), (uint32_t *)(work->data + 64));
  1451. work->blk.nonce = 0;
  1452. while (1) {
  1453. struct timeval tv_gpustart, tv_gpuend;
  1454. suseconds_t gpu_us;
  1455. gettimeofday(&tv_gpustart, NULL);
  1456. timeval_subtract(&diff, &tv_gpustart, &tv_gpuend);
  1457. /* This finish flushes the readbuffer set with CL_FALSE later */
  1458. clFinish(clState->commandQueue);
  1459. gettimeofday(&tv_gpuend, NULL);
  1460. timeval_subtract(&diff, &tv_gpuend, &tv_gpustart);
  1461. gpu_us = diff.tv_sec * 1000000 + diff.tv_usec;
  1462. gpu_ms_average = ((gpu_us / 1000) + gpu_ms_average * 0.9) / 1.9;
  1463. if (opt_dynamic) {
  1464. /* Try to not let the GPU be out for longer than 6ms, but
  1465. * increase intensity when the system is idle, unless
  1466. * dynamic is disabled. */
  1467. if (gpu_ms_average > 7) {
  1468. if (scan_intensity > 0)
  1469. scan_intensity--;
  1470. set_threads_hashes(vectors, &threads, &hashes, globalThreads);
  1471. } else if (gpu_ms_average < 3) {
  1472. if (scan_intensity < 14)
  1473. scan_intensity++;
  1474. set_threads_hashes(vectors, &threads, &hashes, globalThreads);
  1475. }
  1476. }
  1477. if (diff.tv_sec > opt_scantime ||
  1478. work->blk.nonce >= MAXTHREADS - hashes ||
  1479. work_restart[thr_id].restart ||
  1480. stale_work(work)) {
  1481. /* Ignore any reads since we're getting new work and queue a clean buffer */
  1482. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  1483. BUFFERSIZE, blank_res, 0, NULL, NULL);
  1484. if (unlikely(status != CL_SUCCESS))
  1485. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  1486. memset(res, 0, BUFFERSIZE);
  1487. gettimeofday(&tv_workstart, NULL);
  1488. /* obtain new work from internal workio thread */
  1489. if (unlikely(!get_work(work, requested))) {
  1490. applog(LOG_ERR, "work retrieval failed, exiting "
  1491. "gpu mining thread %d", mythr->id);
  1492. goto out;
  1493. }
  1494. mythr->best_g = ~0;
  1495. mythr->cgpu->getworks++;
  1496. work->thr_id = thr_id;
  1497. requested = false;
  1498. precalc_hash(&work->blk, (uint32_t *)(work->midstate), (uint32_t *)(work->data + 64));
  1499. work->blk.nonce = 0;
  1500. work_restart[thr_id].restart = 0;
  1501. if (opt_debug)
  1502. applog(LOG_DEBUG, "getwork thread %d", thr_id);
  1503. /* Flushes the writebuffer set with CL_FALSE above */
  1504. clFinish(clState->commandQueue);
  1505. }
  1506. status = queue_kernel_parameters(clState, &work->blk);
  1507. if (unlikely(status != CL_SUCCESS))
  1508. { applog(LOG_ERR, "Error: clSetKernelArg of all params failed."); goto out; }
  1509. /* MAXBUFFERS entry is used as a flag to say nonces exist */
  1510. if (res[MAXBUFFERS]) {
  1511. /* Clear the buffer again */
  1512. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  1513. BUFFERSIZE, blank_res, 0, NULL, NULL);
  1514. if (unlikely(status != CL_SUCCESS))
  1515. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  1516. if (opt_debug)
  1517. applog(LOG_DEBUG, "GPU %d found something?", dev_from_id(thr_id));
  1518. postcalc_hash_async(mythr, work, res);
  1519. memset(res, 0, BUFFERSIZE);
  1520. clFinish(clState->commandQueue);
  1521. }
  1522. status = clEnqueueNDRangeKernel(clState->commandQueue, *kernel, 1, NULL,
  1523. globalThreads, localThreads, 0, NULL, NULL);
  1524. if (unlikely(status != CL_SUCCESS))
  1525. { applog(LOG_ERR, "Error: Enqueueing kernel onto command queue. (clEnqueueNDRangeKernel)"); goto out; }
  1526. status = clEnqueueReadBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  1527. BUFFERSIZE, res, 0, NULL, NULL);
  1528. if (unlikely(status != CL_SUCCESS))
  1529. { applog(LOG_ERR, "Error: clEnqueueReadBuffer failed. (clEnqueueReadBuffer)"); goto out;}
  1530. gettimeofday(&tv_end, NULL);
  1531. timeval_subtract(&diff, &tv_end, &tv_start);
  1532. hashes_done += hashes;
  1533. work->blk.nonce += hashes;
  1534. if (diff.tv_usec > 500000)
  1535. diff.tv_sec++;
  1536. if (diff.tv_sec >= cycle) {
  1537. hashmeter(thr_id, &diff, hashes_done);
  1538. gettimeofday(&tv_start, NULL);
  1539. hashes_done = 0;
  1540. }
  1541. timeval_subtract(&diff, &tv_end, &tv_workstart);
  1542. if (!requested && (diff.tv_sec > request_interval || work->blk.nonce > request_nonce)) {
  1543. if (unlikely(!queue_request())) {
  1544. applog(LOG_ERR, "Failed to queue_request in gpuminer_thread %d", thr_id);
  1545. goto out;
  1546. }
  1547. requested = true;
  1548. }
  1549. }
  1550. out:
  1551. tq_freeze(mythr->q);
  1552. return NULL;
  1553. }
  1554. #endif /* HAVE_OPENCL */
  1555. static void restart_threads(bool longpoll)
  1556. {
  1557. int i;
  1558. /* Discard old queued requests and get new ones */
  1559. flush_requests(longpoll);
  1560. for (i = 0; i < mining_threads; i++)
  1561. work_restart[i].restart = 1;
  1562. }
  1563. static void *longpoll_thread(void *userdata)
  1564. {
  1565. struct thr_info *mythr = userdata;
  1566. CURL *curl = NULL;
  1567. char *copy_start, *hdr_path, *lp_url = NULL;
  1568. bool need_slash = false;
  1569. int failures = 0;
  1570. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  1571. hdr_path = tq_pop(mythr->q, NULL);
  1572. if (!hdr_path)
  1573. goto out;
  1574. /* full URL */
  1575. if (strstr(hdr_path, "://")) {
  1576. lp_url = hdr_path;
  1577. hdr_path = NULL;
  1578. }
  1579. /* absolute path, on current server */
  1580. else {
  1581. copy_start = (*hdr_path == '/') ? (hdr_path + 1) : hdr_path;
  1582. if (rpc_url[strlen(rpc_url) - 1] != '/')
  1583. need_slash = true;
  1584. lp_url = malloc(strlen(rpc_url) + strlen(copy_start) + 2);
  1585. if (!lp_url)
  1586. goto out;
  1587. sprintf(lp_url, "%s%s%s", rpc_url, need_slash ? "/" : "", copy_start);
  1588. }
  1589. applog(LOG_INFO, "Long-polling activated for %s", lp_url);
  1590. curl = curl_easy_init();
  1591. if (unlikely(!curl)) {
  1592. applog(LOG_ERR, "CURL initialisation failed");
  1593. goto out;
  1594. }
  1595. while (1) {
  1596. struct timeval start, end;
  1597. json_t *val;
  1598. gettimeofday(&start, NULL);
  1599. val = json_rpc_call(curl, lp_url, rpc_userpass, rpc_req,
  1600. false, true);
  1601. if (likely(val)) {
  1602. failures = 0;
  1603. json_decref(val);
  1604. /* Keep track of who ordered a restart_threads to make
  1605. * sure it's only done once per new block */
  1606. if (likely(!strncmp(longpoll_block, blank, 36) ||
  1607. !strncmp(longpoll_block, current_block, 36))) {
  1608. new_blocks++;
  1609. applog(LOG_WARNING, "LONGPOLL detected new block on network, waiting on fresh work");
  1610. restart_threads(true);
  1611. } else
  1612. applog(LOG_WARNING, "LONGPOLL received after new block already detected");
  1613. } else {
  1614. /* Some pools regularly drop the longpoll request so
  1615. * only see this as longpoll failure if it happens
  1616. * immediately and just restart it the rest of the
  1617. * time. */
  1618. gettimeofday(&end, NULL);
  1619. if (end.tv_sec - start.tv_sec > 30)
  1620. continue;
  1621. if (failures++ < 10) {
  1622. sleep(30);
  1623. applog(LOG_WARNING,
  1624. "longpoll failed, sleeping for 30s");
  1625. } else {
  1626. applog(LOG_ERR,
  1627. "longpoll failed, ending thread");
  1628. goto out;
  1629. }
  1630. }
  1631. memcpy(longpoll_block, current_block, 36);
  1632. }
  1633. out:
  1634. free(hdr_path);
  1635. free(lp_url);
  1636. tq_freeze(mythr->q);
  1637. if (curl)
  1638. curl_easy_cleanup(curl);
  1639. return NULL;
  1640. }
  1641. static void reinit_cputhread(int thr_id)
  1642. {
  1643. struct thr_info *thr = &thr_info[thr_id];
  1644. tq_freeze(thr->q);
  1645. if (!(pthread_cancel(thr->pth)) && pthread_join(thr->pth, NULL)) {
  1646. applog(LOG_ERR, "Failed to pthread_join in reinit_cputhread");
  1647. goto failed_out;
  1648. }
  1649. applog(LOG_INFO, "Reinit CPU thread %d", thr_id);
  1650. tq_thaw(thr->q);
  1651. gettimeofday(&thr->last, NULL);
  1652. if (unlikely(pthread_create(&thr->pth, NULL, miner_thread, thr))) {
  1653. applog(LOG_ERR, "thread %d create failed", thr_id);
  1654. goto failed_out;
  1655. }
  1656. return;
  1657. failed_out:
  1658. kill_work();
  1659. }
  1660. #ifdef HAVE_OPENCL
  1661. static void reinit_gputhread(int thr_id)
  1662. {
  1663. int gpu = dev_from_id(thr_id);
  1664. struct thr_info *thr = &thr_info[thr_id];
  1665. char name[256];
  1666. tq_freeze(thr->q);
  1667. if (!(pthread_cancel(thr->pth)) && pthread_join(thr->pth, NULL)) {
  1668. applog(LOG_ERR, "Failed to pthread_join in reinit_gputhread");
  1669. goto failed_out;
  1670. }
  1671. free(clStates[thr_id]);
  1672. applog(LOG_INFO, "Reinit GPU thread %d", thr_id);
  1673. tq_thaw(thr->q);
  1674. clStates[thr_id] = initCl(gpu, name, sizeof(name));
  1675. if (!clStates[thr_id]) {
  1676. applog(LOG_ERR, "Failed to reinit GPU thread %d", thr_id);
  1677. goto failed_out;
  1678. }
  1679. applog(LOG_INFO, "initCl() finished. Found %s", name);
  1680. gettimeofday(&thr->last, NULL);
  1681. if (unlikely(pthread_create(&thr->pth, NULL, gpuminer_thread, thr))) {
  1682. applog(LOG_ERR, "thread %d create failed", thr_id);
  1683. goto failed_out;
  1684. }
  1685. return;
  1686. failed_out:
  1687. kill_work();
  1688. }
  1689. static void reinit_thread(int thr_id)
  1690. {
  1691. if (thr_id < gpu_threads)
  1692. reinit_gputhread(thr_id);
  1693. else
  1694. reinit_cputhread(thr_id);
  1695. }
  1696. #else
  1697. static void reinit_thread(int thr_id)
  1698. {
  1699. reinit_cputhread(thr_id);
  1700. }
  1701. #endif
  1702. /* Determine which are the first threads belonging to a device and if they're
  1703. * active */
  1704. static bool active_device(int thr_id)
  1705. {
  1706. if (thr_id < gpu_threads) {
  1707. if (thr_id >= total_devices)
  1708. return false;
  1709. if (!gpu_devices[dev_from_id(thr_id)])
  1710. return false;
  1711. } else if (thr_id > gpu_threads + num_processors)
  1712. return false;
  1713. return true;
  1714. }
  1715. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  1716. * the screen at regular intervals, and restarts threads if they appear to have
  1717. * died. */
  1718. static void *watchdog_thread(void *userdata)
  1719. {
  1720. const unsigned int interval = opt_log_interval / 2 ? : 1;
  1721. struct timeval zero_tv;
  1722. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  1723. memset(&zero_tv, 0, sizeof(struct timeval));
  1724. while (1) {
  1725. int x, y, logx, logy, i;
  1726. struct timeval now;
  1727. sleep(interval);
  1728. if (requests_queued() < opt_queue)
  1729. queue_request();
  1730. hashmeter(-1, &zero_tv, 0);
  1731. if (curses_active) {
  1732. pthread_mutex_lock(&curses_lock);
  1733. getmaxyx(mainwin, y, x);
  1734. getmaxyx(logwin, logy, logx);
  1735. y -= logcursor;
  1736. /* Detect screen size change */
  1737. if (x != logx || y != logy)
  1738. wresize(logwin, y, x);
  1739. for (i = 0; i < mining_threads; i++) {
  1740. if (active_device(i))
  1741. curses_print_status(i);
  1742. }
  1743. redrawwin(logwin);
  1744. redrawwin(statuswin);
  1745. pthread_mutex_unlock(&curses_lock);
  1746. }
  1747. if (unlikely(work_restart[watchdog_thr_id].restart)) {
  1748. restart_threads(false);
  1749. work_restart[watchdog_thr_id].restart = 0;
  1750. }
  1751. gettimeofday(&now, NULL);
  1752. #if 0
  1753. for (i = 0; i < mining_threads; i++) {
  1754. #else
  1755. for (i = 0; i < gpu_threads; i++) {
  1756. #endif
  1757. struct thr_info *thr = &thr_info[i];
  1758. /* Do not kill threads waiting on longpoll staged work
  1759. * or idle network */
  1760. if (now.tv_sec - thr->last.tv_sec > 60 && !idlenet) {
  1761. applog(LOG_ERR, "Attempting to restart thread %d, idle for more than 60 seconds", i);
  1762. /* Create one mandatory work item */
  1763. inc_staged(1, true);
  1764. if (unlikely(!queue_request())) {
  1765. applog(LOG_ERR, "Failed to queue_request in watchdog_thread");
  1766. kill_work();
  1767. break;
  1768. }
  1769. reinit_thread(i);
  1770. applog(LOG_WARNING, "Thread %d restarted", i);
  1771. }
  1772. }
  1773. }
  1774. return NULL;
  1775. }
  1776. static void print_summary(void)
  1777. {
  1778. struct timeval diff;
  1779. int hours, mins, secs, i;
  1780. double utility, efficiency = 0.0;
  1781. timeval_subtract(&diff, &total_tv_end, &total_tv_start);
  1782. hours = diff.tv_sec / 3600;
  1783. mins = (diff.tv_sec % 3600) / 60;
  1784. secs = diff.tv_sec % 60;
  1785. utility = accepted / ( total_secs ? total_secs : 1 ) * 60;
  1786. efficiency = getwork_requested ? accepted * 100.0 / getwork_requested : 0.0;
  1787. printf("\nSummary of runtime statistics:\n\n");
  1788. printf("Started at %s\n", datestamp);
  1789. printf("Runtime: %d hrs : %d mins : %d secs\n", hours, mins, secs);
  1790. if (total_secs)
  1791. printf("Average hashrate: %.1f Megahash/s\n", total_mhashes_done / total_secs);
  1792. printf("Queued work requests: %d\n", getwork_requested);
  1793. printf("Share submissions: %d\n", accepted + rejected);
  1794. printf("Accepted shares: %d\n", accepted);
  1795. printf("Rejected shares: %d\n", rejected);
  1796. if (accepted || rejected)
  1797. printf("Reject ratio: %.1f\n", (double)(rejected * 100) / (double)(accepted + rejected));
  1798. printf("Hardware errors: %d\n", hw_errors);
  1799. printf("Efficiency (accepted / queued): %.0f%%\n", efficiency);
  1800. printf("Utility (accepted shares / min): %.2f/min\n\n", utility);
  1801. printf("Discarded work due to new blocks: %d\n", discarded_work);
  1802. printf("Stale submissions discarded due to new blocks: %d\n", stale_shares);
  1803. printf("Unable to get work from server occasions: %d\n", localgen_occasions);
  1804. printf("Work items generated locally: %d\n", local_work);
  1805. printf("Submitting work remotely delay occasions: %d\n", remotefail_occasions);
  1806. printf("New blocks detected on network: %d\n\n", new_blocks);
  1807. printf("Summary of per device statistics:\n\n");
  1808. for (i = 0; i < mining_threads; i++) {
  1809. if (active_device(i))
  1810. print_status(i);
  1811. }
  1812. printf("\n");
  1813. }
  1814. int main (int argc, char *argv[])
  1815. {
  1816. unsigned int i, j = 0, x, y;
  1817. struct sigaction handler;
  1818. struct thr_info *thr;
  1819. char name[256];
  1820. struct tm tm;
  1821. if (unlikely(pthread_mutex_init(&hash_lock, NULL)))
  1822. return 1;
  1823. if (unlikely(pthread_mutex_init(&qd_lock, NULL)))
  1824. return 1;
  1825. if (unlikely(pthread_mutex_init(&stgd_lock, NULL)))
  1826. return 1;
  1827. if (unlikely(pthread_mutex_init(&curses_lock, NULL)))
  1828. return 1;
  1829. handler.sa_handler = &sighandler;
  1830. sigaction(SIGTERM, &handler, &termhandler);
  1831. sigaction(SIGINT, &handler, &inthandler);
  1832. gettimeofday(&total_tv_start, NULL);
  1833. gettimeofday(&total_tv_end, NULL);
  1834. localtime_r(&total_tv_start.tv_sec, &tm);
  1835. sprintf(datestamp, "[%d-%02d-%02d %02d:%02d:%02d]",
  1836. tm.tm_year + 1900,
  1837. tm.tm_mon + 1,
  1838. tm.tm_mday,
  1839. tm.tm_hour,
  1840. tm.tm_min,
  1841. tm.tm_sec);
  1842. for (i = 0; i < 36; i++) {
  1843. strcat(blank, "0");
  1844. strcat(current_block, "0");
  1845. strcat(longpoll_block, "0");
  1846. }
  1847. #ifdef WIN32
  1848. opt_n_threads = num_processors = 1;
  1849. #else
  1850. num_processors = sysconf(_SC_NPROCESSORS_ONLN);
  1851. opt_n_threads = num_processors;
  1852. #endif /* !WIN32 */
  1853. #ifdef HAVE_OPENCL
  1854. for (i = 0; i < 16; i++)
  1855. gpu_devices[i] = false;
  1856. nDevs = clDevicesNum();
  1857. if (nDevs < 0)
  1858. return 1;
  1859. #endif
  1860. if (nDevs)
  1861. opt_n_threads = 0;
  1862. rpc_url = strdup(DEF_RPC_URL);
  1863. /* parse command line */
  1864. opt_register_table(opt_config_table,
  1865. "Options for both config file and command line");
  1866. opt_register_table(opt_cmdline_table,
  1867. "Options for command line only");
  1868. opt_parse(&argc, argv, applog_and_exit);
  1869. if (argc != 1) {
  1870. applog(LOG_ERR, "Unexpected extra commandline arguments");
  1871. return 1;
  1872. }
  1873. if (total_devices) {
  1874. if (total_devices > nDevs) {
  1875. applog(LOG_ERR, "More devices specified than exist");
  1876. return 1;
  1877. }
  1878. for (i = 0; i < 16; i++)
  1879. if (gpu_devices[i] && i + 1 > nDevs) {
  1880. applog(LOG_ERR, "Command line options set a device that doesn't exist");
  1881. return 1;
  1882. }
  1883. gpu_threads = total_devices * opt_g_threads;
  1884. } else {
  1885. gpu_threads = nDevs * opt_g_threads;
  1886. for (i = 0; i < nDevs; i++)
  1887. gpu_devices[i] = true;
  1888. total_devices = nDevs;
  1889. }
  1890. if (!gpu_threads && !forced_n_threads) {
  1891. /* Maybe they turned GPU off; restore default CPU threads. */
  1892. opt_n_threads = num_processors;
  1893. }
  1894. logcursor = 7;
  1895. mining_threads = opt_n_threads + gpu_threads;
  1896. gpucursor = logcursor;
  1897. cpucursor = gpucursor + nDevs;
  1898. logstart = cpucursor + (opt_n_threads ? num_processors : 0) + 1;
  1899. logcursor = logstart + 1;
  1900. if (!rpc_userpass) {
  1901. if (!rpc_user || !rpc_pass) {
  1902. applog(LOG_ERR, "No login credentials supplied");
  1903. return 1;
  1904. }
  1905. rpc_userpass = malloc(strlen(rpc_user) + strlen(rpc_pass) + 2);
  1906. if (!rpc_userpass)
  1907. return 1;
  1908. sprintf(rpc_userpass, "%s:%s", rpc_user, rpc_pass);
  1909. } else {
  1910. rpc_user = malloc(strlen(rpc_userpass));
  1911. if (!rpc_user)
  1912. return 1;
  1913. strcpy(rpc_user, rpc_userpass);
  1914. rpc_user = strtok(rpc_user, ":");
  1915. if (!rpc_user) {
  1916. applog(LOG_ERR, "Failed to find colon delimiter in userpass");
  1917. return 1;
  1918. }
  1919. }
  1920. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  1921. return 1;
  1922. #ifdef HAVE_SYSLOG_H
  1923. if (use_syslog)
  1924. openlog("cpuminer", LOG_PID, LOG_USER);
  1925. #endif
  1926. work_restart = calloc(mining_threads + 4, sizeof(*work_restart));
  1927. if (!work_restart)
  1928. return 1;
  1929. thr_info = calloc(mining_threads + 4, sizeof(*thr));
  1930. if (!thr_info)
  1931. return 1;
  1932. /* init workio thread info */
  1933. work_thr_id = mining_threads;
  1934. thr = &thr_info[work_thr_id];
  1935. thr->id = work_thr_id;
  1936. thr->q = tq_new();
  1937. if (!thr->q)
  1938. return 1;
  1939. /* start work I/O thread */
  1940. if (pthread_create(&thr->pth, NULL, workio_thread, thr)) {
  1941. applog(LOG_ERR, "workio thread create failed");
  1942. return 1;
  1943. }
  1944. /* init longpoll thread info */
  1945. if (want_longpoll) {
  1946. longpoll_thr_id = mining_threads + 1;
  1947. thr = &thr_info[longpoll_thr_id];
  1948. thr->id = longpoll_thr_id;
  1949. thr->q = tq_new();
  1950. if (!thr->q)
  1951. return 1;
  1952. /* start longpoll thread */
  1953. if (unlikely(pthread_create(&thr->pth, NULL, longpoll_thread, thr))) {
  1954. applog(LOG_ERR, "longpoll thread create failed");
  1955. return 1;
  1956. }
  1957. pthread_detach(thr->pth);
  1958. } else
  1959. longpoll_thr_id = -1;
  1960. if (opt_n_threads ) {
  1961. cpus = calloc(num_processors, sizeof(struct cgpu_info));
  1962. if (unlikely(!cpus)) {
  1963. applog(LOG_ERR, "Failed to calloc cpus");
  1964. return 1;
  1965. }
  1966. }
  1967. if (gpu_threads) {
  1968. gpus = calloc(nDevs, sizeof(struct cgpu_info));
  1969. if (unlikely(!gpus)) {
  1970. applog(LOG_ERR, "Failed to calloc gpus");
  1971. return 1;
  1972. }
  1973. }
  1974. stage_thr_id = mining_threads + 3;
  1975. thr = &thr_info[stage_thr_id];
  1976. thr->q = tq_new();
  1977. if (!thr->q)
  1978. return 1;
  1979. /* start stage thread */
  1980. if (pthread_create(&thr->pth, NULL, stage_thread, thr)) {
  1981. applog(LOG_ERR, "stage thread create failed");
  1982. return 1;
  1983. }
  1984. /* Flag the work as ready forcing the mining threads to wait till we
  1985. * actually put something into the queue */
  1986. inc_staged(mining_threads, true);
  1987. /* Create a unique get work queue */
  1988. getq = tq_new();
  1989. if (!getq) {
  1990. applog(LOG_ERR, "Failed to create getq");
  1991. return 1;
  1992. }
  1993. #ifdef HAVE_OPENCL
  1994. i = 0;
  1995. /* start GPU mining threads */
  1996. for (j = 0; j < nDevs * opt_g_threads; j++) {
  1997. int gpu = j % nDevs;
  1998. gpus[gpu].is_gpu = 1;
  1999. gpus[gpu].cpu_gpu = gpu;
  2000. /* Skip devices not set to mine */
  2001. if (!gpu_devices[gpu])
  2002. continue;
  2003. thr = &thr_info[i];
  2004. thr->id = i;
  2005. thr->cgpu = &gpus[gpu];
  2006. thr->q = tq_new();
  2007. if (!thr->q) {
  2008. applog(LOG_ERR, "tq_new failed in starting gpu mining threads");
  2009. return 1;
  2010. }
  2011. applog(LOG_INFO, "Init GPU thread %i", i);
  2012. clStates[i] = initCl(gpu, name, sizeof(name));
  2013. if (!clStates[i]) {
  2014. applog(LOG_ERR, "Failed to init GPU thread %d", i);
  2015. continue;
  2016. }
  2017. applog(LOG_INFO, "initCl() finished. Found %s", name);
  2018. gettimeofday(&thr->last, NULL);
  2019. if (unlikely(pthread_create(&thr->pth, NULL, gpuminer_thread, thr))) {
  2020. applog(LOG_ERR, "thread %d create failed", i);
  2021. return 1;
  2022. }
  2023. i++;
  2024. }
  2025. applog(LOG_INFO, "%d gpu miner threads started", gpu_threads);
  2026. #endif
  2027. /* start CPU mining threads */
  2028. for (i = gpu_threads; i < mining_threads; i++) {
  2029. int cpu = (i - gpu_threads) % num_processors;
  2030. thr = &thr_info[i];
  2031. thr->id = i;
  2032. cpus[cpu].cpu_gpu = cpu;
  2033. thr->cgpu = &cpus[cpu];
  2034. thr->q = tq_new();
  2035. if (!thr->q) {
  2036. applog(LOG_ERR, "tq_new failed in starting cpu mining threads");
  2037. return 1;
  2038. }
  2039. gettimeofday(&thr->last, NULL);
  2040. if (unlikely(pthread_create(&thr->pth, NULL, miner_thread, thr))) {
  2041. applog(LOG_ERR, "thread %d create failed", i);
  2042. return 1;
  2043. }
  2044. }
  2045. applog(LOG_INFO, "%d cpu miner threads started, "
  2046. "using SHA256 '%s' algorithm.",
  2047. opt_n_threads,
  2048. algo_names[opt_algo]);
  2049. watchdog_thr_id = mining_threads + 2;
  2050. thr = &thr_info[watchdog_thr_id];
  2051. /* start wakeup thread */
  2052. if (pthread_create(&thr->pth, NULL, watchdog_thread, NULL)) {
  2053. applog(LOG_ERR, "wakeup thread create failed");
  2054. return 1;
  2055. }
  2056. /* Restart count as it will be wrong till all threads are started */
  2057. pthread_mutex_lock(&hash_lock);
  2058. gettimeofday(&total_tv_start, NULL);
  2059. gettimeofday(&total_tv_end, NULL);
  2060. total_mhashes_done = 0;
  2061. pthread_mutex_unlock(&hash_lock);
  2062. /* Set up the ncurses interface */
  2063. if (!opt_quiet && use_curses) {
  2064. mainwin = initscr();
  2065. getmaxyx(mainwin, y, x);
  2066. statuswin = newwin(logstart, x, 0, 0);
  2067. logwin = newwin(y - logcursor, 0, logcursor, 0);
  2068. idlok(logwin, true);
  2069. scrollok(logwin, true);
  2070. leaveok(logwin, true);
  2071. leaveok(statuswin, true);
  2072. curses_active = true;
  2073. for (i = 0; i < mining_threads; i++)
  2074. print_status(i);
  2075. }
  2076. /* Now that everything's ready put enough work in the queue */
  2077. for (i = 0; i < opt_queue + mining_threads; i++) {
  2078. if (unlikely(!queue_request())) {
  2079. applog(LOG_ERR, "Failed to queue_request in main");
  2080. return 1;
  2081. }
  2082. }
  2083. /* main loop - simply wait for workio thread to exit */
  2084. pthread_join(thr_info[work_thr_id].pth, NULL);
  2085. applog(LOG_INFO, "workio thread dead, exiting.");
  2086. gettimeofday(&total_tv_end, NULL);
  2087. curl_global_cleanup();
  2088. disable_curses();
  2089. if (!opt_quiet && successful_connect)
  2090. print_summary();
  2091. if (gpu_threads)
  2092. free(gpus);
  2093. if (opt_n_threads)
  2094. free(cpus);
  2095. return 0;
  2096. }