main.c 92 KB

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