main.c 75 KB

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