main.c 71 KB

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