main.c 102 KB

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