main.c 99 KB

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