main.c 103 KB

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