main.c 92 KB

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