main.c 75 KB

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