main.c 83 KB

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