main.c 90 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478
  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 = pool->prio = 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, "[P]ool management [S]ettings [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. pthread_mutex_unlock(&curses_lock);
  693. }
  694. }
  695. void log_curses(const char *f, va_list ap)
  696. {
  697. if (curses_active) {
  698. if (!opt_loginput) {
  699. pthread_mutex_lock(&curses_lock);
  700. vw_printw(logwin, f, ap);
  701. wrefresh(logwin);
  702. pthread_mutex_unlock(&curses_lock);
  703. }
  704. } else
  705. vprintf(f, ap);
  706. }
  707. static void clear_logwin(void)
  708. {
  709. pthread_mutex_lock(&curses_lock);
  710. wclear(logwin);
  711. wrefresh(logwin);
  712. pthread_mutex_unlock(&curses_lock);
  713. }
  714. static bool submit_upstream_work(const struct work *work)
  715. {
  716. char *hexstr = NULL;
  717. json_t *val, *res;
  718. char s[345];
  719. bool rc = false;
  720. int thr_id = work->thr_id;
  721. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  722. CURL *curl = curl_easy_init();
  723. struct pool *pool = work->pool;
  724. if (unlikely(!curl)) {
  725. applog(LOG_ERR, "CURL initialisation failed");
  726. return rc;
  727. }
  728. /* build hex string */
  729. hexstr = bin2hex(work->data, sizeof(work->data));
  730. if (unlikely(!hexstr)) {
  731. applog(LOG_ERR, "submit_upstream_work OOM");
  732. goto out_nofree;
  733. }
  734. /* build JSON-RPC request */
  735. sprintf(s,
  736. "{\"method\": \"getwork\", \"params\": [ \"%s\" ], \"id\":1}\r\n",
  737. hexstr);
  738. if (opt_debug)
  739. applog(LOG_DEBUG, "DBG: sending RPC call: %s", s);
  740. /* issue JSON-RPC request */
  741. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, s, false, false, pool);
  742. if (unlikely(!val)) {
  743. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  744. if (!pool_tset(pool, &pool->submit_fail)) {
  745. total_ro++;
  746. pool->remotefail_occasions++;
  747. applog(LOG_WARNING, "Pool %d communication failure, caching submissions", pool->pool_no);
  748. }
  749. goto out;
  750. } else if (pool_tclear(pool, &pool->submit_fail))
  751. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  752. res = json_object_get(val, "result");
  753. /* Theoretically threads could race when modifying accepted and
  754. * rejected values but the chance of two submits completing at the
  755. * same time is zero so there is no point adding extra locking */
  756. if (json_is_true(res)) {
  757. cgpu->accepted++;
  758. total_accepted++;
  759. pool->accepted++;
  760. if (opt_debug)
  761. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  762. if (!opt_quiet) {
  763. if (total_pools > 1)
  764. applog(LOG_WARNING, "Accepted %.8s %sPU %d thread %d pool %d",
  765. hexstr + 152, cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, thr_id, work->pool->pool_no);
  766. else
  767. applog(LOG_WARNING, "Accepted %.8s %sPU %d thread %d",
  768. hexstr + 152, cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, thr_id);
  769. }
  770. } else {
  771. cgpu->rejected++;
  772. total_rejected++;
  773. pool->rejected++;
  774. if (opt_debug)
  775. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  776. if (!opt_quiet) {
  777. if (total_pools > 1)
  778. applog(LOG_WARNING, "Rejected %.8s %sPU %d thread %d pool %d",
  779. hexstr + 152, cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, thr_id, work->pool->pool_no);
  780. else
  781. applog(LOG_WARNING, "Rejected %.8s %sPU %d thread %d",
  782. hexstr + 152, cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, thr_id);
  783. }
  784. }
  785. cgpu->utility = cgpu->accepted / ( total_secs ? total_secs : 1 ) * 60;
  786. cgpu->efficiency = cgpu->getworks ? cgpu->accepted * 100.0 / cgpu->getworks : 0.0;
  787. if (!opt_quiet)
  788. print_status(thr_id);
  789. applog(LOG_INFO, "%sPU %d Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m",
  790. cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, cgpu->getworks, cgpu->accepted,
  791. cgpu->rejected, cgpu->hw_errors, cgpu->efficiency, cgpu->utility);
  792. json_decref(val);
  793. rc = true;
  794. out:
  795. free(hexstr);
  796. out_nofree:
  797. curl_easy_cleanup(curl);
  798. return rc;
  799. }
  800. static const char *rpc_req =
  801. "{\"method\": \"getwork\", \"params\": [], \"id\":0}\r\n";
  802. static int rotating_pool;
  803. /* Select any active pool in a rotating fashion when loadbalance is chosen */
  804. static inline struct pool *select_pool(void)
  805. {
  806. if (pool_strategy == POOL_LOADBALANCE) {
  807. struct pool *pool;
  808. rotating_pool++;
  809. if (rotating_pool >= total_pools)
  810. rotating_pool = 0;
  811. pool = pools[rotating_pool];
  812. if (!pool->idle && pool->enabled)
  813. return pools[rotating_pool];
  814. }
  815. return current_pool();
  816. }
  817. static bool get_upstream_work(struct work *work)
  818. {
  819. struct pool *pool = select_pool();
  820. json_t *val;
  821. bool rc = false;
  822. CURL *curl = curl_easy_init();
  823. if (unlikely(!curl)) {
  824. applog(LOG_ERR, "CURL initialisation failed");
  825. return rc;
  826. }
  827. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  828. want_longpoll, false, pool);
  829. if (unlikely(!val)) {
  830. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  831. goto out;
  832. }
  833. rc = work_decode(json_object_get(val, "result"), work);
  834. work->pool = pool;
  835. total_getworks++;
  836. pool->getwork_requested++;
  837. json_decref(val);
  838. out:
  839. curl_easy_cleanup(curl);
  840. return rc;
  841. }
  842. static void workio_cmd_free(struct workio_cmd *wc)
  843. {
  844. if (!wc)
  845. return;
  846. switch (wc->cmd) {
  847. case WC_SUBMIT_WORK:
  848. free(wc->u.work);
  849. break;
  850. default: /* do nothing */
  851. break;
  852. }
  853. memset(wc, 0, sizeof(*wc)); /* poison */
  854. free(wc);
  855. }
  856. static void disable_curses(void)
  857. {
  858. if (test_and_clear(&curses_active)) {
  859. #ifdef WIN32
  860. leaveok(logwin, false);
  861. leaveok(statuswin, false);
  862. leaveok(mainwin, false);
  863. #endif
  864. nocbreak();
  865. echo();
  866. delwin(logwin);
  867. delwin(statuswin);
  868. delwin(mainwin);
  869. endwin();
  870. refresh();
  871. #ifdef WIN32
  872. // Move the cursor to after curses output.
  873. HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
  874. CONSOLE_SCREEN_BUFFER_INFO csbi;
  875. COORD coord;
  876. if (GetConsoleScreenBufferInfo(hout, &csbi)) {
  877. coord.X = 0;
  878. coord.Y = csbi.dwSize.Y - 1;
  879. SetConsoleCursorPosition(hout, coord);
  880. }
  881. #endif
  882. }
  883. }
  884. void kill_work(void)
  885. {
  886. struct workio_cmd *wc;
  887. struct thr_info *thr;
  888. unsigned int i;
  889. disable_curses();
  890. applog(LOG_INFO, "Received kill message");
  891. /* Kill the watchdog thread */
  892. thr = &thr_info[watchdog_thr_id];
  893. pthread_cancel(*thr->pth);
  894. /* Stop the mining threads*/
  895. for (i = 0; i < mining_threads; i++) {
  896. thr = &thr_info[i];
  897. if (!thr->pth)
  898. continue;
  899. tq_freeze(thr->q);
  900. /* No need to check if this succeeds or not */
  901. pthread_cancel(*thr->pth);
  902. }
  903. /* Stop the others */
  904. thr = &thr_info[stage_thr_id];
  905. pthread_cancel(*thr->pth);
  906. thr = &thr_info[longpoll_thr_id];
  907. pthread_cancel(*thr->pth);
  908. wc = calloc(1, sizeof(*wc));
  909. if (unlikely(!wc)) {
  910. applog(LOG_ERR, "Failed to calloc wc in kill_work");
  911. /* We're just trying to die anyway, so forget graceful */
  912. exit (1);
  913. }
  914. wc->cmd = WC_DIE;
  915. wc->thr = 0;
  916. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  917. applog(LOG_ERR, "Failed to tq_push work in kill_work");
  918. exit (1);
  919. }
  920. }
  921. static void sighandler(int sig)
  922. {
  923. /* Restore signal handlers so we can still quit if kill_work fails */
  924. sigaction(SIGTERM, &termhandler, NULL);
  925. sigaction(SIGINT, &inthandler, NULL);
  926. kill_work();
  927. }
  928. static void *get_work_thread(void *userdata)
  929. {
  930. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  931. struct work *ret_work;
  932. int failures = 0;
  933. pthread_detach(pthread_self());
  934. ret_work = calloc(1, sizeof(*ret_work));
  935. if (unlikely(!ret_work)) {
  936. applog(LOG_ERR, "Failed to calloc ret_work in workio_get_work");
  937. kill_work();
  938. goto out;
  939. }
  940. /* obtain new work from bitcoin via JSON-RPC */
  941. while (!get_upstream_work(ret_work)) {
  942. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  943. applog(LOG_ERR, "json_rpc_call failed, terminating workio thread");
  944. free(ret_work);
  945. kill_work();
  946. goto out;
  947. }
  948. /* pause, then restart work-request loop */
  949. applog(LOG_DEBUG, "json_rpc_call failed on get work, retry after %d seconds",
  950. opt_fail_pause);
  951. sleep(opt_fail_pause);
  952. }
  953. /* send work to requesting thread */
  954. if (unlikely(!tq_push(thr_info[stage_thr_id].q, ret_work))) {
  955. applog(LOG_ERR, "Failed to tq_push work in workio_get_work");
  956. kill_work();
  957. free(ret_work);
  958. }
  959. out:
  960. workio_cmd_free(wc);
  961. return NULL;
  962. }
  963. static bool workio_get_work(struct workio_cmd *wc)
  964. {
  965. pthread_t get_thread;
  966. if (unlikely(pthread_create(&get_thread, NULL, get_work_thread, (void *)wc))) {
  967. applog(LOG_ERR, "Failed to create get_work_thread");
  968. return false;
  969. }
  970. return true;
  971. }
  972. static bool stale_work(struct work *work)
  973. {
  974. bool ret = false;
  975. char *hexstr;
  976. /* Only use the primary pool for determination as the work may
  977. * interleave at times of new blocks */
  978. if (work->pool != current_pool())
  979. return ret;
  980. hexstr = bin2hex(work->data, 36);
  981. if (unlikely(!hexstr)) {
  982. applog(LOG_ERR, "submit_work_thread OOM");
  983. return ret;
  984. }
  985. if (strncmp(hexstr, current_block, 36))
  986. ret = true;
  987. free(hexstr);
  988. return ret;
  989. }
  990. static void *submit_work_thread(void *userdata)
  991. {
  992. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  993. struct work *work = wc->u.work;
  994. struct pool *pool = work->pool;
  995. int failures = 0;
  996. pthread_detach(pthread_self());
  997. if (stale_work(work)) {
  998. applog(LOG_WARNING, "Stale share detected, discarding");
  999. total_stale++;
  1000. pool->stale_shares++;
  1001. goto out;
  1002. }
  1003. /* submit solution to bitcoin via JSON-RPC */
  1004. while (!submit_upstream_work(work)) {
  1005. if (stale_work(work)) {
  1006. applog(LOG_WARNING, "Stale share detected, discarding");
  1007. total_stale++;
  1008. pool->stale_shares++;
  1009. break;
  1010. }
  1011. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  1012. applog(LOG_ERR, "Failed %d retries ...terminating workio thread", opt_retries);
  1013. kill_work();
  1014. break;
  1015. }
  1016. /* pause, then restart work-request loop */
  1017. applog(LOG_INFO, "json_rpc_call failed on submit_work, retry after %d seconds",
  1018. opt_fail_pause);
  1019. sleep(opt_fail_pause);
  1020. }
  1021. out:
  1022. workio_cmd_free(wc);
  1023. return NULL;
  1024. }
  1025. static bool workio_submit_work(struct workio_cmd *wc)
  1026. {
  1027. pthread_t submit_thread;
  1028. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, (void *)wc))) {
  1029. applog(LOG_ERR, "Failed to create submit_work_thread");
  1030. return false;
  1031. }
  1032. return true;
  1033. }
  1034. static void inc_staged(struct pool *pool, int inc, bool lp)
  1035. {
  1036. pthread_mutex_lock(&stgd_lock);
  1037. if (lp) {
  1038. lp_staged += inc;
  1039. total_staged += inc;
  1040. } else if (lp_staged)
  1041. --lp_staged;
  1042. else
  1043. total_staged += inc;
  1044. pthread_mutex_unlock(&stgd_lock);
  1045. }
  1046. static void dec_staged(int inc)
  1047. {
  1048. pthread_mutex_lock(&stgd_lock);
  1049. total_staged -= inc;
  1050. pthread_mutex_unlock(&stgd_lock);
  1051. }
  1052. static int requests_staged(void)
  1053. {
  1054. int ret;
  1055. pthread_mutex_lock(&stgd_lock);
  1056. ret = total_staged;
  1057. pthread_mutex_unlock(&stgd_lock);
  1058. return ret;
  1059. }
  1060. static int real_staged(void)
  1061. {
  1062. int ret;
  1063. pthread_mutex_lock(&stgd_lock);
  1064. ret = total_staged - lp_staged;
  1065. pthread_mutex_unlock(&stgd_lock);
  1066. return ret;
  1067. }
  1068. /* Find the pool that currently has the highest priority */
  1069. static struct pool *priority_pool(int choice)
  1070. {
  1071. struct pool *ret = NULL;
  1072. int i;
  1073. for (i = 0; i < total_pools; i++) {
  1074. struct pool *pool = pools[i];
  1075. if (pool->prio == choice) {
  1076. ret = pool;
  1077. break;
  1078. }
  1079. }
  1080. if (unlikely(!ret)) {
  1081. applog(LOG_ERR, "WTF No pool %d found!", choice);
  1082. return pools[choice];
  1083. }
  1084. return ret;
  1085. }
  1086. static void restart_longpoll(void);
  1087. static void switch_pools(struct pool *selected)
  1088. {
  1089. struct pool *pool, *last_pool;
  1090. int i, pool_no;
  1091. pthread_mutex_lock(&control_lock);
  1092. last_pool = currentpool;
  1093. pool_no = currentpool->pool_no;
  1094. /* Switch selected to pool number 0 and move the rest down */
  1095. if (selected) {
  1096. if (selected->prio != 0) {
  1097. for (i = 0; i < total_pools; i++) {
  1098. pool = pools[i];
  1099. if (pool->prio < selected->prio)
  1100. pool->prio++;
  1101. }
  1102. selected->prio = 0;
  1103. }
  1104. }
  1105. switch (pool_strategy) {
  1106. /* Both of these set to the master pool */
  1107. case POOL_FAILOVER:
  1108. case POOL_LOADBALANCE:
  1109. for (i = 0; i < total_pools; i++) {
  1110. pool = priority_pool(i);
  1111. if (!pool->idle && pool->enabled) {
  1112. pool_no = pool->pool_no;
  1113. break;
  1114. }
  1115. }
  1116. break;
  1117. /* Both of these simply increment and cycle */
  1118. case POOL_ROUNDROBIN:
  1119. case POOL_ROTATE:
  1120. if (selected) {
  1121. pool_no = selected->pool_no;
  1122. break;
  1123. }
  1124. pool_no++;
  1125. if (pool_no >= total_pools)
  1126. pool_no = 0;
  1127. break;
  1128. default:
  1129. break;
  1130. }
  1131. currentpool = pools[pool_no];
  1132. pool = currentpool;
  1133. pthread_mutex_unlock(&control_lock);
  1134. if (pool != last_pool) {
  1135. applog(LOG_WARNING, "Switching to %s", pool->rpc_url);
  1136. restart_longpoll();
  1137. }
  1138. /* Reset the queued amount to allow more to be queued for the new pool */
  1139. pthread_mutex_lock(&qd_lock);
  1140. total_queued = 0;
  1141. pthread_mutex_unlock(&qd_lock);
  1142. inc_staged(pool, 1, true);
  1143. }
  1144. static void set_curblock(char *hexstr)
  1145. {
  1146. struct timeval tv_now;
  1147. struct tm tm;
  1148. memcpy(current_block, hexstr, 36);
  1149. gettimeofday(&tv_now, NULL);
  1150. localtime_r(&tv_now.tv_sec, &tm);
  1151. sprintf(blockdate, "[%d-%02d-%02d %02d:%02d:%02d]",
  1152. tm.tm_year + 1900,
  1153. tm.tm_mon + 1,
  1154. tm.tm_mday,
  1155. tm.tm_hour,
  1156. tm.tm_min,
  1157. tm.tm_sec);
  1158. }
  1159. static void test_work_current(struct work *work)
  1160. {
  1161. char *hexstr;
  1162. /* Only use the primary pool for determination */
  1163. if (work->pool != current_pool())
  1164. return;
  1165. hexstr = bin2hex(work->data, 36);
  1166. if (unlikely(!hexstr)) {
  1167. applog(LOG_ERR, "stage_thread OOM");
  1168. return;
  1169. }
  1170. /* current_block is blanked out on successful longpoll */
  1171. if (unlikely(strncmp(hexstr, current_block, 36))) {
  1172. if (block_changed != BLOCK_LP && block_changed != BLOCK_FIRST) {
  1173. block_changed = BLOCK_DETECT;
  1174. new_blocks++;
  1175. if (have_longpoll)
  1176. applog(LOG_WARNING, "New block detected on network before longpoll, waiting on fresh work");
  1177. else
  1178. applog(LOG_WARNING, "New block detected on network, waiting on fresh work");
  1179. /* As we can't flush the work from here, signal the
  1180. * wakeup thread to restart all the threads */
  1181. work_restart[watchdog_thr_id].restart = 1;
  1182. } else
  1183. block_changed = BLOCK_NONE;
  1184. set_curblock(hexstr);
  1185. }
  1186. free(hexstr);
  1187. }
  1188. static void *stage_thread(void *userdata)
  1189. {
  1190. struct thr_info *mythr = userdata;
  1191. bool ok = true;
  1192. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  1193. while (ok) {
  1194. struct work *work = NULL;
  1195. work = tq_pop(mythr->q, NULL);
  1196. if (unlikely(!work)) {
  1197. applog(LOG_ERR, "Failed to tq_pop in stage_thread");
  1198. ok = false;
  1199. break;
  1200. }
  1201. test_work_current(work);
  1202. if (unlikely(!tq_push(getq, work))) {
  1203. applog(LOG_ERR, "Failed to tq_push work in stage_thread");
  1204. ok = false;
  1205. break;
  1206. }
  1207. inc_staged(work->pool, 1, false);
  1208. }
  1209. tq_freeze(mythr->q);
  1210. return NULL;
  1211. }
  1212. static char *curses_input(const char *query);
  1213. static int curses_int(const char *query)
  1214. {
  1215. int ret;
  1216. char *cvar;
  1217. cvar = curses_input(query);
  1218. ret = atoi(cvar);
  1219. free(cvar);
  1220. return ret;
  1221. }
  1222. static bool input_pool(bool live);
  1223. static int active_pools(void)
  1224. {
  1225. int ret = 0;
  1226. int i;
  1227. for (i = 0; i < total_pools; i++) {
  1228. if ((pools[i])->enabled)
  1229. ret++;
  1230. }
  1231. return ret;
  1232. }
  1233. static void display_pool_summary(struct pool *pool)
  1234. {
  1235. double efficiency = 0.0;
  1236. wprintw(logwin, "Pool: %s\n", pool->rpc_url);
  1237. wprintw(logwin, " Queued work requests: %d\n", pool->getwork_requested);
  1238. wprintw(logwin, " Share submissions: %d\n", pool->accepted + pool->rejected);
  1239. wprintw(logwin, " Accepted shares: %d\n", pool->accepted);
  1240. wprintw(logwin, " Rejected shares: %d\n", pool->rejected);
  1241. if (pool->accepted || pool->rejected)
  1242. wprintw(logwin, " Reject ratio: %.1f\n", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  1243. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  1244. wprintw(logwin, " Efficiency (accepted / queued): %.0f%%\n", efficiency);
  1245. wprintw(logwin, " Discarded work due to new blocks: %d\n", pool->discarded_work);
  1246. wprintw(logwin, " Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  1247. wprintw(logwin, " Unable to get work from server occasions: %d\n", pool->localgen_occasions);
  1248. wprintw(logwin, " Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  1249. }
  1250. /* We can't remove the memory used for this struct pool because there may
  1251. * still be work referencing it. We just remove it from the pools list */
  1252. static void remove_pool(struct pool *pool)
  1253. {
  1254. int i, last_pool = total_pools - 1;
  1255. struct pool *other;
  1256. /* Boost priority of any lower prio than this one */
  1257. for (i = 0; i < total_pools; i++) {
  1258. other = pools[i];
  1259. if (other->prio > pool->prio)
  1260. other->prio--;
  1261. }
  1262. if (pool->pool_no < last_pool) {
  1263. /* Swap the last pool for this one */
  1264. (pools[last_pool])->pool_no = pool->pool_no;
  1265. pools[pool->pool_no] = pools[last_pool];
  1266. }
  1267. /* Give it an invalid number */
  1268. pool->pool_no = total_pools;
  1269. total_pools--;
  1270. }
  1271. static void display_pools(void)
  1272. {
  1273. struct pool *pool;
  1274. int selected, i;
  1275. char input;
  1276. opt_loginput = true;
  1277. immedok(logwin, true);
  1278. updated:
  1279. clear_logwin();
  1280. pthread_mutex_lock(&curses_lock);
  1281. for (i = 0; i < total_pools; i++) {
  1282. pool = pools[i];
  1283. if (pool == current_pool())
  1284. wattron(logwin, A_BOLD);
  1285. if (!pool->enabled)
  1286. wattron(logwin, A_DIM);
  1287. wprintw(logwin, "%d: %s %s Priority %d: %s User:%s\n",
  1288. pool->pool_no,
  1289. pool->enabled? "Enabled" : "Disabled",
  1290. pool->idle? "Dead" : "Alive",
  1291. pool->prio,
  1292. pool->rpc_url, pool->rpc_user);
  1293. wattroff(logwin, A_BOLD | A_DIM);
  1294. }
  1295. retry:
  1296. wprintw(logwin, "\nCurrent pool management strategy: %s\n",
  1297. strategies[pool_strategy]);
  1298. if (pool_strategy == POOL_ROTATE)
  1299. wprintw(logwin, "Set to rotate every %d minutes\n", opt_rotate_period);
  1300. wprintw(logwin, "[A]dd pool [R]emove pool [D]isable pool [E]nable pool\n");
  1301. wprintw(logwin, "[C]hange management strategy [S]witch pool [I]nformation\n");
  1302. wprintw(logwin, "Or press any other key to continue\n");
  1303. pthread_mutex_unlock(&curses_lock);
  1304. input = getch();
  1305. if (!strncasecmp(&input, "a", 1)) {
  1306. input_pool(true);
  1307. goto updated;
  1308. } else if (!strncasecmp(&input, "r", 1)) {
  1309. if (active_pools() <= 1) {
  1310. wprintw(logwin, "Cannot remove last pool");
  1311. goto retry;
  1312. }
  1313. selected = curses_int("Select pool number");
  1314. if (selected < 0 || selected >= total_pools) {
  1315. wprintw(logwin, "Invalid selection\n");
  1316. goto retry;
  1317. }
  1318. pool = pools[selected];
  1319. if (pool == current_pool())
  1320. switch_pools(NULL);
  1321. if (pool == current_pool()) {
  1322. wprintw(logwin, "Unable to remove pool due to activity\n");
  1323. goto retry;
  1324. }
  1325. pool->enabled = false;
  1326. remove_pool(pool);
  1327. goto updated;
  1328. } else if (!strncasecmp(&input, "s", 1)) {
  1329. selected = curses_int("Select pool number");
  1330. if (selected < 0 || selected >= total_pools) {
  1331. wprintw(logwin, "Invalid selection\n");
  1332. goto retry;
  1333. }
  1334. pool = pools[selected];
  1335. pool->enabled = true;
  1336. switch_pools(pool);
  1337. goto updated;
  1338. } else if (!strncasecmp(&input, "d", 1)) {
  1339. if (active_pools() <= 1) {
  1340. wprintw(logwin, "Cannot disable last pool");
  1341. goto retry;
  1342. }
  1343. selected = curses_int("Select pool number");
  1344. if (selected < 0 || selected >= total_pools) {
  1345. wprintw(logwin, "Invalid selection\n");
  1346. goto retry;
  1347. }
  1348. pool = pools[selected];
  1349. pool->enabled = false;
  1350. if (pool == current_pool())
  1351. switch_pools(NULL);
  1352. goto updated;
  1353. } else if (!strncasecmp(&input, "e", 1)) {
  1354. selected = curses_int("Select pool number");
  1355. if (selected < 0 || selected >= total_pools) {
  1356. wprintw(logwin, "Invalid selection\n");
  1357. goto retry;
  1358. }
  1359. pool = pools[selected];
  1360. pool->enabled = true;
  1361. if (pool->prio < current_pool()->prio)
  1362. switch_pools(pool);
  1363. goto updated;
  1364. } else if (!strncasecmp(&input, "c", 1)) {
  1365. for (i = 0; i <= TOP_STRATEGY; i++)
  1366. wprintw(logwin, "%d: %s\n", i, strategies[i]);
  1367. selected = curses_int("Select strategy number type");
  1368. if (selected < 0 || selected > TOP_STRATEGY) {
  1369. wprintw(logwin, "Invalid selection\n");
  1370. goto retry;
  1371. }
  1372. if (selected == POOL_ROTATE) {
  1373. opt_rotate_period = curses_int("Select interval in minutes");
  1374. if (opt_rotate_period < 0 || opt_rotate_period > 9999) {
  1375. opt_rotate_period = 0;
  1376. wprintw(logwin, "Invalid selection\n");
  1377. goto retry;
  1378. }
  1379. }
  1380. pool_strategy = selected;
  1381. switch_pools(NULL);
  1382. goto updated;
  1383. } else if (!strncasecmp(&input, "i", 1)) {
  1384. selected = curses_int("Select pool number");
  1385. if (selected < 0 || selected >= total_pools) {
  1386. wprintw(logwin, "Invalid selection\n");
  1387. goto retry;
  1388. }
  1389. pool = pools[selected];
  1390. display_pool_summary(pool);
  1391. goto retry;
  1392. }
  1393. clear_logwin();
  1394. immedok(logwin, false);
  1395. opt_loginput = false;
  1396. }
  1397. static void display_options(void)
  1398. {
  1399. int selected;
  1400. char input;
  1401. opt_loginput = true;
  1402. immedok(logwin, true);
  1403. retry:
  1404. wprintw(logwin, "\nToggle: [D]ebug [N]ormal [S]ilent [V]erbose [R]PC debug\n");
  1405. wprintw(logwin, "[L]og interval [C]lear\n");
  1406. wprintw(logwin, "Select an option or any other key to return\n");
  1407. input = getch();
  1408. if (!strncasecmp(&input, "s", 1)) {
  1409. opt_quiet ^= true;
  1410. applog(LOG_WARNING, "Silent mode %s", opt_quiet ? "enabled" : "disabled");
  1411. } else if (!strncasecmp(&input, "v", 1)) {
  1412. opt_log_output ^= true;
  1413. applog(LOG_WARNING, "Verbose mode %s", opt_log_output ? "enabled" : "disabled");
  1414. } else if (!strncasecmp(&input, "n", 1)) {
  1415. opt_log_output = false;
  1416. opt_debug = false;
  1417. opt_quiet = false;
  1418. opt_protocol = false;
  1419. applog(LOG_WARNING, "Output mode reset to normal");
  1420. } else if (!strncasecmp(&input, "d", 1)) {
  1421. opt_debug ^= true;
  1422. if (opt_debug)
  1423. opt_log_output = true;
  1424. applog(LOG_WARNING, "Debug mode %s", opt_debug ? "enabled" : "disabled");
  1425. } else if (!strncasecmp(&input, "r", 1)) {
  1426. opt_protocol ^= true;
  1427. applog(LOG_WARNING, "RPC protocol debugging %s", opt_protocol ? "enabled" : "disabled");
  1428. } else if (!strncasecmp(&input, "c", 1))
  1429. clear_logwin();
  1430. else if (!strncasecmp(&input, "l", 1)) {
  1431. selected = curses_int("Interval in seconds");
  1432. if (selected < 0 || selected > 9999) {
  1433. wprintw(logwin, "Invalid selection\n");
  1434. goto retry;
  1435. }
  1436. opt_log_interval = selected;
  1437. }
  1438. wclear(logwin);
  1439. immedok(logwin, false);
  1440. opt_loginput = false;
  1441. }
  1442. static void set_options(void)
  1443. {
  1444. int selected;
  1445. char input;
  1446. opt_loginput = true;
  1447. immedok(logwin, true);
  1448. retry:
  1449. wclear(logwin);
  1450. wprintw(logwin, "\n[D]ynamic mode: %s\n[L]ongpoll: %s\n",
  1451. opt_dynamic ? "On" : "Off", want_longpoll ? "On" : "Off");
  1452. if (opt_dynamic)
  1453. wprintw(logwin, "[I]ntensity: Dynamic\n");
  1454. else
  1455. wprintw(logwin, "[I]ntensity: %d\n", scan_intensity);
  1456. wprintw(logwin, "[Q]ueue: %d\n[S]cantime: %d\n[R]etries: %d\n[P]ause: %d\n",
  1457. opt_queue, opt_scantime, opt_retries, opt_fail_pause);
  1458. wprintw(logwin, "Select an option or any other key to return\n");
  1459. input = getch();
  1460. if (!strncasecmp(&input, "q", 1)) {
  1461. selected = curses_int("Extra work items to queue");
  1462. if (selected < 0 || selected > 9999) {
  1463. wprintw(logwin, "Invalid selection\n");
  1464. goto retry;
  1465. }
  1466. opt_queue = selected;
  1467. goto retry;
  1468. } else if (!strncasecmp(&input, "d", 1)) {
  1469. opt_dynamic ^= true;
  1470. goto retry;
  1471. } else if (!strncasecmp(&input, "l", 1)) {
  1472. want_longpoll ^= true;
  1473. applog(LOG_WARNING, "Longpoll %s", want_longpoll ? "enabled" : "disabled");
  1474. restart_longpoll();
  1475. goto retry;
  1476. } else if (!strncasecmp(&input, "i", 1)) {
  1477. selected = curses_int("Set GPU scan intensity (0-10)");
  1478. if (selected < 0 || selected > 10) {
  1479. wprintw(logwin, "Invalid selection\n");
  1480. goto retry;
  1481. }
  1482. opt_dynamic = false;
  1483. scan_intensity = selected;
  1484. goto retry;
  1485. } else if (!strncasecmp(&input, "s", 1)) {
  1486. selected = curses_int("Set scantime in seconds");
  1487. if (selected < 0 || selected > 9999) {
  1488. wprintw(logwin, "Invalid selection\n");
  1489. goto retry;
  1490. }
  1491. opt_scantime = selected;
  1492. goto retry;
  1493. } else if (!strncasecmp(&input, "r", 1)) {
  1494. selected = curses_int("Retries before failing (-1 infinite)");
  1495. if (selected < -1 || selected > 9999) {
  1496. wprintw(logwin, "Invalid selection\n");
  1497. goto retry;
  1498. }
  1499. opt_retries = selected;
  1500. goto retry;
  1501. } else if (!strncasecmp(&input, "p", 1)) {
  1502. selected = curses_int("Seconds to pause before network retries");
  1503. if (selected < 1 || selected > 9999) {
  1504. wprintw(logwin, "Invalid selection\n");
  1505. goto retry;
  1506. }
  1507. opt_fail_pause = selected;
  1508. goto retry;
  1509. }
  1510. wclear(logwin);
  1511. immedok(logwin, false);
  1512. opt_loginput = false;
  1513. }
  1514. static void *input_thread(void *userdata)
  1515. {
  1516. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  1517. if (!curses_active)
  1518. return NULL;
  1519. while (1) {
  1520. char input;
  1521. input = getch();
  1522. if (!strncasecmp(&input, "q", 1)) {
  1523. kill_work();
  1524. return NULL;
  1525. } else if (!strncasecmp(&input, "d", 1))
  1526. display_options();
  1527. else if (!strncasecmp(&input, "p", 1))
  1528. display_pools();
  1529. else if (!strncasecmp(&input, "s", 1))
  1530. set_options();
  1531. }
  1532. return NULL;
  1533. }
  1534. static void *workio_thread(void *userdata)
  1535. {
  1536. struct thr_info *mythr = userdata;
  1537. bool ok = true;
  1538. while (ok) {
  1539. struct workio_cmd *wc;
  1540. /* wait for workio_cmd sent to us, on our queue */
  1541. wc = tq_pop(mythr->q, NULL);
  1542. if (unlikely(!wc)) {
  1543. applog(LOG_ERR, "Failed to tq_pop in workio_thread");
  1544. ok = false;
  1545. break;
  1546. }
  1547. /* process workio_cmd */
  1548. switch (wc->cmd) {
  1549. case WC_GET_WORK:
  1550. ok = workio_get_work(wc);
  1551. break;
  1552. case WC_SUBMIT_WORK:
  1553. ok = workio_submit_work(wc);
  1554. break;
  1555. case WC_DIE:
  1556. default:
  1557. ok = false;
  1558. break;
  1559. }
  1560. }
  1561. tq_freeze(mythr->q);
  1562. return NULL;
  1563. }
  1564. static void thread_reportin(struct thr_info *thr)
  1565. {
  1566. gettimeofday(&thr->last, NULL);
  1567. thr->getwork = false;
  1568. }
  1569. static inline void thread_reportout(struct thr_info *thr)
  1570. {
  1571. thr->getwork = true;
  1572. }
  1573. static void hashmeter(int thr_id, struct timeval *diff,
  1574. unsigned long hashes_done)
  1575. {
  1576. struct timeval temp_tv_end, total_diff;
  1577. double khashes, secs;
  1578. double local_secs;
  1579. double utility, efficiency = 0.0;
  1580. static double local_mhashes_done = 0;
  1581. static double rolling_local = 0;
  1582. double local_mhashes = (double)hashes_done / 1000000.0;
  1583. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  1584. /* Update the last time this thread reported in */
  1585. if (thr_id >= 0)
  1586. gettimeofday(&thr_info[thr_id].last, NULL);
  1587. /* Don't bother calculating anything if we're not displaying it */
  1588. if (opt_quiet || !opt_log_interval)
  1589. return;
  1590. khashes = hashes_done / 1000.0;
  1591. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  1592. if (thr_id >= 0 && secs) {
  1593. /* So we can call hashmeter from a non worker thread */
  1594. if (opt_debug)
  1595. applog(LOG_DEBUG, "[thread %d: %lu hashes, %.0f khash/sec]",
  1596. thr_id, hashes_done, hashes_done / secs);
  1597. cgpu->local_mhashes += local_mhashes;
  1598. cgpu->total_mhashes += local_mhashes;
  1599. }
  1600. /* Totals are updated by all threads so can race without locking */
  1601. pthread_mutex_lock(&hash_lock);
  1602. gettimeofday(&temp_tv_end, NULL);
  1603. timeval_subtract(&total_diff, &temp_tv_end, &total_tv_end);
  1604. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  1605. total_mhashes_done += local_mhashes;
  1606. local_mhashes_done += local_mhashes;
  1607. if (total_diff.tv_sec < opt_log_interval)
  1608. /* Only update the total every opt_log_interval seconds */
  1609. goto out_unlock;
  1610. gettimeofday(&total_tv_end, NULL);
  1611. /* Use a rolling average by faking an exponential decay over 5 * log */
  1612. rolling_local = ((rolling_local * 0.9) + local_mhashes_done) / 1.9;
  1613. timeval_subtract(&total_diff, &total_tv_end, &total_tv_start);
  1614. total_secs = (double)total_diff.tv_sec +
  1615. ((double)total_diff.tv_usec / 1000000.0);
  1616. utility = total_accepted / ( total_secs ? total_secs : 1 ) * 60;
  1617. efficiency = total_getworks ? total_accepted * 100.0 / total_getworks : 0.0;
  1618. sprintf(statusline, "[(%ds):%.1f (avg):%.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]",
  1619. opt_log_interval, rolling_local / local_secs, total_mhashes_done / total_secs,
  1620. total_getworks, total_accepted, total_rejected, hw_errors, efficiency, utility);
  1621. if (!curses_active) {
  1622. printf("%s \r", statusline);
  1623. fflush(stdout);
  1624. } else
  1625. applog(LOG_INFO, "%s", statusline);
  1626. local_mhashes_done = 0;
  1627. out_unlock:
  1628. pthread_mutex_unlock(&hash_lock);
  1629. }
  1630. /* This is overkill, but at least we'll know accurately how much work is
  1631. * queued to prevent ever being left without work */
  1632. static void inc_queued(void)
  1633. {
  1634. pthread_mutex_lock(&qd_lock);
  1635. total_queued++;
  1636. pthread_mutex_unlock(&qd_lock);
  1637. }
  1638. static void dec_queued(void)
  1639. {
  1640. pthread_mutex_lock(&qd_lock);
  1641. if (total_queued > 0)
  1642. total_queued--;
  1643. pthread_mutex_unlock(&qd_lock);
  1644. dec_staged(1);
  1645. }
  1646. static int requests_queued(void)
  1647. {
  1648. int ret;
  1649. pthread_mutex_lock(&qd_lock);
  1650. ret = total_queued;
  1651. pthread_mutex_unlock(&qd_lock);
  1652. return ret;
  1653. }
  1654. static bool pool_active(struct pool *pool)
  1655. {
  1656. bool ret = false;
  1657. json_t *val;
  1658. CURL *curl;
  1659. curl = curl_easy_init();
  1660. if (unlikely(!curl)) {
  1661. applog(LOG_ERR, "CURL initialisation failed");
  1662. return false;
  1663. }
  1664. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  1665. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  1666. true, false, pool);
  1667. if (val) {
  1668. struct work *work = malloc(sizeof(struct work));
  1669. bool rc;
  1670. if (!work) {
  1671. applog(LOG_ERR, "Unable to malloc work in pool_active");
  1672. goto out;
  1673. }
  1674. rc = work_decode(json_object_get(val, "result"), work);
  1675. if (rc) {
  1676. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  1677. pool->pool_no, pool->rpc_url);
  1678. work->pool = pool;
  1679. tq_push(thr_info[stage_thr_id].q, work);
  1680. total_getworks++;
  1681. pool->getwork_requested++;
  1682. inc_queued();
  1683. ret = true;
  1684. gettimeofday(&pool->tv_idle, NULL);
  1685. } else {
  1686. applog(LOG_DEBUG, "Successfully retreived but FAILED to decipher work from pool %u %s",
  1687. pool->pool_no, pool->rpc_url);
  1688. free(work);
  1689. }
  1690. json_decref(val);
  1691. } else {
  1692. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  1693. pool->pool_no, pool->rpc_url);
  1694. applog(LOG_WARNING, "Pool down, URL or credentials invalid");
  1695. }
  1696. out:
  1697. curl_easy_cleanup(curl);
  1698. return ret;
  1699. }
  1700. static void pool_died(struct pool *pool)
  1701. {
  1702. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  1703. gettimeofday(&pool->tv_idle, NULL);
  1704. switch_pools(NULL);
  1705. }
  1706. static void pool_resus(struct pool *pool)
  1707. {
  1708. applog(LOG_WARNING, "Pool %d %s recovered", pool->pool_no, pool->rpc_url);
  1709. if (pool->prio < current_pool()->prio && pool_strategy == POOL_FAILOVER)
  1710. switch_pools(NULL);
  1711. }
  1712. static bool queue_request(void)
  1713. {
  1714. int maxq = opt_queue + mining_threads;
  1715. struct workio_cmd *wc;
  1716. /* If we've been generating lots of local work we may already have
  1717. * enough in the queue */
  1718. if (requests_queued() >= maxq || real_staged() >= maxq)
  1719. return true;
  1720. /* fill out work request message */
  1721. wc = calloc(1, sizeof(*wc));
  1722. if (unlikely(!wc)) {
  1723. applog(LOG_ERR, "Failed to tq_pop in queue_request");
  1724. return false;
  1725. }
  1726. wc->cmd = WC_GET_WORK;
  1727. /* The get work does not belong to any thread */
  1728. wc->thr = NULL;
  1729. /* send work request to workio thread */
  1730. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  1731. applog(LOG_ERR, "Failed to tq_push in queue_request");
  1732. workio_cmd_free(wc);
  1733. return false;
  1734. }
  1735. inc_queued();
  1736. return true;
  1737. }
  1738. static void discard_staged(void)
  1739. {
  1740. struct timespec abstime = {};
  1741. struct timeval now;
  1742. struct work *work_heap;
  1743. struct pool *pool;
  1744. /* Just in case we fell in a hole and missed a queue filling */
  1745. if (unlikely(!requests_staged()))
  1746. return;
  1747. gettimeofday(&now, NULL);
  1748. abstime.tv_sec = now.tv_sec + 60;
  1749. work_heap = tq_pop(getq, &abstime);
  1750. if (unlikely(!work_heap))
  1751. return;
  1752. pool = work_heap->pool;
  1753. free(work_heap);
  1754. dec_queued();
  1755. pool->discarded_work++;
  1756. total_discarded++;
  1757. }
  1758. static void flush_requests(void)
  1759. {
  1760. struct pool *pool = current_pool();
  1761. int i, stale;
  1762. /* We should have one fresh work item staged from the block change. */
  1763. stale = requests_staged() - 1;
  1764. /* Temporarily increase the staged count so that get_work thinks there
  1765. * is work available instead of making threads reuse existing work */
  1766. inc_staged(pool, mining_threads, true);
  1767. for (i = 0; i < stale; i++) {
  1768. /* Queue a whole batch of new requests */
  1769. if (unlikely(!queue_request())) {
  1770. applog(LOG_ERR, "Failed to queue requests in flush_requests");
  1771. kill_work();
  1772. break;
  1773. }
  1774. /* Pop off the old requests. Cancelling the requests would be better
  1775. * but is tricky */
  1776. discard_staged();
  1777. }
  1778. }
  1779. static inline bool can_roll(struct work *work)
  1780. {
  1781. return (!stale_work(work) && work->pool->has_rolltime && work->rolls < 11);
  1782. }
  1783. static bool get_work(struct work *work, bool queued, struct thr_info *thr,
  1784. const int thr_id)
  1785. {
  1786. struct timespec abstime = {};
  1787. struct timeval now;
  1788. struct work *work_heap;
  1789. struct pool *pool;
  1790. bool ret = false;
  1791. int failures = 0;
  1792. /* Tell the watchdog thread this thread is waiting on getwork and
  1793. * should not be restarted */
  1794. thread_reportout(thr);
  1795. retry:
  1796. pool = current_pool();
  1797. if (unlikely(!queued && !queue_request())) {
  1798. applog(LOG_WARNING, "Failed to queue_request in get_work");
  1799. goto out;
  1800. }
  1801. if (!requests_staged() && can_roll(work)) {
  1802. uint32_t *work_ntime;
  1803. uint32_t ntime;
  1804. /* Only print this message once each time we shift to localgen */
  1805. if (!pool_tset(pool, &pool->idle)) {
  1806. applog(LOG_WARNING, "Pool %d not providing work fast enough, generating work locally",
  1807. pool->pool_no);
  1808. pool->localgen_occasions++;
  1809. total_lo++;
  1810. gettimeofday(&pool->tv_idle, NULL);
  1811. } else {
  1812. struct timeval tv_now, diff;
  1813. gettimeofday(&tv_now, NULL);
  1814. timeval_subtract(&diff, &tv_now, &pool->tv_idle);
  1815. /* Attempt to switch pools if this one has been unresponsive for >half
  1816. * a block's duration */
  1817. if (diff.tv_sec > 300) {
  1818. pool_died(pool);
  1819. goto retry;
  1820. }
  1821. }
  1822. work_ntime = (uint32_t *)(work->data + 68);
  1823. ntime = be32toh(*work_ntime);
  1824. ntime++;
  1825. *work_ntime = htobe32(ntime);
  1826. ret = true;
  1827. local_work++;
  1828. work->rolls++;
  1829. goto out;
  1830. }
  1831. gettimeofday(&now, NULL);
  1832. abstime.tv_sec = now.tv_sec + 60;
  1833. /* wait for 1st response, or get cached response */
  1834. work_heap = tq_pop(getq, &abstime);
  1835. if (unlikely(!work_heap)) {
  1836. /* Attempt to switch pools if this one has mandatory work that
  1837. * has timed out or does not support rolltime */
  1838. pool->localgen_occasions++;
  1839. total_lo++;
  1840. pool_died(pool);
  1841. goto retry;
  1842. }
  1843. pool = work_heap->pool;
  1844. /* If we make it here we have succeeded in getting fresh work */
  1845. if (pool_tclear(pool, &pool->idle))
  1846. pool_resus(pool);
  1847. dec_queued();
  1848. memcpy(work, work_heap, sizeof(*work));
  1849. ret = true;
  1850. free(work_heap);
  1851. out:
  1852. if (unlikely(ret == false)) {
  1853. if ((opt_retries >= 0) && (++failures > opt_retries)) {
  1854. applog(LOG_ERR, "Failed %d times to get_work");
  1855. return ret;
  1856. }
  1857. applog(LOG_DEBUG, "Retrying after %d seconds", opt_fail_pause);
  1858. sleep(opt_fail_pause);
  1859. goto retry;
  1860. }
  1861. work->thr_id = thr_id;
  1862. thread_reportin(thr);
  1863. return ret;
  1864. }
  1865. static bool submit_work_sync(struct thr_info *thr, const struct work *work_in)
  1866. {
  1867. struct workio_cmd *wc;
  1868. /* fill out work request message */
  1869. wc = calloc(1, sizeof(*wc));
  1870. if (unlikely(!wc)) {
  1871. applog(LOG_ERR, "Failed to calloc wc in submit_work_sync");
  1872. return false;
  1873. }
  1874. wc->u.work = malloc(sizeof(*work_in));
  1875. if (unlikely(!wc->u.work)) {
  1876. applog(LOG_ERR, "Failed to calloc work in submit_work_sync");
  1877. goto err_out;
  1878. }
  1879. wc->cmd = WC_SUBMIT_WORK;
  1880. wc->thr = thr;
  1881. memcpy(wc->u.work, work_in, sizeof(*work_in));
  1882. /* send solution to workio thread */
  1883. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  1884. applog(LOG_ERR, "Failed to tq_push work in submit_work_sync");
  1885. goto err_out;
  1886. }
  1887. return true;
  1888. err_out:
  1889. workio_cmd_free(wc);
  1890. return false;
  1891. }
  1892. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  1893. {
  1894. work->data[64+12+0] = (nonce>>0) & 0xff;
  1895. work->data[64+12+1] = (nonce>>8) & 0xff;
  1896. work->data[64+12+2] = (nonce>>16) & 0xff;
  1897. work->data[64+12+3] = (nonce>>24) & 0xff;
  1898. /* Do one last check before attempting to submit the work */
  1899. if (!fulltest(work->data + 64, work->target))
  1900. return true;
  1901. return submit_work_sync(thr, work);
  1902. }
  1903. static void *miner_thread(void *userdata)
  1904. {
  1905. struct thr_info *mythr = userdata;
  1906. const int thr_id = mythr->id;
  1907. uint32_t max_nonce = 0xffffff;
  1908. unsigned long hashes_done = max_nonce;
  1909. bool needs_work = true;
  1910. /* Try to cycle approximately 5 times before each log update */
  1911. const unsigned long cycle = opt_log_interval / 5 ? : 1;
  1912. /* Request the next work item at 2/3 of the scantime */
  1913. unsigned const int request_interval = opt_scantime * 2 / 3 ? : 1;
  1914. unsigned const long request_nonce = MAXTHREADS / 3 * 2;
  1915. bool requested = true;
  1916. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  1917. /* Set worker threads to nice 19 and then preferentially to SCHED_IDLE
  1918. * and if that fails, then SCHED_BATCH. No need for this to be an
  1919. * error if it fails */
  1920. setpriority(PRIO_PROCESS, 0, 19);
  1921. drop_policy();
  1922. /* Cpu affinity only makes sense if the number of threads is a multiple
  1923. * of the number of CPUs */
  1924. if (!(opt_n_threads % num_processors))
  1925. affine_to_cpu(thr_id - gpu_threads, dev_from_id(thr_id));
  1926. while (1) {
  1927. struct work work __attribute__((aligned(128)));
  1928. struct timeval tv_workstart, tv_start, tv_end, diff;
  1929. uint64_t max64;
  1930. bool rc;
  1931. if (needs_work) {
  1932. gettimeofday(&tv_workstart, NULL);
  1933. /* obtain new work from internal workio thread */
  1934. if (unlikely(!get_work(&work, requested, mythr, thr_id))) {
  1935. applog(LOG_ERR, "work retrieval failed, exiting "
  1936. "mining thread %d", thr_id);
  1937. goto out;
  1938. }
  1939. mythr->cgpu->getworks++;
  1940. needs_work = requested = false;
  1941. work.blk.nonce = 0;
  1942. max_nonce = hashes_done;
  1943. }
  1944. hashes_done = 0;
  1945. gettimeofday(&tv_start, NULL);
  1946. /* scan nonces for a proof-of-work hash */
  1947. switch (opt_algo) {
  1948. case ALGO_C:
  1949. rc = scanhash_c(thr_id, work.midstate, work.data + 64,
  1950. work.hash1, work.hash, work.target,
  1951. max_nonce, &hashes_done,
  1952. work.blk.nonce);
  1953. break;
  1954. #ifdef WANT_X8664_SSE2
  1955. case ALGO_SSE2_64: {
  1956. unsigned int rc5 =
  1957. scanhash_sse2_64(thr_id, work.midstate, work.data + 64,
  1958. work.hash1, work.hash,
  1959. work.target,
  1960. max_nonce, &hashes_done,
  1961. work.blk.nonce);
  1962. rc = (rc5 == -1) ? false : true;
  1963. }
  1964. break;
  1965. #endif
  1966. #ifdef WANT_X8664_SSE4
  1967. case ALGO_SSE4_64: {
  1968. unsigned int rc5 =
  1969. scanhash_sse4_64(thr_id, work.midstate, work.data + 64,
  1970. work.hash1, work.hash,
  1971. work.target,
  1972. max_nonce, &hashes_done,
  1973. work.blk.nonce);
  1974. rc = (rc5 == -1) ? false : true;
  1975. }
  1976. break;
  1977. #endif
  1978. #ifdef WANT_SSE2_4WAY
  1979. case ALGO_4WAY: {
  1980. unsigned int rc4 =
  1981. ScanHash_4WaySSE2(thr_id, work.midstate, work.data + 64,
  1982. work.hash1, work.hash,
  1983. work.target,
  1984. max_nonce, &hashes_done,
  1985. work.blk.nonce);
  1986. rc = (rc4 == -1) ? false : true;
  1987. }
  1988. break;
  1989. #endif
  1990. #ifdef WANT_VIA_PADLOCK
  1991. case ALGO_VIA:
  1992. rc = scanhash_via(thr_id, work.data, work.target,
  1993. max_nonce, &hashes_done,
  1994. work.blk.nonce);
  1995. break;
  1996. #endif
  1997. case ALGO_CRYPTOPP:
  1998. rc = scanhash_cryptopp(thr_id, work.midstate, work.data + 64,
  1999. work.hash1, work.hash, work.target,
  2000. max_nonce, &hashes_done,
  2001. work.blk.nonce);
  2002. break;
  2003. #ifdef WANT_CRYPTOPP_ASM32
  2004. case ALGO_CRYPTOPP_ASM32:
  2005. rc = scanhash_asm32(thr_id, work.midstate, work.data + 64,
  2006. work.hash1, work.hash, work.target,
  2007. max_nonce, &hashes_done,
  2008. work.blk.nonce);
  2009. break;
  2010. #endif
  2011. default:
  2012. /* should never happen */
  2013. goto out;
  2014. }
  2015. /* record scanhash elapsed time */
  2016. gettimeofday(&tv_end, NULL);
  2017. timeval_subtract(&diff, &tv_end, &tv_start);
  2018. hashes_done -= work.blk.nonce;
  2019. hashmeter(thr_id, &diff, hashes_done);
  2020. work.blk.nonce += hashes_done;
  2021. /* adjust max_nonce to meet target cycle time */
  2022. if (diff.tv_usec > 500000)
  2023. diff.tv_sec++;
  2024. if (diff.tv_sec && diff.tv_sec != cycle) {
  2025. max64 = work.blk.nonce +
  2026. ((uint64_t)hashes_done * cycle) / diff.tv_sec;
  2027. } else
  2028. max64 = work.blk.nonce + hashes_done;
  2029. if (max64 > 0xfffffffaULL)
  2030. max64 = 0xfffffffaULL;
  2031. max_nonce = max64;
  2032. /* if nonce found, submit work */
  2033. if (unlikely(rc)) {
  2034. if (opt_debug)
  2035. applog(LOG_DEBUG, "CPU %d found something?", dev_from_id(thr_id));
  2036. if (unlikely(!submit_work_sync(mythr, &work))) {
  2037. applog(LOG_ERR, "Failed to submit_work_sync in miner_thread %d", thr_id);
  2038. break;
  2039. }
  2040. work.blk.nonce += 4;
  2041. }
  2042. timeval_subtract(&diff, &tv_end, &tv_workstart);
  2043. if (!requested && (diff.tv_sec > request_interval || work.blk.nonce > request_nonce)) {
  2044. if (unlikely(!queue_request())) {
  2045. applog(LOG_ERR, "Failed to queue_request in miner_thread %d", thr_id);
  2046. goto out;
  2047. }
  2048. requested = true;
  2049. }
  2050. if (diff.tv_sec > opt_scantime || work_restart[thr_id].restart ||
  2051. work.blk.nonce >= MAXTHREADS - hashes_done ||
  2052. stale_work(&work))
  2053. needs_work = true;
  2054. }
  2055. out:
  2056. tq_freeze(mythr->q);
  2057. return NULL;
  2058. }
  2059. enum {
  2060. STAT_SLEEP_INTERVAL = 1,
  2061. STAT_CTR_INTERVAL = 10000000,
  2062. FAILURE_INTERVAL = 30,
  2063. };
  2064. #ifdef HAVE_OPENCL
  2065. static _clState *clStates[16];
  2066. static inline cl_int queue_kernel_parameters(_clState *clState, dev_blk_ctx *blk)
  2067. {
  2068. cl_kernel *kernel = &clState->kernel;
  2069. cl_int status = 0;
  2070. int num = 0;
  2071. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_a);
  2072. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_b);
  2073. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_c);
  2074. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_d);
  2075. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_e);
  2076. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_f);
  2077. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_g);
  2078. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_h);
  2079. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_b);
  2080. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_c);
  2081. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_d);
  2082. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_f);
  2083. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_g);
  2084. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_h);
  2085. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->nonce);
  2086. if (clState->hasBitAlign == true) {
  2087. /* Parameters for phatk kernel */
  2088. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W2);
  2089. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W16);
  2090. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W17);
  2091. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreVal4);
  2092. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->T1);
  2093. } else {
  2094. /* Parameters for poclbm kernel */
  2095. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW0);
  2096. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW1);
  2097. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW2);
  2098. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW3);
  2099. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW15);
  2100. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW01r);
  2101. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e);
  2102. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e2);
  2103. }
  2104. status |= clSetKernelArg(*kernel, num++, sizeof(clState->outputBuffer),
  2105. (void *)&clState->outputBuffer);
  2106. return status;
  2107. }
  2108. static void set_threads_hashes(unsigned int vectors, unsigned int *threads,
  2109. unsigned int *hashes, size_t *globalThreads)
  2110. {
  2111. *globalThreads = *threads = 1 << (15 + scan_intensity);
  2112. *hashes = *threads * vectors;
  2113. }
  2114. static void *gpuminer_thread(void *userdata)
  2115. {
  2116. const unsigned long cycle = opt_log_interval / 5 ? : 1;
  2117. struct timeval tv_start, tv_end, diff, tv_workstart;
  2118. struct thr_info *mythr = userdata;
  2119. const int thr_id = mythr->id;
  2120. uint32_t *res, *blank_res;
  2121. double gpu_ms_average = 7;
  2122. size_t globalThreads[1];
  2123. size_t localThreads[1];
  2124. cl_int status;
  2125. _clState *clState = clStates[thr_id];
  2126. const cl_kernel *kernel = &clState->kernel;
  2127. struct work *work = malloc(sizeof(struct work));
  2128. unsigned int threads = 1 << (15 + scan_intensity);
  2129. unsigned const int vectors = clState->preferred_vwidth;
  2130. unsigned int hashes = threads * vectors;
  2131. unsigned int hashes_done = 0;
  2132. /* Request the next work item at 2/3 of the scantime */
  2133. unsigned const int request_interval = opt_scantime * 2 / 3 ? : 1;
  2134. unsigned const long request_nonce = MAXTHREADS / 3 * 2;
  2135. bool requested = true;
  2136. if (opt_dynamic) {
  2137. /* Minimise impact on desktop if we want dynamic mode */
  2138. setpriority(PRIO_PROCESS, 0, 19);
  2139. drop_policy();
  2140. }
  2141. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2142. res = calloc(BUFFERSIZE, 1);
  2143. blank_res = calloc(BUFFERSIZE, 1);
  2144. if (!res || !blank_res) {
  2145. applog(LOG_ERR, "Failed to calloc in gpuminer_thread");
  2146. goto out;
  2147. }
  2148. gettimeofday(&tv_start, NULL);
  2149. globalThreads[0] = threads;
  2150. localThreads[0] = clState->work_size;
  2151. diff.tv_sec = 0;
  2152. gettimeofday(&tv_end, NULL);
  2153. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_TRUE, 0,
  2154. BUFFERSIZE, blank_res, 0, NULL, NULL);
  2155. if (unlikely(status != CL_SUCCESS))
  2156. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  2157. gettimeofday(&tv_workstart, NULL);
  2158. /* obtain new work from internal workio thread */
  2159. if (unlikely(!get_work(work, requested, mythr, thr_id))) {
  2160. applog(LOG_ERR, "work retrieval failed, exiting "
  2161. "gpu mining thread %d", thr_id);
  2162. goto out;
  2163. }
  2164. mythr->cgpu->getworks++;
  2165. requested = false;
  2166. precalc_hash(&work->blk, (uint32_t *)(work->midstate), (uint32_t *)(work->data + 64));
  2167. work->blk.nonce = 0;
  2168. while (1) {
  2169. struct timeval tv_gpustart, tv_gpuend;
  2170. suseconds_t gpu_us;
  2171. gettimeofday(&tv_gpustart, NULL);
  2172. timeval_subtract(&diff, &tv_gpustart, &tv_gpuend);
  2173. /* This finish flushes the readbuffer set with CL_FALSE later */
  2174. clFinish(clState->commandQueue);
  2175. gettimeofday(&tv_gpuend, NULL);
  2176. timeval_subtract(&diff, &tv_gpuend, &tv_gpustart);
  2177. gpu_us = diff.tv_sec * 1000000 + diff.tv_usec;
  2178. gpu_ms_average = ((gpu_us / 1000) + gpu_ms_average * 0.9) / 1.9;
  2179. if (opt_dynamic) {
  2180. /* Try to not let the GPU be out for longer than 6ms, but
  2181. * increase intensity when the system is idle, unless
  2182. * dynamic is disabled. */
  2183. if (gpu_ms_average > 7) {
  2184. if (scan_intensity > 0)
  2185. scan_intensity--;
  2186. set_threads_hashes(vectors, &threads, &hashes, globalThreads);
  2187. } else if (gpu_ms_average < 3) {
  2188. if (scan_intensity < 14)
  2189. scan_intensity++;
  2190. set_threads_hashes(vectors, &threads, &hashes, globalThreads);
  2191. }
  2192. }
  2193. if (diff.tv_sec > opt_scantime ||
  2194. work->blk.nonce >= MAXTHREADS - hashes ||
  2195. work_restart[thr_id].restart ||
  2196. stale_work(work)) {
  2197. /* Ignore any reads since we're getting new work and queue a clean buffer */
  2198. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  2199. BUFFERSIZE, blank_res, 0, NULL, NULL);
  2200. if (unlikely(status != CL_SUCCESS))
  2201. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  2202. memset(res, 0, BUFFERSIZE);
  2203. gettimeofday(&tv_workstart, NULL);
  2204. /* obtain new work from internal workio thread */
  2205. if (unlikely(!get_work(work, requested, mythr, thr_id))) {
  2206. applog(LOG_ERR, "work retrieval failed, exiting "
  2207. "gpu mining thread %d", thr_id);
  2208. goto out;
  2209. }
  2210. mythr->cgpu->getworks++;
  2211. requested = false;
  2212. precalc_hash(&work->blk, (uint32_t *)(work->midstate), (uint32_t *)(work->data + 64));
  2213. work->blk.nonce = 0;
  2214. work_restart[thr_id].restart = 0;
  2215. if (opt_debug)
  2216. applog(LOG_DEBUG, "getwork thread %d", thr_id);
  2217. /* Flushes the writebuffer set with CL_FALSE above */
  2218. clFinish(clState->commandQueue);
  2219. }
  2220. status = queue_kernel_parameters(clState, &work->blk);
  2221. if (unlikely(status != CL_SUCCESS))
  2222. { applog(LOG_ERR, "Error: clSetKernelArg of all params failed."); goto out; }
  2223. /* MAXBUFFERS entry is used as a flag to say nonces exist */
  2224. if (res[MAXBUFFERS]) {
  2225. /* Clear the buffer again */
  2226. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  2227. BUFFERSIZE, blank_res, 0, NULL, NULL);
  2228. if (unlikely(status != CL_SUCCESS))
  2229. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  2230. if (opt_debug)
  2231. applog(LOG_DEBUG, "GPU %d found something?", dev_from_id(thr_id));
  2232. postcalc_hash_async(mythr, work, res);
  2233. memset(res, 0, BUFFERSIZE);
  2234. clFinish(clState->commandQueue);
  2235. }
  2236. status = clEnqueueNDRangeKernel(clState->commandQueue, *kernel, 1, NULL,
  2237. globalThreads, localThreads, 0, NULL, NULL);
  2238. if (unlikely(status != CL_SUCCESS))
  2239. { applog(LOG_ERR, "Error: Enqueueing kernel onto command queue. (clEnqueueNDRangeKernel)"); goto out; }
  2240. status = clEnqueueReadBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  2241. BUFFERSIZE, res, 0, NULL, NULL);
  2242. if (unlikely(status != CL_SUCCESS))
  2243. { applog(LOG_ERR, "Error: clEnqueueReadBuffer failed. (clEnqueueReadBuffer)"); goto out;}
  2244. gettimeofday(&tv_end, NULL);
  2245. timeval_subtract(&diff, &tv_end, &tv_start);
  2246. hashes_done += hashes;
  2247. work->blk.nonce += hashes;
  2248. if (diff.tv_usec > 500000)
  2249. diff.tv_sec++;
  2250. if (diff.tv_sec >= cycle) {
  2251. hashmeter(thr_id, &diff, hashes_done);
  2252. gettimeofday(&tv_start, NULL);
  2253. hashes_done = 0;
  2254. }
  2255. timeval_subtract(&diff, &tv_end, &tv_workstart);
  2256. if (!requested && (diff.tv_sec > request_interval || work->blk.nonce > request_nonce)) {
  2257. if (unlikely(!queue_request())) {
  2258. applog(LOG_ERR, "Failed to queue_request in gpuminer_thread %d", thr_id);
  2259. goto out;
  2260. }
  2261. requested = true;
  2262. }
  2263. }
  2264. out:
  2265. tq_freeze(mythr->q);
  2266. return NULL;
  2267. }
  2268. #endif /* HAVE_OPENCL */
  2269. static void restart_threads(void)
  2270. {
  2271. int i;
  2272. if (block_changed == BLOCK_DETECT)
  2273. block_changed = BLOCK_NONE;
  2274. /* Discard old queued requests and get new ones */
  2275. flush_requests();
  2276. for (i = 0; i < mining_threads; i++)
  2277. work_restart[i].restart = 1;
  2278. }
  2279. /* Stage another work item from the work returned in a longpoll */
  2280. static void convert_to_work(json_t *val)
  2281. {
  2282. struct work *work;
  2283. bool rc;
  2284. work = calloc(sizeof(*work), 1);
  2285. if (unlikely(!work)) {
  2286. applog(LOG_ERR, "OOM in convert_to_work");
  2287. return;
  2288. }
  2289. rc= work_decode(json_object_get(val, "result"), work);
  2290. if (unlikely(!rc)) {
  2291. applog(LOG_ERR, "Could not convert longpoll data to work");
  2292. return;
  2293. }
  2294. work->pool = current_pool();
  2295. if (unlikely(!tq_push(thr_info[stage_thr_id].q, work)))
  2296. applog(LOG_ERR, "Could not tq_push work in convert_to_work");
  2297. else if (opt_debug)
  2298. applog(LOG_DEBUG, "Converted longpoll data to work");
  2299. }
  2300. static void *longpoll_thread(void *userdata)
  2301. {
  2302. struct thr_info *mythr = userdata;
  2303. CURL *curl = NULL;
  2304. char *copy_start, *hdr_path, *lp_url = NULL;
  2305. bool need_slash = false;
  2306. int failures = 0;
  2307. struct pool *pool = current_pool();
  2308. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2309. curl = curl_easy_init();
  2310. if (unlikely(!curl)) {
  2311. applog(LOG_ERR, "CURL initialisation failed");
  2312. goto out;
  2313. }
  2314. hdr_path = tq_pop(mythr->q, NULL);
  2315. if (!hdr_path) {
  2316. applog(LOG_WARNING, "No long-poll found on this server");
  2317. goto out;
  2318. }
  2319. /* full URL */
  2320. if (strstr(hdr_path, "://")) {
  2321. lp_url = hdr_path;
  2322. hdr_path = NULL;
  2323. }
  2324. /* absolute path, on current server */
  2325. else {
  2326. copy_start = (*hdr_path == '/') ? (hdr_path + 1) : hdr_path;
  2327. if (pool->rpc_url[strlen(pool->rpc_url) - 1] != '/')
  2328. need_slash = true;
  2329. lp_url = malloc(strlen(pool->rpc_url) + strlen(copy_start) + 2);
  2330. if (!lp_url)
  2331. goto out;
  2332. sprintf(lp_url, "%s%s%s", pool->rpc_url, need_slash ? "/" : "", copy_start);
  2333. }
  2334. free(hdr_path);
  2335. applog(LOG_WARNING, "Long-polling activated for %s", lp_url);
  2336. while (1) {
  2337. struct timeval start, end;
  2338. json_t *val;
  2339. gettimeofday(&start, NULL);
  2340. val = json_rpc_call(curl, lp_url, pool->rpc_userpass, rpc_req,
  2341. false, true, pool);
  2342. if (likely(val)) {
  2343. /* Keep track of who ordered a restart_threads to make
  2344. * sure it's only done once per new block */
  2345. if (block_changed != BLOCK_DETECT) {
  2346. block_changed = BLOCK_LP;
  2347. new_blocks++;
  2348. applog(LOG_WARNING, "LONGPOLL detected new block on network, waiting on fresh work");
  2349. restart_threads();
  2350. } else {
  2351. applog(LOG_WARNING, "LONGPOLL received after new block already detected");
  2352. block_changed = BLOCK_NONE;
  2353. }
  2354. convert_to_work(val);
  2355. failures = 0;
  2356. json_decref(val);
  2357. } else {
  2358. /* Some pools regularly drop the longpoll request so
  2359. * only see this as longpoll failure if it happens
  2360. * immediately and just restart it the rest of the
  2361. * time. */
  2362. gettimeofday(&end, NULL);
  2363. if (end.tv_sec - start.tv_sec > 30)
  2364. continue;
  2365. if (failures++ < 10) {
  2366. sleep(30);
  2367. applog(LOG_WARNING,
  2368. "longpoll failed, sleeping for 30s");
  2369. } else {
  2370. applog(LOG_ERR,
  2371. "longpoll failed, ending thread");
  2372. goto out;
  2373. }
  2374. }
  2375. }
  2376. out:
  2377. free(lp_url);
  2378. tq_freeze(mythr->q);
  2379. if (curl)
  2380. curl_easy_cleanup(curl);
  2381. return NULL;
  2382. }
  2383. static void stop_longpoll(void)
  2384. {
  2385. struct thr_info *thr = &thr_info[longpoll_thr_id];
  2386. tq_freeze(thr->q);
  2387. pthread_cancel(*thr->pth);
  2388. have_longpoll = false;
  2389. }
  2390. static void quit(int status, const char *format, ...);
  2391. static void start_longpoll(void)
  2392. {
  2393. struct thr_info *thr = &thr_info[longpoll_thr_id];
  2394. tq_thaw(thr->q);
  2395. if (unlikely(thr_info_create(thr, NULL, longpoll_thread, thr)))
  2396. quit(1, "longpoll thread create failed");
  2397. pthread_detach(*thr->pth);
  2398. }
  2399. static void restart_longpoll(void)
  2400. {
  2401. stop_longpoll();
  2402. if (want_longpoll)
  2403. start_longpoll();
  2404. }
  2405. static void reinit_cputhread(int thr_id)
  2406. {
  2407. struct thr_info *thr = &thr_info[thr_id];
  2408. tq_freeze(thr->q);
  2409. if (!(pthread_cancel(*thr->pth)) && pthread_join(*thr->pth, NULL)) {
  2410. applog(LOG_ERR, "Failed to pthread_join in reinit_cputhread");
  2411. goto failed_out;
  2412. }
  2413. applog(LOG_INFO, "Reinit CPU thread %d", thr_id);
  2414. tq_thaw(thr->q);
  2415. thread_reportin(thr);
  2416. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr))) {
  2417. applog(LOG_ERR, "thread %d create failed", thr_id);
  2418. goto failed_out;
  2419. }
  2420. return;
  2421. failed_out:
  2422. kill_work();
  2423. }
  2424. #ifdef HAVE_OPENCL
  2425. static void reinit_gputhread(int thr_id)
  2426. {
  2427. int gpu = dev_from_id(thr_id);
  2428. struct thr_info *thr = &thr_info[thr_id];
  2429. char name[256];
  2430. tq_freeze(thr->q);
  2431. if (!(pthread_cancel(*thr->pth)) && pthread_join(*thr->pth, NULL)) {
  2432. applog(LOG_ERR, "Failed to pthread_join in reinit_gputhread");
  2433. goto failed_out;
  2434. }
  2435. free(clStates[thr_id]);
  2436. applog(LOG_INFO, "Reinit GPU thread %d", thr_id);
  2437. tq_thaw(thr->q);
  2438. clStates[thr_id] = initCl(gpu, name, sizeof(name));
  2439. if (!clStates[thr_id]) {
  2440. applog(LOG_ERR, "Failed to reinit GPU thread %d", thr_id);
  2441. goto failed_out;
  2442. }
  2443. applog(LOG_INFO, "initCl() finished. Found %s", name);
  2444. thread_reportin(thr);
  2445. if (unlikely(thr_info_create(thr, NULL, gpuminer_thread, thr))) {
  2446. applog(LOG_ERR, "thread %d create failed", thr_id);
  2447. goto failed_out;
  2448. }
  2449. return;
  2450. failed_out:
  2451. kill_work();
  2452. }
  2453. static void reinit_thread(int thr_id)
  2454. {
  2455. if (thr_id < gpu_threads)
  2456. reinit_gputhread(thr_id);
  2457. else
  2458. reinit_cputhread(thr_id);
  2459. }
  2460. #else /* HAVE_OPENCL */
  2461. static void reinit_thread(int thr_id)
  2462. {
  2463. reinit_cputhread(thr_id);
  2464. }
  2465. #endif
  2466. /* Determine which are the first threads belonging to a device and if they're
  2467. * active */
  2468. static bool active_device(int thr_id)
  2469. {
  2470. if (thr_id < gpu_threads) {
  2471. if (thr_id >= total_devices)
  2472. return false;
  2473. if (!gpu_devices[dev_from_id(thr_id)])
  2474. return false;
  2475. } else if (thr_id > gpu_threads + num_processors)
  2476. return false;
  2477. return true;
  2478. }
  2479. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  2480. * the screen at regular intervals, and restarts threads if they appear to have
  2481. * died. */
  2482. static void *watchdog_thread(void *userdata)
  2483. {
  2484. const unsigned int interval = opt_log_interval / 2 ? : 1;
  2485. static struct timeval rotate_tv;
  2486. struct timeval zero_tv;
  2487. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2488. memset(&zero_tv, 0, sizeof(struct timeval));
  2489. gettimeofday(&rotate_tv, NULL);
  2490. while (1) {
  2491. int x, y, logx, logy, i;
  2492. struct timeval now;
  2493. sleep(interval);
  2494. if (requests_queued() < opt_queue)
  2495. queue_request();
  2496. hashmeter(-1, &zero_tv, 0);
  2497. if (curses_active) {
  2498. pthread_mutex_lock(&curses_lock);
  2499. getmaxyx(mainwin, y, x);
  2500. getmaxyx(logwin, logy, logx);
  2501. y -= logcursor;
  2502. /* Detect screen size change */
  2503. if (x != logx || y != logy)
  2504. wresize(logwin, y, x);
  2505. for (i = 0; i < mining_threads; i++) {
  2506. if (active_device(i))
  2507. curses_print_status(i);
  2508. }
  2509. redrawwin(logwin);
  2510. redrawwin(statuswin);
  2511. pthread_mutex_unlock(&curses_lock);
  2512. }
  2513. if (unlikely(work_restart[watchdog_thr_id].restart)) {
  2514. restart_threads();
  2515. work_restart[watchdog_thr_id].restart = 0;
  2516. }
  2517. gettimeofday(&now, NULL);
  2518. for (i = 0; i < total_pools; i++) {
  2519. struct pool *pool = pools[i];
  2520. if (!pool->enabled)
  2521. continue;
  2522. /* Test pool is idle once every minute */
  2523. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 60) {
  2524. gettimeofday(&pool->tv_idle, NULL);
  2525. if (pool_active(pool) && pool_tclear(pool, &pool->idle))
  2526. pool_resus(pool);
  2527. }
  2528. }
  2529. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  2530. gettimeofday(&rotate_tv, NULL);
  2531. switch_pools(NULL);
  2532. }
  2533. //for (i = 0; i < mining_threads; i++) {
  2534. for (i = 0; i < gpu_threads; i++) {
  2535. struct thr_info *thr = &thr_info[i];
  2536. /* Thread is waiting on getwork, don't test it */
  2537. if (thr->getwork)
  2538. continue;
  2539. if (now.tv_sec - thr->last.tv_sec > 60) {
  2540. applog(LOG_ERR, "Attempting to restart thread %d, idle for more than 60 seconds", i);
  2541. /* Create one mandatory work item */
  2542. inc_staged(current_pool(), 1, true);
  2543. if (unlikely(!queue_request())) {
  2544. applog(LOG_ERR, "Failed to queue_request in watchdog_thread");
  2545. kill_work();
  2546. break;
  2547. }
  2548. reinit_thread(i);
  2549. applog(LOG_WARNING, "Thread %d restarted", i);
  2550. }
  2551. }
  2552. }
  2553. return NULL;
  2554. }
  2555. static void print_summary(void)
  2556. {
  2557. struct timeval diff;
  2558. int hours, mins, secs, i;
  2559. double utility, efficiency = 0.0;
  2560. timeval_subtract(&diff, &total_tv_end, &total_tv_start);
  2561. hours = diff.tv_sec / 3600;
  2562. mins = (diff.tv_sec % 3600) / 60;
  2563. secs = diff.tv_sec % 60;
  2564. utility = total_accepted / ( total_secs ? total_secs : 1 ) * 60;
  2565. efficiency = total_getworks ? total_accepted * 100.0 / total_getworks : 0.0;
  2566. printf("\nSummary of runtime statistics:\n\n");
  2567. printf("Started at %s\n", datestamp);
  2568. printf("Runtime: %d hrs : %d mins : %d secs\n", hours, mins, secs);
  2569. if (total_secs)
  2570. printf("Average hashrate: %.1f Megahash/s\n", total_mhashes_done / total_secs);
  2571. printf("Queued work requests: %d\n", total_getworks);
  2572. printf("Share submissions: %d\n", total_accepted + total_rejected);
  2573. printf("Accepted shares: %d\n", total_accepted);
  2574. printf("Rejected shares: %d\n", total_rejected);
  2575. if (total_accepted || total_rejected)
  2576. printf("Reject ratio: %.1f\n", (double)(total_rejected * 100) / (double)(total_accepted + total_rejected));
  2577. printf("Hardware errors: %d\n", hw_errors);
  2578. printf("Efficiency (accepted / queued): %.0f%%\n", efficiency);
  2579. printf("Utility (accepted shares / min): %.2f/min\n\n", utility);
  2580. printf("Discarded work due to new blocks: %d\n", total_discarded);
  2581. printf("Stale submissions discarded due to new blocks: %d\n", total_stale);
  2582. printf("Unable to get work from server occasions: %d\n", total_lo);
  2583. printf("Work items generated locally: %d\n", local_work);
  2584. printf("Submitting work remotely delay occasions: %d\n", total_ro);
  2585. printf("New blocks detected on network: %d\n\n", new_blocks);
  2586. if (total_pools > 1) {
  2587. for (i = 0; i < total_pools; i++) {
  2588. struct pool *pool = pools[i];
  2589. printf("Pool: %s\n", pool->rpc_url);
  2590. printf(" Queued work requests: %d\n", pool->getwork_requested);
  2591. printf(" Share submissions: %d\n", pool->accepted + pool->rejected);
  2592. printf(" Accepted shares: %d\n", pool->accepted);
  2593. printf(" Rejected shares: %d\n", pool->rejected);
  2594. if (pool->accepted || pool->rejected)
  2595. printf(" Reject ratio: %.1f\n", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  2596. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  2597. printf(" Efficiency (accepted / queued): %.0f%%\n", efficiency);
  2598. printf(" Discarded work due to new blocks: %d\n", pool->discarded_work);
  2599. printf(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  2600. printf(" Unable to get work from server occasions: %d\n", pool->localgen_occasions);
  2601. printf(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  2602. }
  2603. }
  2604. printf("Summary of per device statistics:\n\n");
  2605. for (i = 0; i < mining_threads; i++) {
  2606. if (active_device(i))
  2607. print_status(i);
  2608. }
  2609. printf("\n");
  2610. }
  2611. static void quit(int status, const char *format, ...)
  2612. {
  2613. va_list ap;
  2614. disable_curses();
  2615. if (format) {
  2616. va_start(ap, format);
  2617. vfprintf(stderr, format, ap);
  2618. va_end(ap);
  2619. }
  2620. fprintf(stderr, "\n");
  2621. fflush(stderr);
  2622. exit(status);
  2623. }
  2624. static char *curses_input(const char *query)
  2625. {
  2626. char *input;
  2627. echo();
  2628. input = malloc(255);
  2629. if (!input)
  2630. quit(1, "Failed to malloc input");
  2631. leaveok(logwin, false);
  2632. wprintw(logwin, "%s: ", query);
  2633. wrefresh(logwin);
  2634. wgetnstr(logwin, input, 255);
  2635. leaveok(logwin, true);
  2636. noecho();
  2637. wprintw(logwin, "\n");
  2638. return input;
  2639. }
  2640. static bool input_pool(bool live)
  2641. {
  2642. char *url, *user, *pass;
  2643. struct pool *pool;
  2644. bool ret = false;
  2645. immedok(logwin, true);
  2646. if (total_pools == MAX_POOLS) {
  2647. wprintw(logwin, "Reached maximum number of pools.\n");
  2648. goto out;
  2649. }
  2650. wprintw(logwin, "Input server details.\n");
  2651. url = curses_input("URL");
  2652. if (strncmp(url, "http://", 7) &&
  2653. strncmp(url, "https://", 8)) {
  2654. applog(LOG_ERR, "URL must start with http:// or https://");
  2655. goto out;
  2656. }
  2657. user = curses_input("Username");
  2658. if (!user)
  2659. goto out;
  2660. pass = curses_input("Password");
  2661. if (!pass)
  2662. goto out;
  2663. pool = calloc(sizeof(struct pool), 1);
  2664. if (!pool)
  2665. quit(1, "Failed to realloc pools in input_pool");
  2666. pool->pool_no = total_pools;
  2667. pool->prio = total_pools;
  2668. if (unlikely(pthread_mutex_init(&pool->pool_lock, NULL)))
  2669. quit (1, "Failed to pthread_mutex_init in input_pool");
  2670. pool->rpc_url = url;
  2671. pool->rpc_user = user;
  2672. pool->rpc_pass = pass;
  2673. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  2674. if (!pool->rpc_userpass)
  2675. quit(1, "Failed to malloc userpass");
  2676. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  2677. pool->tv_idle.tv_sec = ~0UL;
  2678. /* Test the pool before we enable it if we're live running, otherwise
  2679. * it will be tested separately */
  2680. ret = true;
  2681. if (live && pool_active(pool))
  2682. pool->enabled = true;
  2683. pools[total_pools++] = pool;
  2684. out:
  2685. immedok(logwin, false);
  2686. if (!ret) {
  2687. free(pool);
  2688. if (url)
  2689. free(url);
  2690. if (user)
  2691. free(user);
  2692. if (pass)
  2693. free(pass);
  2694. }
  2695. return ret;
  2696. }
  2697. int main (int argc, char *argv[])
  2698. {
  2699. unsigned int i, j = 0, x, y, pools_active = 0;
  2700. struct sigaction handler;
  2701. struct thr_info *thr;
  2702. char name[256];
  2703. struct tm tm;
  2704. /* This dangerous functions tramples random dynamically allocated
  2705. * variables so do it before anything at all */
  2706. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  2707. quit(1, "Failed to curl_global_init");
  2708. if (unlikely(pthread_mutex_init(&hash_lock, NULL)))
  2709. quit(1, "Failed to pthread_mutex_init");
  2710. if (unlikely(pthread_mutex_init(&qd_lock, NULL)))
  2711. quit(1, "Failed to pthread_mutex_init");
  2712. if (unlikely(pthread_mutex_init(&stgd_lock, NULL)))
  2713. quit(1, "Failed to pthread_mutex_init");
  2714. if (unlikely(pthread_mutex_init(&curses_lock, NULL)))
  2715. quit(1, "Failed to pthread_mutex_init");
  2716. if (unlikely(pthread_mutex_init(&control_lock, NULL)))
  2717. quit(1, "Failed to pthread_mutex_init");
  2718. handler.sa_handler = &sighandler;
  2719. sigaction(SIGTERM, &handler, &termhandler);
  2720. sigaction(SIGINT, &handler, &inthandler);
  2721. gettimeofday(&total_tv_start, NULL);
  2722. gettimeofday(&total_tv_end, NULL);
  2723. localtime_r(&total_tv_start.tv_sec, &tm);
  2724. sprintf(datestamp, "[%d-%02d-%02d %02d:%02d:%02d]",
  2725. tm.tm_year + 1900,
  2726. tm.tm_mon + 1,
  2727. tm.tm_mday,
  2728. tm.tm_hour,
  2729. tm.tm_min,
  2730. tm.tm_sec);
  2731. for (i = 0; i < 36; i++)
  2732. strcat(current_block, "0");
  2733. #ifdef WIN32
  2734. opt_n_threads = num_processors = 1;
  2735. #else
  2736. num_processors = sysconf(_SC_NPROCESSORS_ONLN);
  2737. opt_n_threads = num_processors;
  2738. #endif /* !WIN32 */
  2739. #ifdef HAVE_OPENCL
  2740. for (i = 0; i < 16; i++)
  2741. gpu_devices[i] = false;
  2742. nDevs = clDevicesNum();
  2743. if (nDevs < 0)
  2744. quit(1, "clDevicesNum returned error");
  2745. #endif
  2746. if (nDevs)
  2747. opt_n_threads = 0;
  2748. trpc_url = strdup(DEF_RPC_URL);
  2749. /* parse command line */
  2750. opt_register_table(opt_config_table,
  2751. "Options for both config file and command line");
  2752. opt_register_table(opt_cmdline_table,
  2753. "Options for command line only");
  2754. opt_parse(&argc, argv, applog_and_exit);
  2755. if (argc != 1)
  2756. quit(1, "Unexpected extra commandline arguments");
  2757. if (total_devices) {
  2758. if (total_devices > nDevs)
  2759. quit(1, "More devices specified than exist");
  2760. for (i = 0; i < 16; i++)
  2761. if (gpu_devices[i] && i + 1 > nDevs)
  2762. quit (1, "Command line options set a device that doesn't exist");
  2763. gpu_threads = total_devices * opt_g_threads;
  2764. } else {
  2765. gpu_threads = nDevs * opt_g_threads;
  2766. for (i = 0; i < nDevs; i++)
  2767. gpu_devices[i] = true;
  2768. total_devices = nDevs;
  2769. }
  2770. if (!gpu_threads && !forced_n_threads) {
  2771. /* Maybe they turned GPU off; restore default CPU threads. */
  2772. opt_n_threads = num_processors;
  2773. }
  2774. logcursor = 8;
  2775. gpucursor = logcursor;
  2776. cpucursor = gpucursor + nDevs;
  2777. logstart = cpucursor + (opt_n_threads ? num_processors : 0) + 1;
  2778. logcursor = logstart + 1;
  2779. /* Set up the ncurses interface */
  2780. if (!opt_quiet && use_curses) {
  2781. mainwin = initscr();
  2782. getmaxyx(mainwin, y, x);
  2783. statuswin = newwin(logstart, x, 0, 0);
  2784. leaveok(statuswin, true);
  2785. logwin = newwin(y - logcursor, 0, logcursor, 0);
  2786. idlok(logwin, true);
  2787. scrollok(logwin, true);
  2788. leaveok(logwin, true);
  2789. cbreak();
  2790. noecho();
  2791. test_and_set(&curses_active);
  2792. }
  2793. if (!total_pools) {
  2794. if (curses_active) {
  2795. if (!input_pool(false))
  2796. quit(1, "Pool setup failed");
  2797. } else
  2798. quit(1, "No server specified");
  2799. }
  2800. for (i = 0; i < total_pools; i++) {
  2801. struct pool *pool = pools[i];
  2802. if (!pool->rpc_userpass) {
  2803. if (!pool->rpc_user || !pool->rpc_pass)
  2804. quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  2805. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  2806. if (!pool->rpc_userpass)
  2807. quit(1, "Failed to malloc userpass");
  2808. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  2809. } else {
  2810. pool->rpc_user = malloc(strlen(pool->rpc_userpass));
  2811. if (!pool->rpc_user)
  2812. quit(1, "Failed to malloc user");
  2813. strcpy(pool->rpc_user, pool->rpc_userpass);
  2814. pool->rpc_user = strtok(pool->rpc_user, ":");
  2815. if (!pool->rpc_user)
  2816. quit(1, "Failed to find colon delimiter in userpass");
  2817. }
  2818. }
  2819. /* Set the currentpool to pool 0 */
  2820. currentpool = pools[0];
  2821. #ifdef HAVE_SYSLOG_H
  2822. if (use_syslog)
  2823. openlog("cpuminer", LOG_PID, LOG_USER);
  2824. #endif
  2825. mining_threads = opt_n_threads + gpu_threads;
  2826. total_threads = mining_threads + 5;
  2827. work_restart = calloc(total_threads, sizeof(*work_restart));
  2828. if (!work_restart)
  2829. quit(1, "Failed to calloc work_restart");
  2830. thr_info = calloc(total_threads, sizeof(*thr));
  2831. if (!thr_info)
  2832. quit(1, "Failed to calloc thr_info");
  2833. /* init workio thread info */
  2834. work_thr_id = mining_threads;
  2835. thr = &thr_info[work_thr_id];
  2836. thr->id = work_thr_id;
  2837. thr->q = tq_new();
  2838. if (!thr->q)
  2839. quit(1, "Failed to tq_new");
  2840. /* start work I/O thread */
  2841. if (thr_info_create(thr, NULL, workio_thread, thr))
  2842. quit(1, "workio thread create failed");
  2843. /* init longpoll thread info */
  2844. longpoll_thr_id = mining_threads + 1;
  2845. thr = &thr_info[longpoll_thr_id];
  2846. thr->id = longpoll_thr_id;
  2847. thr->q = tq_new();
  2848. if (!thr->q)
  2849. quit(1, "Failed to tq_new");
  2850. if (want_longpoll)
  2851. start_longpoll();
  2852. if (opt_n_threads ) {
  2853. cpus = calloc(num_processors, sizeof(struct cgpu_info));
  2854. if (unlikely(!cpus))
  2855. quit(1, "Failed to calloc cpus");
  2856. }
  2857. if (gpu_threads) {
  2858. gpus = calloc(nDevs, sizeof(struct cgpu_info));
  2859. if (unlikely(!gpus))
  2860. quit(1, "Failed to calloc gpus");
  2861. }
  2862. stage_thr_id = mining_threads + 3;
  2863. thr = &thr_info[stage_thr_id];
  2864. thr->q = tq_new();
  2865. if (!thr->q)
  2866. quit(1, "Failed to tq_new");
  2867. /* start stage thread */
  2868. if (thr_info_create(thr, NULL, stage_thread, thr))
  2869. quit(1, "stage thread create failed");
  2870. pthread_detach(*thr->pth);
  2871. /* Flag the work as ready forcing the mining threads to wait till we
  2872. * actually put something into the queue */
  2873. inc_staged(current_pool(), mining_threads, true);
  2874. /* Create a unique get work queue */
  2875. getq = tq_new();
  2876. if (!getq)
  2877. quit(1, "Failed to create getq");
  2878. /* Test each pool to see if we can retrieve and use work and for what
  2879. * it supports */
  2880. for (i = 0; i < total_pools; i++) {
  2881. struct pool *pool;
  2882. pool = pools[i];
  2883. if (pool_active(pool)) {
  2884. if (!currentpool)
  2885. currentpool = pool;
  2886. applog(LOG_INFO, "Pool %d %s active", pool->pool_no, pool->rpc_url);
  2887. pools_active++;
  2888. pool->enabled = true;
  2889. } else {
  2890. if (pool == currentpool)
  2891. currentpool = NULL;
  2892. applog(LOG_WARNING, "Unable to get work from pool %d %s", pool->pool_no, pool->rpc_url);
  2893. }
  2894. }
  2895. if (!pools_active)
  2896. quit(0, "No pools active! Exiting.");
  2897. #ifdef HAVE_OPENCL
  2898. i = 0;
  2899. /* Hopefully remove stale references to allow binaries to build */
  2900. if (nDevs)
  2901. clUnloadCompiler();
  2902. /* start GPU mining threads */
  2903. for (j = 0; j < nDevs * opt_g_threads; j++) {
  2904. int gpu = j % nDevs;
  2905. gpus[gpu].is_gpu = 1;
  2906. gpus[gpu].cpu_gpu = gpu;
  2907. /* Skip devices not set to mine */
  2908. if (!gpu_devices[gpu])
  2909. continue;
  2910. thr = &thr_info[i];
  2911. thr->id = i;
  2912. thr->cgpu = &gpus[gpu];
  2913. thr->q = tq_new();
  2914. if (!thr->q)
  2915. quit(1, "tq_new failed in starting gpu mining threads");
  2916. applog(LOG_INFO, "Init GPU thread %i", i);
  2917. clStates[i] = initCl(gpu, name, sizeof(name));
  2918. if (!clStates[i]) {
  2919. applog(LOG_ERR, "Failed to init GPU thread %d", i);
  2920. continue;
  2921. }
  2922. applog(LOG_INFO, "initCl() finished. Found %s", name);
  2923. thread_reportin(thr);
  2924. if (unlikely(thr_info_create(thr, NULL, gpuminer_thread, thr)))
  2925. quit(1, "thread %d create failed", i);
  2926. i++;
  2927. }
  2928. /* Free up resources */
  2929. if (nDevs)
  2930. clUnloadCompiler();
  2931. applog(LOG_INFO, "%d gpu miner threads started", gpu_threads);
  2932. #endif
  2933. /* start CPU mining threads */
  2934. for (i = gpu_threads; i < mining_threads; i++) {
  2935. int cpu = (i - gpu_threads) % num_processors;
  2936. thr = &thr_info[i];
  2937. thr->id = i;
  2938. cpus[cpu].cpu_gpu = cpu;
  2939. thr->cgpu = &cpus[cpu];
  2940. thr->q = tq_new();
  2941. if (!thr->q)
  2942. quit(1, "tq_new failed in starting cpu mining threads");
  2943. thread_reportin(thr);
  2944. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  2945. quit(1, "thread %d create failed", i);
  2946. }
  2947. applog(LOG_INFO, "%d cpu miner threads started, "
  2948. "using SHA256 '%s' algorithm.",
  2949. opt_n_threads,
  2950. algo_names[opt_algo]);
  2951. watchdog_thr_id = mining_threads + 2;
  2952. thr = &thr_info[watchdog_thr_id];
  2953. /* start wakeup thread */
  2954. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  2955. quit(1, "wakeup thread create failed");
  2956. /* Restart count as it will be wrong till all threads are started */
  2957. pthread_mutex_lock(&hash_lock);
  2958. gettimeofday(&total_tv_start, NULL);
  2959. gettimeofday(&total_tv_end, NULL);
  2960. total_mhashes_done = 0;
  2961. pthread_mutex_unlock(&hash_lock);
  2962. /* Now that everything's ready put enough work in the queue */
  2963. for (i = 0; i < opt_queue + mining_threads; i++) {
  2964. if (unlikely(!queue_request()))
  2965. quit(1, "Failed to queue_request in main");
  2966. if (!opt_quiet)
  2967. print_status(i);
  2968. }
  2969. /* Create curses input thread for keyboard input */
  2970. input_thr_id = mining_threads + 4;
  2971. thr = &thr_info[input_thr_id];
  2972. if (thr_info_create(thr, NULL, input_thread, thr))
  2973. quit(1, "input thread create failed");
  2974. pthread_detach(*thr->pth);
  2975. /* main loop - simply wait for workio thread to exit */
  2976. pthread_join(*thr_info[work_thr_id].pth, NULL);
  2977. applog(LOG_INFO, "workio thread dead, exiting.");
  2978. gettimeofday(&total_tv_end, NULL);
  2979. disable_curses();
  2980. if (!opt_quiet && successful_connect)
  2981. print_summary();
  2982. if (gpu_threads)
  2983. free(gpus);
  2984. if (opt_n_threads)
  2985. free(cpus);
  2986. curl_global_cleanup();
  2987. return 0;
  2988. }