main.c 66 KB

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