main.c 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490
  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 for CPU mining:\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 int real_staged(void)
  859. {
  860. int ret;
  861. pthread_mutex_lock(&stgd_lock);
  862. ret = total_staged - lp_staged;
  863. pthread_mutex_unlock(&stgd_lock);
  864. return ret;
  865. }
  866. static void set_curblock(char *hexstr)
  867. {
  868. struct timeval tv_now;
  869. struct tm tm;
  870. memcpy(current_block, hexstr, 36);
  871. gettimeofday(&tv_now, NULL);
  872. localtime_r(&tv_now.tv_sec, &tm);
  873. sprintf(blockdate, "[%d-%02d-%02d %02d:%02d:%02d]",
  874. tm.tm_year + 1900,
  875. tm.tm_mon + 1,
  876. tm.tm_mday,
  877. tm.tm_hour,
  878. tm.tm_min,
  879. tm.tm_sec);
  880. }
  881. static void *stage_thread(void *userdata)
  882. {
  883. struct thr_info *mythr = userdata;
  884. bool ok = true;
  885. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  886. while (ok) {
  887. struct work *work = NULL;
  888. char *hexstr;
  889. work = tq_pop(mythr->q, NULL);
  890. if (unlikely(!work)) {
  891. applog(LOG_ERR, "Failed to tq_pop in stage_thread");
  892. ok = false;
  893. break;
  894. }
  895. hexstr = bin2hex(work->data, 36);
  896. if (unlikely(!hexstr)) {
  897. applog(LOG_ERR, "stage_thread OOM");
  898. break;
  899. }
  900. /* current_block is blanked out on successful longpoll */
  901. if (likely(strncmp(current_block, blank, 36))) {
  902. if (unlikely(strncmp(hexstr, current_block, 36))) {
  903. new_blocks++;
  904. if (have_longpoll)
  905. applog(LOG_WARNING, "New block detected on network before longpoll, waiting on fresh work");
  906. else
  907. applog(LOG_WARNING, "New block detected on network, waiting on fresh work");
  908. /* As we can't flush the work from here, signal
  909. * the wakeup thread to restart all the
  910. * threads */
  911. work_restart[watchdog_thr_id].restart = 1;
  912. set_curblock(hexstr);
  913. }
  914. } else {
  915. set_curblock(hexstr);
  916. memcpy(longpoll_block, hexstr, 36);
  917. }
  918. free(hexstr);
  919. if (unlikely(!tq_push(getq, work))) {
  920. applog(LOG_ERR, "Failed to tq_push work in stage_thread");
  921. ok = false;
  922. break;
  923. }
  924. inc_staged(1, false);
  925. }
  926. tq_freeze(mythr->q);
  927. return NULL;
  928. }
  929. static void *workio_thread(void *userdata)
  930. {
  931. struct thr_info *mythr = userdata;
  932. bool ok = true;
  933. while (ok) {
  934. struct workio_cmd *wc;
  935. /* wait for workio_cmd sent to us, on our queue */
  936. wc = tq_pop(mythr->q, NULL);
  937. if (unlikely(!wc)) {
  938. applog(LOG_ERR, "Failed to tq_pop in workio_thread");
  939. ok = false;
  940. break;
  941. }
  942. /* process workio_cmd */
  943. switch (wc->cmd) {
  944. case WC_GET_WORK:
  945. ok = workio_get_work(wc);
  946. break;
  947. case WC_SUBMIT_WORK:
  948. ok = workio_submit_work(wc);
  949. break;
  950. case WC_DIE:
  951. default:
  952. ok = false;
  953. break;
  954. }
  955. }
  956. tq_freeze(mythr->q);
  957. return NULL;
  958. }
  959. static void hashmeter(int thr_id, struct timeval *diff,
  960. unsigned long hashes_done)
  961. {
  962. struct timeval temp_tv_end, total_diff;
  963. double khashes, secs;
  964. double local_secs;
  965. double utility, efficiency = 0.0;
  966. static double local_mhashes_done = 0;
  967. static double rolling_local = 0;
  968. double local_mhashes = (double)hashes_done / 1000000.0;
  969. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  970. /* Update the last time this thread reported in */
  971. if (thr_id >= 0)
  972. gettimeofday(&thr_info[thr_id].last, NULL);
  973. /* Don't bother calculating anything if we're not displaying it */
  974. if (opt_quiet || !opt_log_interval)
  975. return;
  976. khashes = hashes_done / 1000.0;
  977. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  978. if (thr_id >= 0 && secs) {
  979. /* So we can call hashmeter from a non worker thread */
  980. if (opt_debug)
  981. applog(LOG_DEBUG, "[thread %d: %lu hashes, %.0f khash/sec]",
  982. thr_id, hashes_done, hashes_done / secs);
  983. cgpu->local_mhashes += local_mhashes;
  984. cgpu->total_mhashes += local_mhashes;
  985. }
  986. /* Totals are updated by all threads so can race without locking */
  987. pthread_mutex_lock(&hash_lock);
  988. gettimeofday(&temp_tv_end, NULL);
  989. timeval_subtract(&total_diff, &temp_tv_end, &total_tv_end);
  990. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  991. total_mhashes_done += local_mhashes;
  992. local_mhashes_done += local_mhashes;
  993. if (total_diff.tv_sec < opt_log_interval)
  994. /* Only update the total every opt_log_interval seconds */
  995. goto out_unlock;
  996. gettimeofday(&total_tv_end, NULL);
  997. /* Use a rolling average by faking an exponential decay over 5 * log */
  998. rolling_local = ((rolling_local * 0.9) + local_mhashes_done) / 1.9;
  999. timeval_subtract(&total_diff, &total_tv_end, &total_tv_start);
  1000. total_secs = (double)total_diff.tv_sec +
  1001. ((double)total_diff.tv_usec / 1000000.0);
  1002. utility = accepted / ( total_secs ? total_secs : 1 ) * 60;
  1003. efficiency = getwork_requested ? accepted * 100.0 / getwork_requested : 0.0;
  1004. sprintf(statusline, "[(%ds):%.1f (avg):%.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]",
  1005. opt_log_interval, rolling_local / local_secs, total_mhashes_done / total_secs,
  1006. getwork_requested, accepted, rejected, hw_errors, efficiency, utility);
  1007. if (!curses_active) {
  1008. printf("%s \r", statusline);
  1009. fflush(stdout);
  1010. } else
  1011. applog(LOG_INFO, "%s", statusline);
  1012. local_mhashes_done = 0;
  1013. out_unlock:
  1014. pthread_mutex_unlock(&hash_lock);
  1015. }
  1016. /* This is overkill, but at least we'll know accurately how much work is
  1017. * queued to prevent ever being left without work */
  1018. static void inc_queued(void)
  1019. {
  1020. pthread_mutex_lock(&qd_lock);
  1021. total_queued++;
  1022. pthread_mutex_unlock(&qd_lock);
  1023. }
  1024. static void dec_queued(void)
  1025. {
  1026. pthread_mutex_lock(&qd_lock);
  1027. if (total_queued > total_staged)
  1028. total_queued--;
  1029. pthread_mutex_unlock(&qd_lock);
  1030. dec_staged(1);
  1031. }
  1032. static int requests_queued(void)
  1033. {
  1034. int ret;
  1035. pthread_mutex_lock(&qd_lock);
  1036. ret = total_queued;
  1037. pthread_mutex_unlock(&qd_lock);
  1038. return ret;
  1039. }
  1040. static bool queue_request(void)
  1041. {
  1042. int maxq = opt_queue + mining_threads;
  1043. struct workio_cmd *wc;
  1044. /* If we've been generating lots of local work we may already have
  1045. * enough in the queue */
  1046. if (requests_queued() >= maxq || real_staged() >= maxq)
  1047. return true;
  1048. /* fill out work request message */
  1049. wc = calloc(1, sizeof(*wc));
  1050. if (unlikely(!wc)) {
  1051. applog(LOG_ERR, "Failed to tq_pop in queue_request");
  1052. return false;
  1053. }
  1054. wc->cmd = WC_GET_WORK;
  1055. /* The get work does not belong to any thread */
  1056. wc->thr = NULL;
  1057. /* send work request to workio thread */
  1058. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  1059. applog(LOG_ERR, "Failed to tq_push in queue_request");
  1060. workio_cmd_free(wc);
  1061. return false;
  1062. }
  1063. getwork_requested++;
  1064. inc_queued();
  1065. return true;
  1066. }
  1067. static void discard_staged(void)
  1068. {
  1069. struct work *work_heap;
  1070. /* Just in case we fell in a hole and missed a queue filling */
  1071. if (unlikely(!requests_staged()))
  1072. return;
  1073. work_heap = tq_pop(getq, NULL);
  1074. if (unlikely(!work_heap))
  1075. return;
  1076. free(work_heap);
  1077. dec_queued();
  1078. discarded_work++;
  1079. }
  1080. static void flush_requests(bool longpoll)
  1081. {
  1082. int i, stale;
  1083. /* We should have one fresh work item staged from the block change. */
  1084. stale = requests_staged() - 1;
  1085. if (longpoll)
  1086. memcpy(current_block, blank, 36);
  1087. /* Temporarily increase the staged count so that get_work thinks there
  1088. * is work available instead of making threads reuse existing work */
  1089. inc_staged(mining_threads, true);
  1090. for (i = 0; i < stale; i++) {
  1091. /* Queue a whole batch of new requests */
  1092. if (unlikely(!queue_request())) {
  1093. applog(LOG_ERR, "Failed to queue requests in flush_requests");
  1094. kill_work();
  1095. break;
  1096. }
  1097. /* Pop off the old requests. Cancelling the requests would be better
  1098. * but is tricky */
  1099. discard_staged();
  1100. }
  1101. }
  1102. static bool get_work(struct work *work, bool queued)
  1103. {
  1104. static struct timeval tv_localgen = {};
  1105. struct work *work_heap;
  1106. bool ret = false;
  1107. int failures = 0;
  1108. retry:
  1109. if (unlikely(!queued && !queue_request())) {
  1110. applog(LOG_WARNING, "Failed to queue_request in get_work");
  1111. goto out;
  1112. }
  1113. if (!requests_staged() && !stale_work(work)) {
  1114. uint32_t *work_ntime;
  1115. uint32_t ntime;
  1116. /* Only print this message once each time we shift to localgen */
  1117. if (!test_and_set(&localgen)) {
  1118. applog(LOG_WARNING, "Server not providing work fast enough, generating work locally");
  1119. localgen_occasions++;
  1120. gettimeofday(&tv_localgen, NULL);
  1121. } else {
  1122. struct timeval tv_now, diff;
  1123. gettimeofday(&tv_now, NULL);
  1124. timeval_subtract(&diff, &tv_now, &tv_localgen);
  1125. if (diff.tv_sec > 600) {
  1126. /* A new block appears on average every 10 mins */
  1127. applog(LOG_WARNING, "Prolonged outage. Going idle till network recovers.");
  1128. /* Force every thread to wait for new work */
  1129. inc_staged(mining_threads, true);
  1130. goto retry;
  1131. }
  1132. }
  1133. work_ntime = (uint32_t *)(work->data + 68);
  1134. ntime = be32toh(*work_ntime);
  1135. ntime++;
  1136. *work_ntime = htobe32(ntime);
  1137. ret = true;
  1138. local_work++;
  1139. goto out;
  1140. }
  1141. /* wait for 1st response, or get cached response */
  1142. work_heap = tq_pop(getq, NULL);
  1143. if (unlikely(!work_heap)) {
  1144. applog(LOG_WARNING, "Failed to tq_pop in get_work");
  1145. goto out;
  1146. }
  1147. /* If we make it here we have succeeded in getting fresh work */
  1148. if (test_and_clear(&localgen))
  1149. applog(LOG_WARNING, "Resuming with work from server");
  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_X8664_SSE4
  1266. case ALGO_SSE4_64: {
  1267. unsigned int rc5 =
  1268. scanhash_sse4_64(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 = (rc5 == -1) ? false : true;
  1274. }
  1275. break;
  1276. #endif
  1277. #ifdef WANT_SSE2_4WAY
  1278. case ALGO_4WAY: {
  1279. unsigned int rc4 =
  1280. ScanHash_4WaySSE2(thr_id, work.midstate, work.data + 64,
  1281. work.hash1, work.hash,
  1282. work.target,
  1283. max_nonce, &hashes_done,
  1284. work.blk.nonce);
  1285. rc = (rc4 == -1) ? false : true;
  1286. }
  1287. break;
  1288. #endif
  1289. #ifdef WANT_VIA_PADLOCK
  1290. case ALGO_VIA:
  1291. rc = scanhash_via(thr_id, work.data, work.target,
  1292. max_nonce, &hashes_done,
  1293. work.blk.nonce);
  1294. break;
  1295. #endif
  1296. case ALGO_CRYPTOPP:
  1297. rc = scanhash_cryptopp(thr_id, work.midstate, work.data + 64,
  1298. work.hash1, work.hash, work.target,
  1299. max_nonce, &hashes_done,
  1300. work.blk.nonce);
  1301. break;
  1302. #ifdef WANT_CRYPTOPP_ASM32
  1303. case ALGO_CRYPTOPP_ASM32:
  1304. rc = scanhash_asm32(thr_id, work.midstate, work.data + 64,
  1305. work.hash1, work.hash, work.target,
  1306. max_nonce, &hashes_done,
  1307. work.blk.nonce);
  1308. break;
  1309. #endif
  1310. default:
  1311. /* should never happen */
  1312. goto out;
  1313. }
  1314. /* record scanhash elapsed time */
  1315. gettimeofday(&tv_end, NULL);
  1316. timeval_subtract(&diff, &tv_end, &tv_start);
  1317. hashes_done -= work.blk.nonce;
  1318. hashmeter(thr_id, &diff, hashes_done);
  1319. work.blk.nonce += hashes_done;
  1320. /* adjust max_nonce to meet target cycle time */
  1321. if (diff.tv_usec > 500000)
  1322. diff.tv_sec++;
  1323. if (diff.tv_sec && diff.tv_sec != cycle) {
  1324. max64 = work.blk.nonce +
  1325. ((uint64_t)hashes_done * cycle) / diff.tv_sec;
  1326. } else
  1327. max64 = work.blk.nonce + hashes_done;
  1328. if (max64 > 0xfffffffaULL)
  1329. max64 = 0xfffffffaULL;
  1330. max_nonce = max64;
  1331. /* if nonce found, submit work */
  1332. if (unlikely(rc)) {
  1333. if (opt_debug)
  1334. applog(LOG_DEBUG, "CPU %d found something?", dev_from_id(thr_id));
  1335. if (unlikely(!submit_work_sync(mythr, &work))) {
  1336. applog(LOG_ERR, "Failed to submit_work_sync in miner_thread %d", thr_id);
  1337. break;
  1338. }
  1339. work.blk.nonce += 4;
  1340. }
  1341. timeval_subtract(&diff, &tv_end, &tv_workstart);
  1342. if (!requested && (diff.tv_sec > request_interval || work.blk.nonce > request_nonce)) {
  1343. if (unlikely(!queue_request())) {
  1344. applog(LOG_ERR, "Failed to queue_request in miner_thread %d", thr_id);
  1345. goto out;
  1346. }
  1347. requested = true;
  1348. }
  1349. if (diff.tv_sec > opt_scantime || work_restart[thr_id].restart ||
  1350. work.blk.nonce >= MAXTHREADS - hashes_done ||
  1351. stale_work(&work))
  1352. needs_work = true;
  1353. }
  1354. out:
  1355. tq_freeze(mythr->q);
  1356. return NULL;
  1357. }
  1358. enum {
  1359. STAT_SLEEP_INTERVAL = 1,
  1360. STAT_CTR_INTERVAL = 10000000,
  1361. FAILURE_INTERVAL = 30,
  1362. };
  1363. #ifdef HAVE_OPENCL
  1364. static _clState *clStates[16];
  1365. static inline cl_int queue_kernel_parameters(_clState *clState, dev_blk_ctx *blk)
  1366. {
  1367. cl_kernel *kernel = &clState->kernel;
  1368. cl_int status = 0;
  1369. int num = 0;
  1370. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_a);
  1371. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_b);
  1372. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_c);
  1373. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_d);
  1374. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_e);
  1375. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_f);
  1376. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_g);
  1377. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_h);
  1378. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_b);
  1379. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_c);
  1380. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_d);
  1381. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_f);
  1382. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_g);
  1383. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_h);
  1384. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->nonce);
  1385. if (clState->hasBitAlign == true) {
  1386. /* Parameters for phatk kernel */
  1387. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W2);
  1388. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W16);
  1389. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W17);
  1390. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreVal4);
  1391. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->T1);
  1392. } else {
  1393. /* Parameters for poclbm kernel */
  1394. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW0);
  1395. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW1);
  1396. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW2);
  1397. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW3);
  1398. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW15);
  1399. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW01r);
  1400. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e);
  1401. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e2);
  1402. }
  1403. status |= clSetKernelArg(*kernel, num++, sizeof(clState->outputBuffer),
  1404. (void *)&clState->outputBuffer);
  1405. return status;
  1406. }
  1407. static void set_threads_hashes(unsigned int vectors, unsigned int *threads,
  1408. unsigned int *hashes, size_t *globalThreads)
  1409. {
  1410. *globalThreads = *threads = 1 << (15 + scan_intensity);
  1411. *hashes = *threads * vectors;
  1412. }
  1413. static void *gpuminer_thread(void *userdata)
  1414. {
  1415. const unsigned long cycle = opt_log_interval / 5 ? : 1;
  1416. struct timeval tv_start, tv_end, diff, tv_workstart;
  1417. struct thr_info *mythr = userdata;
  1418. const int thr_id = mythr->id;
  1419. uint32_t *res, *blank_res;
  1420. double gpu_ms_average = 7;
  1421. size_t globalThreads[1];
  1422. size_t localThreads[1];
  1423. cl_int status;
  1424. _clState *clState = clStates[thr_id];
  1425. const cl_kernel *kernel = &clState->kernel;
  1426. struct work *work = malloc(sizeof(struct work));
  1427. unsigned int threads = 1 << (15 + scan_intensity);
  1428. unsigned const int vectors = clState->preferred_vwidth;
  1429. unsigned int hashes = threads * vectors;
  1430. unsigned int hashes_done = 0;
  1431. /* Request the next work item at 2/3 of the scantime */
  1432. unsigned const int request_interval = opt_scantime * 2 / 3 ? : 1;
  1433. unsigned const long request_nonce = MAXTHREADS / 3 * 2;
  1434. bool requested = true;
  1435. if (opt_dynamic) {
  1436. /* Minimise impact on desktop if we want dynamic mode */
  1437. setpriority(PRIO_PROCESS, 0, 19);
  1438. drop_policy();
  1439. }
  1440. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  1441. res = calloc(BUFFERSIZE, 1);
  1442. blank_res = calloc(BUFFERSIZE, 1);
  1443. if (!res || !blank_res) {
  1444. applog(LOG_ERR, "Failed to calloc in gpuminer_thread");
  1445. goto out;
  1446. }
  1447. gettimeofday(&tv_start, NULL);
  1448. globalThreads[0] = threads;
  1449. localThreads[0] = clState->work_size;
  1450. diff.tv_sec = 0;
  1451. gettimeofday(&tv_end, NULL);
  1452. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_TRUE, 0,
  1453. BUFFERSIZE, blank_res, 0, NULL, NULL);
  1454. if (unlikely(status != CL_SUCCESS))
  1455. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  1456. gettimeofday(&tv_workstart, NULL);
  1457. /* obtain new work from internal workio thread */
  1458. if (unlikely(!get_work(work, requested))) {
  1459. applog(LOG_ERR, "work retrieval failed, exiting "
  1460. "gpu mining thread %d", mythr->id);
  1461. goto out;
  1462. }
  1463. mythr->cgpu->getworks++;
  1464. work->thr_id = thr_id;
  1465. requested = false;
  1466. precalc_hash(&work->blk, (uint32_t *)(work->midstate), (uint32_t *)(work->data + 64));
  1467. work->blk.nonce = 0;
  1468. while (1) {
  1469. struct timeval tv_gpustart, tv_gpuend;
  1470. suseconds_t gpu_us;
  1471. gettimeofday(&tv_gpustart, NULL);
  1472. timeval_subtract(&diff, &tv_gpustart, &tv_gpuend);
  1473. /* This finish flushes the readbuffer set with CL_FALSE later */
  1474. clFinish(clState->commandQueue);
  1475. gettimeofday(&tv_gpuend, NULL);
  1476. timeval_subtract(&diff, &tv_gpuend, &tv_gpustart);
  1477. gpu_us = diff.tv_sec * 1000000 + diff.tv_usec;
  1478. gpu_ms_average = ((gpu_us / 1000) + gpu_ms_average * 0.9) / 1.9;
  1479. if (opt_dynamic) {
  1480. /* Try to not let the GPU be out for longer than 6ms, but
  1481. * increase intensity when the system is idle, unless
  1482. * dynamic is disabled. */
  1483. if (gpu_ms_average > 7) {
  1484. if (scan_intensity > 0)
  1485. scan_intensity--;
  1486. set_threads_hashes(vectors, &threads, &hashes, globalThreads);
  1487. } else if (gpu_ms_average < 3) {
  1488. if (scan_intensity < 14)
  1489. scan_intensity++;
  1490. set_threads_hashes(vectors, &threads, &hashes, globalThreads);
  1491. }
  1492. }
  1493. if (diff.tv_sec > opt_scantime ||
  1494. work->blk.nonce >= MAXTHREADS - hashes ||
  1495. work_restart[thr_id].restart ||
  1496. stale_work(work)) {
  1497. /* Ignore any reads since we're getting new work and queue a clean buffer */
  1498. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  1499. BUFFERSIZE, blank_res, 0, NULL, NULL);
  1500. if (unlikely(status != CL_SUCCESS))
  1501. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  1502. memset(res, 0, BUFFERSIZE);
  1503. gettimeofday(&tv_workstart, NULL);
  1504. /* obtain new work from internal workio thread */
  1505. if (unlikely(!get_work(work, requested))) {
  1506. applog(LOG_ERR, "work retrieval failed, exiting "
  1507. "gpu mining thread %d", mythr->id);
  1508. goto out;
  1509. }
  1510. mythr->cgpu->getworks++;
  1511. work->thr_id = thr_id;
  1512. requested = false;
  1513. precalc_hash(&work->blk, (uint32_t *)(work->midstate), (uint32_t *)(work->data + 64));
  1514. work->blk.nonce = 0;
  1515. work_restart[thr_id].restart = 0;
  1516. if (opt_debug)
  1517. applog(LOG_DEBUG, "getwork thread %d", thr_id);
  1518. /* Flushes the writebuffer set with CL_FALSE above */
  1519. clFinish(clState->commandQueue);
  1520. }
  1521. status = queue_kernel_parameters(clState, &work->blk);
  1522. if (unlikely(status != CL_SUCCESS))
  1523. { applog(LOG_ERR, "Error: clSetKernelArg of all params failed."); goto out; }
  1524. /* MAXBUFFERS entry is used as a flag to say nonces exist */
  1525. if (res[MAXBUFFERS]) {
  1526. /* Clear the buffer again */
  1527. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  1528. BUFFERSIZE, blank_res, 0, NULL, NULL);
  1529. if (unlikely(status != CL_SUCCESS))
  1530. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  1531. if (opt_debug)
  1532. applog(LOG_DEBUG, "GPU %d found something?", dev_from_id(thr_id));
  1533. postcalc_hash_async(mythr, work, res);
  1534. memset(res, 0, BUFFERSIZE);
  1535. clFinish(clState->commandQueue);
  1536. }
  1537. status = clEnqueueNDRangeKernel(clState->commandQueue, *kernel, 1, NULL,
  1538. globalThreads, localThreads, 0, NULL, NULL);
  1539. if (unlikely(status != CL_SUCCESS))
  1540. { applog(LOG_ERR, "Error: Enqueueing kernel onto command queue. (clEnqueueNDRangeKernel)"); goto out; }
  1541. status = clEnqueueReadBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  1542. BUFFERSIZE, res, 0, NULL, NULL);
  1543. if (unlikely(status != CL_SUCCESS))
  1544. { applog(LOG_ERR, "Error: clEnqueueReadBuffer failed. (clEnqueueReadBuffer)"); goto out;}
  1545. gettimeofday(&tv_end, NULL);
  1546. timeval_subtract(&diff, &tv_end, &tv_start);
  1547. hashes_done += hashes;
  1548. work->blk.nonce += hashes;
  1549. if (diff.tv_usec > 500000)
  1550. diff.tv_sec++;
  1551. if (diff.tv_sec >= cycle) {
  1552. hashmeter(thr_id, &diff, hashes_done);
  1553. gettimeofday(&tv_start, NULL);
  1554. hashes_done = 0;
  1555. }
  1556. timeval_subtract(&diff, &tv_end, &tv_workstart);
  1557. if (!requested && (diff.tv_sec > request_interval || work->blk.nonce > request_nonce)) {
  1558. if (unlikely(!queue_request())) {
  1559. applog(LOG_ERR, "Failed to queue_request in gpuminer_thread %d", thr_id);
  1560. goto out;
  1561. }
  1562. requested = true;
  1563. }
  1564. }
  1565. out:
  1566. tq_freeze(mythr->q);
  1567. return NULL;
  1568. }
  1569. #endif /* HAVE_OPENCL */
  1570. static void restart_threads(bool longpoll)
  1571. {
  1572. int i;
  1573. /* Discard old queued requests and get new ones */
  1574. flush_requests(longpoll);
  1575. for (i = 0; i < mining_threads; i++)
  1576. work_restart[i].restart = 1;
  1577. }
  1578. /* Stage another work item from the work returned in a longpoll */
  1579. static void convert_to_work(json_t *val)
  1580. {
  1581. struct work *work;
  1582. bool rc;
  1583. work = calloc(sizeof(*work), 1);
  1584. if (unlikely(!work)) {
  1585. applog(LOG_ERR, "OOM in convert_to_work");
  1586. return;
  1587. }
  1588. rc= work_decode(json_object_get(val, "result"), work);
  1589. if (unlikely(!rc)) {
  1590. applog(LOG_ERR, "Could not convert longpoll data to work");
  1591. return;
  1592. }
  1593. if (unlikely(!tq_push(thr_info[stage_thr_id].q, work)))
  1594. applog(LOG_ERR, "Could not tq_push work in convert_to_work");
  1595. else if (opt_debug)
  1596. applog(LOG_DEBUG, "Converted longpoll data to work");
  1597. }
  1598. static void *longpoll_thread(void *userdata)
  1599. {
  1600. struct thr_info *mythr = userdata;
  1601. CURL *curl = NULL;
  1602. char *copy_start, *hdr_path, *lp_url = NULL;
  1603. bool need_slash = false;
  1604. int failures = 0;
  1605. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  1606. hdr_path = tq_pop(mythr->q, NULL);
  1607. if (!hdr_path)
  1608. goto out;
  1609. /* full URL */
  1610. if (strstr(hdr_path, "://")) {
  1611. lp_url = hdr_path;
  1612. hdr_path = NULL;
  1613. }
  1614. /* absolute path, on current server */
  1615. else {
  1616. copy_start = (*hdr_path == '/') ? (hdr_path + 1) : hdr_path;
  1617. if (rpc_url[strlen(rpc_url) - 1] != '/')
  1618. need_slash = true;
  1619. lp_url = malloc(strlen(rpc_url) + strlen(copy_start) + 2);
  1620. if (!lp_url)
  1621. goto out;
  1622. sprintf(lp_url, "%s%s%s", rpc_url, need_slash ? "/" : "", copy_start);
  1623. }
  1624. applog(LOG_INFO, "Long-polling activated for %s", lp_url);
  1625. curl = curl_easy_init();
  1626. if (unlikely(!curl)) {
  1627. applog(LOG_ERR, "CURL initialisation failed");
  1628. goto out;
  1629. }
  1630. while (1) {
  1631. struct timeval start, end;
  1632. json_t *val;
  1633. gettimeofday(&start, NULL);
  1634. val = json_rpc_call(curl, lp_url, rpc_userpass, rpc_req,
  1635. false, true);
  1636. if (likely(val)) {
  1637. /* Keep track of who ordered a restart_threads to make
  1638. * sure it's only done once per new block */
  1639. if (likely(!strncmp(longpoll_block, blank, 36) ||
  1640. !strncmp(longpoll_block, current_block, 36))) {
  1641. new_blocks++;
  1642. applog(LOG_WARNING, "LONGPOLL detected new block on network, waiting on fresh work");
  1643. restart_threads(true);
  1644. } else
  1645. applog(LOG_WARNING, "LONGPOLL received after new block already detected");
  1646. convert_to_work(val);
  1647. failures = 0;
  1648. json_decref(val);
  1649. } else {
  1650. /* Some pools regularly drop the longpoll request so
  1651. * only see this as longpoll failure if it happens
  1652. * immediately and just restart it the rest of the
  1653. * time. */
  1654. gettimeofday(&end, NULL);
  1655. if (end.tv_sec - start.tv_sec > 30)
  1656. continue;
  1657. if (failures++ < 10) {
  1658. sleep(30);
  1659. applog(LOG_WARNING,
  1660. "longpoll failed, sleeping for 30s");
  1661. } else {
  1662. applog(LOG_ERR,
  1663. "longpoll failed, ending thread");
  1664. goto out;
  1665. }
  1666. }
  1667. memcpy(longpoll_block, current_block, 36);
  1668. }
  1669. out:
  1670. free(hdr_path);
  1671. free(lp_url);
  1672. tq_freeze(mythr->q);
  1673. if (curl)
  1674. curl_easy_cleanup(curl);
  1675. return NULL;
  1676. }
  1677. static void reinit_cputhread(int thr_id)
  1678. {
  1679. struct thr_info *thr = &thr_info[thr_id];
  1680. tq_freeze(thr->q);
  1681. if (!(pthread_cancel(thr->pth)) && pthread_join(thr->pth, NULL)) {
  1682. applog(LOG_ERR, "Failed to pthread_join in reinit_cputhread");
  1683. goto failed_out;
  1684. }
  1685. applog(LOG_INFO, "Reinit CPU thread %d", thr_id);
  1686. tq_thaw(thr->q);
  1687. gettimeofday(&thr->last, NULL);
  1688. if (unlikely(pthread_create(&thr->pth, NULL, miner_thread, thr))) {
  1689. applog(LOG_ERR, "thread %d create failed", thr_id);
  1690. goto failed_out;
  1691. }
  1692. return;
  1693. failed_out:
  1694. kill_work();
  1695. }
  1696. #ifdef HAVE_OPENCL
  1697. static void reinit_gputhread(int thr_id)
  1698. {
  1699. int gpu = dev_from_id(thr_id);
  1700. struct thr_info *thr = &thr_info[thr_id];
  1701. char name[256];
  1702. tq_freeze(thr->q);
  1703. if (!(pthread_cancel(thr->pth)) && pthread_join(thr->pth, NULL)) {
  1704. applog(LOG_ERR, "Failed to pthread_join in reinit_gputhread");
  1705. goto failed_out;
  1706. }
  1707. free(clStates[thr_id]);
  1708. applog(LOG_INFO, "Reinit GPU thread %d", thr_id);
  1709. tq_thaw(thr->q);
  1710. clStates[thr_id] = initCl(gpu, name, sizeof(name));
  1711. if (!clStates[thr_id]) {
  1712. applog(LOG_ERR, "Failed to reinit GPU thread %d", thr_id);
  1713. goto failed_out;
  1714. }
  1715. applog(LOG_INFO, "initCl() finished. Found %s", name);
  1716. gettimeofday(&thr->last, NULL);
  1717. if (unlikely(pthread_create(&thr->pth, NULL, gpuminer_thread, thr))) {
  1718. applog(LOG_ERR, "thread %d create failed", thr_id);
  1719. goto failed_out;
  1720. }
  1721. return;
  1722. failed_out:
  1723. kill_work();
  1724. }
  1725. static void reinit_thread(int thr_id)
  1726. {
  1727. if (thr_id < gpu_threads)
  1728. reinit_gputhread(thr_id);
  1729. else
  1730. reinit_cputhread(thr_id);
  1731. }
  1732. #else
  1733. static void reinit_thread(int thr_id)
  1734. {
  1735. reinit_cputhread(thr_id);
  1736. }
  1737. #endif
  1738. /* Determine which are the first threads belonging to a device and if they're
  1739. * active */
  1740. static bool active_device(int thr_id)
  1741. {
  1742. if (thr_id < gpu_threads) {
  1743. if (thr_id >= total_devices)
  1744. return false;
  1745. if (!gpu_devices[dev_from_id(thr_id)])
  1746. return false;
  1747. } else if (thr_id > gpu_threads + num_processors)
  1748. return false;
  1749. return true;
  1750. }
  1751. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  1752. * the screen at regular intervals, and restarts threads if they appear to have
  1753. * died. */
  1754. static void *watchdog_thread(void *userdata)
  1755. {
  1756. const unsigned int interval = opt_log_interval / 2 ? : 1;
  1757. struct timeval zero_tv;
  1758. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  1759. memset(&zero_tv, 0, sizeof(struct timeval));
  1760. while (1) {
  1761. int x, y, logx, logy, i;
  1762. struct timeval now;
  1763. sleep(interval);
  1764. if (requests_queued() < opt_queue)
  1765. queue_request();
  1766. hashmeter(-1, &zero_tv, 0);
  1767. if (curses_active) {
  1768. pthread_mutex_lock(&curses_lock);
  1769. getmaxyx(mainwin, y, x);
  1770. getmaxyx(logwin, logy, logx);
  1771. y -= logcursor;
  1772. /* Detect screen size change */
  1773. if (x != logx || y != logy)
  1774. wresize(logwin, y, x);
  1775. for (i = 0; i < mining_threads; i++) {
  1776. if (active_device(i))
  1777. curses_print_status(i);
  1778. }
  1779. redrawwin(logwin);
  1780. redrawwin(statuswin);
  1781. pthread_mutex_unlock(&curses_lock);
  1782. }
  1783. if (unlikely(work_restart[watchdog_thr_id].restart)) {
  1784. restart_threads(false);
  1785. work_restart[watchdog_thr_id].restart = 0;
  1786. }
  1787. gettimeofday(&now, NULL);
  1788. #if 0
  1789. for (i = 0; i < mining_threads; i++) {
  1790. #else
  1791. for (i = 0; i < gpu_threads; i++) {
  1792. #endif
  1793. struct thr_info *thr = &thr_info[i];
  1794. /* Do not kill threads waiting on longpoll staged work
  1795. * or idle network */
  1796. if (now.tv_sec - thr->last.tv_sec > 60 && !idlenet) {
  1797. applog(LOG_ERR, "Attempting to restart thread %d, idle for more than 60 seconds", i);
  1798. /* Create one mandatory work item */
  1799. inc_staged(1, true);
  1800. if (unlikely(!queue_request())) {
  1801. applog(LOG_ERR, "Failed to queue_request in watchdog_thread");
  1802. kill_work();
  1803. break;
  1804. }
  1805. reinit_thread(i);
  1806. applog(LOG_WARNING, "Thread %d restarted", i);
  1807. }
  1808. }
  1809. }
  1810. return NULL;
  1811. }
  1812. static void print_summary(void)
  1813. {
  1814. struct timeval diff;
  1815. int hours, mins, secs, i;
  1816. double utility, efficiency = 0.0;
  1817. timeval_subtract(&diff, &total_tv_end, &total_tv_start);
  1818. hours = diff.tv_sec / 3600;
  1819. mins = (diff.tv_sec % 3600) / 60;
  1820. secs = diff.tv_sec % 60;
  1821. utility = accepted / ( total_secs ? total_secs : 1 ) * 60;
  1822. efficiency = getwork_requested ? accepted * 100.0 / getwork_requested : 0.0;
  1823. printf("\nSummary of runtime statistics:\n\n");
  1824. printf("Started at %s\n", datestamp);
  1825. printf("Runtime: %d hrs : %d mins : %d secs\n", hours, mins, secs);
  1826. if (total_secs)
  1827. printf("Average hashrate: %.1f Megahash/s\n", total_mhashes_done / total_secs);
  1828. printf("Queued work requests: %d\n", getwork_requested);
  1829. printf("Share submissions: %d\n", accepted + rejected);
  1830. printf("Accepted shares: %d\n", accepted);
  1831. printf("Rejected shares: %d\n", rejected);
  1832. if (accepted || rejected)
  1833. printf("Reject ratio: %.1f\n", (double)(rejected * 100) / (double)(accepted + rejected));
  1834. printf("Hardware errors: %d\n", hw_errors);
  1835. printf("Efficiency (accepted / queued): %.0f%%\n", efficiency);
  1836. printf("Utility (accepted shares / min): %.2f/min\n\n", utility);
  1837. printf("Discarded work due to new blocks: %d\n", discarded_work);
  1838. printf("Stale submissions discarded due to new blocks: %d\n", stale_shares);
  1839. printf("Unable to get work from server occasions: %d\n", localgen_occasions);
  1840. printf("Work items generated locally: %d\n", local_work);
  1841. printf("Submitting work remotely delay occasions: %d\n", remotefail_occasions);
  1842. printf("New blocks detected on network: %d\n\n", new_blocks);
  1843. printf("Summary of per device statistics:\n\n");
  1844. for (i = 0; i < mining_threads; i++) {
  1845. if (active_device(i))
  1846. print_status(i);
  1847. }
  1848. printf("\n");
  1849. }
  1850. int main (int argc, char *argv[])
  1851. {
  1852. unsigned int i, j = 0, x, y;
  1853. struct sigaction handler;
  1854. struct thr_info *thr;
  1855. char name[256];
  1856. struct tm tm;
  1857. /* This dangerous functions tramples random dynamically allocated
  1858. * variables so do it before anything at all */
  1859. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  1860. return 1;
  1861. if (unlikely(pthread_mutex_init(&hash_lock, NULL)))
  1862. return 1;
  1863. if (unlikely(pthread_mutex_init(&qd_lock, NULL)))
  1864. return 1;
  1865. if (unlikely(pthread_mutex_init(&stgd_lock, NULL)))
  1866. return 1;
  1867. if (unlikely(pthread_mutex_init(&curses_lock, NULL)))
  1868. return 1;
  1869. if (unlikely(pthread_mutex_init(&control_lock, NULL)))
  1870. return 1;
  1871. handler.sa_handler = &sighandler;
  1872. sigaction(SIGTERM, &handler, &termhandler);
  1873. sigaction(SIGINT, &handler, &inthandler);
  1874. gettimeofday(&total_tv_start, NULL);
  1875. gettimeofday(&total_tv_end, NULL);
  1876. localtime_r(&total_tv_start.tv_sec, &tm);
  1877. sprintf(datestamp, "[%d-%02d-%02d %02d:%02d:%02d]",
  1878. tm.tm_year + 1900,
  1879. tm.tm_mon + 1,
  1880. tm.tm_mday,
  1881. tm.tm_hour,
  1882. tm.tm_min,
  1883. tm.tm_sec);
  1884. for (i = 0; i < 36; i++) {
  1885. strcat(blank, "0");
  1886. strcat(current_block, "0");
  1887. strcat(longpoll_block, "0");
  1888. }
  1889. #ifdef WIN32
  1890. opt_n_threads = num_processors = 1;
  1891. #else
  1892. num_processors = sysconf(_SC_NPROCESSORS_ONLN);
  1893. opt_n_threads = num_processors;
  1894. #endif /* !WIN32 */
  1895. #ifdef HAVE_OPENCL
  1896. for (i = 0; i < 16; i++)
  1897. gpu_devices[i] = false;
  1898. nDevs = clDevicesNum();
  1899. if (nDevs < 0)
  1900. return 1;
  1901. #endif
  1902. if (nDevs)
  1903. opt_n_threads = 0;
  1904. rpc_url = strdup(DEF_RPC_URL);
  1905. /* parse command line */
  1906. opt_register_table(opt_config_table,
  1907. "Options for both config file and command line");
  1908. opt_register_table(opt_cmdline_table,
  1909. "Options for command line only");
  1910. opt_parse(&argc, argv, applog_and_exit);
  1911. if (argc != 1) {
  1912. applog(LOG_ERR, "Unexpected extra commandline arguments");
  1913. return 1;
  1914. }
  1915. if (total_devices) {
  1916. if (total_devices > nDevs) {
  1917. applog(LOG_ERR, "More devices specified than exist");
  1918. return 1;
  1919. }
  1920. for (i = 0; i < 16; i++)
  1921. if (gpu_devices[i] && i + 1 > nDevs) {
  1922. applog(LOG_ERR, "Command line options set a device that doesn't exist");
  1923. return 1;
  1924. }
  1925. gpu_threads = total_devices * opt_g_threads;
  1926. } else {
  1927. gpu_threads = nDevs * opt_g_threads;
  1928. for (i = 0; i < nDevs; i++)
  1929. gpu_devices[i] = true;
  1930. total_devices = nDevs;
  1931. }
  1932. if (!gpu_threads && !forced_n_threads) {
  1933. /* Maybe they turned GPU off; restore default CPU threads. */
  1934. opt_n_threads = num_processors;
  1935. }
  1936. logcursor = 7;
  1937. mining_threads = opt_n_threads + gpu_threads;
  1938. gpucursor = logcursor;
  1939. cpucursor = gpucursor + nDevs;
  1940. logstart = cpucursor + (opt_n_threads ? num_processors : 0) + 1;
  1941. logcursor = logstart + 1;
  1942. if (!rpc_userpass) {
  1943. if (!rpc_user || !rpc_pass) {
  1944. applog(LOG_ERR, "No login credentials supplied");
  1945. return 1;
  1946. }
  1947. rpc_userpass = malloc(strlen(rpc_user) + strlen(rpc_pass) + 2);
  1948. if (!rpc_userpass)
  1949. return 1;
  1950. sprintf(rpc_userpass, "%s:%s", rpc_user, rpc_pass);
  1951. } else {
  1952. rpc_user = malloc(strlen(rpc_userpass));
  1953. if (!rpc_user)
  1954. return 1;
  1955. strcpy(rpc_user, rpc_userpass);
  1956. rpc_user = strtok(rpc_user, ":");
  1957. if (!rpc_user) {
  1958. applog(LOG_ERR, "Failed to find colon delimiter in userpass");
  1959. return 1;
  1960. }
  1961. }
  1962. #ifdef HAVE_SYSLOG_H
  1963. if (use_syslog)
  1964. openlog("cpuminer", LOG_PID, LOG_USER);
  1965. #endif
  1966. work_restart = calloc(mining_threads + 4, sizeof(*work_restart));
  1967. if (!work_restart)
  1968. return 1;
  1969. thr_info = calloc(mining_threads + 4, sizeof(*thr));
  1970. if (!thr_info)
  1971. return 1;
  1972. /* init workio thread info */
  1973. work_thr_id = mining_threads;
  1974. thr = &thr_info[work_thr_id];
  1975. thr->id = work_thr_id;
  1976. thr->q = tq_new();
  1977. if (!thr->q)
  1978. return 1;
  1979. /* start work I/O thread */
  1980. if (pthread_create(&thr->pth, NULL, workio_thread, thr)) {
  1981. applog(LOG_ERR, "workio thread create failed");
  1982. return 1;
  1983. }
  1984. /* init longpoll thread info */
  1985. if (want_longpoll) {
  1986. longpoll_thr_id = mining_threads + 1;
  1987. thr = &thr_info[longpoll_thr_id];
  1988. thr->id = longpoll_thr_id;
  1989. thr->q = tq_new();
  1990. if (!thr->q)
  1991. return 1;
  1992. /* start longpoll thread */
  1993. if (unlikely(pthread_create(&thr->pth, NULL, longpoll_thread, thr))) {
  1994. applog(LOG_ERR, "longpoll thread create failed");
  1995. return 1;
  1996. }
  1997. pthread_detach(thr->pth);
  1998. } else
  1999. longpoll_thr_id = -1;
  2000. if (opt_n_threads ) {
  2001. cpus = calloc(num_processors, sizeof(struct cgpu_info));
  2002. if (unlikely(!cpus)) {
  2003. applog(LOG_ERR, "Failed to calloc cpus");
  2004. return 1;
  2005. }
  2006. }
  2007. if (gpu_threads) {
  2008. gpus = calloc(nDevs, sizeof(struct cgpu_info));
  2009. if (unlikely(!gpus)) {
  2010. applog(LOG_ERR, "Failed to calloc gpus");
  2011. return 1;
  2012. }
  2013. }
  2014. stage_thr_id = mining_threads + 3;
  2015. thr = &thr_info[stage_thr_id];
  2016. thr->q = tq_new();
  2017. if (!thr->q)
  2018. return 1;
  2019. /* start stage thread */
  2020. if (pthread_create(&thr->pth, NULL, stage_thread, thr)) {
  2021. applog(LOG_ERR, "stage thread create failed");
  2022. return 1;
  2023. }
  2024. /* Flag the work as ready forcing the mining threads to wait till we
  2025. * actually put something into the queue */
  2026. inc_staged(mining_threads, true);
  2027. /* Create a unique get work queue */
  2028. getq = tq_new();
  2029. if (!getq) {
  2030. applog(LOG_ERR, "Failed to create getq");
  2031. return 1;
  2032. }
  2033. #ifdef HAVE_OPENCL
  2034. i = 0;
  2035. /* start GPU mining threads */
  2036. for (j = 0; j < nDevs * opt_g_threads; j++) {
  2037. int gpu = j % nDevs;
  2038. gpus[gpu].is_gpu = 1;
  2039. gpus[gpu].cpu_gpu = gpu;
  2040. /* Skip devices not set to mine */
  2041. if (!gpu_devices[gpu])
  2042. continue;
  2043. thr = &thr_info[i];
  2044. thr->id = i;
  2045. thr->cgpu = &gpus[gpu];
  2046. thr->q = tq_new();
  2047. if (!thr->q) {
  2048. applog(LOG_ERR, "tq_new failed in starting gpu mining threads");
  2049. return 1;
  2050. }
  2051. applog(LOG_INFO, "Init GPU thread %i", i);
  2052. clStates[i] = initCl(gpu, name, sizeof(name));
  2053. if (!clStates[i]) {
  2054. applog(LOG_ERR, "Failed to init GPU thread %d", i);
  2055. continue;
  2056. }
  2057. applog(LOG_INFO, "initCl() finished. Found %s", name);
  2058. gettimeofday(&thr->last, NULL);
  2059. if (unlikely(pthread_create(&thr->pth, NULL, gpuminer_thread, thr))) {
  2060. applog(LOG_ERR, "thread %d create failed", i);
  2061. return 1;
  2062. }
  2063. i++;
  2064. }
  2065. applog(LOG_INFO, "%d gpu miner threads started", gpu_threads);
  2066. #endif
  2067. /* start CPU mining threads */
  2068. for (i = gpu_threads; i < mining_threads; i++) {
  2069. int cpu = (i - gpu_threads) % num_processors;
  2070. thr = &thr_info[i];
  2071. thr->id = i;
  2072. cpus[cpu].cpu_gpu = cpu;
  2073. thr->cgpu = &cpus[cpu];
  2074. thr->q = tq_new();
  2075. if (!thr->q) {
  2076. applog(LOG_ERR, "tq_new failed in starting cpu mining threads");
  2077. return 1;
  2078. }
  2079. gettimeofday(&thr->last, NULL);
  2080. if (unlikely(pthread_create(&thr->pth, NULL, miner_thread, thr))) {
  2081. applog(LOG_ERR, "thread %d create failed", i);
  2082. return 1;
  2083. }
  2084. }
  2085. applog(LOG_INFO, "%d cpu miner threads started, "
  2086. "using SHA256 '%s' algorithm.",
  2087. opt_n_threads,
  2088. algo_names[opt_algo]);
  2089. watchdog_thr_id = mining_threads + 2;
  2090. thr = &thr_info[watchdog_thr_id];
  2091. /* start wakeup thread */
  2092. if (pthread_create(&thr->pth, NULL, watchdog_thread, NULL)) {
  2093. applog(LOG_ERR, "wakeup thread create failed");
  2094. return 1;
  2095. }
  2096. /* Restart count as it will be wrong till all threads are started */
  2097. pthread_mutex_lock(&hash_lock);
  2098. gettimeofday(&total_tv_start, NULL);
  2099. gettimeofday(&total_tv_end, NULL);
  2100. total_mhashes_done = 0;
  2101. pthread_mutex_unlock(&hash_lock);
  2102. /* Set up the ncurses interface */
  2103. if (!opt_quiet && use_curses) {
  2104. mainwin = initscr();
  2105. getmaxyx(mainwin, y, x);
  2106. statuswin = newwin(logstart, x, 0, 0);
  2107. logwin = newwin(y - logcursor, 0, logcursor, 0);
  2108. idlok(logwin, true);
  2109. scrollok(logwin, true);
  2110. leaveok(logwin, true);
  2111. leaveok(statuswin, true);
  2112. test_and_set(&curses_active);
  2113. for (i = 0; i < mining_threads; i++)
  2114. print_status(i);
  2115. }
  2116. /* Now that everything's ready put enough work in the queue */
  2117. for (i = 0; i < opt_queue + mining_threads; i++) {
  2118. if (unlikely(!queue_request())) {
  2119. applog(LOG_ERR, "Failed to queue_request in main");
  2120. return 1;
  2121. }
  2122. }
  2123. /* main loop - simply wait for workio thread to exit */
  2124. pthread_join(thr_info[work_thr_id].pth, NULL);
  2125. applog(LOG_INFO, "workio thread dead, exiting.");
  2126. gettimeofday(&total_tv_end, NULL);
  2127. disable_curses();
  2128. if (!opt_quiet && successful_connect)
  2129. print_summary();
  2130. if (gpu_threads)
  2131. free(gpus);
  2132. if (opt_n_threads)
  2133. free(cpus);
  2134. curl_global_cleanup();
  2135. return 0;
  2136. }