main.c 97 KB

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