main.c 63 KB

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