main.c 92 KB

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