main.c 52 KB

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