main.c 107 KB

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