main.c 105 KB

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