main.c 82 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204
  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 bool opt_loginput = false;
  120. static int opt_retries = -1;
  121. static int opt_fail_pause = 5;
  122. static int opt_log_interval = 5;
  123. bool opt_log_output = false;
  124. static bool opt_dynamic = true;
  125. static int opt_queue;
  126. int opt_vectors;
  127. int opt_worksize;
  128. int opt_scantime = 60;
  129. static const bool opt_time = true;
  130. #ifdef WANT_X8664_SSE4
  131. static enum sha256_algos opt_algo = ALGO_SSE4_64;
  132. #elif WANT_X8664_SSE2
  133. static enum sha256_algos opt_algo = ALGO_SSE2_64;
  134. #else
  135. static enum sha256_algos opt_algo = ALGO_C;
  136. #endif
  137. static int nDevs;
  138. static int opt_g_threads = 2;
  139. static int opt_device;
  140. static int total_devices;
  141. static bool gpu_devices[16];
  142. static int gpu_threads;
  143. static bool forced_n_threads;
  144. static int opt_n_threads;
  145. static int mining_threads;
  146. static int num_processors;
  147. static int scan_intensity;
  148. static bool use_curses = true;
  149. struct thr_info *thr_info;
  150. static int work_thr_id;
  151. int longpoll_thr_id;
  152. static int stage_thr_id;
  153. static int watchdog_thr_id;
  154. static int input_thr_id;
  155. static int total_threads;
  156. struct work_restart *work_restart = NULL;
  157. static pthread_mutex_t hash_lock;
  158. static pthread_mutex_t qd_lock;
  159. static pthread_mutex_t stgd_lock;
  160. static pthread_mutex_t curses_lock;
  161. static double total_mhashes_done;
  162. static struct timeval total_tv_start, total_tv_end;
  163. pthread_mutex_t control_lock;
  164. int hw_errors;
  165. static int total_accepted, total_rejected;
  166. static int total_getworks, total_stale, total_discarded;
  167. static int total_queued, total_staged, lp_staged;
  168. static unsigned int new_blocks;
  169. static unsigned int local_work;
  170. static unsigned int total_lo, total_ro;
  171. #define MAX_POOLS (32)
  172. static struct pool *pools[MAX_POOLS];
  173. static struct pool *currentpool = NULL;
  174. static int total_pools;
  175. static enum pool_strategy pool_strategy = POOL_FAILOVER;
  176. static int opt_rotate_period;
  177. static int total_urls, total_users, total_passes, total_userpasses;
  178. static bool curses_active = false;
  179. static char current_block[37];
  180. static char longpoll_block[37];
  181. static char blank[37];
  182. static char datestamp[40];
  183. static char blockdate[40];
  184. struct sigaction termhandler, inthandler;
  185. struct thread_q *getq;
  186. static void applog_and_exit(const char *fmt, ...)
  187. {
  188. va_list ap;
  189. va_start(ap, fmt);
  190. vapplog(LOG_ERR, fmt, ap);
  191. va_end(ap);
  192. exit(1);
  193. }
  194. static void add_pool(void)
  195. {
  196. struct pool *pool;
  197. pool = calloc(sizeof(struct pool), 1);
  198. if (!pool) {
  199. applog(LOG_ERR, "Failed to malloc pool in add_pool");
  200. exit (1);
  201. }
  202. pool->pool_no = total_pools;
  203. pools[total_pools++] = pool;
  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. if (!opt_loginput) {
  685. pthread_mutex_lock(&curses_lock);
  686. vw_printw(logwin, f, ap);
  687. wrefresh(logwin);
  688. pthread_mutex_unlock(&curses_lock);
  689. }
  690. } else
  691. vprintf(f, ap);
  692. }
  693. static void clear_logwin(void)
  694. {
  695. pthread_mutex_lock(&curses_lock);
  696. wclear(logwin);
  697. wrefresh(logwin);
  698. pthread_mutex_unlock(&curses_lock);
  699. }
  700. static bool submit_upstream_work(const struct work *work)
  701. {
  702. char *hexstr = NULL;
  703. json_t *val, *res;
  704. char s[345];
  705. bool rc = false;
  706. int thr_id = work->thr_id;
  707. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  708. CURL *curl = curl_easy_init();
  709. struct pool *pool = work->pool;
  710. if (unlikely(!curl)) {
  711. applog(LOG_ERR, "CURL initialisation failed");
  712. return rc;
  713. }
  714. /* build hex string */
  715. hexstr = bin2hex(work->data, sizeof(work->data));
  716. if (unlikely(!hexstr)) {
  717. applog(LOG_ERR, "submit_upstream_work OOM");
  718. goto out_nofree;
  719. }
  720. /* build JSON-RPC request */
  721. sprintf(s,
  722. "{\"method\": \"getwork\", \"params\": [ \"%s\" ], \"id\":1}\r\n",
  723. hexstr);
  724. if (opt_debug)
  725. applog(LOG_DEBUG, "DBG: sending RPC call: %s", s);
  726. /* issue JSON-RPC request */
  727. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, s, false, false, pool);
  728. if (unlikely(!val)) {
  729. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  730. if (!pool_tset(pool, &pool->submit_fail)) {
  731. total_ro++;
  732. pool->remotefail_occasions++;
  733. applog(LOG_WARNING, "Pool %d communication failure, caching submissions", pool->pool_no);
  734. }
  735. goto out;
  736. } else if (pool_tclear(pool, &pool->submit_fail))
  737. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  738. res = json_object_get(val, "result");
  739. /* Theoretically threads could race when modifying accepted and
  740. * rejected values but the chance of two submits completing at the
  741. * same time is zero so there is no point adding extra locking */
  742. if (json_is_true(res)) {
  743. cgpu->accepted++;
  744. total_accepted++;
  745. pool->accepted++;
  746. if (opt_debug)
  747. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  748. if (!opt_quiet) {
  749. if (total_pools > 1)
  750. applog(LOG_WARNING, "Accepted %.8s %sPU %d thread %d pool %d",
  751. hexstr + 152, cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, thr_id, work->pool->pool_no);
  752. else
  753. applog(LOG_WARNING, "Accepted %.8s %sPU %d thread %d",
  754. hexstr + 152, cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, thr_id);
  755. }
  756. } else {
  757. cgpu->rejected++;
  758. total_rejected++;
  759. pool->rejected++;
  760. if (opt_debug)
  761. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  762. if (!opt_quiet) {
  763. if (total_pools > 1)
  764. applog(LOG_WARNING, "Rejected %.8s %sPU %d thread %d pool %d",
  765. hexstr + 152, cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, thr_id, work->pool->pool_no);
  766. else
  767. applog(LOG_WARNING, "Rejected %.8s %sPU %d thread %d",
  768. hexstr + 152, cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, thr_id);
  769. }
  770. }
  771. cgpu->utility = cgpu->accepted / ( total_secs ? total_secs : 1 ) * 60;
  772. cgpu->efficiency = cgpu->getworks ? cgpu->accepted * 100.0 / cgpu->getworks : 0.0;
  773. if (!opt_quiet)
  774. print_status(thr_id);
  775. applog(LOG_INFO, "%sPU %d Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m",
  776. cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, cgpu->getworks, cgpu->accepted,
  777. cgpu->rejected, cgpu->hw_errors, cgpu->efficiency, cgpu->utility);
  778. json_decref(val);
  779. rc = true;
  780. out:
  781. free(hexstr);
  782. out_nofree:
  783. curl_easy_cleanup(curl);
  784. return rc;
  785. }
  786. static const char *rpc_req =
  787. "{\"method\": \"getwork\", \"params\": [], \"id\":0}\r\n";
  788. static int rotating_pool;
  789. /* Select any active pool in a rotating fashion when loadbalance is chosen */
  790. static inline struct pool *select_pool(void)
  791. {
  792. if (pool_strategy == POOL_LOADBALANCE) {
  793. struct pool *pool;
  794. rotating_pool++;
  795. if (rotating_pool >= total_pools)
  796. rotating_pool = 0;
  797. pool = pools[rotating_pool];
  798. if (!pool->idle && pool->enabled)
  799. return pools[rotating_pool];
  800. }
  801. return current_pool();
  802. }
  803. static bool get_upstream_work(struct work *work)
  804. {
  805. struct pool *pool = select_pool();
  806. json_t *val;
  807. bool rc = false;
  808. CURL *curl = curl_easy_init();
  809. if (unlikely(!curl)) {
  810. applog(LOG_ERR, "CURL initialisation failed");
  811. return rc;
  812. }
  813. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  814. want_longpoll, false, pool);
  815. if (unlikely(!val)) {
  816. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  817. goto out;
  818. }
  819. rc = work_decode(json_object_get(val, "result"), work);
  820. work->pool = pool;
  821. total_getworks++;
  822. pool->getwork_requested++;
  823. json_decref(val);
  824. out:
  825. curl_easy_cleanup(curl);
  826. return rc;
  827. }
  828. static void workio_cmd_free(struct workio_cmd *wc)
  829. {
  830. if (!wc)
  831. return;
  832. switch (wc->cmd) {
  833. case WC_SUBMIT_WORK:
  834. free(wc->u.work);
  835. break;
  836. default: /* do nothing */
  837. break;
  838. }
  839. memset(wc, 0, sizeof(*wc)); /* poison */
  840. free(wc);
  841. }
  842. static void disable_curses(void)
  843. {
  844. if (test_and_clear(&curses_active)) {
  845. nocbreak();
  846. echo();
  847. delwin(logwin);
  848. delwin(statuswin);
  849. delwin(mainwin);
  850. endwin();
  851. refresh();
  852. }
  853. }
  854. void kill_work(void)
  855. {
  856. struct workio_cmd *wc;
  857. struct thr_info *thr;
  858. unsigned int i;
  859. disable_curses();
  860. applog(LOG_INFO, "Received kill message");
  861. /* Kill the watchdog thread */
  862. thr = &thr_info[watchdog_thr_id];
  863. pthread_cancel(thr->pth);
  864. /* Stop the mining threads*/
  865. for (i = 0; i < mining_threads; i++) {
  866. thr = &thr_info[i];
  867. if (!thr->pth)
  868. continue;
  869. tq_freeze(thr->q);
  870. /* No need to check if this succeeds or not */
  871. pthread_cancel(thr->pth);
  872. }
  873. /* Stop the others */
  874. thr = &thr_info[stage_thr_id];
  875. pthread_cancel(thr->pth);
  876. thr = &thr_info[longpoll_thr_id];
  877. pthread_cancel(thr->pth);
  878. wc = calloc(1, sizeof(*wc));
  879. if (unlikely(!wc)) {
  880. applog(LOG_ERR, "Failed to calloc wc in kill_work");
  881. /* We're just trying to die anyway, so forget graceful */
  882. exit (1);
  883. }
  884. wc->cmd = WC_DIE;
  885. wc->thr = 0;
  886. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  887. applog(LOG_ERR, "Failed to tq_push work in kill_work");
  888. exit (1);
  889. }
  890. }
  891. static void sighandler(int sig)
  892. {
  893. /* Restore signal handlers so we can still quit if kill_work fails */
  894. sigaction(SIGTERM, &termhandler, NULL);
  895. sigaction(SIGINT, &inthandler, NULL);
  896. kill_work();
  897. }
  898. static void *get_work_thread(void *userdata)
  899. {
  900. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  901. struct work *ret_work;
  902. int failures = 0;
  903. pthread_detach(pthread_self());
  904. ret_work = calloc(1, sizeof(*ret_work));
  905. if (unlikely(!ret_work)) {
  906. applog(LOG_ERR, "Failed to calloc ret_work in workio_get_work");
  907. kill_work();
  908. goto out;
  909. }
  910. /* obtain new work from bitcoin via JSON-RPC */
  911. while (!get_upstream_work(ret_work)) {
  912. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  913. applog(LOG_ERR, "json_rpc_call failed, terminating workio thread");
  914. free(ret_work);
  915. kill_work();
  916. goto out;
  917. }
  918. /* pause, then restart work-request loop */
  919. applog(LOG_DEBUG, "json_rpc_call failed on get work, retry after %d seconds",
  920. opt_fail_pause);
  921. sleep(opt_fail_pause);
  922. }
  923. /* send work to requesting thread */
  924. if (unlikely(!tq_push(thr_info[stage_thr_id].q, ret_work))) {
  925. applog(LOG_ERR, "Failed to tq_push work in workio_get_work");
  926. kill_work();
  927. free(ret_work);
  928. }
  929. out:
  930. workio_cmd_free(wc);
  931. return NULL;
  932. }
  933. static bool workio_get_work(struct workio_cmd *wc)
  934. {
  935. pthread_t get_thread;
  936. if (unlikely(pthread_create(&get_thread, NULL, get_work_thread, (void *)wc))) {
  937. applog(LOG_ERR, "Failed to create get_work_thread");
  938. return false;
  939. }
  940. return true;
  941. }
  942. static bool stale_work(struct work *work)
  943. {
  944. bool ret = false;
  945. char *hexstr;
  946. /* Only use the primary pool for determination as the work may
  947. * interleave at times of new blocks */
  948. if (work->pool != current_pool())
  949. return ret;
  950. if (!strncmp(blank, current_block, 36))
  951. return ret;
  952. hexstr = bin2hex(work->data, 36);
  953. if (unlikely(!hexstr)) {
  954. applog(LOG_ERR, "submit_work_thread OOM");
  955. return ret;
  956. }
  957. if (strncmp(hexstr, current_block, 36))
  958. ret = true;
  959. free(hexstr);
  960. return ret;
  961. }
  962. static void *submit_work_thread(void *userdata)
  963. {
  964. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  965. struct work *work = wc->u.work;
  966. struct pool *pool = work->pool;
  967. int failures = 0;
  968. pthread_detach(pthread_self());
  969. if (stale_work(work)) {
  970. applog(LOG_WARNING, "Stale share detected, discarding");
  971. total_stale++;
  972. pool->stale_shares++;
  973. goto out;
  974. }
  975. /* submit solution to bitcoin via JSON-RPC */
  976. while (!submit_upstream_work(work)) {
  977. if (stale_work(work)) {
  978. applog(LOG_WARNING, "Stale share detected, discarding");
  979. total_stale++;
  980. pool->stale_shares++;
  981. break;
  982. }
  983. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  984. applog(LOG_ERR, "Failed %d retries ...terminating workio thread", opt_retries);
  985. kill_work();
  986. break;
  987. }
  988. /* pause, then restart work-request loop */
  989. applog(LOG_INFO, "json_rpc_call failed on submit_work, retry after %d seconds",
  990. opt_fail_pause);
  991. sleep(opt_fail_pause);
  992. }
  993. out:
  994. workio_cmd_free(wc);
  995. return NULL;
  996. }
  997. static bool workio_submit_work(struct workio_cmd *wc)
  998. {
  999. pthread_t submit_thread;
  1000. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, (void *)wc))) {
  1001. applog(LOG_ERR, "Failed to create submit_work_thread");
  1002. return false;
  1003. }
  1004. return true;
  1005. }
  1006. static void inc_staged(struct pool *pool, int inc, bool lp)
  1007. {
  1008. pthread_mutex_lock(&stgd_lock);
  1009. if (lp) {
  1010. lp_staged += inc;
  1011. total_staged += inc;
  1012. } else if (lp_staged)
  1013. --lp_staged;
  1014. else
  1015. total_staged += inc;
  1016. pthread_mutex_unlock(&stgd_lock);
  1017. }
  1018. static void dec_staged(int inc)
  1019. {
  1020. pthread_mutex_lock(&stgd_lock);
  1021. total_staged -= inc;
  1022. pthread_mutex_unlock(&stgd_lock);
  1023. }
  1024. static int requests_staged(void)
  1025. {
  1026. int ret;
  1027. pthread_mutex_lock(&stgd_lock);
  1028. ret = total_staged;
  1029. pthread_mutex_unlock(&stgd_lock);
  1030. return ret;
  1031. }
  1032. static int real_staged(void)
  1033. {
  1034. int ret;
  1035. pthread_mutex_lock(&stgd_lock);
  1036. ret = total_staged - lp_staged;
  1037. pthread_mutex_unlock(&stgd_lock);
  1038. return ret;
  1039. }
  1040. /* Find the pool that currently has the highest priority */
  1041. static struct pool *priority_pool(int choice)
  1042. {
  1043. struct pool *ret = NULL;
  1044. int i;
  1045. for (i = 0; i < total_pools; i++) {
  1046. struct pool *pool = pools[i];
  1047. if (pool->prio == choice) {
  1048. ret = pool;
  1049. break;
  1050. }
  1051. }
  1052. if (unlikely(!ret)) {
  1053. applog(LOG_ERR, "WTF No pool %d found!", choice);
  1054. return pools[choice];
  1055. }
  1056. return ret;
  1057. }
  1058. static void switch_pools(struct pool *selected)
  1059. {
  1060. struct pool *pool, *last_pool;
  1061. int i, pool_no;
  1062. pthread_mutex_lock(&control_lock);
  1063. last_pool = currentpool;
  1064. pool_no = currentpool->pool_no;
  1065. /* Switch selected to pool number 0 and move the rest down */
  1066. if (selected) {
  1067. if (selected->prio != 0) {
  1068. for (i = 0; i < total_pools; i++) {
  1069. pool = pools[i];
  1070. if (pool->prio < selected->prio)
  1071. pool->prio++;
  1072. }
  1073. selected->prio = 0;
  1074. }
  1075. }
  1076. switch (pool_strategy) {
  1077. /* Both of these set to the master pool */
  1078. case POOL_FAILOVER:
  1079. case POOL_LOADBALANCE:
  1080. for (i = 0; i < total_pools; i++) {
  1081. pool = priority_pool(i);
  1082. if (!pool->idle && pool->enabled) {
  1083. pool_no = pool->pool_no;
  1084. break;
  1085. }
  1086. }
  1087. break;
  1088. /* Both of these simply increment and cycle */
  1089. case POOL_ROUNDROBIN:
  1090. case POOL_ROTATE:
  1091. if (selected) {
  1092. pool_no = selected->pool_no;
  1093. break;
  1094. }
  1095. pool_no++;
  1096. if (pool_no >= total_pools)
  1097. pool_no = 0;
  1098. break;
  1099. default:
  1100. break;
  1101. }
  1102. currentpool = pools[pool_no];
  1103. pool = currentpool;
  1104. pthread_mutex_unlock(&control_lock);
  1105. if (pool != last_pool)
  1106. applog(LOG_WARNING, "Switching to %s", pool->rpc_url);
  1107. /* Reset the queued amount to allow more to be queued for the new pool */
  1108. pthread_mutex_lock(&qd_lock);
  1109. total_queued = 0;
  1110. pthread_mutex_unlock(&qd_lock);
  1111. inc_staged(pool, 1, true);
  1112. }
  1113. static void set_curblock(char *hexstr)
  1114. {
  1115. struct timeval tv_now;
  1116. struct tm tm;
  1117. memcpy(current_block, hexstr, 36);
  1118. gettimeofday(&tv_now, NULL);
  1119. localtime_r(&tv_now.tv_sec, &tm);
  1120. sprintf(blockdate, "[%d-%02d-%02d %02d:%02d:%02d]",
  1121. tm.tm_year + 1900,
  1122. tm.tm_mon + 1,
  1123. tm.tm_mday,
  1124. tm.tm_hour,
  1125. tm.tm_min,
  1126. tm.tm_sec);
  1127. }
  1128. static void test_work_current(struct work *work)
  1129. {
  1130. char *hexstr;
  1131. /* Only use the primary pool for determination */
  1132. if (work->pool != current_pool())
  1133. return;
  1134. hexstr = bin2hex(work->data, 36);
  1135. if (unlikely(!hexstr)) {
  1136. applog(LOG_ERR, "stage_thread OOM");
  1137. return;
  1138. }
  1139. /* current_block is blanked out on successful longpoll */
  1140. if (likely(strncmp(current_block, blank, 36))) {
  1141. if (unlikely(strncmp(hexstr, current_block, 36))) {
  1142. new_blocks++;
  1143. if (have_longpoll)
  1144. applog(LOG_WARNING, "New block detected on network before longpoll, waiting on fresh work");
  1145. else
  1146. applog(LOG_WARNING, "New block detected on network, waiting on fresh work");
  1147. /* As we can't flush the work from here, signal the
  1148. * wakeup thread to restart all the threads */
  1149. work_restart[watchdog_thr_id].restart = 1;
  1150. set_curblock(hexstr);
  1151. }
  1152. } else {
  1153. set_curblock(hexstr);
  1154. memcpy(longpoll_block, hexstr, 36);
  1155. }
  1156. free(hexstr);
  1157. }
  1158. static void *stage_thread(void *userdata)
  1159. {
  1160. struct thr_info *mythr = userdata;
  1161. bool ok = true;
  1162. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  1163. while (ok) {
  1164. struct work *work = NULL;
  1165. work = tq_pop(mythr->q, NULL);
  1166. if (unlikely(!work)) {
  1167. applog(LOG_ERR, "Failed to tq_pop in stage_thread");
  1168. ok = false;
  1169. break;
  1170. }
  1171. test_work_current(work);
  1172. if (unlikely(!tq_push(getq, work))) {
  1173. applog(LOG_ERR, "Failed to tq_push work in stage_thread");
  1174. ok = false;
  1175. break;
  1176. }
  1177. inc_staged(work->pool, 1, false);
  1178. }
  1179. tq_freeze(mythr->q);
  1180. return NULL;
  1181. }
  1182. static char *curses_input(const char *query);
  1183. static int curses_int(const char *query)
  1184. {
  1185. int ret;
  1186. char *cvar;
  1187. cvar = curses_input(query);
  1188. ret = atoi(cvar);
  1189. free(cvar);
  1190. return ret;
  1191. }
  1192. static bool input_pool(bool live);
  1193. static void display_pools(void)
  1194. {
  1195. int i, active = 0;
  1196. struct pool *pool;
  1197. int selected;
  1198. char input;
  1199. opt_loginput = true;
  1200. updated:
  1201. clear_logwin();
  1202. pthread_mutex_lock(&curses_lock);
  1203. for (i = 0; i < total_pools; i++) {
  1204. pool = pools[i];
  1205. if (pool == current_pool())
  1206. wattron(logwin, A_BOLD);
  1207. if (!pool->enabled)
  1208. wattron(logwin, A_DIM);
  1209. wprintw(logwin, "%s Pool %d: %s User:%s\n", pool->enabled? "Enabled" : "Disabled",
  1210. pool->pool_no, pool->rpc_url, pool->rpc_user);
  1211. wattroff(logwin, A_BOLD | A_DIM);
  1212. }
  1213. retry:
  1214. wprintw(logwin, "\n[A]dd pool [S]witch pool [D]isable pool [E]nable pool\n");
  1215. wprintw(logwin, "Or press any other key to continue\n");
  1216. wrefresh(logwin);
  1217. pthread_mutex_unlock(&curses_lock);
  1218. input = getch();
  1219. if (!strncasecmp(&input, "a", 1)) {
  1220. input_pool(true);
  1221. goto updated;
  1222. } else if (!strncasecmp(&input, "s", 1)) {
  1223. selected = curses_int("Select pool number");
  1224. if (selected < 0 || selected >= total_pools) {
  1225. wprintw(logwin, "Invalid selection");
  1226. goto retry;
  1227. }
  1228. pool = pools[selected];
  1229. pool->enabled = true;
  1230. switch_pools(pool);
  1231. goto updated;
  1232. } else if (!strncasecmp(&input, "d", 1)) {
  1233. for (i = 0; i < total_pools; i++) {
  1234. if ((pools[i])->enabled)
  1235. active++;
  1236. }
  1237. if (active <= 1) {
  1238. wprintw(logwin, "Cannot disable last pool");
  1239. goto retry;
  1240. }
  1241. selected = curses_int("Select pool number");
  1242. if (selected < 0 || selected >= total_pools) {
  1243. wprintw(logwin, "Invalid selection");
  1244. goto retry;
  1245. }
  1246. pool = pools[selected];
  1247. pool->enabled = false;
  1248. if (pool == current_pool())
  1249. switch_pools(NULL);
  1250. goto updated;
  1251. } else if (!strncasecmp(&input, "e", 1)) {
  1252. selected = curses_int("Select pool number");
  1253. if (selected < 0 || selected >= total_pools) {
  1254. wprintw(logwin, "Invalid selection");
  1255. goto retry;
  1256. }
  1257. pool = pools[selected];
  1258. pool->enabled = true;
  1259. if (pool->prio < current_pool()->prio)
  1260. switch_pools(pool);
  1261. goto updated;
  1262. }
  1263. opt_loginput = false;
  1264. clear_logwin();
  1265. }
  1266. static void *input_thread(void *userdata)
  1267. {
  1268. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  1269. if (!curses_active)
  1270. return NULL;
  1271. while (1) {
  1272. char input;
  1273. input = getch();
  1274. if (!strncasecmp(&input, "q", 1)) {
  1275. kill_work();
  1276. return NULL;
  1277. } else if (!strncasecmp(&input, "s", 1)) {
  1278. opt_quiet ^= true;
  1279. applog(LOG_WARNING, "Silent mode %s", opt_quiet ? "enabled" : "disabled");
  1280. } else if (!strncasecmp(&input, "v", 1)) {
  1281. opt_log_output ^= true;
  1282. applog(LOG_WARNING, "Verbose mode %s", opt_log_output ? "enabled" : "disabled");
  1283. } else if (!strncasecmp(&input, "n", 1)) {
  1284. opt_log_output = true;
  1285. opt_debug = false;
  1286. opt_quiet = false;
  1287. opt_protocol = false;
  1288. applog(LOG_WARNING, "Output mode reset to normal");
  1289. } else if (!strncasecmp(&input, "d", 1)) {
  1290. opt_debug ^= true;
  1291. applog(LOG_WARNING, "Debug mode %s", opt_debug ? "enabled" : "disabled");
  1292. } else if (!strncasecmp(&input, "r", 1)) {
  1293. opt_protocol ^= true;
  1294. applog(LOG_WARNING, "RPC protocl debugging %s", opt_protocol ? "enabled" : "disabled");
  1295. } else if (!strncasecmp(&input, "c", 1))
  1296. clear_logwin();
  1297. else if (!strncasecmp(&input, "p", 1))
  1298. display_pools();
  1299. }
  1300. return NULL;
  1301. }
  1302. static void *workio_thread(void *userdata)
  1303. {
  1304. struct thr_info *mythr = userdata;
  1305. bool ok = true;
  1306. while (ok) {
  1307. struct workio_cmd *wc;
  1308. /* wait for workio_cmd sent to us, on our queue */
  1309. wc = tq_pop(mythr->q, NULL);
  1310. if (unlikely(!wc)) {
  1311. applog(LOG_ERR, "Failed to tq_pop in workio_thread");
  1312. ok = false;
  1313. break;
  1314. }
  1315. /* process workio_cmd */
  1316. switch (wc->cmd) {
  1317. case WC_GET_WORK:
  1318. ok = workio_get_work(wc);
  1319. break;
  1320. case WC_SUBMIT_WORK:
  1321. ok = workio_submit_work(wc);
  1322. break;
  1323. case WC_DIE:
  1324. default:
  1325. ok = false;
  1326. break;
  1327. }
  1328. }
  1329. tq_freeze(mythr->q);
  1330. return NULL;
  1331. }
  1332. static void thread_reportin(struct thr_info *thr)
  1333. {
  1334. gettimeofday(&thr->last, NULL);
  1335. thr->getwork = false;
  1336. }
  1337. static inline void thread_reportout(struct thr_info *thr)
  1338. {
  1339. thr->getwork = true;
  1340. }
  1341. static void hashmeter(int thr_id, struct timeval *diff,
  1342. unsigned long hashes_done)
  1343. {
  1344. struct timeval temp_tv_end, total_diff;
  1345. double khashes, secs;
  1346. double local_secs;
  1347. double utility, efficiency = 0.0;
  1348. static double local_mhashes_done = 0;
  1349. static double rolling_local = 0;
  1350. double local_mhashes = (double)hashes_done / 1000000.0;
  1351. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  1352. /* Update the last time this thread reported in */
  1353. if (thr_id >= 0)
  1354. gettimeofday(&thr_info[thr_id].last, NULL);
  1355. /* Don't bother calculating anything if we're not displaying it */
  1356. if (opt_quiet || !opt_log_interval)
  1357. return;
  1358. khashes = hashes_done / 1000.0;
  1359. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  1360. if (thr_id >= 0 && secs) {
  1361. /* So we can call hashmeter from a non worker thread */
  1362. if (opt_debug)
  1363. applog(LOG_DEBUG, "[thread %d: %lu hashes, %.0f khash/sec]",
  1364. thr_id, hashes_done, hashes_done / secs);
  1365. cgpu->local_mhashes += local_mhashes;
  1366. cgpu->total_mhashes += local_mhashes;
  1367. }
  1368. /* Totals are updated by all threads so can race without locking */
  1369. pthread_mutex_lock(&hash_lock);
  1370. gettimeofday(&temp_tv_end, NULL);
  1371. timeval_subtract(&total_diff, &temp_tv_end, &total_tv_end);
  1372. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  1373. total_mhashes_done += local_mhashes;
  1374. local_mhashes_done += local_mhashes;
  1375. if (total_diff.tv_sec < opt_log_interval)
  1376. /* Only update the total every opt_log_interval seconds */
  1377. goto out_unlock;
  1378. gettimeofday(&total_tv_end, NULL);
  1379. /* Use a rolling average by faking an exponential decay over 5 * log */
  1380. rolling_local = ((rolling_local * 0.9) + local_mhashes_done) / 1.9;
  1381. timeval_subtract(&total_diff, &total_tv_end, &total_tv_start);
  1382. total_secs = (double)total_diff.tv_sec +
  1383. ((double)total_diff.tv_usec / 1000000.0);
  1384. utility = total_accepted / ( total_secs ? total_secs : 1 ) * 60;
  1385. efficiency = total_getworks ? total_accepted * 100.0 / total_getworks : 0.0;
  1386. sprintf(statusline, "[(%ds):%.1f (avg):%.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]",
  1387. opt_log_interval, rolling_local / local_secs, total_mhashes_done / total_secs,
  1388. total_getworks, total_accepted, total_rejected, hw_errors, efficiency, utility);
  1389. if (!curses_active) {
  1390. printf("%s \r", statusline);
  1391. fflush(stdout);
  1392. } else
  1393. applog(LOG_INFO, "%s", statusline);
  1394. local_mhashes_done = 0;
  1395. out_unlock:
  1396. pthread_mutex_unlock(&hash_lock);
  1397. }
  1398. /* This is overkill, but at least we'll know accurately how much work is
  1399. * queued to prevent ever being left without work */
  1400. static void inc_queued(void)
  1401. {
  1402. pthread_mutex_lock(&qd_lock);
  1403. total_queued++;
  1404. pthread_mutex_unlock(&qd_lock);
  1405. }
  1406. static void dec_queued(void)
  1407. {
  1408. pthread_mutex_lock(&qd_lock);
  1409. if (total_queued > 0)
  1410. total_queued--;
  1411. pthread_mutex_unlock(&qd_lock);
  1412. dec_staged(1);
  1413. }
  1414. static int requests_queued(void)
  1415. {
  1416. int ret;
  1417. pthread_mutex_lock(&qd_lock);
  1418. ret = total_queued;
  1419. pthread_mutex_unlock(&qd_lock);
  1420. return ret;
  1421. }
  1422. static bool pool_active(struct pool *pool)
  1423. {
  1424. bool ret = false;
  1425. json_t *val;
  1426. CURL *curl;
  1427. curl = curl_easy_init();
  1428. if (unlikely(!curl)) {
  1429. applog(LOG_ERR, "CURL initialisation failed");
  1430. return false;
  1431. }
  1432. applog(LOG_WARNING, "Testing pool %s", pool->rpc_url);
  1433. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  1434. true, false, pool);
  1435. if (val) {
  1436. struct work *work = malloc(sizeof(struct work));
  1437. bool rc;
  1438. if (!work) {
  1439. applog(LOG_ERR, "Unable to malloc work in pool_active");
  1440. goto out;
  1441. }
  1442. rc = work_decode(json_object_get(val, "result"), work);
  1443. if (rc) {
  1444. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  1445. pool->pool_no, pool->rpc_url);
  1446. work->pool = pool;
  1447. tq_push(thr_info[stage_thr_id].q, work);
  1448. total_getworks++;
  1449. pool->getwork_requested++;
  1450. inc_queued();
  1451. ret = true;
  1452. gettimeofday(&pool->tv_idle, NULL);
  1453. } else {
  1454. applog(LOG_DEBUG, "Successfully retreived but FAILED to decipher work from pool %u %s",
  1455. pool->pool_no, pool->rpc_url);
  1456. free(work);
  1457. }
  1458. json_decref(val);
  1459. } else {
  1460. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  1461. pool->pool_no, pool->rpc_url);
  1462. applog(LOG_WARNING, "Pool down, URL or credentials invalid");
  1463. }
  1464. out:
  1465. curl_easy_cleanup(curl);
  1466. return ret;
  1467. }
  1468. static void pool_died(struct pool *pool)
  1469. {
  1470. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  1471. gettimeofday(&pool->tv_idle, NULL);
  1472. switch_pools(NULL);
  1473. }
  1474. static void pool_resus(struct pool *pool)
  1475. {
  1476. applog(LOG_WARNING, "Pool %d %s recovered", pool->pool_no, pool->rpc_url);
  1477. if (pool->prio < current_pool()->prio && pool_strategy == POOL_FAILOVER)
  1478. switch_pools(NULL);
  1479. }
  1480. static bool queue_request(void)
  1481. {
  1482. int maxq = opt_queue + mining_threads;
  1483. struct workio_cmd *wc;
  1484. /* If we've been generating lots of local work we may already have
  1485. * enough in the queue */
  1486. if (requests_queued() >= maxq || real_staged() >= maxq)
  1487. return true;
  1488. /* fill out work request message */
  1489. wc = calloc(1, sizeof(*wc));
  1490. if (unlikely(!wc)) {
  1491. applog(LOG_ERR, "Failed to tq_pop in queue_request");
  1492. return false;
  1493. }
  1494. wc->cmd = WC_GET_WORK;
  1495. /* The get work does not belong to any thread */
  1496. wc->thr = NULL;
  1497. /* send work request to workio thread */
  1498. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  1499. applog(LOG_ERR, "Failed to tq_push in queue_request");
  1500. workio_cmd_free(wc);
  1501. return false;
  1502. }
  1503. inc_queued();
  1504. return true;
  1505. }
  1506. static void discard_staged(void)
  1507. {
  1508. struct timespec abstime = {};
  1509. struct timeval now;
  1510. struct work *work_heap;
  1511. struct pool *pool;
  1512. /* Just in case we fell in a hole and missed a queue filling */
  1513. if (unlikely(!requests_staged()))
  1514. return;
  1515. gettimeofday(&now, NULL);
  1516. abstime.tv_sec = now.tv_sec + 60;
  1517. work_heap = tq_pop(getq, &abstime);
  1518. if (unlikely(!work_heap))
  1519. return;
  1520. pool = work_heap->pool;
  1521. free(work_heap);
  1522. dec_queued();
  1523. pool->discarded_work++;
  1524. total_discarded++;
  1525. }
  1526. static void flush_requests(bool longpoll)
  1527. {
  1528. struct pool *pool = current_pool();
  1529. int i, stale;
  1530. /* We should have one fresh work item staged from the block change. */
  1531. stale = requests_staged() - 1;
  1532. if (longpoll)
  1533. memcpy(current_block, blank, 36);
  1534. /* Temporarily increase the staged count so that get_work thinks there
  1535. * is work available instead of making threads reuse existing work */
  1536. inc_staged(pool, mining_threads, true);
  1537. for (i = 0; i < stale; i++) {
  1538. /* Queue a whole batch of new requests */
  1539. if (unlikely(!queue_request())) {
  1540. applog(LOG_ERR, "Failed to queue requests in flush_requests");
  1541. kill_work();
  1542. break;
  1543. }
  1544. /* Pop off the old requests. Cancelling the requests would be better
  1545. * but is tricky */
  1546. discard_staged();
  1547. }
  1548. }
  1549. static bool get_work(struct work *work, bool queued, struct thr_info *thr,
  1550. const int thr_id)
  1551. {
  1552. struct timespec abstime = {};
  1553. struct timeval now;
  1554. struct work *work_heap;
  1555. struct pool *pool;
  1556. bool ret = false;
  1557. int failures = 0;
  1558. /* Tell the watchdog thread this thread is waiting on getwork and
  1559. * should not be restarted */
  1560. thread_reportout(thr);
  1561. retry:
  1562. pool = current_pool();
  1563. if (unlikely(!queued && !queue_request())) {
  1564. applog(LOG_WARNING, "Failed to queue_request in get_work");
  1565. goto out;
  1566. }
  1567. if (!requests_staged() && !stale_work(work) && work->pool->has_rolltime) {
  1568. uint32_t *work_ntime;
  1569. uint32_t ntime;
  1570. /* Only print this message once each time we shift to localgen */
  1571. if (!pool_tset(pool, &pool->idle)) {
  1572. applog(LOG_WARNING, "Pool %d not providing work fast enough, generating work locally",
  1573. pool->pool_no);
  1574. pool->localgen_occasions++;
  1575. total_lo++;
  1576. gettimeofday(&pool->tv_idle, NULL);
  1577. } else {
  1578. struct timeval tv_now, diff;
  1579. gettimeofday(&tv_now, NULL);
  1580. timeval_subtract(&diff, &tv_now, &pool->tv_idle);
  1581. /* Attempt to switch pools if this one has been unresponsive for >half
  1582. * a block's duration */
  1583. if (diff.tv_sec > 300) {
  1584. pool_died(pool);
  1585. goto retry;
  1586. }
  1587. }
  1588. work_ntime = (uint32_t *)(work->data + 68);
  1589. ntime = be32toh(*work_ntime);
  1590. ntime++;
  1591. *work_ntime = htobe32(ntime);
  1592. ret = true;
  1593. local_work++;
  1594. goto out;
  1595. }
  1596. gettimeofday(&now, NULL);
  1597. abstime.tv_sec = now.tv_sec + 60;
  1598. /* wait for 1st response, or get cached response */
  1599. work_heap = tq_pop(getq, &abstime);
  1600. if (unlikely(!work_heap)) {
  1601. /* Attempt to switch pools if this one has mandatory work that
  1602. * has timed out or does not support rolltime */
  1603. pool->localgen_occasions++;
  1604. total_lo++;
  1605. pool_died(pool);
  1606. goto retry;
  1607. }
  1608. pool = work_heap->pool;
  1609. /* If we make it here we have succeeded in getting fresh work */
  1610. if (pool_tclear(pool, &pool->idle))
  1611. pool_resus(pool);
  1612. dec_queued();
  1613. memcpy(work, work_heap, sizeof(*work));
  1614. ret = true;
  1615. free(work_heap);
  1616. out:
  1617. if (unlikely(ret == false)) {
  1618. if ((opt_retries >= 0) && (++failures > opt_retries)) {
  1619. applog(LOG_ERR, "Failed %d times to get_work");
  1620. return ret;
  1621. }
  1622. applog(LOG_DEBUG, "Retrying after %d seconds", opt_fail_pause);
  1623. sleep(opt_fail_pause);
  1624. goto retry;
  1625. }
  1626. work->thr_id = thr_id;
  1627. thread_reportin(thr);
  1628. return ret;
  1629. }
  1630. static bool submit_work_sync(struct thr_info *thr, const struct work *work_in)
  1631. {
  1632. struct workio_cmd *wc;
  1633. /* fill out work request message */
  1634. wc = calloc(1, sizeof(*wc));
  1635. if (unlikely(!wc)) {
  1636. applog(LOG_ERR, "Failed to calloc wc in submit_work_sync");
  1637. return false;
  1638. }
  1639. wc->u.work = malloc(sizeof(*work_in));
  1640. if (unlikely(!wc->u.work)) {
  1641. applog(LOG_ERR, "Failed to calloc work in submit_work_sync");
  1642. goto err_out;
  1643. }
  1644. wc->cmd = WC_SUBMIT_WORK;
  1645. wc->thr = thr;
  1646. memcpy(wc->u.work, work_in, sizeof(*work_in));
  1647. /* send solution to workio thread */
  1648. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  1649. applog(LOG_ERR, "Failed to tq_push work in submit_work_sync");
  1650. goto err_out;
  1651. }
  1652. return true;
  1653. err_out:
  1654. workio_cmd_free(wc);
  1655. return false;
  1656. }
  1657. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  1658. {
  1659. work->data[64+12+0] = (nonce>>0) & 0xff;
  1660. work->data[64+12+1] = (nonce>>8) & 0xff;
  1661. work->data[64+12+2] = (nonce>>16) & 0xff;
  1662. work->data[64+12+3] = (nonce>>24) & 0xff;
  1663. /* Do one last check before attempting to submit the work */
  1664. if (!fulltest(work->data + 64, work->target))
  1665. return true;
  1666. return submit_work_sync(thr, work);
  1667. }
  1668. static void *miner_thread(void *userdata)
  1669. {
  1670. struct thr_info *mythr = userdata;
  1671. const int thr_id = mythr->id;
  1672. uint32_t max_nonce = 0xffffff;
  1673. unsigned long hashes_done = max_nonce;
  1674. bool needs_work = true;
  1675. /* Try to cycle approximately 5 times before each log update */
  1676. const unsigned long cycle = opt_log_interval / 5 ? : 1;
  1677. /* Request the next work item at 2/3 of the scantime */
  1678. unsigned const int request_interval = opt_scantime * 2 / 3 ? : 1;
  1679. unsigned const long request_nonce = MAXTHREADS / 3 * 2;
  1680. bool requested = true;
  1681. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  1682. /* Set worker threads to nice 19 and then preferentially to SCHED_IDLE
  1683. * and if that fails, then SCHED_BATCH. No need for this to be an
  1684. * error if it fails */
  1685. setpriority(PRIO_PROCESS, 0, 19);
  1686. drop_policy();
  1687. /* Cpu affinity only makes sense if the number of threads is a multiple
  1688. * of the number of CPUs */
  1689. if (!(opt_n_threads % num_processors))
  1690. affine_to_cpu(thr_id - gpu_threads, dev_from_id(thr_id));
  1691. while (1) {
  1692. struct work work __attribute__((aligned(128)));
  1693. struct timeval tv_workstart, tv_start, tv_end, diff;
  1694. uint64_t max64;
  1695. bool rc;
  1696. if (needs_work) {
  1697. gettimeofday(&tv_workstart, NULL);
  1698. /* obtain new work from internal workio thread */
  1699. if (unlikely(!get_work(&work, requested, mythr, thr_id))) {
  1700. applog(LOG_ERR, "work retrieval failed, exiting "
  1701. "mining thread %d", thr_id);
  1702. goto out;
  1703. }
  1704. mythr->cgpu->getworks++;
  1705. needs_work = requested = false;
  1706. work.blk.nonce = 0;
  1707. max_nonce = hashes_done;
  1708. }
  1709. hashes_done = 0;
  1710. gettimeofday(&tv_start, NULL);
  1711. /* scan nonces for a proof-of-work hash */
  1712. switch (opt_algo) {
  1713. case ALGO_C:
  1714. rc = scanhash_c(thr_id, work.midstate, work.data + 64,
  1715. work.hash1, work.hash, work.target,
  1716. max_nonce, &hashes_done,
  1717. work.blk.nonce);
  1718. break;
  1719. #ifdef WANT_X8664_SSE2
  1720. case ALGO_SSE2_64: {
  1721. unsigned int rc5 =
  1722. scanhash_sse2_64(thr_id, work.midstate, work.data + 64,
  1723. work.hash1, work.hash,
  1724. work.target,
  1725. max_nonce, &hashes_done,
  1726. work.blk.nonce);
  1727. rc = (rc5 == -1) ? false : true;
  1728. }
  1729. break;
  1730. #endif
  1731. #ifdef WANT_X8664_SSE4
  1732. case ALGO_SSE4_64: {
  1733. unsigned int rc5 =
  1734. scanhash_sse4_64(thr_id, work.midstate, work.data + 64,
  1735. work.hash1, work.hash,
  1736. work.target,
  1737. max_nonce, &hashes_done,
  1738. work.blk.nonce);
  1739. rc = (rc5 == -1) ? false : true;
  1740. }
  1741. break;
  1742. #endif
  1743. #ifdef WANT_SSE2_4WAY
  1744. case ALGO_4WAY: {
  1745. unsigned int rc4 =
  1746. ScanHash_4WaySSE2(thr_id, work.midstate, work.data + 64,
  1747. work.hash1, work.hash,
  1748. work.target,
  1749. max_nonce, &hashes_done,
  1750. work.blk.nonce);
  1751. rc = (rc4 == -1) ? false : true;
  1752. }
  1753. break;
  1754. #endif
  1755. #ifdef WANT_VIA_PADLOCK
  1756. case ALGO_VIA:
  1757. rc = scanhash_via(thr_id, work.data, work.target,
  1758. max_nonce, &hashes_done,
  1759. work.blk.nonce);
  1760. break;
  1761. #endif
  1762. case ALGO_CRYPTOPP:
  1763. rc = scanhash_cryptopp(thr_id, work.midstate, work.data + 64,
  1764. work.hash1, work.hash, work.target,
  1765. max_nonce, &hashes_done,
  1766. work.blk.nonce);
  1767. break;
  1768. #ifdef WANT_CRYPTOPP_ASM32
  1769. case ALGO_CRYPTOPP_ASM32:
  1770. rc = scanhash_asm32(thr_id, work.midstate, work.data + 64,
  1771. work.hash1, work.hash, work.target,
  1772. max_nonce, &hashes_done,
  1773. work.blk.nonce);
  1774. break;
  1775. #endif
  1776. default:
  1777. /* should never happen */
  1778. goto out;
  1779. }
  1780. /* record scanhash elapsed time */
  1781. gettimeofday(&tv_end, NULL);
  1782. timeval_subtract(&diff, &tv_end, &tv_start);
  1783. hashes_done -= work.blk.nonce;
  1784. hashmeter(thr_id, &diff, hashes_done);
  1785. work.blk.nonce += hashes_done;
  1786. /* adjust max_nonce to meet target cycle time */
  1787. if (diff.tv_usec > 500000)
  1788. diff.tv_sec++;
  1789. if (diff.tv_sec && diff.tv_sec != cycle) {
  1790. max64 = work.blk.nonce +
  1791. ((uint64_t)hashes_done * cycle) / diff.tv_sec;
  1792. } else
  1793. max64 = work.blk.nonce + hashes_done;
  1794. if (max64 > 0xfffffffaULL)
  1795. max64 = 0xfffffffaULL;
  1796. max_nonce = max64;
  1797. /* if nonce found, submit work */
  1798. if (unlikely(rc)) {
  1799. if (opt_debug)
  1800. applog(LOG_DEBUG, "CPU %d found something?", dev_from_id(thr_id));
  1801. if (unlikely(!submit_work_sync(mythr, &work))) {
  1802. applog(LOG_ERR, "Failed to submit_work_sync in miner_thread %d", thr_id);
  1803. break;
  1804. }
  1805. work.blk.nonce += 4;
  1806. }
  1807. timeval_subtract(&diff, &tv_end, &tv_workstart);
  1808. if (!requested && (diff.tv_sec > request_interval || work.blk.nonce > request_nonce)) {
  1809. if (unlikely(!queue_request())) {
  1810. applog(LOG_ERR, "Failed to queue_request in miner_thread %d", thr_id);
  1811. goto out;
  1812. }
  1813. requested = true;
  1814. }
  1815. if (diff.tv_sec > opt_scantime || work_restart[thr_id].restart ||
  1816. work.blk.nonce >= MAXTHREADS - hashes_done ||
  1817. stale_work(&work))
  1818. needs_work = true;
  1819. }
  1820. out:
  1821. tq_freeze(mythr->q);
  1822. return NULL;
  1823. }
  1824. enum {
  1825. STAT_SLEEP_INTERVAL = 1,
  1826. STAT_CTR_INTERVAL = 10000000,
  1827. FAILURE_INTERVAL = 30,
  1828. };
  1829. #ifdef HAVE_OPENCL
  1830. static _clState *clStates[16];
  1831. static inline cl_int queue_kernel_parameters(_clState *clState, dev_blk_ctx *blk)
  1832. {
  1833. cl_kernel *kernel = &clState->kernel;
  1834. cl_int status = 0;
  1835. int num = 0;
  1836. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_a);
  1837. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_b);
  1838. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_c);
  1839. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_d);
  1840. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_e);
  1841. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_f);
  1842. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_g);
  1843. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_h);
  1844. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_b);
  1845. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_c);
  1846. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_d);
  1847. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_f);
  1848. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_g);
  1849. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_h);
  1850. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->nonce);
  1851. if (clState->hasBitAlign == true) {
  1852. /* Parameters for phatk kernel */
  1853. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W2);
  1854. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W16);
  1855. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W17);
  1856. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreVal4);
  1857. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->T1);
  1858. } else {
  1859. /* Parameters for poclbm kernel */
  1860. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW0);
  1861. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW1);
  1862. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW2);
  1863. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW3);
  1864. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW15);
  1865. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW01r);
  1866. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e);
  1867. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e2);
  1868. }
  1869. status |= clSetKernelArg(*kernel, num++, sizeof(clState->outputBuffer),
  1870. (void *)&clState->outputBuffer);
  1871. return status;
  1872. }
  1873. static void set_threads_hashes(unsigned int vectors, unsigned int *threads,
  1874. unsigned int *hashes, size_t *globalThreads)
  1875. {
  1876. *globalThreads = *threads = 1 << (15 + scan_intensity);
  1877. *hashes = *threads * vectors;
  1878. }
  1879. static void *gpuminer_thread(void *userdata)
  1880. {
  1881. const unsigned long cycle = opt_log_interval / 5 ? : 1;
  1882. struct timeval tv_start, tv_end, diff, tv_workstart;
  1883. struct thr_info *mythr = userdata;
  1884. const int thr_id = mythr->id;
  1885. uint32_t *res, *blank_res;
  1886. double gpu_ms_average = 7;
  1887. size_t globalThreads[1];
  1888. size_t localThreads[1];
  1889. cl_int status;
  1890. _clState *clState = clStates[thr_id];
  1891. const cl_kernel *kernel = &clState->kernel;
  1892. struct work *work = malloc(sizeof(struct work));
  1893. unsigned int threads = 1 << (15 + scan_intensity);
  1894. unsigned const int vectors = clState->preferred_vwidth;
  1895. unsigned int hashes = threads * vectors;
  1896. unsigned int hashes_done = 0;
  1897. /* Request the next work item at 2/3 of the scantime */
  1898. unsigned const int request_interval = opt_scantime * 2 / 3 ? : 1;
  1899. unsigned const long request_nonce = MAXTHREADS / 3 * 2;
  1900. bool requested = true;
  1901. if (opt_dynamic) {
  1902. /* Minimise impact on desktop if we want dynamic mode */
  1903. setpriority(PRIO_PROCESS, 0, 19);
  1904. drop_policy();
  1905. }
  1906. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  1907. res = calloc(BUFFERSIZE, 1);
  1908. blank_res = calloc(BUFFERSIZE, 1);
  1909. if (!res || !blank_res) {
  1910. applog(LOG_ERR, "Failed to calloc in gpuminer_thread");
  1911. goto out;
  1912. }
  1913. gettimeofday(&tv_start, NULL);
  1914. globalThreads[0] = threads;
  1915. localThreads[0] = clState->work_size;
  1916. diff.tv_sec = 0;
  1917. gettimeofday(&tv_end, NULL);
  1918. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_TRUE, 0,
  1919. BUFFERSIZE, blank_res, 0, NULL, NULL);
  1920. if (unlikely(status != CL_SUCCESS))
  1921. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  1922. gettimeofday(&tv_workstart, NULL);
  1923. /* obtain new work from internal workio thread */
  1924. if (unlikely(!get_work(work, requested, mythr, thr_id))) {
  1925. applog(LOG_ERR, "work retrieval failed, exiting "
  1926. "gpu mining thread %d", thr_id);
  1927. goto out;
  1928. }
  1929. mythr->cgpu->getworks++;
  1930. requested = false;
  1931. precalc_hash(&work->blk, (uint32_t *)(work->midstate), (uint32_t *)(work->data + 64));
  1932. work->blk.nonce = 0;
  1933. while (1) {
  1934. struct timeval tv_gpustart, tv_gpuend;
  1935. suseconds_t gpu_us;
  1936. gettimeofday(&tv_gpustart, NULL);
  1937. timeval_subtract(&diff, &tv_gpustart, &tv_gpuend);
  1938. /* This finish flushes the readbuffer set with CL_FALSE later */
  1939. clFinish(clState->commandQueue);
  1940. gettimeofday(&tv_gpuend, NULL);
  1941. timeval_subtract(&diff, &tv_gpuend, &tv_gpustart);
  1942. gpu_us = diff.tv_sec * 1000000 + diff.tv_usec;
  1943. gpu_ms_average = ((gpu_us / 1000) + gpu_ms_average * 0.9) / 1.9;
  1944. if (opt_dynamic) {
  1945. /* Try to not let the GPU be out for longer than 6ms, but
  1946. * increase intensity when the system is idle, unless
  1947. * dynamic is disabled. */
  1948. if (gpu_ms_average > 7) {
  1949. if (scan_intensity > 0)
  1950. scan_intensity--;
  1951. set_threads_hashes(vectors, &threads, &hashes, globalThreads);
  1952. } else if (gpu_ms_average < 3) {
  1953. if (scan_intensity < 14)
  1954. scan_intensity++;
  1955. set_threads_hashes(vectors, &threads, &hashes, globalThreads);
  1956. }
  1957. }
  1958. if (diff.tv_sec > opt_scantime ||
  1959. work->blk.nonce >= MAXTHREADS - hashes ||
  1960. work_restart[thr_id].restart ||
  1961. stale_work(work)) {
  1962. /* Ignore any reads since we're getting new work and queue a clean buffer */
  1963. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  1964. BUFFERSIZE, blank_res, 0, NULL, NULL);
  1965. if (unlikely(status != CL_SUCCESS))
  1966. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  1967. memset(res, 0, BUFFERSIZE);
  1968. gettimeofday(&tv_workstart, NULL);
  1969. /* obtain new work from internal workio thread */
  1970. if (unlikely(!get_work(work, requested, mythr, thr_id))) {
  1971. applog(LOG_ERR, "work retrieval failed, exiting "
  1972. "gpu mining thread %d", thr_id);
  1973. goto out;
  1974. }
  1975. mythr->cgpu->getworks++;
  1976. requested = false;
  1977. precalc_hash(&work->blk, (uint32_t *)(work->midstate), (uint32_t *)(work->data + 64));
  1978. work->blk.nonce = 0;
  1979. work_restart[thr_id].restart = 0;
  1980. if (opt_debug)
  1981. applog(LOG_DEBUG, "getwork thread %d", thr_id);
  1982. /* Flushes the writebuffer set with CL_FALSE above */
  1983. clFinish(clState->commandQueue);
  1984. }
  1985. status = queue_kernel_parameters(clState, &work->blk);
  1986. if (unlikely(status != CL_SUCCESS))
  1987. { applog(LOG_ERR, "Error: clSetKernelArg of all params failed."); goto out; }
  1988. /* MAXBUFFERS entry is used as a flag to say nonces exist */
  1989. if (res[MAXBUFFERS]) {
  1990. /* Clear the buffer again */
  1991. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  1992. BUFFERSIZE, blank_res, 0, NULL, NULL);
  1993. if (unlikely(status != CL_SUCCESS))
  1994. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  1995. if (opt_debug)
  1996. applog(LOG_DEBUG, "GPU %d found something?", dev_from_id(thr_id));
  1997. postcalc_hash_async(mythr, work, res);
  1998. memset(res, 0, BUFFERSIZE);
  1999. clFinish(clState->commandQueue);
  2000. }
  2001. status = clEnqueueNDRangeKernel(clState->commandQueue, *kernel, 1, NULL,
  2002. globalThreads, localThreads, 0, NULL, NULL);
  2003. if (unlikely(status != CL_SUCCESS))
  2004. { applog(LOG_ERR, "Error: Enqueueing kernel onto command queue. (clEnqueueNDRangeKernel)"); goto out; }
  2005. status = clEnqueueReadBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  2006. BUFFERSIZE, res, 0, NULL, NULL);
  2007. if (unlikely(status != CL_SUCCESS))
  2008. { applog(LOG_ERR, "Error: clEnqueueReadBuffer failed. (clEnqueueReadBuffer)"); goto out;}
  2009. gettimeofday(&tv_end, NULL);
  2010. timeval_subtract(&diff, &tv_end, &tv_start);
  2011. hashes_done += hashes;
  2012. work->blk.nonce += hashes;
  2013. if (diff.tv_usec > 500000)
  2014. diff.tv_sec++;
  2015. if (diff.tv_sec >= cycle) {
  2016. hashmeter(thr_id, &diff, hashes_done);
  2017. gettimeofday(&tv_start, NULL);
  2018. hashes_done = 0;
  2019. }
  2020. timeval_subtract(&diff, &tv_end, &tv_workstart);
  2021. if (!requested && (diff.tv_sec > request_interval || work->blk.nonce > request_nonce)) {
  2022. if (unlikely(!queue_request())) {
  2023. applog(LOG_ERR, "Failed to queue_request in gpuminer_thread %d", thr_id);
  2024. goto out;
  2025. }
  2026. requested = true;
  2027. }
  2028. }
  2029. out:
  2030. tq_freeze(mythr->q);
  2031. return NULL;
  2032. }
  2033. #endif /* HAVE_OPENCL */
  2034. static void restart_threads(bool longpoll)
  2035. {
  2036. int i;
  2037. /* Discard old queued requests and get new ones */
  2038. flush_requests(longpoll);
  2039. for (i = 0; i < mining_threads; i++)
  2040. work_restart[i].restart = 1;
  2041. }
  2042. /* Stage another work item from the work returned in a longpoll */
  2043. static void convert_to_work(json_t *val)
  2044. {
  2045. struct work *work;
  2046. bool rc;
  2047. work = calloc(sizeof(*work), 1);
  2048. if (unlikely(!work)) {
  2049. applog(LOG_ERR, "OOM in convert_to_work");
  2050. return;
  2051. }
  2052. rc= work_decode(json_object_get(val, "result"), work);
  2053. if (unlikely(!rc)) {
  2054. applog(LOG_ERR, "Could not convert longpoll data to work");
  2055. return;
  2056. }
  2057. work->pool = current_pool();
  2058. if (unlikely(!tq_push(thr_info[stage_thr_id].q, work)))
  2059. applog(LOG_ERR, "Could not tq_push work in convert_to_work");
  2060. else if (opt_debug)
  2061. applog(LOG_DEBUG, "Converted longpoll data to work");
  2062. }
  2063. static void *longpoll_thread(void *userdata)
  2064. {
  2065. struct thr_info *mythr = userdata;
  2066. CURL *curl = NULL;
  2067. char *copy_start, *hdr_path, *lp_url = NULL;
  2068. bool need_slash = false;
  2069. int failures = 0;
  2070. struct pool *pool = current_pool();
  2071. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2072. curl = curl_easy_init();
  2073. if (unlikely(!curl)) {
  2074. applog(LOG_ERR, "CURL initialisation failed");
  2075. goto out;
  2076. }
  2077. /* Longpoll sits waiting on next pushed url */
  2078. next_path:
  2079. hdr_path = tq_pop(mythr->q, NULL);
  2080. if (!hdr_path) {
  2081. applog(LOG_WARNING, "No long-poll found on this server");
  2082. goto next_path;
  2083. }
  2084. /* full URL */
  2085. if (strstr(hdr_path, "://")) {
  2086. lp_url = hdr_path;
  2087. hdr_path = NULL;
  2088. }
  2089. /* absolute path, on current server */
  2090. else {
  2091. copy_start = (*hdr_path == '/') ? (hdr_path + 1) : hdr_path;
  2092. if (pool->rpc_url[strlen(pool->rpc_url) - 1] != '/')
  2093. need_slash = true;
  2094. lp_url = malloc(strlen(pool->rpc_url) + strlen(copy_start) + 2);
  2095. if (!lp_url)
  2096. goto out;
  2097. sprintf(lp_url, "%s%s%s", pool->rpc_url, need_slash ? "/" : "", copy_start);
  2098. }
  2099. free(hdr_path);
  2100. applog(LOG_WARNING, "Long-polling activated for %s", lp_url);
  2101. while (1) {
  2102. struct timeval start, end;
  2103. json_t *val;
  2104. gettimeofday(&start, NULL);
  2105. val = json_rpc_call(curl, lp_url, pool->rpc_userpass, rpc_req,
  2106. false, true, pool);
  2107. if (likely(val)) {
  2108. /* Keep track of who ordered a restart_threads to make
  2109. * sure it's only done once per new block */
  2110. if (likely(!strncmp(longpoll_block, blank, 36) ||
  2111. !strncmp(longpoll_block, current_block, 36))) {
  2112. new_blocks++;
  2113. applog(LOG_WARNING, "LONGPOLL detected new block on network, waiting on fresh work");
  2114. restart_threads(true);
  2115. } else
  2116. applog(LOG_WARNING, "LONGPOLL received after new block already detected");
  2117. convert_to_work(val);
  2118. failures = 0;
  2119. json_decref(val);
  2120. } else {
  2121. /* Some pools regularly drop the longpoll request so
  2122. * only see this as longpoll failure if it happens
  2123. * immediately and just restart it the rest of the
  2124. * time. */
  2125. gettimeofday(&end, NULL);
  2126. if (end.tv_sec - start.tv_sec > 30)
  2127. continue;
  2128. if (failures++ < 10) {
  2129. sleep(30);
  2130. applog(LOG_WARNING,
  2131. "longpoll failed, sleeping for 30s");
  2132. } else {
  2133. applog(LOG_ERR,
  2134. "longpoll failed, ending thread");
  2135. goto out;
  2136. }
  2137. }
  2138. memcpy(longpoll_block, current_block, 36);
  2139. if (pool != current_pool()) {
  2140. applog(LOG_WARNING, "Attempting to change longpoll servers");
  2141. pool = current_pool();
  2142. have_longpoll = false;
  2143. goto next_path;
  2144. }
  2145. }
  2146. out:
  2147. free(lp_url);
  2148. tq_freeze(mythr->q);
  2149. if (curl)
  2150. curl_easy_cleanup(curl);
  2151. return NULL;
  2152. }
  2153. static void reinit_cputhread(int thr_id)
  2154. {
  2155. struct thr_info *thr = &thr_info[thr_id];
  2156. tq_freeze(thr->q);
  2157. if (!(pthread_cancel(thr->pth)) && pthread_join(thr->pth, NULL)) {
  2158. applog(LOG_ERR, "Failed to pthread_join in reinit_cputhread");
  2159. goto failed_out;
  2160. }
  2161. applog(LOG_INFO, "Reinit CPU thread %d", thr_id);
  2162. tq_thaw(thr->q);
  2163. thread_reportin(thr);
  2164. if (unlikely(pthread_create(&thr->pth, NULL, miner_thread, thr))) {
  2165. applog(LOG_ERR, "thread %d create failed", thr_id);
  2166. goto failed_out;
  2167. }
  2168. return;
  2169. failed_out:
  2170. kill_work();
  2171. }
  2172. #ifdef HAVE_OPENCL
  2173. static void reinit_gputhread(int thr_id)
  2174. {
  2175. int gpu = dev_from_id(thr_id);
  2176. struct thr_info *thr = &thr_info[thr_id];
  2177. char name[256];
  2178. tq_freeze(thr->q);
  2179. if (!(pthread_cancel(thr->pth)) && pthread_join(thr->pth, NULL)) {
  2180. applog(LOG_ERR, "Failed to pthread_join in reinit_gputhread");
  2181. goto failed_out;
  2182. }
  2183. free(clStates[thr_id]);
  2184. applog(LOG_INFO, "Reinit GPU thread %d", thr_id);
  2185. tq_thaw(thr->q);
  2186. clStates[thr_id] = initCl(gpu, name, sizeof(name));
  2187. if (!clStates[thr_id]) {
  2188. applog(LOG_ERR, "Failed to reinit GPU thread %d", thr_id);
  2189. goto failed_out;
  2190. }
  2191. applog(LOG_INFO, "initCl() finished. Found %s", name);
  2192. thread_reportin(thr);
  2193. if (unlikely(pthread_create(&thr->pth, NULL, gpuminer_thread, thr))) {
  2194. applog(LOG_ERR, "thread %d create failed", thr_id);
  2195. goto failed_out;
  2196. }
  2197. return;
  2198. failed_out:
  2199. kill_work();
  2200. }
  2201. static void reinit_thread(int thr_id)
  2202. {
  2203. if (thr_id < gpu_threads)
  2204. reinit_gputhread(thr_id);
  2205. else
  2206. reinit_cputhread(thr_id);
  2207. }
  2208. #else /* HAVE_OPENCL */
  2209. static void reinit_thread(int thr_id)
  2210. {
  2211. reinit_cputhread(thr_id);
  2212. }
  2213. #endif
  2214. /* Determine which are the first threads belonging to a device and if they're
  2215. * active */
  2216. static bool active_device(int thr_id)
  2217. {
  2218. if (thr_id < gpu_threads) {
  2219. if (thr_id >= total_devices)
  2220. return false;
  2221. if (!gpu_devices[dev_from_id(thr_id)])
  2222. return false;
  2223. } else if (thr_id > gpu_threads + num_processors)
  2224. return false;
  2225. return true;
  2226. }
  2227. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  2228. * the screen at regular intervals, and restarts threads if they appear to have
  2229. * died. */
  2230. static void *watchdog_thread(void *userdata)
  2231. {
  2232. const unsigned int interval = opt_log_interval / 2 ? : 1;
  2233. static struct timeval rotate_tv;
  2234. struct timeval zero_tv;
  2235. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2236. memset(&zero_tv, 0, sizeof(struct timeval));
  2237. gettimeofday(&rotate_tv, NULL);
  2238. while (1) {
  2239. int x, y, logx, logy, i;
  2240. struct timeval now;
  2241. sleep(interval);
  2242. if (requests_queued() < opt_queue)
  2243. queue_request();
  2244. hashmeter(-1, &zero_tv, 0);
  2245. if (curses_active) {
  2246. pthread_mutex_lock(&curses_lock);
  2247. getmaxyx(mainwin, y, x);
  2248. getmaxyx(logwin, logy, logx);
  2249. y -= logcursor;
  2250. /* Detect screen size change */
  2251. if (x != logx || y != logy)
  2252. wresize(logwin, y, x);
  2253. for (i = 0; i < mining_threads; i++) {
  2254. if (active_device(i))
  2255. curses_print_status(i);
  2256. }
  2257. redrawwin(logwin);
  2258. redrawwin(statuswin);
  2259. pthread_mutex_unlock(&curses_lock);
  2260. }
  2261. if (unlikely(work_restart[watchdog_thr_id].restart)) {
  2262. restart_threads(false);
  2263. work_restart[watchdog_thr_id].restart = 0;
  2264. }
  2265. gettimeofday(&now, NULL);
  2266. for (i = 0; i < total_pools; i++) {
  2267. struct pool *pool = pools[i];
  2268. if (!pool->enabled)
  2269. continue;
  2270. /* Test pool is idle once every minute */
  2271. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 60) {
  2272. gettimeofday(&pool->tv_idle, NULL);
  2273. if (pool_active(pool) && pool_tclear(pool, &pool->idle))
  2274. pool_resus(pool);
  2275. }
  2276. }
  2277. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  2278. gettimeofday(&rotate_tv, NULL);
  2279. switch_pools(NULL);
  2280. }
  2281. //for (i = 0; i < mining_threads; i++) {
  2282. for (i = 0; i < gpu_threads; i++) {
  2283. struct thr_info *thr = &thr_info[i];
  2284. /* Thread is waiting on getwork, don't test it */
  2285. if (thr->getwork)
  2286. continue;
  2287. if (now.tv_sec - thr->last.tv_sec > 60) {
  2288. applog(LOG_ERR, "Attempting to restart thread %d, idle for more than 60 seconds", i);
  2289. /* Create one mandatory work item */
  2290. inc_staged(current_pool(), 1, true);
  2291. if (unlikely(!queue_request())) {
  2292. applog(LOG_ERR, "Failed to queue_request in watchdog_thread");
  2293. kill_work();
  2294. break;
  2295. }
  2296. reinit_thread(i);
  2297. applog(LOG_WARNING, "Thread %d restarted", i);
  2298. }
  2299. }
  2300. }
  2301. return NULL;
  2302. }
  2303. static void print_summary(void)
  2304. {
  2305. struct timeval diff;
  2306. int hours, mins, secs, i;
  2307. double utility, efficiency = 0.0;
  2308. timeval_subtract(&diff, &total_tv_end, &total_tv_start);
  2309. hours = diff.tv_sec / 3600;
  2310. mins = (diff.tv_sec % 3600) / 60;
  2311. secs = diff.tv_sec % 60;
  2312. utility = total_accepted / ( total_secs ? total_secs : 1 ) * 60;
  2313. efficiency = total_getworks ? total_accepted * 100.0 / total_getworks : 0.0;
  2314. printf("\nSummary of runtime statistics:\n\n");
  2315. printf("Started at %s\n", datestamp);
  2316. printf("Runtime: %d hrs : %d mins : %d secs\n", hours, mins, secs);
  2317. if (total_secs)
  2318. printf("Average hashrate: %.1f Megahash/s\n", total_mhashes_done / total_secs);
  2319. printf("Queued work requests: %d\n", total_getworks);
  2320. printf("Share submissions: %d\n", total_accepted + total_rejected);
  2321. printf("Accepted shares: %d\n", total_accepted);
  2322. printf("Rejected shares: %d\n", total_rejected);
  2323. if (total_accepted || total_rejected)
  2324. printf("Reject ratio: %.1f\n", (double)(total_rejected * 100) / (double)(total_accepted + total_rejected));
  2325. printf("Hardware errors: %d\n", hw_errors);
  2326. printf("Efficiency (accepted / queued): %.0f%%\n", efficiency);
  2327. printf("Utility (accepted shares / min): %.2f/min\n\n", utility);
  2328. printf("Discarded work due to new blocks: %d\n", total_discarded);
  2329. printf("Stale submissions discarded due to new blocks: %d\n", total_stale);
  2330. printf("Unable to get work from server occasions: %d\n", total_lo);
  2331. printf("Work items generated locally: %d\n", local_work);
  2332. printf("Submitting work remotely delay occasions: %d\n", total_ro);
  2333. printf("New blocks detected on network: %d\n\n", new_blocks);
  2334. if (total_pools > 1) {
  2335. for (i = 0; i < total_pools; i++) {
  2336. struct pool *pool = pools[i];
  2337. printf("Pool: %s\n", pool->rpc_url);
  2338. printf(" Queued work requests: %d\n", pool->getwork_requested);
  2339. printf(" Share submissions: %d\n", pool->accepted + pool->rejected);
  2340. printf(" Accepted shares: %d\n", pool->accepted);
  2341. printf(" Rejected shares: %d\n", pool->rejected);
  2342. if (pool->accepted || pool->rejected)
  2343. printf(" Reject ratio: %.1f\n", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  2344. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  2345. printf(" Efficiency (accepted / queued): %.0f%%\n", efficiency);
  2346. printf(" Discarded work due to new blocks: %d\n", pool->discarded_work);
  2347. printf(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  2348. printf(" Unable to get work from server occasions: %d\n", pool->localgen_occasions);
  2349. printf(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  2350. }
  2351. }
  2352. printf("Summary of per device statistics:\n\n");
  2353. for (i = 0; i < mining_threads; i++) {
  2354. if (active_device(i))
  2355. print_status(i);
  2356. }
  2357. printf("\n");
  2358. }
  2359. static void quit(int status, const char *format, ...)
  2360. {
  2361. va_list ap;
  2362. disable_curses();
  2363. if (format) {
  2364. va_start(ap, format);
  2365. vfprintf(stderr, format, ap);
  2366. va_end(ap);
  2367. }
  2368. fprintf(stderr, "\n");
  2369. fflush(stderr);
  2370. exit(status);
  2371. }
  2372. static char *curses_input(const char *query)
  2373. {
  2374. char *input;
  2375. echo();
  2376. input = malloc(255);
  2377. if (!input)
  2378. quit(1, "Failed to malloc input");
  2379. leaveok(logwin, false);
  2380. wprintw(logwin, "%s: ", query);
  2381. wrefresh(logwin);
  2382. wgetnstr(logwin, input, 255);
  2383. leaveok(logwin, true);
  2384. noecho();
  2385. return input;
  2386. }
  2387. static bool input_pool(bool live)
  2388. {
  2389. char *url, *user, *pass;
  2390. struct pool *pool;
  2391. bool ret = false;
  2392. immedok(logwin, true);
  2393. if (total_pools == MAX_POOLS) {
  2394. wprintw(logwin, "Reached maximum number of pools.\n");
  2395. goto out;
  2396. }
  2397. wprintw(logwin, "Input server details.\n");
  2398. url = curses_input("URL");
  2399. if (strncmp(url, "http://", 7) &&
  2400. strncmp(url, "https://", 8)) {
  2401. applog(LOG_ERR, "URL must start with http:// or https://");
  2402. goto out;
  2403. }
  2404. user = curses_input("Username");
  2405. if (!user)
  2406. goto out;
  2407. pass = curses_input("Password");
  2408. if (!pass)
  2409. goto out;
  2410. pool = calloc(sizeof(struct pool), 1);
  2411. if (!pool)
  2412. quit(1, "Failed to realloc pools in input_pool");
  2413. pool->pool_no = total_pools;
  2414. pool->prio = total_pools;
  2415. if (unlikely(pthread_mutex_init(&pool->pool_lock, NULL)))
  2416. quit (1, "Failed to pthread_mutex_init in input_pool");
  2417. pool->rpc_url = url;
  2418. pool->rpc_user = user;
  2419. pool->rpc_pass = pass;
  2420. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  2421. if (!pool->rpc_userpass)
  2422. quit(1, "Failed to malloc userpass");
  2423. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  2424. pool->tv_idle.tv_sec = ~0UL;
  2425. /* Test the pool before we enable it if we're live running, otherwise
  2426. * it will be tested separately */
  2427. ret = true;
  2428. if (live && pool_active(pool))
  2429. pool->enabled = true;
  2430. pools[total_pools++] = pool;
  2431. out:
  2432. immedok(logwin, false);
  2433. if (!ret) {
  2434. free(pool);
  2435. if (url)
  2436. free(url);
  2437. if (user)
  2438. free(user);
  2439. if (pass)
  2440. free(pass);
  2441. }
  2442. return ret;
  2443. }
  2444. int main (int argc, char *argv[])
  2445. {
  2446. unsigned int i, j = 0, x, y, pools_active = 0;
  2447. struct sigaction handler;
  2448. struct thr_info *thr;
  2449. char name[256];
  2450. struct tm tm;
  2451. /* This dangerous functions tramples random dynamically allocated
  2452. * variables so do it before anything at all */
  2453. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  2454. quit(1, "Failed to curl_global_init");
  2455. if (unlikely(pthread_mutex_init(&hash_lock, NULL)))
  2456. quit(1, "Failed to pthread_mutex_init");
  2457. if (unlikely(pthread_mutex_init(&qd_lock, NULL)))
  2458. quit(1, "Failed to pthread_mutex_init");
  2459. if (unlikely(pthread_mutex_init(&stgd_lock, NULL)))
  2460. quit(1, "Failed to pthread_mutex_init");
  2461. if (unlikely(pthread_mutex_init(&curses_lock, NULL)))
  2462. quit(1, "Failed to pthread_mutex_init");
  2463. if (unlikely(pthread_mutex_init(&control_lock, NULL)))
  2464. quit(1, "Failed to pthread_mutex_init");
  2465. handler.sa_handler = &sighandler;
  2466. sigaction(SIGTERM, &handler, &termhandler);
  2467. sigaction(SIGINT, &handler, &inthandler);
  2468. gettimeofday(&total_tv_start, NULL);
  2469. gettimeofday(&total_tv_end, NULL);
  2470. localtime_r(&total_tv_start.tv_sec, &tm);
  2471. sprintf(datestamp, "[%d-%02d-%02d %02d:%02d:%02d]",
  2472. tm.tm_year + 1900,
  2473. tm.tm_mon + 1,
  2474. tm.tm_mday,
  2475. tm.tm_hour,
  2476. tm.tm_min,
  2477. tm.tm_sec);
  2478. for (i = 0; i < 36; i++) {
  2479. strcat(blank, "0");
  2480. strcat(current_block, "0");
  2481. strcat(longpoll_block, "0");
  2482. }
  2483. #ifdef WIN32
  2484. opt_n_threads = num_processors = 1;
  2485. #else
  2486. num_processors = sysconf(_SC_NPROCESSORS_ONLN);
  2487. opt_n_threads = num_processors;
  2488. #endif /* !WIN32 */
  2489. #ifdef HAVE_OPENCL
  2490. for (i = 0; i < 16; i++)
  2491. gpu_devices[i] = false;
  2492. nDevs = clDevicesNum();
  2493. if (nDevs < 0)
  2494. quit(1, "clDevicesNum returned error");
  2495. #endif
  2496. if (nDevs)
  2497. opt_n_threads = 0;
  2498. trpc_url = strdup(DEF_RPC_URL);
  2499. /* parse command line */
  2500. opt_register_table(opt_config_table,
  2501. "Options for both config file and command line");
  2502. opt_register_table(opt_cmdline_table,
  2503. "Options for command line only");
  2504. opt_parse(&argc, argv, applog_and_exit);
  2505. if (argc != 1)
  2506. quit(1, "Unexpected extra commandline arguments");
  2507. if (total_devices) {
  2508. if (total_devices > nDevs)
  2509. quit(1, "More devices specified than exist");
  2510. for (i = 0; i < 16; i++)
  2511. if (gpu_devices[i] && i + 1 > nDevs)
  2512. quit (1, "Command line options set a device that doesn't exist");
  2513. gpu_threads = total_devices * opt_g_threads;
  2514. } else {
  2515. gpu_threads = nDevs * opt_g_threads;
  2516. for (i = 0; i < nDevs; i++)
  2517. gpu_devices[i] = true;
  2518. total_devices = nDevs;
  2519. }
  2520. if (!gpu_threads && !forced_n_threads) {
  2521. /* Maybe they turned GPU off; restore default CPU threads. */
  2522. opt_n_threads = num_processors;
  2523. }
  2524. logcursor = 7;
  2525. gpucursor = logcursor;
  2526. cpucursor = gpucursor + nDevs;
  2527. logstart = cpucursor + (opt_n_threads ? num_processors : 0) + 1;
  2528. logcursor = logstart + 1;
  2529. /* Set up the ncurses interface */
  2530. if (!opt_quiet && use_curses) {
  2531. mainwin = initscr();
  2532. getmaxyx(mainwin, y, x);
  2533. statuswin = newwin(logstart, x, 0, 0);
  2534. leaveok(statuswin, true);
  2535. logwin = newwin(y - logcursor, 0, logcursor, 0);
  2536. idlok(logwin, true);
  2537. scrollok(logwin, true);
  2538. leaveok(logwin, true);
  2539. cbreak();
  2540. noecho();
  2541. test_and_set(&curses_active);
  2542. }
  2543. if (!total_pools) {
  2544. if (curses_active) {
  2545. if (!input_pool(false))
  2546. quit(1, "Pool setup failed");
  2547. } else
  2548. quit(1, "No server specified");
  2549. }
  2550. for (i = 0; i < total_pools; i++) {
  2551. struct pool *pool = pools[i];
  2552. if (!pool->rpc_userpass) {
  2553. if (!pool->rpc_user || !pool->rpc_pass)
  2554. quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  2555. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  2556. if (!pool->rpc_userpass)
  2557. quit(1, "Failed to malloc userpass");
  2558. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  2559. } else {
  2560. pool->rpc_user = malloc(strlen(pool->rpc_userpass));
  2561. if (!pool->rpc_user)
  2562. quit(1, "Failed to malloc user");
  2563. strcpy(pool->rpc_user, pool->rpc_userpass);
  2564. pool->rpc_user = strtok(pool->rpc_user, ":");
  2565. if (!pool->rpc_user)
  2566. quit(1, "Failed to find colon delimiter in userpass");
  2567. }
  2568. }
  2569. /* Set the currentpool to pool 0 */
  2570. currentpool = pools[0];
  2571. #ifdef HAVE_SYSLOG_H
  2572. if (use_syslog)
  2573. openlog("cpuminer", LOG_PID, LOG_USER);
  2574. #endif
  2575. mining_threads = opt_n_threads + gpu_threads;
  2576. total_threads = mining_threads + 5;
  2577. work_restart = calloc(total_threads, sizeof(*work_restart));
  2578. if (!work_restart)
  2579. quit(1, "Failed to calloc work_restart");
  2580. thr_info = calloc(total_threads, sizeof(*thr));
  2581. if (!thr_info)
  2582. quit(1, "Failed to calloc thr_info");
  2583. /* init workio thread info */
  2584. work_thr_id = mining_threads;
  2585. thr = &thr_info[work_thr_id];
  2586. thr->id = work_thr_id;
  2587. thr->q = tq_new();
  2588. if (!thr->q)
  2589. quit(1, "Failed to tq_new");
  2590. /* start work I/O thread */
  2591. if (pthread_create(&thr->pth, NULL, workio_thread, thr))
  2592. quit(1, "workio thread create failed");
  2593. /* init longpoll thread info */
  2594. if (want_longpoll) {
  2595. longpoll_thr_id = mining_threads + 1;
  2596. thr = &thr_info[longpoll_thr_id];
  2597. thr->id = longpoll_thr_id;
  2598. thr->q = tq_new();
  2599. if (!thr->q)
  2600. quit(1, "Failed to tq_new");
  2601. /* start longpoll thread */
  2602. if (unlikely(pthread_create(&thr->pth, NULL, longpoll_thread, thr)))
  2603. quit(1, "longpoll thread create failed");
  2604. pthread_detach(thr->pth);
  2605. } else
  2606. longpoll_thr_id = -1;
  2607. if (opt_n_threads ) {
  2608. cpus = calloc(num_processors, sizeof(struct cgpu_info));
  2609. if (unlikely(!cpus))
  2610. quit(1, "Failed to calloc cpus");
  2611. }
  2612. if (gpu_threads) {
  2613. gpus = calloc(nDevs, sizeof(struct cgpu_info));
  2614. if (unlikely(!gpus))
  2615. quit(1, "Failed to calloc gpus");
  2616. }
  2617. stage_thr_id = mining_threads + 3;
  2618. thr = &thr_info[stage_thr_id];
  2619. thr->q = tq_new();
  2620. if (!thr->q)
  2621. quit(1, "Failed to tq_new");
  2622. /* start stage thread */
  2623. if (pthread_create(&thr->pth, NULL, stage_thread, thr))
  2624. quit(1, "stage thread create failed");
  2625. pthread_detach(thr->pth);
  2626. /* Flag the work as ready forcing the mining threads to wait till we
  2627. * actually put something into the queue */
  2628. inc_staged(current_pool(), mining_threads, true);
  2629. /* Create a unique get work queue */
  2630. getq = tq_new();
  2631. if (!getq)
  2632. quit(1, "Failed to create getq");
  2633. /* Test each pool to see if we can retrieve and use work and for what
  2634. * it supports */
  2635. for (i = 0; i < total_pools; i++) {
  2636. struct pool *pool;
  2637. pool = pools[i];
  2638. if (pool_active(pool)) {
  2639. if (!currentpool)
  2640. currentpool = pool;
  2641. applog(LOG_INFO, "Pool %d %s active", pool->pool_no, pool->rpc_url);
  2642. pools_active++;
  2643. pool->enabled = true;
  2644. } else {
  2645. if (pool == currentpool)
  2646. currentpool = NULL;
  2647. applog(LOG_WARNING, "Unable to get work from pool %d %s", pool->pool_no, pool->rpc_url);
  2648. }
  2649. }
  2650. if (!pools_active)
  2651. quit(0, "No pools active! Exiting.");
  2652. #ifdef HAVE_OPENCL
  2653. i = 0;
  2654. /* Hopefully remove stale references to allow binaries to build */
  2655. if (nDevs)
  2656. clUnloadCompiler();
  2657. /* start GPU mining threads */
  2658. for (j = 0; j < nDevs * opt_g_threads; j++) {
  2659. int gpu = j % nDevs;
  2660. gpus[gpu].is_gpu = 1;
  2661. gpus[gpu].cpu_gpu = gpu;
  2662. /* Skip devices not set to mine */
  2663. if (!gpu_devices[gpu])
  2664. continue;
  2665. thr = &thr_info[i];
  2666. thr->id = i;
  2667. thr->cgpu = &gpus[gpu];
  2668. thr->q = tq_new();
  2669. if (!thr->q)
  2670. quit(1, "tq_new failed in starting gpu mining threads");
  2671. applog(LOG_INFO, "Init GPU thread %i", i);
  2672. clStates[i] = initCl(gpu, name, sizeof(name));
  2673. if (!clStates[i]) {
  2674. applog(LOG_ERR, "Failed to init GPU thread %d", i);
  2675. continue;
  2676. }
  2677. applog(LOG_INFO, "initCl() finished. Found %s", name);
  2678. thread_reportin(thr);
  2679. if (unlikely(pthread_create(&thr->pth, NULL, gpuminer_thread, thr)))
  2680. quit(1, "thread %d create failed", i);
  2681. i++;
  2682. }
  2683. /* Free up resources */
  2684. if (nDevs)
  2685. clUnloadCompiler();
  2686. applog(LOG_INFO, "%d gpu miner threads started", gpu_threads);
  2687. #endif
  2688. /* start CPU mining threads */
  2689. for (i = gpu_threads; i < mining_threads; i++) {
  2690. int cpu = (i - gpu_threads) % num_processors;
  2691. thr = &thr_info[i];
  2692. thr->id = i;
  2693. cpus[cpu].cpu_gpu = cpu;
  2694. thr->cgpu = &cpus[cpu];
  2695. thr->q = tq_new();
  2696. if (!thr->q)
  2697. quit(1, "tq_new failed in starting cpu mining threads");
  2698. thread_reportin(thr);
  2699. if (unlikely(pthread_create(&thr->pth, NULL, miner_thread, thr)))
  2700. quit(1, "thread %d create failed", i);
  2701. }
  2702. applog(LOG_INFO, "%d cpu miner threads started, "
  2703. "using SHA256 '%s' algorithm.",
  2704. opt_n_threads,
  2705. algo_names[opt_algo]);
  2706. watchdog_thr_id = mining_threads + 2;
  2707. thr = &thr_info[watchdog_thr_id];
  2708. /* start wakeup thread */
  2709. if (pthread_create(&thr->pth, NULL, watchdog_thread, NULL))
  2710. quit(1, "wakeup thread create failed");
  2711. /* Restart count as it will be wrong till all threads are started */
  2712. pthread_mutex_lock(&hash_lock);
  2713. gettimeofday(&total_tv_start, NULL);
  2714. gettimeofday(&total_tv_end, NULL);
  2715. total_mhashes_done = 0;
  2716. pthread_mutex_unlock(&hash_lock);
  2717. /* Now that everything's ready put enough work in the queue */
  2718. for (i = 0; i < opt_queue + mining_threads; i++) {
  2719. if (unlikely(!queue_request()))
  2720. quit(1, "Failed to queue_request in main");
  2721. if (!opt_quiet)
  2722. print_status(i);
  2723. }
  2724. /* Create curses input thread for keyboard input */
  2725. input_thr_id = mining_threads + 4;
  2726. thr = &thr_info[input_thr_id];
  2727. if (pthread_create(&thr->pth, NULL, input_thread, thr))
  2728. quit(1, "input thread create failed");
  2729. pthread_detach(thr->pth);
  2730. /* main loop - simply wait for workio thread to exit */
  2731. pthread_join(thr_info[work_thr_id].pth, NULL);
  2732. applog(LOG_INFO, "workio thread dead, exiting.");
  2733. gettimeofday(&total_tv_end, NULL);
  2734. disable_curses();
  2735. if (!opt_quiet && successful_connect)
  2736. print_summary();
  2737. if (gpu_threads)
  2738. free(gpus);
  2739. if (opt_n_threads)
  2740. free(cpus);
  2741. curl_global_cleanup();
  2742. return 0;
  2743. }