main.c 92 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537
  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. #if defined(WANT_X8664_SSE4) && defined(__SSE4_1__)
  140. static enum sha256_algos opt_algo = ALGO_SSE4_64;
  141. #elif defined(WANT_X8664_SSE2) && defined(__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. leaveok(logwin, false);
  863. leaveok(statuswin, false);
  864. leaveok(mainwin, false);
  865. nocbreak();
  866. echo();
  867. delwin(logwin);
  868. delwin(statuswin);
  869. delwin(mainwin);
  870. endwin();
  871. refresh();
  872. #ifdef WIN32
  873. // Move the cursor to after curses output.
  874. HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
  875. CONSOLE_SCREEN_BUFFER_INFO csbi;
  876. COORD coord;
  877. if (GetConsoleScreenBufferInfo(hout, &csbi)) {
  878. coord.X = 0;
  879. coord.Y = csbi.dwSize.Y - 1;
  880. SetConsoleCursorPosition(hout, coord);
  881. }
  882. #endif
  883. }
  884. }
  885. void kill_work(void)
  886. {
  887. struct workio_cmd *wc;
  888. struct thr_info *thr;
  889. unsigned int i;
  890. disable_curses();
  891. applog(LOG_INFO, "Received kill message");
  892. /* Kill the watchdog thread */
  893. thr = &thr_info[watchdog_thr_id];
  894. pthread_cancel(*thr->pth);
  895. /* Stop the mining threads*/
  896. for (i = 0; i < mining_threads; i++) {
  897. thr = &thr_info[i];
  898. if (!thr->pth)
  899. continue;
  900. tq_freeze(thr->q);
  901. /* No need to check if this succeeds or not */
  902. pthread_cancel(*thr->pth);
  903. }
  904. /* Stop the others */
  905. thr = &thr_info[stage_thr_id];
  906. pthread_cancel(*thr->pth);
  907. thr = &thr_info[longpoll_thr_id];
  908. pthread_cancel(*thr->pth);
  909. wc = calloc(1, sizeof(*wc));
  910. if (unlikely(!wc)) {
  911. applog(LOG_ERR, "Failed to calloc wc in kill_work");
  912. /* We're just trying to die anyway, so forget graceful */
  913. exit (1);
  914. }
  915. wc->cmd = WC_DIE;
  916. wc->thr = 0;
  917. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  918. applog(LOG_ERR, "Failed to tq_push work in kill_work");
  919. exit (1);
  920. }
  921. }
  922. static void sighandler(int sig)
  923. {
  924. /* Restore signal handlers so we can still quit if kill_work fails */
  925. sigaction(SIGTERM, &termhandler, NULL);
  926. sigaction(SIGINT, &inthandler, NULL);
  927. kill_work();
  928. }
  929. static void *get_work_thread(void *userdata)
  930. {
  931. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  932. struct work *ret_work;
  933. int failures = 0;
  934. pthread_detach(pthread_self());
  935. ret_work = calloc(1, sizeof(*ret_work));
  936. if (unlikely(!ret_work)) {
  937. applog(LOG_ERR, "Failed to calloc ret_work in workio_get_work");
  938. kill_work();
  939. goto out;
  940. }
  941. /* obtain new work from bitcoin via JSON-RPC */
  942. while (!get_upstream_work(ret_work)) {
  943. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  944. applog(LOG_ERR, "json_rpc_call failed, terminating workio thread");
  945. free(ret_work);
  946. kill_work();
  947. goto out;
  948. }
  949. /* pause, then restart work-request loop */
  950. applog(LOG_DEBUG, "json_rpc_call failed on get work, retry after %d seconds",
  951. opt_fail_pause);
  952. sleep(opt_fail_pause);
  953. }
  954. /* send work to requesting thread */
  955. if (unlikely(!tq_push(thr_info[stage_thr_id].q, ret_work))) {
  956. applog(LOG_ERR, "Failed to tq_push work in workio_get_work");
  957. kill_work();
  958. free(ret_work);
  959. }
  960. out:
  961. workio_cmd_free(wc);
  962. return NULL;
  963. }
  964. static bool workio_get_work(struct workio_cmd *wc)
  965. {
  966. pthread_t get_thread;
  967. if (unlikely(pthread_create(&get_thread, NULL, get_work_thread, (void *)wc))) {
  968. applog(LOG_ERR, "Failed to create get_work_thread");
  969. return false;
  970. }
  971. return true;
  972. }
  973. static bool stale_work(struct work *work)
  974. {
  975. bool ret = false;
  976. char *hexstr;
  977. /* Only use the primary pool for determination as the work may
  978. * interleave at times of new blocks */
  979. if (work->pool != current_pool())
  980. return ret;
  981. hexstr = bin2hex(work->data, 36);
  982. if (unlikely(!hexstr)) {
  983. applog(LOG_ERR, "submit_work_thread OOM");
  984. return ret;
  985. }
  986. if (strncmp(hexstr, current_block, 36))
  987. ret = true;
  988. free(hexstr);
  989. return ret;
  990. }
  991. static void *submit_work_thread(void *userdata)
  992. {
  993. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  994. struct work *work = wc->u.work;
  995. struct pool *pool = work->pool;
  996. int failures = 0;
  997. pthread_detach(pthread_self());
  998. if (stale_work(work)) {
  999. applog(LOG_WARNING, "Stale share detected, discarding");
  1000. total_stale++;
  1001. pool->stale_shares++;
  1002. goto out;
  1003. }
  1004. /* submit solution to bitcoin via JSON-RPC */
  1005. while (!submit_upstream_work(work)) {
  1006. if (stale_work(work)) {
  1007. applog(LOG_WARNING, "Stale share detected, discarding");
  1008. total_stale++;
  1009. pool->stale_shares++;
  1010. break;
  1011. }
  1012. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  1013. applog(LOG_ERR, "Failed %d retries ...terminating workio thread", opt_retries);
  1014. kill_work();
  1015. break;
  1016. }
  1017. /* pause, then restart work-request loop */
  1018. applog(LOG_INFO, "json_rpc_call failed on submit_work, retry after %d seconds",
  1019. opt_fail_pause);
  1020. sleep(opt_fail_pause);
  1021. }
  1022. out:
  1023. workio_cmd_free(wc);
  1024. return NULL;
  1025. }
  1026. static bool workio_submit_work(struct workio_cmd *wc)
  1027. {
  1028. pthread_t submit_thread;
  1029. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, (void *)wc))) {
  1030. applog(LOG_ERR, "Failed to create submit_work_thread");
  1031. return false;
  1032. }
  1033. return true;
  1034. }
  1035. static void inc_staged(struct pool *pool, int inc, bool lp)
  1036. {
  1037. pthread_mutex_lock(&stgd_lock);
  1038. if (lp) {
  1039. lp_staged += inc;
  1040. total_staged += inc;
  1041. } else if (lp_staged)
  1042. --lp_staged;
  1043. else
  1044. total_staged += inc;
  1045. pthread_mutex_unlock(&stgd_lock);
  1046. }
  1047. static void dec_staged(int inc)
  1048. {
  1049. pthread_mutex_lock(&stgd_lock);
  1050. total_staged -= inc;
  1051. pthread_mutex_unlock(&stgd_lock);
  1052. }
  1053. static int requests_staged(void)
  1054. {
  1055. int ret;
  1056. pthread_mutex_lock(&stgd_lock);
  1057. ret = total_staged;
  1058. pthread_mutex_unlock(&stgd_lock);
  1059. return ret;
  1060. }
  1061. static int real_staged(void)
  1062. {
  1063. int ret;
  1064. pthread_mutex_lock(&stgd_lock);
  1065. ret = total_staged - lp_staged;
  1066. pthread_mutex_unlock(&stgd_lock);
  1067. return ret;
  1068. }
  1069. /* Find the pool that currently has the highest priority */
  1070. static struct pool *priority_pool(int choice)
  1071. {
  1072. struct pool *ret = NULL;
  1073. int i;
  1074. for (i = 0; i < total_pools; i++) {
  1075. struct pool *pool = pools[i];
  1076. if (pool->prio == choice) {
  1077. ret = pool;
  1078. break;
  1079. }
  1080. }
  1081. if (unlikely(!ret)) {
  1082. applog(LOG_ERR, "WTF No pool %d found!", choice);
  1083. return pools[choice];
  1084. }
  1085. return ret;
  1086. }
  1087. static void restart_longpoll(void);
  1088. static void switch_pools(struct pool *selected)
  1089. {
  1090. struct pool *pool, *last_pool;
  1091. int i, pool_no;
  1092. pthread_mutex_lock(&control_lock);
  1093. last_pool = currentpool;
  1094. pool_no = currentpool->pool_no;
  1095. /* Switch selected to pool number 0 and move the rest down */
  1096. if (selected) {
  1097. if (selected->prio != 0) {
  1098. for (i = 0; i < total_pools; i++) {
  1099. pool = pools[i];
  1100. if (pool->prio < selected->prio)
  1101. pool->prio++;
  1102. }
  1103. selected->prio = 0;
  1104. }
  1105. }
  1106. switch (pool_strategy) {
  1107. /* Both of these set to the master pool */
  1108. case POOL_FAILOVER:
  1109. case POOL_LOADBALANCE:
  1110. for (i = 0; i < total_pools; i++) {
  1111. pool = priority_pool(i);
  1112. if (!pool->idle && pool->enabled) {
  1113. pool_no = pool->pool_no;
  1114. break;
  1115. }
  1116. }
  1117. break;
  1118. /* Both of these simply increment and cycle */
  1119. case POOL_ROUNDROBIN:
  1120. case POOL_ROTATE:
  1121. if (selected) {
  1122. pool_no = selected->pool_no;
  1123. break;
  1124. }
  1125. pool_no++;
  1126. if (pool_no >= total_pools)
  1127. pool_no = 0;
  1128. break;
  1129. default:
  1130. break;
  1131. }
  1132. currentpool = pools[pool_no];
  1133. pool = currentpool;
  1134. pthread_mutex_unlock(&control_lock);
  1135. if (pool != last_pool) {
  1136. applog(LOG_WARNING, "Switching to %s", pool->rpc_url);
  1137. restart_longpoll();
  1138. }
  1139. /* Reset the queued amount to allow more to be queued for the new pool */
  1140. pthread_mutex_lock(&qd_lock);
  1141. total_queued = 0;
  1142. pthread_mutex_unlock(&qd_lock);
  1143. inc_staged(pool, 1, true);
  1144. }
  1145. static void set_curblock(char *hexstr)
  1146. {
  1147. struct timeval tv_now;
  1148. struct tm tm;
  1149. memcpy(current_block, hexstr, 36);
  1150. gettimeofday(&tv_now, NULL);
  1151. localtime_r(&tv_now.tv_sec, &tm);
  1152. sprintf(blockdate, "[%d-%02d-%02d %02d:%02d:%02d]",
  1153. tm.tm_year + 1900,
  1154. tm.tm_mon + 1,
  1155. tm.tm_mday,
  1156. tm.tm_hour,
  1157. tm.tm_min,
  1158. tm.tm_sec);
  1159. }
  1160. static void test_work_current(struct work *work)
  1161. {
  1162. char *hexstr;
  1163. /* Only use the primary pool for determination */
  1164. if (work->pool != current_pool())
  1165. return;
  1166. hexstr = bin2hex(work->data, 36);
  1167. if (unlikely(!hexstr)) {
  1168. applog(LOG_ERR, "stage_thread OOM");
  1169. return;
  1170. }
  1171. /* current_block is blanked out on successful longpoll */
  1172. if (unlikely(strncmp(hexstr, current_block, 36))) {
  1173. if (block_changed != BLOCK_LP && block_changed != BLOCK_FIRST) {
  1174. block_changed = BLOCK_DETECT;
  1175. new_blocks++;
  1176. if (have_longpoll)
  1177. applog(LOG_WARNING, "New block detected on network before longpoll, waiting on fresh work");
  1178. else
  1179. applog(LOG_WARNING, "New block detected on network, waiting on fresh work");
  1180. /* As we can't flush the work from here, signal the
  1181. * wakeup thread to restart all the threads */
  1182. work_restart[watchdog_thr_id].restart = 1;
  1183. } else
  1184. block_changed = BLOCK_NONE;
  1185. set_curblock(hexstr);
  1186. }
  1187. free(hexstr);
  1188. }
  1189. static void *stage_thread(void *userdata)
  1190. {
  1191. struct thr_info *mythr = userdata;
  1192. bool ok = true;
  1193. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  1194. while (ok) {
  1195. struct work *work = NULL;
  1196. work = tq_pop(mythr->q, NULL);
  1197. if (unlikely(!work)) {
  1198. applog(LOG_ERR, "Failed to tq_pop in stage_thread");
  1199. ok = false;
  1200. break;
  1201. }
  1202. test_work_current(work);
  1203. if (unlikely(!tq_push(getq, work))) {
  1204. applog(LOG_ERR, "Failed to tq_push work in stage_thread");
  1205. ok = false;
  1206. break;
  1207. }
  1208. inc_staged(work->pool, 1, false);
  1209. }
  1210. tq_freeze(mythr->q);
  1211. return NULL;
  1212. }
  1213. static char *curses_input(const char *query);
  1214. static int curses_int(const char *query)
  1215. {
  1216. int ret;
  1217. char *cvar;
  1218. cvar = curses_input(query);
  1219. ret = atoi(cvar);
  1220. free(cvar);
  1221. return ret;
  1222. }
  1223. static bool input_pool(bool live);
  1224. static int active_pools(void)
  1225. {
  1226. int ret = 0;
  1227. int i;
  1228. for (i = 0; i < total_pools; i++) {
  1229. if ((pools[i])->enabled)
  1230. ret++;
  1231. }
  1232. return ret;
  1233. }
  1234. static void display_pool_summary(struct pool *pool)
  1235. {
  1236. double efficiency = 0.0;
  1237. wprintw(logwin, "Pool: %s\n", pool->rpc_url);
  1238. wprintw(logwin, " Queued work requests: %d\n", pool->getwork_requested);
  1239. wprintw(logwin, " Share submissions: %d\n", pool->accepted + pool->rejected);
  1240. wprintw(logwin, " Accepted shares: %d\n", pool->accepted);
  1241. wprintw(logwin, " Rejected shares: %d\n", pool->rejected);
  1242. if (pool->accepted || pool->rejected)
  1243. wprintw(logwin, " Reject ratio: %.1f\n", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  1244. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  1245. wprintw(logwin, " Efficiency (accepted / queued): %.0f%%\n", efficiency);
  1246. wprintw(logwin, " Discarded work due to new blocks: %d\n", pool->discarded_work);
  1247. wprintw(logwin, " Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  1248. wprintw(logwin, " Unable to get work from server occasions: %d\n", pool->localgen_occasions);
  1249. wprintw(logwin, " Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  1250. }
  1251. /* We can't remove the memory used for this struct pool because there may
  1252. * still be work referencing it. We just remove it from the pools list */
  1253. static void remove_pool(struct pool *pool)
  1254. {
  1255. int i, last_pool = total_pools - 1;
  1256. struct pool *other;
  1257. /* Boost priority of any lower prio than this one */
  1258. for (i = 0; i < total_pools; i++) {
  1259. other = pools[i];
  1260. if (other->prio > pool->prio)
  1261. other->prio--;
  1262. }
  1263. if (pool->pool_no < last_pool) {
  1264. /* Swap the last pool for this one */
  1265. (pools[last_pool])->pool_no = pool->pool_no;
  1266. pools[pool->pool_no] = pools[last_pool];
  1267. }
  1268. /* Give it an invalid number */
  1269. pool->pool_no = total_pools;
  1270. total_pools--;
  1271. }
  1272. static void display_pools(void)
  1273. {
  1274. struct pool *pool;
  1275. int selected, i;
  1276. char input;
  1277. opt_loginput = true;
  1278. immedok(logwin, true);
  1279. updated:
  1280. clear_logwin();
  1281. for (i = 0; i < total_pools; i++) {
  1282. pool = pools[i];
  1283. if (pool == current_pool())
  1284. wattron(logwin, A_BOLD);
  1285. if (!pool->enabled)
  1286. wattron(logwin, A_DIM);
  1287. wprintw(logwin, "%d: %s %s Priority %d: %s User:%s\n",
  1288. pool->pool_no,
  1289. pool->enabled? "Enabled" : "Disabled",
  1290. pool->idle? "Dead" : "Alive",
  1291. pool->prio,
  1292. pool->rpc_url, pool->rpc_user);
  1293. wattroff(logwin, A_BOLD | A_DIM);
  1294. }
  1295. retry:
  1296. wprintw(logwin, "\nCurrent pool management strategy: %s\n",
  1297. strategies[pool_strategy]);
  1298. if (pool_strategy == POOL_ROTATE)
  1299. wprintw(logwin, "Set to rotate every %d minutes\n", opt_rotate_period);
  1300. wprintw(logwin, "[A]dd pool [R]emove pool [D]isable pool [E]nable pool\n");
  1301. wprintw(logwin, "[C]hange management strategy [S]witch pool [I]nformation\n");
  1302. wprintw(logwin, "Or press any other key to continue\n");
  1303. wrefresh(logwin);
  1304. input = getch();
  1305. if (!strncasecmp(&input, "a", 1)) {
  1306. input_pool(true);
  1307. goto updated;
  1308. } else if (!strncasecmp(&input, "r", 1)) {
  1309. if (active_pools() <= 1) {
  1310. wprintw(logwin, "Cannot remove last pool");
  1311. goto retry;
  1312. }
  1313. selected = curses_int("Select pool number");
  1314. if (selected < 0 || selected >= total_pools) {
  1315. wprintw(logwin, "Invalid selection\n");
  1316. goto retry;
  1317. }
  1318. pool = pools[selected];
  1319. if (pool == current_pool())
  1320. switch_pools(NULL);
  1321. if (pool == current_pool()) {
  1322. wprintw(logwin, "Unable to remove pool due to activity\n");
  1323. goto retry;
  1324. }
  1325. pool->enabled = false;
  1326. remove_pool(pool);
  1327. goto updated;
  1328. } else if (!strncasecmp(&input, "s", 1)) {
  1329. selected = curses_int("Select pool number");
  1330. if (selected < 0 || selected >= total_pools) {
  1331. wprintw(logwin, "Invalid selection\n");
  1332. goto retry;
  1333. }
  1334. pool = pools[selected];
  1335. pool->enabled = true;
  1336. switch_pools(pool);
  1337. goto updated;
  1338. } else if (!strncasecmp(&input, "d", 1)) {
  1339. if (active_pools() <= 1) {
  1340. wprintw(logwin, "Cannot disable last pool");
  1341. goto retry;
  1342. }
  1343. selected = curses_int("Select pool number");
  1344. if (selected < 0 || selected >= total_pools) {
  1345. wprintw(logwin, "Invalid selection\n");
  1346. goto retry;
  1347. }
  1348. pool = pools[selected];
  1349. pool->enabled = false;
  1350. if (pool == current_pool())
  1351. switch_pools(NULL);
  1352. goto updated;
  1353. } else if (!strncasecmp(&input, "e", 1)) {
  1354. selected = curses_int("Select pool number");
  1355. if (selected < 0 || selected >= total_pools) {
  1356. wprintw(logwin, "Invalid selection\n");
  1357. goto retry;
  1358. }
  1359. pool = pools[selected];
  1360. pool->enabled = true;
  1361. if (pool->prio < current_pool()->prio)
  1362. switch_pools(pool);
  1363. goto updated;
  1364. } else if (!strncasecmp(&input, "c", 1)) {
  1365. for (i = 0; i <= TOP_STRATEGY; i++)
  1366. wprintw(logwin, "%d: %s\n", i, strategies[i]);
  1367. selected = curses_int("Select strategy number type");
  1368. if (selected < 0 || selected > TOP_STRATEGY) {
  1369. wprintw(logwin, "Invalid selection\n");
  1370. goto retry;
  1371. }
  1372. if (selected == POOL_ROTATE) {
  1373. opt_rotate_period = curses_int("Select interval in minutes");
  1374. if (opt_rotate_period < 0 || opt_rotate_period > 9999) {
  1375. opt_rotate_period = 0;
  1376. wprintw(logwin, "Invalid selection\n");
  1377. goto retry;
  1378. }
  1379. }
  1380. pool_strategy = selected;
  1381. switch_pools(NULL);
  1382. goto updated;
  1383. } else if (!strncasecmp(&input, "i", 1)) {
  1384. selected = curses_int("Select pool number");
  1385. if (selected < 0 || selected >= total_pools) {
  1386. wprintw(logwin, "Invalid selection\n");
  1387. goto retry;
  1388. }
  1389. pool = pools[selected];
  1390. display_pool_summary(pool);
  1391. goto retry;
  1392. }
  1393. clear_logwin();
  1394. immedok(logwin, false);
  1395. opt_loginput = false;
  1396. }
  1397. static void display_options(void)
  1398. {
  1399. int selected;
  1400. char input;
  1401. opt_loginput = true;
  1402. immedok(logwin, true);
  1403. retry:
  1404. clear_logwin();
  1405. wprintw(logwin, "\nToggle: [D]ebug [N]ormal [S]ilent [V]erbose [R]PC debug\n");
  1406. wprintw(logwin, "[L]og interval [C]lear\n");
  1407. wprintw(logwin, "Select an option or any other key to return\n");
  1408. input = getch();
  1409. if (!strncasecmp(&input, "s", 1)) {
  1410. opt_quiet ^= true;
  1411. applog(LOG_WARNING, "Silent mode %s", opt_quiet ? "enabled" : "disabled");
  1412. } else if (!strncasecmp(&input, "v", 1)) {
  1413. opt_log_output ^= true;
  1414. applog(LOG_WARNING, "Verbose mode %s", opt_log_output ? "enabled" : "disabled");
  1415. } else if (!strncasecmp(&input, "n", 1)) {
  1416. opt_log_output = false;
  1417. opt_debug = false;
  1418. opt_quiet = false;
  1419. opt_protocol = false;
  1420. applog(LOG_WARNING, "Output mode reset to normal");
  1421. } else if (!strncasecmp(&input, "d", 1)) {
  1422. opt_debug ^= true;
  1423. if (opt_debug)
  1424. opt_log_output = true;
  1425. applog(LOG_WARNING, "Debug mode %s", opt_debug ? "enabled" : "disabled");
  1426. } else if (!strncasecmp(&input, "r", 1)) {
  1427. opt_protocol ^= true;
  1428. applog(LOG_WARNING, "RPC protocol debugging %s", opt_protocol ? "enabled" : "disabled");
  1429. } else if (!strncasecmp(&input, "c", 1))
  1430. clear_logwin();
  1431. else if (!strncasecmp(&input, "l", 1)) {
  1432. selected = curses_int("Interval in seconds");
  1433. if (selected < 0 || selected > 9999) {
  1434. wprintw(logwin, "Invalid selection\n");
  1435. goto retry;
  1436. }
  1437. opt_log_interval = selected;
  1438. }
  1439. clear_logwin();
  1440. immedok(logwin, false);
  1441. opt_loginput = false;
  1442. }
  1443. static void set_options(void)
  1444. {
  1445. int selected;
  1446. char input;
  1447. opt_loginput = true;
  1448. immedok(logwin, true);
  1449. retry:
  1450. clear_logwin();
  1451. wprintw(logwin, "\n[D]ynamic mode: %s\n[L]ongpoll: %s\n",
  1452. opt_dynamic ? "On" : "Off", want_longpoll ? "On" : "Off");
  1453. if (opt_dynamic)
  1454. wprintw(logwin, "[I]ntensity: Dynamic\n");
  1455. else
  1456. wprintw(logwin, "[I]ntensity: %d\n", scan_intensity);
  1457. wprintw(logwin, "[Q]ueue: %d\n[S]cantime: %d\n[R]etries: %d\n[P]ause: %d\n",
  1458. opt_queue, opt_scantime, opt_retries, opt_fail_pause);
  1459. wprintw(logwin, "Select an option or any other key to return\n");
  1460. wrefresh(logwin);
  1461. input = getch();
  1462. if (!strncasecmp(&input, "q", 1)) {
  1463. selected = curses_int("Extra work items to queue");
  1464. if (selected < 0 || selected > 9999) {
  1465. wprintw(logwin, "Invalid selection\n");
  1466. goto retry;
  1467. }
  1468. opt_queue = selected;
  1469. goto retry;
  1470. } else if (!strncasecmp(&input, "d", 1)) {
  1471. opt_dynamic ^= true;
  1472. goto retry;
  1473. } else if (!strncasecmp(&input, "l", 1)) {
  1474. want_longpoll ^= true;
  1475. applog(LOG_WARNING, "Longpoll %s", want_longpoll ? "enabled" : "disabled");
  1476. restart_longpoll();
  1477. goto retry;
  1478. } else if (!strncasecmp(&input, "i", 1)) {
  1479. selected = curses_int("Set GPU scan intensity (-10 -> 10)");
  1480. if (selected < -10 || selected > 10) {
  1481. wprintw(logwin, "Invalid selection\n");
  1482. goto retry;
  1483. }
  1484. opt_dynamic = false;
  1485. scan_intensity = selected;
  1486. goto retry;
  1487. } else if (!strncasecmp(&input, "s", 1)) {
  1488. selected = curses_int("Set scantime in seconds");
  1489. if (selected < 0 || selected > 9999) {
  1490. wprintw(logwin, "Invalid selection\n");
  1491. goto retry;
  1492. }
  1493. opt_scantime = selected;
  1494. goto retry;
  1495. } else if (!strncasecmp(&input, "r", 1)) {
  1496. selected = curses_int("Retries before failing (-1 infinite)");
  1497. if (selected < -1 || selected > 9999) {
  1498. wprintw(logwin, "Invalid selection\n");
  1499. goto retry;
  1500. }
  1501. opt_retries = selected;
  1502. goto retry;
  1503. } else if (!strncasecmp(&input, "p", 1)) {
  1504. selected = curses_int("Seconds to pause before network retries");
  1505. if (selected < 1 || selected > 9999) {
  1506. wprintw(logwin, "Invalid selection\n");
  1507. goto retry;
  1508. }
  1509. opt_fail_pause = selected;
  1510. goto retry;
  1511. }
  1512. clear_logwin();
  1513. immedok(logwin, false);
  1514. opt_loginput = false;
  1515. }
  1516. static void *input_thread(void *userdata)
  1517. {
  1518. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  1519. if (!curses_active)
  1520. return NULL;
  1521. while (1) {
  1522. char input;
  1523. input = getch();
  1524. if (!strncasecmp(&input, "q", 1)) {
  1525. kill_work();
  1526. return NULL;
  1527. } else if (!strncasecmp(&input, "d", 1))
  1528. display_options();
  1529. else if (!strncasecmp(&input, "p", 1))
  1530. display_pools();
  1531. else if (!strncasecmp(&input, "s", 1))
  1532. set_options();
  1533. }
  1534. return NULL;
  1535. }
  1536. static void *workio_thread(void *userdata)
  1537. {
  1538. struct thr_info *mythr = userdata;
  1539. bool ok = true;
  1540. while (ok) {
  1541. struct workio_cmd *wc;
  1542. /* wait for workio_cmd sent to us, on our queue */
  1543. wc = tq_pop(mythr->q, NULL);
  1544. if (unlikely(!wc)) {
  1545. applog(LOG_ERR, "Failed to tq_pop in workio_thread");
  1546. ok = false;
  1547. break;
  1548. }
  1549. /* process workio_cmd */
  1550. switch (wc->cmd) {
  1551. case WC_GET_WORK:
  1552. ok = workio_get_work(wc);
  1553. break;
  1554. case WC_SUBMIT_WORK:
  1555. ok = workio_submit_work(wc);
  1556. break;
  1557. case WC_DIE:
  1558. default:
  1559. ok = false;
  1560. break;
  1561. }
  1562. }
  1563. tq_freeze(mythr->q);
  1564. return NULL;
  1565. }
  1566. static void thread_reportin(struct thr_info *thr)
  1567. {
  1568. gettimeofday(&thr->last, NULL);
  1569. thr->getwork = false;
  1570. }
  1571. static inline void thread_reportout(struct thr_info *thr)
  1572. {
  1573. thr->getwork = true;
  1574. }
  1575. static void hashmeter(int thr_id, struct timeval *diff,
  1576. unsigned long hashes_done)
  1577. {
  1578. struct timeval temp_tv_end, total_diff;
  1579. double khashes, secs;
  1580. double local_secs;
  1581. double utility, efficiency = 0.0;
  1582. static double local_mhashes_done = 0;
  1583. static double rolling_local = 0;
  1584. double local_mhashes = (double)hashes_done / 1000000.0;
  1585. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  1586. /* Update the last time this thread reported in */
  1587. if (thr_id >= 0)
  1588. gettimeofday(&thr_info[thr_id].last, NULL);
  1589. /* Don't bother calculating anything if we're not displaying it */
  1590. if (opt_quiet || !opt_log_interval)
  1591. return;
  1592. khashes = hashes_done / 1000.0;
  1593. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  1594. if (thr_id >= 0 && secs) {
  1595. /* So we can call hashmeter from a non worker thread */
  1596. if (opt_debug)
  1597. applog(LOG_DEBUG, "[thread %d: %lu hashes, %.0f khash/sec]",
  1598. thr_id, hashes_done, hashes_done / secs);
  1599. cgpu->local_mhashes += local_mhashes;
  1600. cgpu->total_mhashes += local_mhashes;
  1601. }
  1602. /* Totals are updated by all threads so can race without locking */
  1603. pthread_mutex_lock(&hash_lock);
  1604. gettimeofday(&temp_tv_end, NULL);
  1605. timeval_subtract(&total_diff, &temp_tv_end, &total_tv_end);
  1606. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  1607. total_mhashes_done += local_mhashes;
  1608. local_mhashes_done += local_mhashes;
  1609. if (total_diff.tv_sec < opt_log_interval)
  1610. /* Only update the total every opt_log_interval seconds */
  1611. goto out_unlock;
  1612. gettimeofday(&total_tv_end, NULL);
  1613. /* Use a rolling average by faking an exponential decay over 5 * log */
  1614. rolling_local = ((rolling_local * 0.9) + local_mhashes_done) / 1.9;
  1615. timeval_subtract(&total_diff, &total_tv_end, &total_tv_start);
  1616. total_secs = (double)total_diff.tv_sec +
  1617. ((double)total_diff.tv_usec / 1000000.0);
  1618. utility = total_accepted / ( total_secs ? total_secs : 1 ) * 60;
  1619. efficiency = total_getworks ? total_accepted * 100.0 / total_getworks : 0.0;
  1620. sprintf(statusline, "[(%ds):%.1f (avg):%.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]",
  1621. opt_log_interval, rolling_local / local_secs, total_mhashes_done / total_secs,
  1622. total_getworks, total_accepted, total_rejected, hw_errors, efficiency, utility);
  1623. if (!curses_active) {
  1624. printf("%s \r", statusline);
  1625. fflush(stdout);
  1626. } else
  1627. applog(LOG_INFO, "%s", statusline);
  1628. local_mhashes_done = 0;
  1629. out_unlock:
  1630. pthread_mutex_unlock(&hash_lock);
  1631. }
  1632. /* This is overkill, but at least we'll know accurately how much work is
  1633. * queued to prevent ever being left without work */
  1634. static void inc_queued(void)
  1635. {
  1636. pthread_mutex_lock(&qd_lock);
  1637. total_queued++;
  1638. pthread_mutex_unlock(&qd_lock);
  1639. }
  1640. static void dec_queued(void)
  1641. {
  1642. pthread_mutex_lock(&qd_lock);
  1643. if (total_queued > 0)
  1644. total_queued--;
  1645. pthread_mutex_unlock(&qd_lock);
  1646. dec_staged(1);
  1647. }
  1648. static int requests_queued(void)
  1649. {
  1650. int ret;
  1651. pthread_mutex_lock(&qd_lock);
  1652. ret = total_queued;
  1653. pthread_mutex_unlock(&qd_lock);
  1654. return ret;
  1655. }
  1656. static bool pool_active(struct pool *pool)
  1657. {
  1658. bool ret = false;
  1659. json_t *val;
  1660. CURL *curl;
  1661. curl = curl_easy_init();
  1662. if (unlikely(!curl)) {
  1663. applog(LOG_ERR, "CURL initialisation failed");
  1664. return false;
  1665. }
  1666. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  1667. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  1668. true, false, pool);
  1669. if (val) {
  1670. struct work *work = malloc(sizeof(struct work));
  1671. bool rc;
  1672. if (!work) {
  1673. applog(LOG_ERR, "Unable to malloc work in pool_active");
  1674. goto out;
  1675. }
  1676. rc = work_decode(json_object_get(val, "result"), work);
  1677. if (rc) {
  1678. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  1679. pool->pool_no, pool->rpc_url);
  1680. work->pool = pool;
  1681. tq_push(thr_info[stage_thr_id].q, work);
  1682. total_getworks++;
  1683. pool->getwork_requested++;
  1684. inc_queued();
  1685. ret = true;
  1686. gettimeofday(&pool->tv_idle, NULL);
  1687. } else {
  1688. applog(LOG_DEBUG, "Successfully retreived but FAILED to decipher work from pool %u %s",
  1689. pool->pool_no, pool->rpc_url);
  1690. free(work);
  1691. }
  1692. json_decref(val);
  1693. } else {
  1694. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  1695. pool->pool_no, pool->rpc_url);
  1696. applog(LOG_WARNING, "Pool down, URL or credentials invalid");
  1697. }
  1698. out:
  1699. curl_easy_cleanup(curl);
  1700. return ret;
  1701. }
  1702. static void pool_died(struct pool *pool)
  1703. {
  1704. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  1705. gettimeofday(&pool->tv_idle, NULL);
  1706. switch_pools(NULL);
  1707. }
  1708. static void pool_resus(struct pool *pool)
  1709. {
  1710. applog(LOG_WARNING, "Pool %d %s recovered", pool->pool_no, pool->rpc_url);
  1711. if (pool->prio < current_pool()->prio && pool_strategy == POOL_FAILOVER)
  1712. switch_pools(NULL);
  1713. }
  1714. static bool queue_request(void)
  1715. {
  1716. int maxq = opt_queue + mining_threads;
  1717. struct workio_cmd *wc;
  1718. /* If we've been generating lots of local work we may already have
  1719. * enough in the queue */
  1720. if (requests_queued() >= maxq || real_staged() >= maxq)
  1721. return true;
  1722. /* fill out work request message */
  1723. wc = calloc(1, sizeof(*wc));
  1724. if (unlikely(!wc)) {
  1725. applog(LOG_ERR, "Failed to tq_pop in queue_request");
  1726. return false;
  1727. }
  1728. wc->cmd = WC_GET_WORK;
  1729. /* The get work does not belong to any thread */
  1730. wc->thr = NULL;
  1731. /* send work request to workio thread */
  1732. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  1733. applog(LOG_ERR, "Failed to tq_push in queue_request");
  1734. workio_cmd_free(wc);
  1735. return false;
  1736. }
  1737. inc_queued();
  1738. return true;
  1739. }
  1740. static void discard_staged(void)
  1741. {
  1742. struct timespec abstime = {};
  1743. struct timeval now;
  1744. struct work *work_heap;
  1745. struct pool *pool;
  1746. /* Just in case we fell in a hole and missed a queue filling */
  1747. if (unlikely(!requests_staged()))
  1748. return;
  1749. gettimeofday(&now, NULL);
  1750. abstime.tv_sec = now.tv_sec + 60;
  1751. work_heap = tq_pop(getq, &abstime);
  1752. if (unlikely(!work_heap))
  1753. return;
  1754. pool = work_heap->pool;
  1755. free(work_heap);
  1756. dec_queued();
  1757. pool->discarded_work++;
  1758. total_discarded++;
  1759. }
  1760. static void flush_requests(void)
  1761. {
  1762. struct pool *pool = current_pool();
  1763. int i, stale;
  1764. /* We should have one fresh work item staged from the block change. */
  1765. stale = requests_staged() - 1;
  1766. /* Temporarily increase the staged count so that get_work thinks there
  1767. * is work available instead of making threads reuse existing work */
  1768. inc_staged(pool, mining_threads, true);
  1769. for (i = 0; i < stale; i++) {
  1770. /* Queue a whole batch of new requests */
  1771. if (unlikely(!queue_request())) {
  1772. applog(LOG_ERR, "Failed to queue requests in flush_requests");
  1773. kill_work();
  1774. break;
  1775. }
  1776. /* Pop off the old requests. Cancelling the requests would be better
  1777. * but is tricky */
  1778. discard_staged();
  1779. }
  1780. }
  1781. static inline bool can_roll(struct work *work)
  1782. {
  1783. return (work->pool && !stale_work(work) && work->pool->has_rolltime &&
  1784. work->rolls < 11);
  1785. }
  1786. static bool get_work(struct work *work, bool queued, struct thr_info *thr,
  1787. const int thr_id, uint32_t hash_div)
  1788. {
  1789. struct timespec abstime = {};
  1790. struct timeval now;
  1791. struct work *work_heap;
  1792. struct pool *pool;
  1793. bool ret = false;
  1794. int failures = 0;
  1795. /* Tell the watchdog thread this thread is waiting on getwork and
  1796. * should not be restarted */
  1797. thread_reportout(thr);
  1798. retry:
  1799. pool = current_pool();
  1800. if (unlikely(!queued && !queue_request())) {
  1801. applog(LOG_WARNING, "Failed to queue_request in get_work");
  1802. goto out;
  1803. }
  1804. if (!requests_staged() && can_roll(work)) {
  1805. uint32_t *work_ntime;
  1806. uint32_t ntime;
  1807. /* Only print this message once each time we shift to localgen */
  1808. if (!pool_tset(pool, &pool->idle)) {
  1809. applog(LOG_WARNING, "Pool %d not providing work fast enough, generating work locally",
  1810. pool->pool_no);
  1811. pool->localgen_occasions++;
  1812. total_lo++;
  1813. gettimeofday(&pool->tv_idle, NULL);
  1814. } else {
  1815. struct timeval tv_now, diff;
  1816. gettimeofday(&tv_now, NULL);
  1817. timeval_subtract(&diff, &tv_now, &pool->tv_idle);
  1818. /* Attempt to switch pools if this one has been unresponsive for >half
  1819. * a block's duration */
  1820. if (diff.tv_sec > 300) {
  1821. pool_died(pool);
  1822. goto retry;
  1823. }
  1824. }
  1825. work_ntime = (uint32_t *)(work->data + 68);
  1826. ntime = be32toh(*work_ntime);
  1827. ntime++;
  1828. *work_ntime = htobe32(ntime);
  1829. ret = true;
  1830. local_work++;
  1831. work->rolls++;
  1832. goto out;
  1833. }
  1834. gettimeofday(&now, NULL);
  1835. abstime.tv_sec = now.tv_sec + 60;
  1836. /* wait for 1st response, or get cached response */
  1837. work_heap = tq_pop(getq, &abstime);
  1838. if (unlikely(!work_heap)) {
  1839. /* Attempt to switch pools if this one has mandatory work that
  1840. * has timed out or does not support rolltime */
  1841. pool->localgen_occasions++;
  1842. total_lo++;
  1843. pool_died(pool);
  1844. goto retry;
  1845. }
  1846. pool = work_heap->pool;
  1847. /* If we make it here we have succeeded in getting fresh work */
  1848. if (pool_tclear(pool, &pool->idle))
  1849. pool_resus(pool);
  1850. dec_queued();
  1851. memcpy(work, work_heap, sizeof(*work));
  1852. ret = true;
  1853. free(work_heap);
  1854. out:
  1855. if (unlikely(ret == false)) {
  1856. if ((opt_retries >= 0) && (++failures > opt_retries)) {
  1857. applog(LOG_ERR, "Failed %d times to get_work");
  1858. return ret;
  1859. }
  1860. applog(LOG_DEBUG, "Retrying after %d seconds", opt_fail_pause);
  1861. sleep(opt_fail_pause);
  1862. goto retry;
  1863. }
  1864. work->thr_id = thr_id;
  1865. thread_reportin(thr);
  1866. return ret;
  1867. }
  1868. static bool submit_work_sync(struct thr_info *thr, const struct work *work_in)
  1869. {
  1870. struct workio_cmd *wc;
  1871. /* fill out work request message */
  1872. wc = calloc(1, sizeof(*wc));
  1873. if (unlikely(!wc)) {
  1874. applog(LOG_ERR, "Failed to calloc wc in submit_work_sync");
  1875. return false;
  1876. }
  1877. wc->u.work = malloc(sizeof(*work_in));
  1878. if (unlikely(!wc->u.work)) {
  1879. applog(LOG_ERR, "Failed to calloc work in submit_work_sync");
  1880. goto err_out;
  1881. }
  1882. wc->cmd = WC_SUBMIT_WORK;
  1883. wc->thr = thr;
  1884. memcpy(wc->u.work, work_in, sizeof(*work_in));
  1885. /* send solution to workio thread */
  1886. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  1887. applog(LOG_ERR, "Failed to tq_push work in submit_work_sync");
  1888. goto err_out;
  1889. }
  1890. return true;
  1891. err_out:
  1892. workio_cmd_free(wc);
  1893. return false;
  1894. }
  1895. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  1896. {
  1897. work->data[64+12+0] = (nonce>>0) & 0xff;
  1898. work->data[64+12+1] = (nonce>>8) & 0xff;
  1899. work->data[64+12+2] = (nonce>>16) & 0xff;
  1900. work->data[64+12+3] = (nonce>>24) & 0xff;
  1901. /* Do one last check before attempting to submit the work */
  1902. if (!fulltest(work->data + 64, work->target))
  1903. return true;
  1904. return submit_work_sync(thr, work);
  1905. }
  1906. static void *miner_thread(void *userdata)
  1907. {
  1908. struct work work __attribute__((aligned(128)));
  1909. struct thr_info *mythr = userdata;
  1910. const int thr_id = mythr->id;
  1911. uint32_t max_nonce = 0xffffff, total_hashes = 0;
  1912. unsigned long hashes_done = max_nonce;
  1913. bool needs_work = true;
  1914. /* Try to cycle approximately 5 times before each log update */
  1915. const unsigned long cycle = opt_log_interval / 5 ? : 1;
  1916. /* Request the next work item at 2/3 of the scantime */
  1917. unsigned const int request_interval = opt_scantime * 2 / 3 ? : 1;
  1918. unsigned const long request_nonce = MAXTHREADS / 3 * 2;
  1919. bool requested = true;
  1920. uint32_t hash_div = 1;
  1921. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  1922. /* Set worker threads to nice 19 and then preferentially to SCHED_IDLE
  1923. * and if that fails, then SCHED_BATCH. No need for this to be an
  1924. * error if it fails */
  1925. setpriority(PRIO_PROCESS, 0, 19);
  1926. drop_policy();
  1927. /* Cpu affinity only makes sense if the number of threads is a multiple
  1928. * of the number of CPUs */
  1929. if (!(opt_n_threads % num_processors))
  1930. affine_to_cpu(thr_id - gpu_threads, dev_from_id(thr_id));
  1931. /* Invalidate pool so it fails can_roll() test */
  1932. work.pool = NULL;
  1933. while (1) {
  1934. struct timeval tv_workstart, tv_start, tv_end, diff;
  1935. uint64_t max64;
  1936. bool rc;
  1937. if (needs_work) {
  1938. gettimeofday(&tv_workstart, NULL);
  1939. /* obtain new work from internal workio thread */
  1940. if (unlikely(!get_work(&work, requested, mythr, thr_id, hash_div))) {
  1941. applog(LOG_ERR, "work retrieval failed, exiting "
  1942. "mining thread %d", thr_id);
  1943. goto out;
  1944. }
  1945. mythr->cgpu->getworks++;
  1946. needs_work = requested = false;
  1947. total_hashes = 0;
  1948. work.blk.nonce = work.res_nonce;;
  1949. max_nonce = work.blk.nonce + hashes_done;
  1950. }
  1951. hashes_done = 0;
  1952. gettimeofday(&tv_start, NULL);
  1953. /* scan nonces for a proof-of-work hash */
  1954. switch (opt_algo) {
  1955. case ALGO_C:
  1956. rc = scanhash_c(thr_id, work.midstate, work.data + 64,
  1957. work.hash1, work.hash, work.target,
  1958. max_nonce, &hashes_done,
  1959. work.blk.nonce);
  1960. break;
  1961. #ifdef WANT_X8664_SSE2
  1962. case ALGO_SSE2_64: {
  1963. unsigned int rc5 =
  1964. scanhash_sse2_64(thr_id, work.midstate, work.data + 64,
  1965. work.hash1, work.hash,
  1966. work.target,
  1967. max_nonce, &hashes_done,
  1968. work.blk.nonce);
  1969. rc = (rc5 == -1) ? false : true;
  1970. }
  1971. break;
  1972. #endif
  1973. #ifdef WANT_X8664_SSE4
  1974. case ALGO_SSE4_64: {
  1975. unsigned int rc5 =
  1976. scanhash_sse4_64(thr_id, work.midstate, work.data + 64,
  1977. work.hash1, work.hash,
  1978. work.target,
  1979. max_nonce, &hashes_done,
  1980. work.blk.nonce);
  1981. rc = (rc5 == -1) ? false : true;
  1982. }
  1983. break;
  1984. #endif
  1985. #ifdef WANT_SSE2_4WAY
  1986. case ALGO_4WAY: {
  1987. unsigned int rc4 =
  1988. ScanHash_4WaySSE2(thr_id, work.midstate, work.data + 64,
  1989. work.hash1, work.hash,
  1990. work.target,
  1991. max_nonce, &hashes_done,
  1992. work.blk.nonce);
  1993. rc = (rc4 == -1) ? false : true;
  1994. }
  1995. break;
  1996. #endif
  1997. #ifdef WANT_VIA_PADLOCK
  1998. case ALGO_VIA:
  1999. rc = scanhash_via(thr_id, work.data, work.target,
  2000. max_nonce, &hashes_done,
  2001. work.blk.nonce);
  2002. break;
  2003. #endif
  2004. case ALGO_CRYPTOPP:
  2005. rc = scanhash_cryptopp(thr_id, work.midstate, work.data + 64,
  2006. work.hash1, work.hash, work.target,
  2007. max_nonce, &hashes_done,
  2008. work.blk.nonce);
  2009. break;
  2010. #ifdef WANT_CRYPTOPP_ASM32
  2011. case ALGO_CRYPTOPP_ASM32:
  2012. rc = scanhash_asm32(thr_id, work.midstate, work.data + 64,
  2013. work.hash1, work.hash, work.target,
  2014. max_nonce, &hashes_done,
  2015. work.blk.nonce);
  2016. break;
  2017. #endif
  2018. default:
  2019. /* should never happen */
  2020. goto out;
  2021. }
  2022. /* record scanhash elapsed time */
  2023. gettimeofday(&tv_end, NULL);
  2024. timeval_subtract(&diff, &tv_end, &tv_start);
  2025. hashes_done -= work.blk.nonce;
  2026. hashmeter(thr_id, &diff, hashes_done);
  2027. total_hashes += hashes_done;
  2028. work.blk.nonce += hashes_done;
  2029. /* adjust max_nonce to meet target cycle time */
  2030. if (diff.tv_usec > 500000)
  2031. diff.tv_sec++;
  2032. if (diff.tv_sec && diff.tv_sec != cycle) {
  2033. max64 = work.blk.nonce +
  2034. ((uint64_t)hashes_done * cycle) / diff.tv_sec;
  2035. } else
  2036. max64 = work.blk.nonce + hashes_done;
  2037. if (max64 > 0xfffffffaULL)
  2038. max64 = 0xfffffffaULL;
  2039. max_nonce = max64;
  2040. /* if nonce found, submit work */
  2041. if (unlikely(rc)) {
  2042. if (opt_debug)
  2043. applog(LOG_DEBUG, "CPU %d found something?", dev_from_id(thr_id));
  2044. if (unlikely(!submit_work_sync(mythr, &work))) {
  2045. applog(LOG_ERR, "Failed to submit_work_sync in miner_thread %d", thr_id);
  2046. break;
  2047. }
  2048. work.blk.nonce += 4;
  2049. }
  2050. timeval_subtract(&diff, &tv_end, &tv_workstart);
  2051. if (!requested && (diff.tv_sec > request_interval || work.blk.nonce > request_nonce)) {
  2052. if (unlikely(!queue_request())) {
  2053. applog(LOG_ERR, "Failed to queue_request in miner_thread %d", thr_id);
  2054. goto out;
  2055. }
  2056. requested = true;
  2057. }
  2058. if (diff.tv_sec > opt_scantime) {
  2059. hash_div = (MAXTHREADS / total_hashes) ? : 1;
  2060. needs_work = true;
  2061. } else if (work_restart[thr_id].restart || stale_work(&work) ||
  2062. work.blk.nonce >= MAXTHREADS - hashes_done)
  2063. needs_work = true;
  2064. }
  2065. out:
  2066. tq_freeze(mythr->q);
  2067. return NULL;
  2068. }
  2069. enum {
  2070. STAT_SLEEP_INTERVAL = 1,
  2071. STAT_CTR_INTERVAL = 10000000,
  2072. FAILURE_INTERVAL = 30,
  2073. };
  2074. #ifdef HAVE_OPENCL
  2075. static _clState *clStates[16];
  2076. static cl_int queue_poclbm_kernel(_clState *clState, dev_blk_ctx *blk)
  2077. {
  2078. cl_kernel *kernel = &clState->kernel;
  2079. cl_int status = 0;
  2080. int num = 0;
  2081. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_a);
  2082. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_b);
  2083. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_c);
  2084. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_d);
  2085. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_e);
  2086. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_f);
  2087. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_g);
  2088. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_h);
  2089. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_b);
  2090. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_c);
  2091. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_d);
  2092. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_f);
  2093. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_g);
  2094. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_h);
  2095. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->nonce);
  2096. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW0);
  2097. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW1);
  2098. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW2);
  2099. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW3);
  2100. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW15);
  2101. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW01r);
  2102. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e);
  2103. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e2);
  2104. status |= clSetKernelArg(*kernel, num++, sizeof(clState->outputBuffer),
  2105. (void *)&clState->outputBuffer);
  2106. return status;
  2107. }
  2108. static cl_int queue_phatk_kernel(_clState *clState, dev_blk_ctx *blk)
  2109. {
  2110. cl_kernel *kernel = &clState->kernel;
  2111. cl_int status = 0;
  2112. int num = 0;
  2113. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_a);
  2114. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_b);
  2115. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_c);
  2116. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_d);
  2117. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_e);
  2118. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_f);
  2119. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_g);
  2120. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_h);
  2121. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_b);
  2122. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_c);
  2123. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->C1addK5);
  2124. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->D1A);
  2125. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_f);
  2126. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_g);
  2127. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_h);
  2128. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->nonce);
  2129. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W2A);
  2130. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W16);
  2131. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W17);
  2132. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W17_2);
  2133. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreVal4addT1);
  2134. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->T1substate0);
  2135. status |= clSetKernelArg(*kernel, num++, sizeof(clState->outputBuffer),
  2136. (void *)&clState->outputBuffer);
  2137. return status;
  2138. }
  2139. static void set_threads_hashes(unsigned int vectors, unsigned int *threads,
  2140. unsigned int *hashes, size_t *globalThreads,
  2141. unsigned int minthreads)
  2142. {
  2143. *threads = 1 << (15 + scan_intensity);
  2144. if (*threads < minthreads)
  2145. *threads = minthreads;
  2146. *globalThreads = *threads;
  2147. *hashes = *threads * vectors;
  2148. }
  2149. static void *gpuminer_thread(void *userdata)
  2150. {
  2151. cl_int (*queue_kernel_parameters)(_clState *, dev_blk_ctx *);
  2152. const unsigned long cycle = opt_log_interval / 5 ? : 1;
  2153. struct timeval tv_start, tv_end, diff, tv_workstart;
  2154. struct thr_info *mythr = userdata;
  2155. const int thr_id = mythr->id;
  2156. uint32_t *res, *blank_res;
  2157. double gpu_ms_average = 7;
  2158. size_t globalThreads[1];
  2159. size_t localThreads[1];
  2160. cl_int status;
  2161. _clState *clState = clStates[thr_id];
  2162. const cl_kernel *kernel = &clState->kernel;
  2163. struct work *work = malloc(sizeof(struct work));
  2164. unsigned int threads;
  2165. unsigned const int vectors = clState->preferred_vwidth;
  2166. unsigned int hashes;
  2167. unsigned int hashes_done = 0;
  2168. /* Request the next work item at 2/3 of the scantime */
  2169. unsigned const int request_interval = opt_scantime * 2 / 3 ? : 1;
  2170. unsigned const long request_nonce = MAXTHREADS / 3 * 2;
  2171. bool requested = true;
  2172. uint32_t total_hashes = 0, hash_div = 1;
  2173. switch (chosen_kernel) {
  2174. case KL_POCLBM:
  2175. queue_kernel_parameters = &queue_poclbm_kernel;
  2176. break;
  2177. case KL_PHATK:
  2178. default:
  2179. queue_kernel_parameters = &queue_phatk_kernel;
  2180. break;
  2181. }
  2182. if (opt_dynamic) {
  2183. /* Minimise impact on desktop if we want dynamic mode */
  2184. setpriority(PRIO_PROCESS, 0, 19);
  2185. drop_policy();
  2186. }
  2187. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2188. res = calloc(BUFFERSIZE, 1);
  2189. blank_res = calloc(BUFFERSIZE, 1);
  2190. if (!res || !blank_res) {
  2191. applog(LOG_ERR, "Failed to calloc in gpuminer_thread");
  2192. goto out;
  2193. }
  2194. gettimeofday(&tv_start, NULL);
  2195. localThreads[0] = clState->work_size;
  2196. set_threads_hashes(vectors, &threads, &hashes, &globalThreads[0],
  2197. localThreads[0]);
  2198. diff.tv_sec = 0;
  2199. gettimeofday(&tv_end, NULL);
  2200. work->pool = NULL;
  2201. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_TRUE, 0,
  2202. BUFFERSIZE, blank_res, 0, NULL, NULL);
  2203. if (unlikely(status != CL_SUCCESS))
  2204. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  2205. gettimeofday(&tv_workstart, NULL);
  2206. /* obtain new work from internal workio thread */
  2207. if (unlikely(!get_work(work, requested, mythr, thr_id, hash_div))) {
  2208. applog(LOG_ERR, "work retrieval failed, exiting "
  2209. "gpu mining thread %d", thr_id);
  2210. goto out;
  2211. }
  2212. mythr->cgpu->getworks++;
  2213. requested = false;
  2214. precalc_hash(&work->blk, (uint32_t *)(work->midstate), (uint32_t *)(work->data + 64));
  2215. work->blk.nonce = 0;
  2216. while (1) {
  2217. struct timeval tv_gpustart, tv_gpuend;
  2218. suseconds_t gpu_us;
  2219. gettimeofday(&tv_gpustart, NULL);
  2220. timeval_subtract(&diff, &tv_gpustart, &tv_gpuend);
  2221. /* This finish flushes the readbuffer set with CL_FALSE later */
  2222. clFinish(clState->commandQueue);
  2223. gettimeofday(&tv_gpuend, NULL);
  2224. timeval_subtract(&diff, &tv_gpuend, &tv_gpustart);
  2225. gpu_us = diff.tv_sec * 1000000 + diff.tv_usec;
  2226. gpu_ms_average = ((gpu_us / 1000) + gpu_ms_average * 0.9) / 1.9;
  2227. if (opt_dynamic) {
  2228. /* Try to not let the GPU be out for longer than 6ms, but
  2229. * increase intensity when the system is idle, unless
  2230. * dynamic is disabled. */
  2231. if (gpu_ms_average > 7) {
  2232. if (scan_intensity > -10)
  2233. scan_intensity--;
  2234. } else if (gpu_ms_average < 3) {
  2235. if (scan_intensity < 10)
  2236. scan_intensity++;
  2237. }
  2238. }
  2239. set_threads_hashes(vectors, &threads, &hashes, globalThreads, localThreads[0]);
  2240. if (diff.tv_sec > opt_scantime ||
  2241. work->blk.nonce >= MAXTHREADS - hashes ||
  2242. work_restart[thr_id].restart ||
  2243. stale_work(work)) {
  2244. /* Ignore any reads since we're getting new work and queue a clean buffer */
  2245. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  2246. BUFFERSIZE, blank_res, 0, NULL, NULL);
  2247. if (unlikely(status != CL_SUCCESS))
  2248. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  2249. memset(res, 0, BUFFERSIZE);
  2250. gettimeofday(&tv_workstart, NULL);
  2251. /* obtain new work from internal workio thread */
  2252. if (unlikely(!get_work(work, requested, mythr, thr_id, hash_div))) {
  2253. applog(LOG_ERR, "work retrieval failed, exiting "
  2254. "gpu mining thread %d", thr_id);
  2255. goto out;
  2256. }
  2257. mythr->cgpu->getworks++;
  2258. requested = false;
  2259. precalc_hash(&work->blk, (uint32_t *)(work->midstate), (uint32_t *)(work->data + 64));
  2260. work->blk.nonce = 0;
  2261. work_restart[thr_id].restart = 0;
  2262. if (opt_debug)
  2263. applog(LOG_DEBUG, "getwork thread %d", thr_id);
  2264. /* Flushes the writebuffer set with CL_FALSE above */
  2265. clFinish(clState->commandQueue);
  2266. }
  2267. status = queue_kernel_parameters(clState, &work->blk);
  2268. if (unlikely(status != CL_SUCCESS))
  2269. { applog(LOG_ERR, "Error: clSetKernelArg of all params failed."); goto out; }
  2270. /* MAXBUFFERS entry is used as a flag to say nonces exist */
  2271. if (res[MAXBUFFERS]) {
  2272. /* Clear the buffer again */
  2273. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  2274. BUFFERSIZE, blank_res, 0, NULL, NULL);
  2275. if (unlikely(status != CL_SUCCESS))
  2276. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  2277. if (opt_debug)
  2278. applog(LOG_DEBUG, "GPU %d found something?", dev_from_id(thr_id));
  2279. postcalc_hash_async(mythr, work, res);
  2280. memset(res, 0, BUFFERSIZE);
  2281. clFinish(clState->commandQueue);
  2282. }
  2283. status = clEnqueueNDRangeKernel(clState->commandQueue, *kernel, 1, NULL,
  2284. globalThreads, localThreads, 0, NULL, NULL);
  2285. if (unlikely(status != CL_SUCCESS))
  2286. { applog(LOG_ERR, "Error: Enqueueing kernel onto command queue. (clEnqueueNDRangeKernel)"); goto out; }
  2287. status = clEnqueueReadBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  2288. BUFFERSIZE, res, 0, NULL, NULL);
  2289. if (unlikely(status != CL_SUCCESS))
  2290. { applog(LOG_ERR, "Error: clEnqueueReadBuffer failed. (clEnqueueReadBuffer)"); goto out;}
  2291. gettimeofday(&tv_end, NULL);
  2292. timeval_subtract(&diff, &tv_end, &tv_start);
  2293. hashes_done += hashes;
  2294. total_hashes += hashes;
  2295. work->blk.nonce += hashes;
  2296. if (diff.tv_usec > 500000)
  2297. diff.tv_sec++;
  2298. if (diff.tv_sec >= cycle) {
  2299. hashmeter(thr_id, &diff, hashes_done);
  2300. gettimeofday(&tv_start, NULL);
  2301. hashes_done = 0;
  2302. }
  2303. timeval_subtract(&diff, &tv_end, &tv_workstart);
  2304. if (!requested) {
  2305. if (diff.tv_sec > request_interval)
  2306. hash_div = (MAXTHREADS / total_hashes) ? : 1;
  2307. if (diff.tv_sec > request_interval || work->blk.nonce > request_nonce) {
  2308. if (unlikely(!queue_request())) {
  2309. applog(LOG_ERR, "Failed to queue_request in gpuminer_thread %d", thr_id);
  2310. goto out;
  2311. }
  2312. requested = true;
  2313. }
  2314. }
  2315. }
  2316. out:
  2317. tq_freeze(mythr->q);
  2318. return NULL;
  2319. }
  2320. #endif /* HAVE_OPENCL */
  2321. static void restart_threads(void)
  2322. {
  2323. int i;
  2324. if (block_changed == BLOCK_DETECT)
  2325. block_changed = BLOCK_NONE;
  2326. /* Discard old queued requests and get new ones */
  2327. flush_requests();
  2328. for (i = 0; i < mining_threads; i++)
  2329. work_restart[i].restart = 1;
  2330. }
  2331. /* Stage another work item from the work returned in a longpoll */
  2332. static void convert_to_work(json_t *val)
  2333. {
  2334. struct work *work;
  2335. bool rc;
  2336. work = calloc(sizeof(*work), 1);
  2337. if (unlikely(!work)) {
  2338. applog(LOG_ERR, "OOM in convert_to_work");
  2339. return;
  2340. }
  2341. rc= work_decode(json_object_get(val, "result"), work);
  2342. if (unlikely(!rc)) {
  2343. applog(LOG_ERR, "Could not convert longpoll data to work");
  2344. return;
  2345. }
  2346. work->pool = current_pool();
  2347. if (unlikely(!tq_push(thr_info[stage_thr_id].q, work)))
  2348. applog(LOG_ERR, "Could not tq_push work in convert_to_work");
  2349. else if (opt_debug)
  2350. applog(LOG_DEBUG, "Converted longpoll data to work");
  2351. }
  2352. static void *longpoll_thread(void *userdata)
  2353. {
  2354. struct thr_info *mythr = userdata;
  2355. CURL *curl = NULL;
  2356. char *copy_start, *hdr_path, *lp_url = NULL;
  2357. bool need_slash = false;
  2358. int failures = 0;
  2359. struct pool *pool = current_pool();
  2360. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2361. curl = curl_easy_init();
  2362. if (unlikely(!curl)) {
  2363. applog(LOG_ERR, "CURL initialisation failed");
  2364. goto out;
  2365. }
  2366. hdr_path = tq_pop(mythr->q, NULL);
  2367. if (!hdr_path) {
  2368. applog(LOG_WARNING, "No long-poll found on this server");
  2369. goto out;
  2370. }
  2371. /* full URL */
  2372. if (strstr(hdr_path, "://")) {
  2373. lp_url = hdr_path;
  2374. hdr_path = NULL;
  2375. }
  2376. /* absolute path, on current server */
  2377. else {
  2378. copy_start = (*hdr_path == '/') ? (hdr_path + 1) : hdr_path;
  2379. if (pool->rpc_url[strlen(pool->rpc_url) - 1] != '/')
  2380. need_slash = true;
  2381. lp_url = malloc(strlen(pool->rpc_url) + strlen(copy_start) + 2);
  2382. if (!lp_url)
  2383. goto out;
  2384. sprintf(lp_url, "%s%s%s", pool->rpc_url, need_slash ? "/" : "", copy_start);
  2385. }
  2386. free(hdr_path);
  2387. applog(LOG_WARNING, "Long-polling activated for %s", lp_url);
  2388. while (1) {
  2389. struct timeval start, end;
  2390. json_t *val;
  2391. gettimeofday(&start, NULL);
  2392. val = json_rpc_call(curl, lp_url, pool->rpc_userpass, rpc_req,
  2393. false, true, pool);
  2394. if (likely(val)) {
  2395. /* Keep track of who ordered a restart_threads to make
  2396. * sure it's only done once per new block */
  2397. if (block_changed != BLOCK_DETECT) {
  2398. block_changed = BLOCK_LP;
  2399. new_blocks++;
  2400. applog(LOG_WARNING, "LONGPOLL detected new block on network, waiting on fresh work");
  2401. restart_threads();
  2402. } else {
  2403. applog(LOG_WARNING, "LONGPOLL received after new block already detected");
  2404. block_changed = BLOCK_NONE;
  2405. }
  2406. convert_to_work(val);
  2407. failures = 0;
  2408. json_decref(val);
  2409. } else {
  2410. /* Some pools regularly drop the longpoll request so
  2411. * only see this as longpoll failure if it happens
  2412. * immediately and just restart it the rest of the
  2413. * time. */
  2414. gettimeofday(&end, NULL);
  2415. if (end.tv_sec - start.tv_sec > 30)
  2416. continue;
  2417. if (failures++ < 10) {
  2418. sleep(30);
  2419. applog(LOG_WARNING,
  2420. "longpoll failed, sleeping for 30s");
  2421. } else {
  2422. applog(LOG_ERR,
  2423. "longpoll failed, ending thread");
  2424. goto out;
  2425. }
  2426. }
  2427. }
  2428. out:
  2429. free(lp_url);
  2430. tq_freeze(mythr->q);
  2431. if (curl)
  2432. curl_easy_cleanup(curl);
  2433. return NULL;
  2434. }
  2435. static void stop_longpoll(void)
  2436. {
  2437. struct thr_info *thr = &thr_info[longpoll_thr_id];
  2438. tq_freeze(thr->q);
  2439. pthread_cancel(*thr->pth);
  2440. have_longpoll = false;
  2441. }
  2442. static void quit(int status, const char *format, ...);
  2443. static void start_longpoll(void)
  2444. {
  2445. struct thr_info *thr = &thr_info[longpoll_thr_id];
  2446. tq_thaw(thr->q);
  2447. if (unlikely(thr_info_create(thr, NULL, longpoll_thread, thr)))
  2448. quit(1, "longpoll thread create failed");
  2449. pthread_detach(*thr->pth);
  2450. }
  2451. static void restart_longpoll(void)
  2452. {
  2453. stop_longpoll();
  2454. if (want_longpoll)
  2455. start_longpoll();
  2456. }
  2457. static void reinit_cputhread(int thr_id)
  2458. {
  2459. struct thr_info *thr = &thr_info[thr_id];
  2460. tq_freeze(thr->q);
  2461. if (!(pthread_cancel(*thr->pth)) && pthread_join(*thr->pth, NULL)) {
  2462. applog(LOG_ERR, "Failed to pthread_join in reinit_cputhread");
  2463. goto failed_out;
  2464. }
  2465. applog(LOG_INFO, "Reinit CPU thread %d", thr_id);
  2466. tq_thaw(thr->q);
  2467. thread_reportin(thr);
  2468. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr))) {
  2469. applog(LOG_ERR, "thread %d create failed", thr_id);
  2470. goto failed_out;
  2471. }
  2472. return;
  2473. failed_out:
  2474. kill_work();
  2475. }
  2476. #ifdef HAVE_OPENCL
  2477. static void reinit_gputhread(int thr_id)
  2478. {
  2479. int gpu = dev_from_id(thr_id);
  2480. struct thr_info *thr = &thr_info[thr_id];
  2481. char name[256];
  2482. tq_freeze(thr->q);
  2483. if (!(pthread_cancel(*thr->pth)) && pthread_join(*thr->pth, NULL)) {
  2484. applog(LOG_ERR, "Failed to pthread_join in reinit_gputhread");
  2485. goto failed_out;
  2486. }
  2487. free(clStates[thr_id]);
  2488. applog(LOG_INFO, "Reinit GPU thread %d", thr_id);
  2489. tq_thaw(thr->q);
  2490. clStates[thr_id] = initCl(gpu, name, sizeof(name));
  2491. if (!clStates[thr_id]) {
  2492. applog(LOG_ERR, "Failed to reinit GPU thread %d", thr_id);
  2493. goto failed_out;
  2494. }
  2495. applog(LOG_INFO, "initCl() finished. Found %s", name);
  2496. thread_reportin(thr);
  2497. if (unlikely(thr_info_create(thr, NULL, gpuminer_thread, thr))) {
  2498. applog(LOG_ERR, "thread %d create failed", thr_id);
  2499. goto failed_out;
  2500. }
  2501. return;
  2502. failed_out:
  2503. kill_work();
  2504. }
  2505. static void reinit_thread(int thr_id)
  2506. {
  2507. if (thr_id < gpu_threads)
  2508. reinit_gputhread(thr_id);
  2509. else
  2510. reinit_cputhread(thr_id);
  2511. }
  2512. #else /* HAVE_OPENCL */
  2513. static void reinit_thread(int thr_id)
  2514. {
  2515. reinit_cputhread(thr_id);
  2516. }
  2517. #endif
  2518. /* Determine which are the first threads belonging to a device and if they're
  2519. * active */
  2520. static bool active_device(int thr_id)
  2521. {
  2522. if (thr_id < gpu_threads) {
  2523. if (thr_id >= total_devices)
  2524. return false;
  2525. if (!gpu_devices[dev_from_id(thr_id)])
  2526. return false;
  2527. } else if (thr_id > gpu_threads + num_processors)
  2528. return false;
  2529. return true;
  2530. }
  2531. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  2532. * the screen at regular intervals, and restarts threads if they appear to have
  2533. * died. */
  2534. static void *watchdog_thread(void *userdata)
  2535. {
  2536. const unsigned int interval = opt_log_interval / 2 ? : 1;
  2537. static struct timeval rotate_tv;
  2538. struct timeval zero_tv;
  2539. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2540. memset(&zero_tv, 0, sizeof(struct timeval));
  2541. gettimeofday(&rotate_tv, NULL);
  2542. while (1) {
  2543. int x, y, logx, logy, i;
  2544. struct timeval now;
  2545. sleep(interval);
  2546. if (requests_queued() < opt_queue)
  2547. queue_request();
  2548. hashmeter(-1, &zero_tv, 0);
  2549. if (curses_active) {
  2550. pthread_mutex_lock(&curses_lock);
  2551. getmaxyx(mainwin, y, x);
  2552. getmaxyx(logwin, logy, logx);
  2553. y -= logcursor;
  2554. /* Detect screen size change */
  2555. if (x != logx || y != logy)
  2556. wresize(logwin, y, x);
  2557. for (i = 0; i < mining_threads; i++) {
  2558. if (active_device(i))
  2559. curses_print_status(i);
  2560. }
  2561. redrawwin(logwin);
  2562. redrawwin(statuswin);
  2563. pthread_mutex_unlock(&curses_lock);
  2564. }
  2565. if (unlikely(work_restart[watchdog_thr_id].restart)) {
  2566. restart_threads();
  2567. work_restart[watchdog_thr_id].restart = 0;
  2568. }
  2569. gettimeofday(&now, NULL);
  2570. for (i = 0; i < total_pools; i++) {
  2571. struct pool *pool = pools[i];
  2572. if (!pool->enabled)
  2573. continue;
  2574. /* Test pool is idle once every minute */
  2575. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 60) {
  2576. gettimeofday(&pool->tv_idle, NULL);
  2577. if (pool_active(pool) && pool_tclear(pool, &pool->idle))
  2578. pool_resus(pool);
  2579. }
  2580. }
  2581. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  2582. gettimeofday(&rotate_tv, NULL);
  2583. switch_pools(NULL);
  2584. }
  2585. //for (i = 0; i < mining_threads; i++) {
  2586. for (i = 0; i < gpu_threads; i++) {
  2587. struct thr_info *thr = &thr_info[i];
  2588. /* Thread is waiting on getwork, don't test it */
  2589. if (thr->getwork)
  2590. continue;
  2591. if (now.tv_sec - thr->last.tv_sec > 60) {
  2592. applog(LOG_ERR, "Attempting to restart thread %d, idle for more than 60 seconds", i);
  2593. /* Create one mandatory work item */
  2594. inc_staged(current_pool(), 1, true);
  2595. if (unlikely(!queue_request())) {
  2596. applog(LOG_ERR, "Failed to queue_request in watchdog_thread");
  2597. kill_work();
  2598. break;
  2599. }
  2600. reinit_thread(i);
  2601. applog(LOG_WARNING, "Thread %d restarted", i);
  2602. }
  2603. }
  2604. }
  2605. return NULL;
  2606. }
  2607. static void print_summary(void)
  2608. {
  2609. struct timeval diff;
  2610. int hours, mins, secs, i;
  2611. double utility, efficiency = 0.0;
  2612. timeval_subtract(&diff, &total_tv_end, &total_tv_start);
  2613. hours = diff.tv_sec / 3600;
  2614. mins = (diff.tv_sec % 3600) / 60;
  2615. secs = diff.tv_sec % 60;
  2616. utility = total_accepted / ( total_secs ? total_secs : 1 ) * 60;
  2617. efficiency = total_getworks ? total_accepted * 100.0 / total_getworks : 0.0;
  2618. printf("\nSummary of runtime statistics:\n\n");
  2619. printf("Started at %s\n", datestamp);
  2620. printf("Runtime: %d hrs : %d mins : %d secs\n", hours, mins, secs);
  2621. if (total_secs)
  2622. printf("Average hashrate: %.1f Megahash/s\n", total_mhashes_done / total_secs);
  2623. printf("Queued work requests: %d\n", total_getworks);
  2624. printf("Share submissions: %d\n", total_accepted + total_rejected);
  2625. printf("Accepted shares: %d\n", total_accepted);
  2626. printf("Rejected shares: %d\n", total_rejected);
  2627. if (total_accepted || total_rejected)
  2628. printf("Reject ratio: %.1f\n", (double)(total_rejected * 100) / (double)(total_accepted + total_rejected));
  2629. printf("Hardware errors: %d\n", hw_errors);
  2630. printf("Efficiency (accepted / queued): %.0f%%\n", efficiency);
  2631. printf("Utility (accepted shares / min): %.2f/min\n\n", utility);
  2632. printf("Discarded work due to new blocks: %d\n", total_discarded);
  2633. printf("Stale submissions discarded due to new blocks: %d\n", total_stale);
  2634. printf("Unable to get work from server occasions: %d\n", total_lo);
  2635. printf("Work items generated locally: %d\n", local_work);
  2636. printf("Submitting work remotely delay occasions: %d\n", total_ro);
  2637. printf("New blocks detected on network: %d\n\n", new_blocks);
  2638. if (total_pools > 1) {
  2639. for (i = 0; i < total_pools; i++) {
  2640. struct pool *pool = pools[i];
  2641. printf("Pool: %s\n", pool->rpc_url);
  2642. printf(" Queued work requests: %d\n", pool->getwork_requested);
  2643. printf(" Share submissions: %d\n", pool->accepted + pool->rejected);
  2644. printf(" Accepted shares: %d\n", pool->accepted);
  2645. printf(" Rejected shares: %d\n", pool->rejected);
  2646. if (pool->accepted || pool->rejected)
  2647. printf(" Reject ratio: %.1f\n", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  2648. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  2649. printf(" Efficiency (accepted / queued): %.0f%%\n", efficiency);
  2650. printf(" Discarded work due to new blocks: %d\n", pool->discarded_work);
  2651. printf(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  2652. printf(" Unable to get work from server occasions: %d\n", pool->localgen_occasions);
  2653. printf(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  2654. }
  2655. }
  2656. printf("Summary of per device statistics:\n\n");
  2657. for (i = 0; i < mining_threads; i++) {
  2658. if (active_device(i))
  2659. print_status(i);
  2660. }
  2661. printf("\n");
  2662. }
  2663. static void quit(int status, const char *format, ...)
  2664. {
  2665. va_list ap;
  2666. disable_curses();
  2667. if (format) {
  2668. va_start(ap, format);
  2669. vfprintf(stderr, format, ap);
  2670. va_end(ap);
  2671. }
  2672. fprintf(stderr, "\n");
  2673. fflush(stderr);
  2674. exit(status);
  2675. }
  2676. static char *curses_input(const char *query)
  2677. {
  2678. char *input;
  2679. echo();
  2680. input = malloc(255);
  2681. if (!input)
  2682. quit(1, "Failed to malloc input");
  2683. leaveok(logwin, false);
  2684. wprintw(logwin, "%s: ", query);
  2685. wrefresh(logwin);
  2686. wgetnstr(logwin, input, 255);
  2687. leaveok(logwin, true);
  2688. noecho();
  2689. wprintw(logwin, "\n");
  2690. return input;
  2691. }
  2692. static bool input_pool(bool live)
  2693. {
  2694. char *url = NULL, *user = NULL, *pass = NULL;
  2695. struct pool *pool = NULL;
  2696. bool ret = false;
  2697. immedok(logwin, true);
  2698. if (total_pools == MAX_POOLS) {
  2699. wprintw(logwin, "Reached maximum number of pools.\n");
  2700. goto out;
  2701. }
  2702. wprintw(logwin, "Input server details.\n");
  2703. url = curses_input("URL");
  2704. if (strncmp(url, "http://", 7) &&
  2705. strncmp(url, "https://", 8)) {
  2706. applog(LOG_ERR, "URL must start with http:// or https://");
  2707. goto out;
  2708. }
  2709. user = curses_input("Username");
  2710. if (!user)
  2711. goto out;
  2712. pass = curses_input("Password");
  2713. if (!pass)
  2714. goto out;
  2715. pool = calloc(sizeof(struct pool), 1);
  2716. if (!pool)
  2717. quit(1, "Failed to realloc pools in input_pool");
  2718. pool->pool_no = total_pools;
  2719. pool->prio = total_pools;
  2720. if (unlikely(pthread_mutex_init(&pool->pool_lock, NULL)))
  2721. quit (1, "Failed to pthread_mutex_init in input_pool");
  2722. pool->rpc_url = url;
  2723. pool->rpc_user = user;
  2724. pool->rpc_pass = pass;
  2725. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  2726. if (!pool->rpc_userpass)
  2727. quit(1, "Failed to malloc userpass");
  2728. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  2729. pool->tv_idle.tv_sec = ~0UL;
  2730. /* Test the pool before we enable it if we're live running, otherwise
  2731. * it will be tested separately */
  2732. ret = true;
  2733. if (live && pool_active(pool))
  2734. pool->enabled = true;
  2735. pools[total_pools++] = pool;
  2736. out:
  2737. immedok(logwin, false);
  2738. if (!ret) {
  2739. if (url)
  2740. free(url);
  2741. if (user)
  2742. free(user);
  2743. if (pass)
  2744. free(pass);
  2745. if (pool)
  2746. free(pool);
  2747. }
  2748. return ret;
  2749. }
  2750. int main (int argc, char *argv[])
  2751. {
  2752. unsigned int i, j = 0, x, y, pools_active = 0;
  2753. struct sigaction handler;
  2754. struct thr_info *thr;
  2755. char name[256];
  2756. struct tm tm;
  2757. /* This dangerous functions tramples random dynamically allocated
  2758. * variables so do it before anything at all */
  2759. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  2760. quit(1, "Failed to curl_global_init");
  2761. if (unlikely(pthread_mutex_init(&hash_lock, NULL)))
  2762. quit(1, "Failed to pthread_mutex_init");
  2763. if (unlikely(pthread_mutex_init(&qd_lock, NULL)))
  2764. quit(1, "Failed to pthread_mutex_init");
  2765. if (unlikely(pthread_mutex_init(&stgd_lock, NULL)))
  2766. quit(1, "Failed to pthread_mutex_init");
  2767. if (unlikely(pthread_mutex_init(&curses_lock, NULL)))
  2768. quit(1, "Failed to pthread_mutex_init");
  2769. if (unlikely(pthread_mutex_init(&control_lock, NULL)))
  2770. quit(1, "Failed to pthread_mutex_init");
  2771. handler.sa_handler = &sighandler;
  2772. sigaction(SIGTERM, &handler, &termhandler);
  2773. sigaction(SIGINT, &handler, &inthandler);
  2774. gettimeofday(&total_tv_start, NULL);
  2775. gettimeofday(&total_tv_end, NULL);
  2776. localtime_r(&total_tv_start.tv_sec, &tm);
  2777. sprintf(datestamp, "[%d-%02d-%02d %02d:%02d:%02d]",
  2778. tm.tm_year + 1900,
  2779. tm.tm_mon + 1,
  2780. tm.tm_mday,
  2781. tm.tm_hour,
  2782. tm.tm_min,
  2783. tm.tm_sec);
  2784. for (i = 0; i < 36; i++)
  2785. strcat(current_block, "0");
  2786. #ifdef WIN32
  2787. opt_n_threads = num_processors = 1;
  2788. #else
  2789. num_processors = sysconf(_SC_NPROCESSORS_ONLN);
  2790. opt_n_threads = num_processors;
  2791. #endif /* !WIN32 */
  2792. #ifdef HAVE_OPENCL
  2793. for (i = 0; i < 16; i++)
  2794. gpu_devices[i] = false;
  2795. nDevs = clDevicesNum();
  2796. if (nDevs < 0)
  2797. quit(1, "clDevicesNum returned error");
  2798. #endif
  2799. if (nDevs)
  2800. opt_n_threads = 0;
  2801. trpc_url = strdup(DEF_RPC_URL);
  2802. /* parse command line */
  2803. opt_register_table(opt_config_table,
  2804. "Options for both config file and command line");
  2805. opt_register_table(opt_cmdline_table,
  2806. "Options for command line only");
  2807. opt_parse(&argc, argv, applog_and_exit);
  2808. if (argc != 1)
  2809. quit(1, "Unexpected extra commandline arguments");
  2810. if (opt_kernel) {
  2811. if (strcmp(opt_kernel, "poclbm") && strcmp(opt_kernel, "phatk"))
  2812. quit(1, "Invalid kernel name specified - must be poclbm or phatk");
  2813. if (!strcmp(opt_kernel, "poclbm"))
  2814. chosen_kernel = KL_POCLBM;
  2815. else
  2816. chosen_kernel = KL_PHATK;
  2817. } else
  2818. chosen_kernel = KL_NONE;
  2819. if (total_devices) {
  2820. if (total_devices > nDevs)
  2821. quit(1, "More devices specified than exist");
  2822. for (i = 0; i < 16; i++)
  2823. if (gpu_devices[i] && i + 1 > nDevs)
  2824. quit (1, "Command line options set a device that doesn't exist");
  2825. gpu_threads = total_devices * opt_g_threads;
  2826. } else {
  2827. gpu_threads = nDevs * opt_g_threads;
  2828. for (i = 0; i < nDevs; i++)
  2829. gpu_devices[i] = true;
  2830. total_devices = nDevs;
  2831. }
  2832. if (!gpu_threads && !forced_n_threads) {
  2833. /* Maybe they turned GPU off; restore default CPU threads. */
  2834. opt_n_threads = num_processors;
  2835. }
  2836. logcursor = 8;
  2837. gpucursor = logcursor;
  2838. cpucursor = gpucursor + nDevs;
  2839. logstart = cpucursor + (opt_n_threads ? num_processors : 0) + 1;
  2840. logcursor = logstart + 1;
  2841. /* Set up the ncurses interface */
  2842. if (!opt_quiet && use_curses) {
  2843. mainwin = initscr();
  2844. getmaxyx(mainwin, y, x);
  2845. statuswin = newwin(logstart, x, 0, 0);
  2846. leaveok(statuswin, true);
  2847. logwin = newwin(y - logcursor, 0, logcursor, 0);
  2848. idlok(logwin, true);
  2849. scrollok(logwin, true);
  2850. leaveok(logwin, true);
  2851. cbreak();
  2852. noecho();
  2853. test_and_set(&curses_active);
  2854. }
  2855. if (!total_pools) {
  2856. if (curses_active) {
  2857. if (!input_pool(false))
  2858. quit(1, "Pool setup failed");
  2859. } else
  2860. quit(1, "No server specified");
  2861. }
  2862. for (i = 0; i < total_pools; i++) {
  2863. struct pool *pool = pools[i];
  2864. if (!pool->rpc_userpass) {
  2865. if (!pool->rpc_user || !pool->rpc_pass)
  2866. quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  2867. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  2868. if (!pool->rpc_userpass)
  2869. quit(1, "Failed to malloc userpass");
  2870. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  2871. } else {
  2872. pool->rpc_user = malloc(strlen(pool->rpc_userpass));
  2873. if (!pool->rpc_user)
  2874. quit(1, "Failed to malloc user");
  2875. strcpy(pool->rpc_user, pool->rpc_userpass);
  2876. pool->rpc_user = strtok(pool->rpc_user, ":");
  2877. if (!pool->rpc_user)
  2878. quit(1, "Failed to find colon delimiter in userpass");
  2879. }
  2880. }
  2881. /* Set the currentpool to pool 0 */
  2882. currentpool = pools[0];
  2883. #ifdef HAVE_SYSLOG_H
  2884. if (use_syslog)
  2885. openlog("cpuminer", LOG_PID, LOG_USER);
  2886. #endif
  2887. mining_threads = opt_n_threads + gpu_threads;
  2888. total_threads = mining_threads + 5;
  2889. work_restart = calloc(total_threads, sizeof(*work_restart));
  2890. if (!work_restart)
  2891. quit(1, "Failed to calloc work_restart");
  2892. thr_info = calloc(total_threads, sizeof(*thr));
  2893. if (!thr_info)
  2894. quit(1, "Failed to calloc thr_info");
  2895. /* init workio thread info */
  2896. work_thr_id = mining_threads;
  2897. thr = &thr_info[work_thr_id];
  2898. thr->id = work_thr_id;
  2899. thr->q = tq_new();
  2900. if (!thr->q)
  2901. quit(1, "Failed to tq_new");
  2902. /* start work I/O thread */
  2903. if (thr_info_create(thr, NULL, workio_thread, thr))
  2904. quit(1, "workio thread create failed");
  2905. /* init longpoll thread info */
  2906. longpoll_thr_id = mining_threads + 1;
  2907. thr = &thr_info[longpoll_thr_id];
  2908. thr->id = longpoll_thr_id;
  2909. thr->q = tq_new();
  2910. if (!thr->q)
  2911. quit(1, "Failed to tq_new");
  2912. if (want_longpoll)
  2913. start_longpoll();
  2914. if (opt_n_threads ) {
  2915. cpus = calloc(num_processors, sizeof(struct cgpu_info));
  2916. if (unlikely(!cpus))
  2917. quit(1, "Failed to calloc cpus");
  2918. }
  2919. if (gpu_threads) {
  2920. gpus = calloc(nDevs, sizeof(struct cgpu_info));
  2921. if (unlikely(!gpus))
  2922. quit(1, "Failed to calloc gpus");
  2923. }
  2924. stage_thr_id = mining_threads + 3;
  2925. thr = &thr_info[stage_thr_id];
  2926. thr->q = tq_new();
  2927. if (!thr->q)
  2928. quit(1, "Failed to tq_new");
  2929. /* start stage thread */
  2930. if (thr_info_create(thr, NULL, stage_thread, thr))
  2931. quit(1, "stage thread create failed");
  2932. pthread_detach(*thr->pth);
  2933. /* Create a unique get work queue */
  2934. getq = tq_new();
  2935. if (!getq)
  2936. quit(1, "Failed to create getq");
  2937. /* Test each pool to see if we can retrieve and use work and for what
  2938. * it supports */
  2939. for (i = 0; i < total_pools; i++) {
  2940. struct pool *pool;
  2941. pool = pools[i];
  2942. if (pool_active(pool)) {
  2943. if (!currentpool)
  2944. currentpool = pool;
  2945. applog(LOG_INFO, "Pool %d %s active", pool->pool_no, pool->rpc_url);
  2946. pools_active++;
  2947. pool->enabled = true;
  2948. } else {
  2949. if (pool == currentpool)
  2950. currentpool = NULL;
  2951. applog(LOG_WARNING, "Unable to get work from pool %d %s", pool->pool_no, pool->rpc_url);
  2952. }
  2953. }
  2954. if (!pools_active)
  2955. quit(0, "No pools active! Exiting.");
  2956. #ifdef HAVE_OPENCL
  2957. i = 0;
  2958. /* start GPU mining threads */
  2959. for (j = 0; j < nDevs * opt_g_threads; j++) {
  2960. int gpu = j % nDevs;
  2961. gpus[gpu].is_gpu = 1;
  2962. gpus[gpu].cpu_gpu = gpu;
  2963. /* Skip devices not set to mine */
  2964. if (!gpu_devices[gpu])
  2965. continue;
  2966. thr = &thr_info[i];
  2967. thr->id = i;
  2968. thr->cgpu = &gpus[gpu];
  2969. thr->q = tq_new();
  2970. if (!thr->q)
  2971. quit(1, "tq_new failed in starting gpu mining threads");
  2972. applog(LOG_INFO, "Init GPU thread %i", i);
  2973. clStates[i] = initCl(gpu, name, sizeof(name));
  2974. if (!clStates[i]) {
  2975. applog(LOG_ERR, "Failed to init GPU thread %d", i);
  2976. continue;
  2977. }
  2978. applog(LOG_INFO, "initCl() finished. Found %s", name);
  2979. thread_reportin(thr);
  2980. if (unlikely(thr_info_create(thr, NULL, gpuminer_thread, thr)))
  2981. quit(1, "thread %d create failed", i);
  2982. i++;
  2983. }
  2984. applog(LOG_INFO, "%d gpu miner threads started", gpu_threads);
  2985. #endif
  2986. /* start CPU mining threads */
  2987. for (i = gpu_threads; i < mining_threads; i++) {
  2988. int cpu = (i - gpu_threads) % num_processors;
  2989. thr = &thr_info[i];
  2990. thr->id = i;
  2991. cpus[cpu].cpu_gpu = cpu;
  2992. thr->cgpu = &cpus[cpu];
  2993. thr->q = tq_new();
  2994. if (!thr->q)
  2995. quit(1, "tq_new failed in starting cpu mining threads");
  2996. thread_reportin(thr);
  2997. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  2998. quit(1, "thread %d create failed", i);
  2999. }
  3000. applog(LOG_INFO, "%d cpu miner threads started, "
  3001. "using SHA256 '%s' algorithm.",
  3002. opt_n_threads,
  3003. algo_names[opt_algo]);
  3004. watchdog_thr_id = mining_threads + 2;
  3005. thr = &thr_info[watchdog_thr_id];
  3006. /* start wakeup thread */
  3007. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  3008. quit(1, "wakeup thread create failed");
  3009. /* Now that everything's ready put enough work in the queue */
  3010. for (i = 0; i < mining_threads; i++) {
  3011. if (unlikely(!queue_request()))
  3012. quit(1, "Failed to queue_request in main");
  3013. if (!opt_quiet && active_device(i))
  3014. print_status(i);
  3015. }
  3016. /* Create curses input thread for keyboard input */
  3017. input_thr_id = mining_threads + 4;
  3018. thr = &thr_info[input_thr_id];
  3019. if (thr_info_create(thr, NULL, input_thread, thr))
  3020. quit(1, "input thread create failed");
  3021. pthread_detach(*thr->pth);
  3022. /* main loop - simply wait for workio thread to exit */
  3023. pthread_join(*thr_info[work_thr_id].pth, NULL);
  3024. applog(LOG_INFO, "workio thread dead, exiting.");
  3025. gettimeofday(&total_tv_end, NULL);
  3026. disable_curses();
  3027. if (!opt_quiet && successful_connect)
  3028. print_summary();
  3029. if (gpu_threads)
  3030. free(gpus);
  3031. if (opt_n_threads)
  3032. free(cpus);
  3033. curl_global_cleanup();
  3034. return 0;
  3035. }