main.c 101 KB

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