main.c 61 KB

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