main.c 70 KB

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