main.c 106 KB

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