main.c 62 KB

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