main.c 73 KB

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