main.c 93 KB

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