main.c 107 KB

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