main.c 96 KB

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