main.c 107 KB

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