main.c 105 KB

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