main.c 85 KB

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