main.c 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459
  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 bool discard_request(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_queued())) {
  1053. applog(LOG_WARNING, "Tried to discard_request with nil queued");
  1054. return true;
  1055. }
  1056. work_heap = tq_pop(getq, NULL);
  1057. if (unlikely(!work_heap)) {
  1058. applog(LOG_ERR, "Failed to tq_pop in discard_request");
  1059. return false;
  1060. }
  1061. free(work_heap);
  1062. dec_queued();
  1063. discarded_work++;
  1064. return true;
  1065. }
  1066. static void flush_requests(bool longpoll)
  1067. {
  1068. int i, extra;
  1069. extra = requests_queued();
  1070. /* When flushing from longpoll, we don't know the new work yet. When
  1071. * not flushing from longpoll, the first work item is valid so do not
  1072. * discard it */
  1073. if (longpoll)
  1074. memcpy(current_block, blank, 36);
  1075. else
  1076. extra--;
  1077. /* Temporarily increase the staged count so that get_work thinks there
  1078. * is work available instead of making threads reuse existing work */
  1079. inc_staged(mining_threads, true);
  1080. for (i = 0; i < extra; i++) {
  1081. /* Queue a whole batch of new requests */
  1082. if (unlikely(!queue_request())) {
  1083. applog(LOG_ERR, "Failed to queue requests in flush_requests");
  1084. kill_work();
  1085. break;
  1086. }
  1087. /* Pop off the old requests. Cancelling the requests would be better
  1088. * but is tricky */
  1089. if (unlikely(!discard_request())) {
  1090. applog(LOG_ERR, "Failed to discard requests in flush_requests");
  1091. kill_work();
  1092. break;
  1093. }
  1094. }
  1095. }
  1096. static bool get_work(struct work *work, bool queued)
  1097. {
  1098. static struct timeval tv_localgen = {};
  1099. struct work *work_heap;
  1100. bool ret = false;
  1101. int failures = 0;
  1102. retry:
  1103. if (unlikely(!queued && !queue_request())) {
  1104. applog(LOG_WARNING, "Failed to queue_request in get_work");
  1105. goto out;
  1106. }
  1107. if (!requests_staged() && !stale_work(work)) {
  1108. uint32_t *work_ntime;
  1109. uint32_t ntime;
  1110. /* Only print this message once each time we shift to localgen */
  1111. if (!test_and_set(&localgen)) {
  1112. applog(LOG_WARNING, "Server not providing work fast enough, generating work locally");
  1113. localgen_occasions++;
  1114. gettimeofday(&tv_localgen, NULL);
  1115. } else {
  1116. struct timeval tv_now, diff;
  1117. gettimeofday(&tv_now, NULL);
  1118. timeval_subtract(&diff, &tv_now, &tv_localgen);
  1119. if (diff.tv_sec > 600) {
  1120. /* A new block appears on average every 10 mins */
  1121. applog(LOG_WARNING, "Prolonged outage. Going idle till network recovers.");
  1122. /* Force every thread to wait for new work */
  1123. inc_staged(mining_threads, true);
  1124. goto retry;
  1125. }
  1126. }
  1127. work_ntime = (uint32_t *)(work->data + 68);
  1128. ntime = be32toh(*work_ntime);
  1129. ntime++;
  1130. *work_ntime = htobe32(ntime);
  1131. ret = true;
  1132. local_work++;
  1133. goto out;
  1134. }
  1135. /* wait for 1st response, or get cached response */
  1136. work_heap = tq_pop(getq, NULL);
  1137. if (unlikely(!work_heap)) {
  1138. applog(LOG_WARNING, "Failed to tq_pop in get_work");
  1139. goto out;
  1140. }
  1141. /* If we make it here we have succeeded in getting fresh work */
  1142. if (test_and_clear(&localgen))
  1143. applog(LOG_WARNING, "Resuming with work from server");
  1144. dec_queued();
  1145. memcpy(work, work_heap, sizeof(*work));
  1146. ret = true;
  1147. free(work_heap);
  1148. out:
  1149. if (unlikely(ret == false)) {
  1150. if ((opt_retries >= 0) && (++failures > opt_retries)) {
  1151. applog(LOG_ERR, "Failed %d times to get_work");
  1152. return ret;
  1153. }
  1154. applog(LOG_DEBUG, "Retrying after %d seconds", opt_fail_pause);
  1155. sleep(opt_fail_pause);
  1156. goto retry;
  1157. }
  1158. return ret;
  1159. }
  1160. static bool submit_work_sync(struct thr_info *thr, const struct work *work_in)
  1161. {
  1162. struct workio_cmd *wc;
  1163. /* fill out work request message */
  1164. wc = calloc(1, sizeof(*wc));
  1165. if (unlikely(!wc)) {
  1166. applog(LOG_ERR, "Failed to calloc wc in submit_work_sync");
  1167. return false;
  1168. }
  1169. wc->u.work = malloc(sizeof(*work_in));
  1170. if (unlikely(!wc->u.work)) {
  1171. applog(LOG_ERR, "Failed to calloc work in submit_work_sync");
  1172. goto err_out;
  1173. }
  1174. wc->cmd = WC_SUBMIT_WORK;
  1175. wc->thr = thr;
  1176. memcpy(wc->u.work, work_in, sizeof(*work_in));
  1177. /* send solution to workio thread */
  1178. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  1179. applog(LOG_ERR, "Failed to tq_push work in submit_work_sync");
  1180. goto err_out;
  1181. }
  1182. return true;
  1183. err_out:
  1184. workio_cmd_free(wc);
  1185. return false;
  1186. }
  1187. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  1188. {
  1189. work->data[64+12+0] = (nonce>>0) & 0xff;
  1190. work->data[64+12+1] = (nonce>>8) & 0xff;
  1191. work->data[64+12+2] = (nonce>>16) & 0xff;
  1192. work->data[64+12+3] = (nonce>>24) & 0xff;
  1193. return submit_work_sync(thr, work);
  1194. }
  1195. static void *miner_thread(void *userdata)
  1196. {
  1197. struct thr_info *mythr = userdata;
  1198. const int thr_id = mythr->id;
  1199. uint32_t max_nonce = 0xffffff;
  1200. unsigned long hashes_done = max_nonce;
  1201. bool needs_work = true;
  1202. /* Try to cycle approximately 5 times before each log update */
  1203. const unsigned long cycle = opt_log_interval / 5 ? : 1;
  1204. /* Request the next work item at 2/3 of the scantime */
  1205. unsigned const int request_interval = opt_scantime * 2 / 3 ? : 1;
  1206. unsigned const long request_nonce = MAXTHREADS / 3 * 2;
  1207. bool requested = true;
  1208. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  1209. /* Set worker threads to nice 19 and then preferentially to SCHED_IDLE
  1210. * and if that fails, then SCHED_BATCH. No need for this to be an
  1211. * error if it fails */
  1212. setpriority(PRIO_PROCESS, 0, 19);
  1213. drop_policy();
  1214. /* Cpu affinity only makes sense if the number of threads is a multiple
  1215. * of the number of CPUs */
  1216. if (!(opt_n_threads % num_processors))
  1217. affine_to_cpu(thr_id - gpu_threads, dev_from_id(thr_id));
  1218. while (1) {
  1219. struct work work __attribute__((aligned(128)));
  1220. struct timeval tv_workstart, tv_start, tv_end, diff;
  1221. uint64_t max64;
  1222. bool rc;
  1223. if (needs_work) {
  1224. gettimeofday(&tv_workstart, NULL);
  1225. /* obtain new work from internal workio thread */
  1226. if (unlikely(!get_work(&work, requested))) {
  1227. applog(LOG_ERR, "work retrieval failed, exiting "
  1228. "mining thread %d", thr_id);
  1229. goto out;
  1230. }
  1231. mythr->cgpu->getworks++;
  1232. work.thr_id = thr_id;
  1233. needs_work = requested = false;
  1234. work.blk.nonce = 0;
  1235. max_nonce = hashes_done;
  1236. }
  1237. hashes_done = 0;
  1238. gettimeofday(&tv_start, NULL);
  1239. /* scan nonces for a proof-of-work hash */
  1240. switch (opt_algo) {
  1241. case ALGO_C:
  1242. rc = scanhash_c(thr_id, work.midstate, work.data + 64,
  1243. work.hash1, work.hash, work.target,
  1244. max_nonce, &hashes_done,
  1245. work.blk.nonce);
  1246. break;
  1247. #ifdef WANT_X8664_SSE2
  1248. case ALGO_SSE2_64: {
  1249. unsigned int rc5 =
  1250. scanhash_sse2_64(thr_id, work.midstate, work.data + 64,
  1251. work.hash1, work.hash,
  1252. work.target,
  1253. max_nonce, &hashes_done,
  1254. work.blk.nonce);
  1255. rc = (rc5 == -1) ? false : true;
  1256. }
  1257. break;
  1258. #endif
  1259. #ifdef WANT_SSE2_4WAY
  1260. case ALGO_4WAY: {
  1261. unsigned int rc4 =
  1262. ScanHash_4WaySSE2(thr_id, work.midstate, work.data + 64,
  1263. work.hash1, work.hash,
  1264. work.target,
  1265. max_nonce, &hashes_done,
  1266. work.blk.nonce);
  1267. rc = (rc4 == -1) ? false : true;
  1268. }
  1269. break;
  1270. #endif
  1271. #ifdef WANT_VIA_PADLOCK
  1272. case ALGO_VIA:
  1273. rc = scanhash_via(thr_id, work.data, work.target,
  1274. max_nonce, &hashes_done,
  1275. work.blk.nonce);
  1276. break;
  1277. #endif
  1278. case ALGO_CRYPTOPP:
  1279. rc = scanhash_cryptopp(thr_id, work.midstate, work.data + 64,
  1280. work.hash1, work.hash, work.target,
  1281. max_nonce, &hashes_done,
  1282. work.blk.nonce);
  1283. break;
  1284. #ifdef WANT_CRYPTOPP_ASM32
  1285. case ALGO_CRYPTOPP_ASM32:
  1286. rc = scanhash_asm32(thr_id, work.midstate, work.data + 64,
  1287. work.hash1, work.hash, work.target,
  1288. max_nonce, &hashes_done,
  1289. work.blk.nonce);
  1290. break;
  1291. #endif
  1292. default:
  1293. /* should never happen */
  1294. goto out;
  1295. }
  1296. /* record scanhash elapsed time */
  1297. gettimeofday(&tv_end, NULL);
  1298. timeval_subtract(&diff, &tv_end, &tv_start);
  1299. hashes_done -= work.blk.nonce;
  1300. hashmeter(thr_id, &diff, hashes_done);
  1301. work.blk.nonce += hashes_done;
  1302. /* adjust max_nonce to meet target cycle time */
  1303. if (diff.tv_usec > 500000)
  1304. diff.tv_sec++;
  1305. if (diff.tv_sec && diff.tv_sec != cycle) {
  1306. max64 = work.blk.nonce +
  1307. ((uint64_t)hashes_done * cycle) / diff.tv_sec;
  1308. } else
  1309. max64 = work.blk.nonce + hashes_done;
  1310. if (max64 > 0xfffffffaULL)
  1311. max64 = 0xfffffffaULL;
  1312. max_nonce = max64;
  1313. /* if nonce found, submit work */
  1314. if (unlikely(rc)) {
  1315. if (opt_debug)
  1316. applog(LOG_DEBUG, "CPU %d found something?", dev_from_id(thr_id));
  1317. if (unlikely(!submit_work_sync(mythr, &work))) {
  1318. applog(LOG_ERR, "Failed to submit_work_sync in miner_thread %d", thr_id);
  1319. break;
  1320. }
  1321. work.blk.nonce += 4;
  1322. }
  1323. timeval_subtract(&diff, &tv_end, &tv_workstart);
  1324. if (!requested && (diff.tv_sec > request_interval || work.blk.nonce > request_nonce)) {
  1325. if (unlikely(!queue_request())) {
  1326. applog(LOG_ERR, "Failed to queue_request in miner_thread %d", thr_id);
  1327. goto out;
  1328. }
  1329. requested = true;
  1330. }
  1331. if (diff.tv_sec > opt_scantime || work_restart[thr_id].restart ||
  1332. work.blk.nonce >= MAXTHREADS - hashes_done ||
  1333. stale_work(&work))
  1334. needs_work = true;
  1335. }
  1336. out:
  1337. tq_freeze(mythr->q);
  1338. return NULL;
  1339. }
  1340. enum {
  1341. STAT_SLEEP_INTERVAL = 1,
  1342. STAT_CTR_INTERVAL = 10000000,
  1343. FAILURE_INTERVAL = 30,
  1344. };
  1345. #ifdef HAVE_OPENCL
  1346. static _clState *clStates[16];
  1347. static inline cl_int queue_kernel_parameters(_clState *clState, dev_blk_ctx *blk)
  1348. {
  1349. cl_kernel *kernel = &clState->kernel;
  1350. cl_int status = 0;
  1351. int num = 0;
  1352. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_a);
  1353. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_b);
  1354. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_c);
  1355. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_d);
  1356. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_e);
  1357. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_f);
  1358. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_g);
  1359. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_h);
  1360. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_b);
  1361. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_c);
  1362. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_d);
  1363. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_f);
  1364. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_g);
  1365. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_h);
  1366. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->nonce);
  1367. if (clState->hasBitAlign == true) {
  1368. /* Parameters for phatk kernel */
  1369. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W2);
  1370. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W16);
  1371. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W17);
  1372. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreVal4);
  1373. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->T1);
  1374. } else {
  1375. /* Parameters for poclbm kernel */
  1376. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW0);
  1377. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW1);
  1378. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW2);
  1379. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW3);
  1380. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW15);
  1381. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW01r);
  1382. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e);
  1383. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e2);
  1384. }
  1385. status |= clSetKernelArg(*kernel, num++, sizeof(clState->outputBuffer),
  1386. (void *)&clState->outputBuffer);
  1387. return status;
  1388. }
  1389. static void set_threads_hashes(unsigned int vectors, unsigned int *threads,
  1390. unsigned int *hashes, size_t *globalThreads)
  1391. {
  1392. *globalThreads = *threads = 1 << (15 + scan_intensity);
  1393. *hashes = *threads * vectors;
  1394. }
  1395. static void *gpuminer_thread(void *userdata)
  1396. {
  1397. const unsigned long cycle = opt_log_interval / 5 ? : 1;
  1398. struct timeval tv_start, tv_end, diff, tv_workstart;
  1399. struct thr_info *mythr = userdata;
  1400. const int thr_id = mythr->id;
  1401. uint32_t *res, *blank_res;
  1402. double gpu_ms_average = 7;
  1403. size_t globalThreads[1];
  1404. size_t localThreads[1];
  1405. cl_int status;
  1406. _clState *clState = clStates[thr_id];
  1407. const cl_kernel *kernel = &clState->kernel;
  1408. struct work *work = malloc(sizeof(struct work));
  1409. unsigned int threads = 1 << (15 + scan_intensity);
  1410. unsigned const int vectors = clState->preferred_vwidth;
  1411. unsigned int hashes = threads * vectors;
  1412. unsigned int hashes_done = 0;
  1413. /* Request the next work item at 2/3 of the scantime */
  1414. unsigned const int request_interval = opt_scantime * 2 / 3 ? : 1;
  1415. unsigned const long request_nonce = MAXTHREADS / 3 * 2;
  1416. bool requested = true;
  1417. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  1418. res = calloc(BUFFERSIZE, 1);
  1419. blank_res = calloc(BUFFERSIZE, 1);
  1420. if (!res || !blank_res) {
  1421. applog(LOG_ERR, "Failed to calloc in gpuminer_thread");
  1422. goto out;
  1423. }
  1424. gettimeofday(&tv_start, NULL);
  1425. globalThreads[0] = threads;
  1426. localThreads[0] = clState->work_size;
  1427. diff.tv_sec = 0;
  1428. gettimeofday(&tv_end, NULL);
  1429. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_TRUE, 0,
  1430. BUFFERSIZE, blank_res, 0, NULL, NULL);
  1431. if (unlikely(status != CL_SUCCESS))
  1432. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  1433. gettimeofday(&tv_workstart, NULL);
  1434. /* obtain new work from internal workio thread */
  1435. if (unlikely(!get_work(work, requested))) {
  1436. applog(LOG_ERR, "work retrieval failed, exiting "
  1437. "gpu mining thread %d", mythr->id);
  1438. goto out;
  1439. }
  1440. mythr->cgpu->getworks++;
  1441. work->thr_id = thr_id;
  1442. requested = false;
  1443. precalc_hash(&work->blk, (uint32_t *)(work->midstate), (uint32_t *)(work->data + 64));
  1444. work->blk.nonce = 0;
  1445. while (1) {
  1446. struct timeval tv_gpustart, tv_gpuend;
  1447. suseconds_t gpu_us;
  1448. gettimeofday(&tv_gpustart, NULL);
  1449. timeval_subtract(&diff, &tv_gpustart, &tv_gpuend);
  1450. /* This finish flushes the readbuffer set with CL_FALSE later */
  1451. clFinish(clState->commandQueue);
  1452. gettimeofday(&tv_gpuend, NULL);
  1453. timeval_subtract(&diff, &tv_gpuend, &tv_gpustart);
  1454. gpu_us = diff.tv_sec * 1000000 + diff.tv_usec;
  1455. gpu_ms_average = ((gpu_us / 1000) + gpu_ms_average * 0.9) / 1.9;
  1456. if (opt_dynamic) {
  1457. /* Try to not let the GPU be out for longer than 6ms, but
  1458. * increase intensity when the system is idle, unless
  1459. * dynamic is disabled. */
  1460. if (gpu_ms_average > 7) {
  1461. if (scan_intensity > 0)
  1462. scan_intensity--;
  1463. set_threads_hashes(vectors, &threads, &hashes, globalThreads);
  1464. } else if (gpu_ms_average < 3) {
  1465. if (scan_intensity < 14)
  1466. scan_intensity++;
  1467. set_threads_hashes(vectors, &threads, &hashes, globalThreads);
  1468. }
  1469. }
  1470. if (diff.tv_sec > opt_scantime ||
  1471. work->blk.nonce >= MAXTHREADS - hashes ||
  1472. work_restart[thr_id].restart ||
  1473. stale_work(work)) {
  1474. /* Ignore any reads since we're getting new work and queue a clean buffer */
  1475. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  1476. BUFFERSIZE, blank_res, 0, NULL, NULL);
  1477. if (unlikely(status != CL_SUCCESS))
  1478. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  1479. memset(res, 0, BUFFERSIZE);
  1480. gettimeofday(&tv_workstart, NULL);
  1481. /* obtain new work from internal workio thread */
  1482. if (unlikely(!get_work(work, requested))) {
  1483. applog(LOG_ERR, "work retrieval failed, exiting "
  1484. "gpu mining thread %d", mythr->id);
  1485. goto out;
  1486. }
  1487. mythr->cgpu->getworks++;
  1488. work->thr_id = thr_id;
  1489. requested = false;
  1490. precalc_hash(&work->blk, (uint32_t *)(work->midstate), (uint32_t *)(work->data + 64));
  1491. work->blk.nonce = 0;
  1492. work_restart[thr_id].restart = 0;
  1493. if (opt_debug)
  1494. applog(LOG_DEBUG, "getwork thread %d", thr_id);
  1495. /* Flushes the writebuffer set with CL_FALSE above */
  1496. clFinish(clState->commandQueue);
  1497. }
  1498. status = queue_kernel_parameters(clState, &work->blk);
  1499. if (unlikely(status != CL_SUCCESS))
  1500. { applog(LOG_ERR, "Error: clSetKernelArg of all params failed."); goto out; }
  1501. /* MAXBUFFERS entry is used as a flag to say nonces exist */
  1502. if (res[MAXBUFFERS]) {
  1503. /* Clear the buffer again */
  1504. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  1505. BUFFERSIZE, blank_res, 0, NULL, NULL);
  1506. if (unlikely(status != CL_SUCCESS))
  1507. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  1508. if (opt_debug)
  1509. applog(LOG_DEBUG, "GPU %d found something?", dev_from_id(thr_id));
  1510. postcalc_hash_async(mythr, work, res);
  1511. memset(res, 0, BUFFERSIZE);
  1512. clFinish(clState->commandQueue);
  1513. }
  1514. status = clEnqueueNDRangeKernel(clState->commandQueue, *kernel, 1, NULL,
  1515. globalThreads, localThreads, 0, NULL, NULL);
  1516. if (unlikely(status != CL_SUCCESS))
  1517. { applog(LOG_ERR, "Error: Enqueueing kernel onto command queue. (clEnqueueNDRangeKernel)"); goto out; }
  1518. status = clEnqueueReadBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  1519. BUFFERSIZE, res, 0, NULL, NULL);
  1520. if (unlikely(status != CL_SUCCESS))
  1521. { applog(LOG_ERR, "Error: clEnqueueReadBuffer failed. (clEnqueueReadBuffer)"); goto out;}
  1522. gettimeofday(&tv_end, NULL);
  1523. timeval_subtract(&diff, &tv_end, &tv_start);
  1524. hashes_done += hashes;
  1525. work->blk.nonce += hashes;
  1526. if (diff.tv_usec > 500000)
  1527. diff.tv_sec++;
  1528. if (diff.tv_sec >= cycle) {
  1529. hashmeter(thr_id, &diff, hashes_done);
  1530. gettimeofday(&tv_start, NULL);
  1531. hashes_done = 0;
  1532. }
  1533. timeval_subtract(&diff, &tv_end, &tv_workstart);
  1534. if (!requested && (diff.tv_sec > request_interval || work->blk.nonce > request_nonce)) {
  1535. if (unlikely(!queue_request())) {
  1536. applog(LOG_ERR, "Failed to queue_request in gpuminer_thread %d", thr_id);
  1537. goto out;
  1538. }
  1539. requested = true;
  1540. }
  1541. }
  1542. out:
  1543. tq_freeze(mythr->q);
  1544. return NULL;
  1545. }
  1546. #endif /* HAVE_OPENCL */
  1547. static void restart_threads(bool longpoll)
  1548. {
  1549. int i;
  1550. /* Discard old queued requests and get new ones */
  1551. flush_requests(longpoll);
  1552. for (i = 0; i < mining_threads; i++)
  1553. work_restart[i].restart = 1;
  1554. }
  1555. /* Stage another work item from the work returned in a longpoll */
  1556. static void convert_to_work(json_t *val)
  1557. {
  1558. struct work *work;
  1559. bool rc;
  1560. work = calloc(sizeof(*work), 1);
  1561. if (unlikely(!work)) {
  1562. applog(LOG_ERR, "OOM in convert_to_work");
  1563. return;
  1564. }
  1565. rc= work_decode(json_object_get(val, "result"), work);
  1566. if (unlikely(!rc)) {
  1567. applog(LOG_ERR, "Could not convert longpoll data to work");
  1568. return;
  1569. }
  1570. if (unlikely(!tq_push(thr_info[stage_thr_id].q, work)))
  1571. applog(LOG_ERR, "Could not tq_push work in convert_to_work");
  1572. else if (opt_debug)
  1573. applog(LOG_DEBUG, "Converted longpoll data to work");
  1574. }
  1575. static void *longpoll_thread(void *userdata)
  1576. {
  1577. struct thr_info *mythr = userdata;
  1578. CURL *curl = NULL;
  1579. char *copy_start, *hdr_path, *lp_url = NULL;
  1580. bool need_slash = false;
  1581. int failures = 0;
  1582. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  1583. hdr_path = tq_pop(mythr->q, NULL);
  1584. if (!hdr_path)
  1585. goto out;
  1586. /* full URL */
  1587. if (strstr(hdr_path, "://")) {
  1588. lp_url = hdr_path;
  1589. hdr_path = NULL;
  1590. }
  1591. /* absolute path, on current server */
  1592. else {
  1593. copy_start = (*hdr_path == '/') ? (hdr_path + 1) : hdr_path;
  1594. if (rpc_url[strlen(rpc_url) - 1] != '/')
  1595. need_slash = true;
  1596. lp_url = malloc(strlen(rpc_url) + strlen(copy_start) + 2);
  1597. if (!lp_url)
  1598. goto out;
  1599. sprintf(lp_url, "%s%s%s", rpc_url, need_slash ? "/" : "", copy_start);
  1600. }
  1601. applog(LOG_INFO, "Long-polling activated for %s", lp_url);
  1602. curl = curl_easy_init();
  1603. if (unlikely(!curl)) {
  1604. applog(LOG_ERR, "CURL initialisation failed");
  1605. goto out;
  1606. }
  1607. while (1) {
  1608. struct timeval start, end;
  1609. json_t *val;
  1610. gettimeofday(&start, NULL);
  1611. val = json_rpc_call(curl, lp_url, rpc_userpass, rpc_req,
  1612. false, true);
  1613. if (likely(val)) {
  1614. convert_to_work(val);
  1615. failures = 0;
  1616. json_decref(val);
  1617. /* Keep track of who ordered a restart_threads to make
  1618. * sure it's only done once per new block */
  1619. if (likely(!strncmp(longpoll_block, blank, 36) ||
  1620. !strncmp(longpoll_block, current_block, 36))) {
  1621. new_blocks++;
  1622. applog(LOG_WARNING, "LONGPOLL detected new block on network, waiting on fresh work");
  1623. restart_threads(true);
  1624. } else
  1625. applog(LOG_WARNING, "LONGPOLL received after new block already detected");
  1626. } else {
  1627. /* Some pools regularly drop the longpoll request so
  1628. * only see this as longpoll failure if it happens
  1629. * immediately and just restart it the rest of the
  1630. * time. */
  1631. gettimeofday(&end, NULL);
  1632. if (end.tv_sec - start.tv_sec > 30)
  1633. continue;
  1634. if (failures++ < 10) {
  1635. sleep(30);
  1636. applog(LOG_WARNING,
  1637. "longpoll failed, sleeping for 30s");
  1638. } else {
  1639. applog(LOG_ERR,
  1640. "longpoll failed, ending thread");
  1641. goto out;
  1642. }
  1643. }
  1644. memcpy(longpoll_block, current_block, 36);
  1645. }
  1646. out:
  1647. free(hdr_path);
  1648. free(lp_url);
  1649. tq_freeze(mythr->q);
  1650. if (curl)
  1651. curl_easy_cleanup(curl);
  1652. return NULL;
  1653. }
  1654. static void reinit_cputhread(int thr_id)
  1655. {
  1656. struct thr_info *thr = &thr_info[thr_id];
  1657. tq_freeze(thr->q);
  1658. if (!(pthread_cancel(thr->pth)) && pthread_join(thr->pth, NULL)) {
  1659. applog(LOG_ERR, "Failed to pthread_join in reinit_cputhread");
  1660. goto failed_out;
  1661. }
  1662. applog(LOG_INFO, "Reinit CPU thread %d", thr_id);
  1663. tq_thaw(thr->q);
  1664. gettimeofday(&thr->last, NULL);
  1665. if (unlikely(pthread_create(&thr->pth, NULL, miner_thread, thr))) {
  1666. applog(LOG_ERR, "thread %d create failed", thr_id);
  1667. goto failed_out;
  1668. }
  1669. return;
  1670. failed_out:
  1671. kill_work();
  1672. }
  1673. #ifdef HAVE_OPENCL
  1674. static void reinit_gputhread(int thr_id)
  1675. {
  1676. int gpu = dev_from_id(thr_id);
  1677. struct thr_info *thr = &thr_info[thr_id];
  1678. char name[256];
  1679. tq_freeze(thr->q);
  1680. if (!(pthread_cancel(thr->pth)) && pthread_join(thr->pth, NULL)) {
  1681. applog(LOG_ERR, "Failed to pthread_join in reinit_gputhread");
  1682. goto failed_out;
  1683. }
  1684. free(clStates[thr_id]);
  1685. applog(LOG_INFO, "Reinit GPU thread %d", thr_id);
  1686. tq_thaw(thr->q);
  1687. clStates[thr_id] = initCl(gpu, name, sizeof(name));
  1688. if (!clStates[thr_id]) {
  1689. applog(LOG_ERR, "Failed to reinit GPU thread %d", thr_id);
  1690. goto failed_out;
  1691. }
  1692. applog(LOG_INFO, "initCl() finished. Found %s", name);
  1693. gettimeofday(&thr->last, NULL);
  1694. if (unlikely(pthread_create(&thr->pth, NULL, gpuminer_thread, thr))) {
  1695. applog(LOG_ERR, "thread %d create failed", thr_id);
  1696. goto failed_out;
  1697. }
  1698. return;
  1699. failed_out:
  1700. kill_work();
  1701. }
  1702. static void reinit_thread(int thr_id)
  1703. {
  1704. if (thr_id < gpu_threads)
  1705. reinit_gputhread(thr_id);
  1706. else
  1707. reinit_cputhread(thr_id);
  1708. }
  1709. #else
  1710. static void reinit_thread(int thr_id)
  1711. {
  1712. reinit_cputhread(thr_id);
  1713. }
  1714. #endif
  1715. /* Determine which are the first threads belonging to a device and if they're
  1716. * active */
  1717. static bool active_device(int thr_id)
  1718. {
  1719. if (thr_id < gpu_threads) {
  1720. if (thr_id >= total_devices)
  1721. return false;
  1722. if (!gpu_devices[dev_from_id(thr_id)])
  1723. return false;
  1724. } else if (thr_id > gpu_threads + num_processors)
  1725. return false;
  1726. return true;
  1727. }
  1728. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  1729. * the screen at regular intervals, and restarts threads if they appear to have
  1730. * died. */
  1731. static void *watchdog_thread(void *userdata)
  1732. {
  1733. const unsigned int interval = opt_log_interval / 2 ? : 1;
  1734. struct timeval zero_tv;
  1735. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  1736. memset(&zero_tv, 0, sizeof(struct timeval));
  1737. while (1) {
  1738. int x, y, logx, logy, i;
  1739. struct timeval now;
  1740. sleep(interval);
  1741. if (requests_queued() < opt_queue)
  1742. queue_request();
  1743. hashmeter(-1, &zero_tv, 0);
  1744. if (curses_active) {
  1745. pthread_mutex_lock(&curses_lock);
  1746. getmaxyx(mainwin, y, x);
  1747. getmaxyx(logwin, logy, logx);
  1748. y -= logcursor;
  1749. /* Detect screen size change */
  1750. if (x != logx || y != logy)
  1751. wresize(logwin, y, x);
  1752. for (i = 0; i < mining_threads; i++) {
  1753. if (active_device(i))
  1754. curses_print_status(i);
  1755. }
  1756. redrawwin(logwin);
  1757. redrawwin(statuswin);
  1758. pthread_mutex_unlock(&curses_lock);
  1759. }
  1760. if (unlikely(work_restart[watchdog_thr_id].restart)) {
  1761. restart_threads(false);
  1762. work_restart[watchdog_thr_id].restart = 0;
  1763. }
  1764. gettimeofday(&now, NULL);
  1765. #if 0
  1766. for (i = 0; i < mining_threads; i++) {
  1767. #else
  1768. for (i = 0; i < gpu_threads; i++) {
  1769. #endif
  1770. struct thr_info *thr = &thr_info[i];
  1771. /* Do not kill threads waiting on longpoll staged work
  1772. * or idle network */
  1773. if (now.tv_sec - thr->last.tv_sec > 60 && !idlenet) {
  1774. applog(LOG_ERR, "Attempting to restart thread %d, idle for more than 60 seconds", i);
  1775. /* Create one mandatory work item */
  1776. inc_staged(1, true);
  1777. if (unlikely(!queue_request())) {
  1778. applog(LOG_ERR, "Failed to queue_request in watchdog_thread");
  1779. kill_work();
  1780. break;
  1781. }
  1782. reinit_thread(i);
  1783. applog(LOG_WARNING, "Thread %d restarted", i);
  1784. }
  1785. }
  1786. }
  1787. return NULL;
  1788. }
  1789. static void print_summary(void)
  1790. {
  1791. struct timeval diff;
  1792. int hours, mins, secs, i;
  1793. double utility, efficiency = 0.0;
  1794. timeval_subtract(&diff, &total_tv_end, &total_tv_start);
  1795. hours = diff.tv_sec / 3600;
  1796. mins = (diff.tv_sec % 3600) / 60;
  1797. secs = diff.tv_sec % 60;
  1798. utility = accepted / ( total_secs ? total_secs : 1 ) * 60;
  1799. efficiency = getwork_requested ? accepted * 100.0 / getwork_requested : 0.0;
  1800. printf("\nSummary of runtime statistics:\n\n");
  1801. printf("Started at %s\n", datestamp);
  1802. printf("Runtime: %d hrs : %d mins : %d secs\n", hours, mins, secs);
  1803. if (total_secs)
  1804. printf("Average hashrate: %.1f Megahash/s\n", total_mhashes_done / total_secs);
  1805. printf("Queued work requests: %d\n", getwork_requested);
  1806. printf("Share submissions: %d\n", accepted + rejected);
  1807. printf("Accepted shares: %d\n", accepted);
  1808. printf("Rejected shares: %d\n", rejected);
  1809. if (accepted || rejected)
  1810. printf("Reject ratio: %.1f\n", (double)(rejected * 100) / (double)(accepted + rejected));
  1811. printf("Hardware errors: %d\n", hw_errors);
  1812. printf("Efficiency (accepted / queued): %.0f%%\n", efficiency);
  1813. printf("Utility (accepted shares / min): %.2f/min\n\n", utility);
  1814. printf("Discarded work due to new blocks: %d\n", discarded_work);
  1815. printf("Stale submissions discarded due to new blocks: %d\n", stale_shares);
  1816. printf("Unable to get work from server occasions: %d\n", localgen_occasions);
  1817. printf("Work items generated locally: %d\n", local_work);
  1818. printf("Submitting work remotely delay occasions: %d\n", remotefail_occasions);
  1819. printf("New blocks detected on network: %d\n\n", new_blocks);
  1820. printf("Summary of per device statistics:\n\n");
  1821. for (i = 0; i < mining_threads; i++) {
  1822. if (active_device(i))
  1823. print_status(i);
  1824. }
  1825. printf("\n");
  1826. }
  1827. int main (int argc, char *argv[])
  1828. {
  1829. unsigned int i, j = 0, x, y;
  1830. struct sigaction handler;
  1831. struct thr_info *thr;
  1832. char name[256];
  1833. struct tm tm;
  1834. if (unlikely(pthread_mutex_init(&hash_lock, NULL)))
  1835. return 1;
  1836. if (unlikely(pthread_mutex_init(&qd_lock, NULL)))
  1837. return 1;
  1838. if (unlikely(pthread_mutex_init(&stgd_lock, NULL)))
  1839. return 1;
  1840. if (unlikely(pthread_mutex_init(&curses_lock, NULL)))
  1841. return 1;
  1842. if (unlikely(pthread_mutex_init(&control_lock, NULL)))
  1843. return 1;
  1844. handler.sa_handler = &sighandler;
  1845. sigaction(SIGTERM, &handler, &termhandler);
  1846. sigaction(SIGINT, &handler, &inthandler);
  1847. gettimeofday(&total_tv_start, NULL);
  1848. gettimeofday(&total_tv_end, NULL);
  1849. localtime_r(&total_tv_start.tv_sec, &tm);
  1850. sprintf(datestamp, "[%d-%02d-%02d %02d:%02d:%02d]",
  1851. tm.tm_year + 1900,
  1852. tm.tm_mon + 1,
  1853. tm.tm_mday,
  1854. tm.tm_hour,
  1855. tm.tm_min,
  1856. tm.tm_sec);
  1857. for (i = 0; i < 36; i++) {
  1858. strcat(blank, "0");
  1859. strcat(current_block, "0");
  1860. strcat(longpoll_block, "0");
  1861. }
  1862. #ifdef WIN32
  1863. opt_n_threads = num_processors = 1;
  1864. #else
  1865. num_processors = sysconf(_SC_NPROCESSORS_ONLN);
  1866. opt_n_threads = num_processors;
  1867. #endif /* !WIN32 */
  1868. #ifdef HAVE_OPENCL
  1869. for (i = 0; i < 16; i++)
  1870. gpu_devices[i] = false;
  1871. nDevs = clDevicesNum();
  1872. if (nDevs < 0)
  1873. return 1;
  1874. #endif
  1875. if (nDevs)
  1876. opt_n_threads = 0;
  1877. rpc_url = strdup(DEF_RPC_URL);
  1878. /* parse command line */
  1879. opt_register_table(opt_config_table,
  1880. "Options for both config file and command line");
  1881. opt_register_table(opt_cmdline_table,
  1882. "Options for command line only");
  1883. opt_parse(&argc, argv, applog_and_exit);
  1884. if (argc != 1) {
  1885. applog(LOG_ERR, "Unexpected extra commandline arguments");
  1886. return 1;
  1887. }
  1888. if (total_devices) {
  1889. if (total_devices > nDevs) {
  1890. applog(LOG_ERR, "More devices specified than exist");
  1891. return 1;
  1892. }
  1893. for (i = 0; i < 16; i++)
  1894. if (gpu_devices[i] && i + 1 > nDevs) {
  1895. applog(LOG_ERR, "Command line options set a device that doesn't exist");
  1896. return 1;
  1897. }
  1898. gpu_threads = total_devices * opt_g_threads;
  1899. } else {
  1900. gpu_threads = nDevs * opt_g_threads;
  1901. for (i = 0; i < nDevs; i++)
  1902. gpu_devices[i] = true;
  1903. total_devices = nDevs;
  1904. }
  1905. if (!gpu_threads && !forced_n_threads) {
  1906. /* Maybe they turned GPU off; restore default CPU threads. */
  1907. opt_n_threads = num_processors;
  1908. }
  1909. logcursor = 7;
  1910. mining_threads = opt_n_threads + gpu_threads;
  1911. gpucursor = logcursor;
  1912. cpucursor = gpucursor + nDevs;
  1913. logstart = cpucursor + (opt_n_threads ? num_processors : 0) + 1;
  1914. logcursor = logstart + 1;
  1915. if (!rpc_userpass) {
  1916. if (!rpc_user || !rpc_pass) {
  1917. applog(LOG_ERR, "No login credentials supplied");
  1918. return 1;
  1919. }
  1920. rpc_userpass = malloc(strlen(rpc_user) + strlen(rpc_pass) + 2);
  1921. if (!rpc_userpass)
  1922. return 1;
  1923. sprintf(rpc_userpass, "%s:%s", rpc_user, rpc_pass);
  1924. } else {
  1925. rpc_user = malloc(strlen(rpc_userpass));
  1926. if (!rpc_user)
  1927. return 1;
  1928. strcpy(rpc_user, rpc_userpass);
  1929. rpc_user = strtok(rpc_user, ":");
  1930. if (!rpc_user) {
  1931. applog(LOG_ERR, "Failed to find colon delimiter in userpass");
  1932. return 1;
  1933. }
  1934. }
  1935. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  1936. return 1;
  1937. #ifdef HAVE_SYSLOG_H
  1938. if (use_syslog)
  1939. openlog("cpuminer", LOG_PID, LOG_USER);
  1940. #endif
  1941. work_restart = calloc(mining_threads + 4, sizeof(*work_restart));
  1942. if (!work_restart)
  1943. return 1;
  1944. thr_info = calloc(mining_threads + 4, sizeof(*thr));
  1945. if (!thr_info)
  1946. return 1;
  1947. /* init workio thread info */
  1948. work_thr_id = mining_threads;
  1949. thr = &thr_info[work_thr_id];
  1950. thr->id = work_thr_id;
  1951. thr->q = tq_new();
  1952. if (!thr->q)
  1953. return 1;
  1954. /* start work I/O thread */
  1955. if (pthread_create(&thr->pth, NULL, workio_thread, thr)) {
  1956. applog(LOG_ERR, "workio thread create failed");
  1957. return 1;
  1958. }
  1959. /* init longpoll thread info */
  1960. if (want_longpoll) {
  1961. longpoll_thr_id = mining_threads + 1;
  1962. thr = &thr_info[longpoll_thr_id];
  1963. thr->id = longpoll_thr_id;
  1964. thr->q = tq_new();
  1965. if (!thr->q)
  1966. return 1;
  1967. /* start longpoll thread */
  1968. if (unlikely(pthread_create(&thr->pth, NULL, longpoll_thread, thr))) {
  1969. applog(LOG_ERR, "longpoll thread create failed");
  1970. return 1;
  1971. }
  1972. pthread_detach(thr->pth);
  1973. } else
  1974. longpoll_thr_id = -1;
  1975. if (opt_n_threads ) {
  1976. cpus = calloc(num_processors, sizeof(struct cgpu_info));
  1977. if (unlikely(!cpus)) {
  1978. applog(LOG_ERR, "Failed to calloc cpus");
  1979. return 1;
  1980. }
  1981. }
  1982. if (gpu_threads) {
  1983. gpus = calloc(nDevs, sizeof(struct cgpu_info));
  1984. if (unlikely(!gpus)) {
  1985. applog(LOG_ERR, "Failed to calloc gpus");
  1986. return 1;
  1987. }
  1988. }
  1989. stage_thr_id = mining_threads + 3;
  1990. thr = &thr_info[stage_thr_id];
  1991. thr->q = tq_new();
  1992. if (!thr->q)
  1993. return 1;
  1994. /* start stage thread */
  1995. if (pthread_create(&thr->pth, NULL, stage_thread, thr)) {
  1996. applog(LOG_ERR, "stage thread create failed");
  1997. return 1;
  1998. }
  1999. /* Flag the work as ready forcing the mining threads to wait till we
  2000. * actually put something into the queue */
  2001. inc_staged(mining_threads, true);
  2002. /* Create a unique get work queue */
  2003. getq = tq_new();
  2004. if (!getq) {
  2005. applog(LOG_ERR, "Failed to create getq");
  2006. return 1;
  2007. }
  2008. #ifdef HAVE_OPENCL
  2009. i = 0;
  2010. /* start GPU mining threads */
  2011. for (j = 0; j < nDevs * opt_g_threads; j++) {
  2012. int gpu = j % nDevs;
  2013. gpus[gpu].is_gpu = 1;
  2014. gpus[gpu].cpu_gpu = gpu;
  2015. /* Skip devices not set to mine */
  2016. if (!gpu_devices[gpu])
  2017. continue;
  2018. thr = &thr_info[i];
  2019. thr->id = i;
  2020. thr->cgpu = &gpus[gpu];
  2021. thr->q = tq_new();
  2022. if (!thr->q) {
  2023. applog(LOG_ERR, "tq_new failed in starting gpu mining threads");
  2024. return 1;
  2025. }
  2026. applog(LOG_INFO, "Init GPU thread %i", i);
  2027. clStates[i] = initCl(gpu, name, sizeof(name));
  2028. if (!clStates[i]) {
  2029. applog(LOG_ERR, "Failed to init GPU thread %d", i);
  2030. continue;
  2031. }
  2032. applog(LOG_INFO, "initCl() finished. Found %s", name);
  2033. gettimeofday(&thr->last, NULL);
  2034. if (unlikely(pthread_create(&thr->pth, NULL, gpuminer_thread, thr))) {
  2035. applog(LOG_ERR, "thread %d create failed", i);
  2036. return 1;
  2037. }
  2038. i++;
  2039. }
  2040. applog(LOG_INFO, "%d gpu miner threads started", gpu_threads);
  2041. #endif
  2042. /* start CPU mining threads */
  2043. for (i = gpu_threads; i < mining_threads; i++) {
  2044. int cpu = (i - gpu_threads) % num_processors;
  2045. thr = &thr_info[i];
  2046. thr->id = i;
  2047. cpus[cpu].cpu_gpu = cpu;
  2048. thr->cgpu = &cpus[cpu];
  2049. thr->q = tq_new();
  2050. if (!thr->q) {
  2051. applog(LOG_ERR, "tq_new failed in starting cpu mining threads");
  2052. return 1;
  2053. }
  2054. gettimeofday(&thr->last, NULL);
  2055. if (unlikely(pthread_create(&thr->pth, NULL, miner_thread, thr))) {
  2056. applog(LOG_ERR, "thread %d create failed", i);
  2057. return 1;
  2058. }
  2059. }
  2060. applog(LOG_INFO, "%d cpu miner threads started, "
  2061. "using SHA256 '%s' algorithm.",
  2062. opt_n_threads,
  2063. algo_names[opt_algo]);
  2064. watchdog_thr_id = mining_threads + 2;
  2065. thr = &thr_info[watchdog_thr_id];
  2066. /* start wakeup thread */
  2067. if (pthread_create(&thr->pth, NULL, watchdog_thread, NULL)) {
  2068. applog(LOG_ERR, "wakeup thread create failed");
  2069. return 1;
  2070. }
  2071. /* Restart count as it will be wrong till all threads are started */
  2072. pthread_mutex_lock(&hash_lock);
  2073. gettimeofday(&total_tv_start, NULL);
  2074. gettimeofday(&total_tv_end, NULL);
  2075. total_mhashes_done = 0;
  2076. pthread_mutex_unlock(&hash_lock);
  2077. /* Set up the ncurses interface */
  2078. if (!opt_quiet && use_curses) {
  2079. mainwin = initscr();
  2080. getmaxyx(mainwin, y, x);
  2081. statuswin = newwin(logstart, x, 0, 0);
  2082. logwin = newwin(y - logcursor, 0, logcursor, 0);
  2083. idlok(logwin, true);
  2084. scrollok(logwin, true);
  2085. leaveok(logwin, true);
  2086. leaveok(statuswin, true);
  2087. test_and_set(&curses_active);
  2088. for (i = 0; i < mining_threads; i++)
  2089. print_status(i);
  2090. }
  2091. /* Now that everything's ready put enough work in the queue */
  2092. for (i = 0; i < opt_queue + mining_threads; i++) {
  2093. if (unlikely(!queue_request())) {
  2094. applog(LOG_ERR, "Failed to queue_request in main");
  2095. return 1;
  2096. }
  2097. }
  2098. /* main loop - simply wait for workio thread to exit */
  2099. pthread_join(thr_info[work_thr_id].pth, NULL);
  2100. applog(LOG_INFO, "workio thread dead, exiting.");
  2101. gettimeofday(&total_tv_end, NULL);
  2102. curl_global_cleanup();
  2103. disable_curses();
  2104. if (!opt_quiet && successful_connect)
  2105. print_summary();
  2106. if (gpu_threads)
  2107. free(gpus);
  2108. if (opt_n_threads)
  2109. free(cpus);
  2110. return 0;
  2111. }