main.c 93 KB

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