main.c 58 KB

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