main.c 88 KB

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