main.c 89 KB

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