main.c 63 KB

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