main.c 69 KB

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