main.c 76 KB

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