main.c 92 KB

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