main.c 100 KB

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