main.c 80 KB

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