main.c 107 KB

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