main.c 61 KB

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