main.c 99 KB

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