main.c 92 KB

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