main.c 103 KB

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