main.c 62 KB

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