main.c 90 KB

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