main.c 75 KB

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