main.c 66 KB

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