main.c 83 KB

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