main.c 100 KB

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