main.c 106 KB

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