main.c 107 KB

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