main.c 83 KB

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