main.c 79 KB

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