main.c 63 KB

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