main.c 83 KB

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