main.c 64 KB

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