main.c 98 KB

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