cgminer.c 117 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547
  1. /*
  2. * Copyright 2011-2012 Con Kolivas
  3. * Copyright 2011-2012 Luke Dashjr
  4. * Copyright 2010 Jeff Garzik
  5. *
  6. * This program is free software; you can redistribute it and/or modify it
  7. * under the terms of the GNU General Public License as published by the Free
  8. * Software Foundation; either version 2 of the License, or (at your option)
  9. * any later version. See COPYING for more details.
  10. */
  11. #include "config.h"
  12. #include <curses.h>
  13. #include <stdio.h>
  14. #include <stdlib.h>
  15. #include <string.h>
  16. #include <stdbool.h>
  17. #include <stdint.h>
  18. #include <unistd.h>
  19. #include <sys/time.h>
  20. #include <time.h>
  21. #include <math.h>
  22. #include <stdarg.h>
  23. #include <assert.h>
  24. #include <signal.h>
  25. #include <sys/stat.h>
  26. #include <sys/types.h>
  27. #ifndef WIN32
  28. #include <sys/resource.h>
  29. #endif
  30. #include <ccan/opt/opt.h>
  31. #include <jansson.h>
  32. #include <curl/curl.h>
  33. #include <libgen.h>
  34. #include <sha2.h>
  35. #include "compat.h"
  36. #include "miner.h"
  37. #include "findnonce.h"
  38. #include "bench_block.h"
  39. #include "ocl.h"
  40. #include "uthash.h"
  41. #include "adl.h"
  42. #include "device-cpu.h"
  43. #include "device-gpu.h"
  44. #if defined(unix)
  45. #include <errno.h>
  46. #include <fcntl.h>
  47. #include <sys/wait.h>
  48. #endif
  49. enum workio_commands {
  50. WC_GET_WORK,
  51. WC_SUBMIT_WORK,
  52. };
  53. struct workio_cmd {
  54. enum workio_commands cmd;
  55. struct thr_info *thr;
  56. union {
  57. struct work *work;
  58. } u;
  59. bool lagging;
  60. };
  61. struct strategies strategies[] = {
  62. { "Failover" },
  63. { "Round Robin" },
  64. { "Rotate" },
  65. { "Load Balance" },
  66. };
  67. static char packagename[255];
  68. int gpu_threads;
  69. bool opt_debug = false;
  70. bool opt_protocol = false;
  71. static bool want_longpoll = true;
  72. static bool have_longpoll = false;
  73. static bool want_per_device_stats = false;
  74. bool use_syslog = false;
  75. static bool opt_quiet = false;
  76. static bool opt_realquiet = false;
  77. bool opt_loginput = false;
  78. const int opt_cutofftemp = 95;
  79. static int opt_retries = -1;
  80. static int opt_fail_pause = 5;
  81. static int fail_pause = 5;
  82. int opt_log_interval = 5;
  83. bool opt_log_output = false;
  84. static int opt_queue = 1;
  85. int opt_vectors;
  86. int opt_worksize;
  87. int opt_scantime = 60;
  88. int opt_expiry = 120;
  89. int opt_bench_algo = -1;
  90. static const bool opt_time = true;
  91. #ifdef HAVE_OPENCL
  92. static bool opt_restart = true;
  93. static bool opt_nogpu;
  94. #endif
  95. struct list_head scan_devices;
  96. int nDevs;
  97. int opt_g_threads = 2;
  98. static signed int devices_enabled = 0;
  99. static bool opt_removedisabled = false;
  100. int total_devices = 0;
  101. struct cgpu_info *devices[MAX_DEVICES];
  102. bool have_opencl = false;
  103. int gpu_threads;
  104. int opt_n_threads = -1;
  105. int mining_threads;
  106. int num_processors;
  107. bool use_curses = true;
  108. static bool opt_submit_stale;
  109. static int opt_shares;
  110. static bool opt_fail_only;
  111. bool opt_autofan;
  112. bool opt_autoengine;
  113. bool opt_noadl;
  114. char *opt_api_allow = NULL;
  115. char *opt_api_description = PACKAGE_STRING;
  116. int opt_api_port = 4028;
  117. bool opt_api_listen = false;
  118. bool opt_api_network = false;
  119. bool opt_delaynet = false;
  120. char *opt_kernel_path;
  121. char *cgminer_path;
  122. #define QUIET (opt_quiet || opt_realquiet)
  123. struct thr_info *thr_info;
  124. static int work_thr_id;
  125. int longpoll_thr_id;
  126. static int stage_thr_id;
  127. static int watchpool_thr_id;
  128. static int watchdog_thr_id;
  129. static int input_thr_id;
  130. int gpur_thr_id;
  131. static int api_thr_id;
  132. static int total_threads;
  133. struct work_restart *work_restart = NULL;
  134. static pthread_mutex_t hash_lock;
  135. static pthread_mutex_t qd_lock;
  136. static pthread_mutex_t *stgd_lock;
  137. static pthread_mutex_t curses_lock;
  138. static pthread_rwlock_t blk_lock;
  139. pthread_rwlock_t netacc_lock;
  140. double total_mhashes_done;
  141. static struct timeval total_tv_start, total_tv_end;
  142. pthread_mutex_t control_lock;
  143. int hw_errors;
  144. int total_accepted, total_rejected;
  145. int total_getworks, total_stale, total_discarded;
  146. static int total_queued;
  147. unsigned int new_blocks;
  148. static unsigned int work_block;
  149. unsigned int found_blocks;
  150. unsigned int local_work;
  151. unsigned int total_go, total_ro;
  152. struct pool *pools[MAX_POOLS];
  153. static struct pool *currentpool = NULL;
  154. int total_pools;
  155. enum pool_strategy pool_strategy = POOL_FAILOVER;
  156. int opt_rotate_period;
  157. static int total_urls, total_users, total_passes, total_userpasses;
  158. static bool curses_active = false;
  159. static char current_block[37];
  160. static char *current_hash;
  161. static char datestamp[40];
  162. static char blocktime[30];
  163. struct block {
  164. char hash[37];
  165. UT_hash_handle hh;
  166. };
  167. static struct block *blocks = NULL;
  168. char *opt_kernel = NULL;
  169. char *opt_socks_proxy = NULL;
  170. static const char def_conf[] = "cgminer.conf";
  171. static bool config_loaded = false;
  172. #if defined(unix)
  173. static char *opt_stderr_cmd = NULL;
  174. #endif // defined(unix)
  175. enum cl_kernels chosen_kernel;
  176. bool ping = true;
  177. struct sigaction termhandler, inthandler;
  178. struct thread_q *getq;
  179. static int total_work;
  180. struct work *staged_work = NULL;
  181. static int staged_clones;
  182. struct schedtime {
  183. bool enable;
  184. struct tm tm;
  185. };
  186. struct schedtime schedstart;
  187. struct schedtime schedstop;
  188. bool sched_paused;
  189. static bool time_before(struct tm *tm1, struct tm *tm2)
  190. {
  191. if (tm1->tm_hour < tm2->tm_hour)
  192. return true;
  193. if (tm1->tm_hour == tm2->tm_hour && tm1->tm_min < tm2->tm_min)
  194. return true;
  195. return false;
  196. }
  197. static bool should_run(void)
  198. {
  199. struct timeval tv;
  200. struct tm *tm;
  201. if (!schedstart.enable && !schedstop.enable)
  202. return true;
  203. gettimeofday(&tv, NULL);
  204. tm = localtime(&tv.tv_sec);
  205. if (schedstart.enable) {
  206. if (!schedstop.enable) {
  207. if (time_before(tm, &schedstart.tm))
  208. return false;
  209. /* This is a once off event with no stop time set */
  210. schedstart.enable = false;
  211. return true;
  212. }
  213. if (time_before(&schedstart.tm, &schedstop.tm)) {
  214. if (time_before(tm, &schedstop.tm) && !time_before(tm, &schedstart.tm))
  215. return true;
  216. return false;
  217. } /* Times are reversed */
  218. if (time_before(tm, &schedstart.tm)) {
  219. if (time_before(tm, &schedstop.tm))
  220. return true;
  221. return false;
  222. }
  223. return true;
  224. }
  225. /* only schedstop.enable == true */
  226. if (!time_before(tm, &schedstop.tm))
  227. return false;
  228. return true;
  229. }
  230. void get_datestamp(char *f, struct timeval *tv)
  231. {
  232. struct tm *tm;
  233. tm = localtime(&tv->tv_sec);
  234. sprintf(f, "[%d-%02d-%02d %02d:%02d:%02d]",
  235. tm->tm_year + 1900,
  236. tm->tm_mon + 1,
  237. tm->tm_mday,
  238. tm->tm_hour,
  239. tm->tm_min,
  240. tm->tm_sec);
  241. }
  242. void get_timestamp(char *f, struct timeval *tv)
  243. {
  244. struct tm *tm;
  245. tm = localtime(&tv->tv_sec);
  246. sprintf(f, "[%02d:%02d:%02d]",
  247. tm->tm_hour,
  248. tm->tm_min,
  249. tm->tm_sec);
  250. }
  251. static void applog_and_exit(const char *fmt, ...)
  252. {
  253. va_list ap;
  254. va_start(ap, fmt);
  255. vapplog(LOG_ERR, fmt, ap);
  256. va_end(ap);
  257. exit(1);
  258. }
  259. static void add_pool(void)
  260. {
  261. struct pool *pool;
  262. pool = calloc(sizeof(struct pool), 1);
  263. if (!pool) {
  264. applog(LOG_ERR, "Failed to malloc pool in add_pool");
  265. exit (1);
  266. }
  267. pool->pool_no = pool->prio = total_pools;
  268. pools[total_pools++] = pool;
  269. if (unlikely(pthread_mutex_init(&pool->pool_lock, NULL))) {
  270. applog(LOG_ERR, "Failed to pthread_mutex_init in add_pool");
  271. exit (1);
  272. }
  273. /* Make sure the pool doesn't think we've been idle since time 0 */
  274. pool->tv_idle.tv_sec = ~0UL;
  275. }
  276. /* Pool variant of test and set */
  277. static bool pool_tset(struct pool *pool, bool *var)
  278. {
  279. bool ret;
  280. mutex_lock(&pool->pool_lock);
  281. ret = *var;
  282. *var = true;
  283. mutex_unlock(&pool->pool_lock);
  284. return ret;
  285. }
  286. static bool pool_tclear(struct pool *pool, bool *var)
  287. {
  288. bool ret;
  289. mutex_lock(&pool->pool_lock);
  290. ret = *var;
  291. *var = false;
  292. mutex_unlock(&pool->pool_lock);
  293. return ret;
  294. }
  295. static bool pool_isset(struct pool *pool, bool *var)
  296. {
  297. bool ret;
  298. mutex_lock(&pool->pool_lock);
  299. ret = *var;
  300. mutex_unlock(&pool->pool_lock);
  301. return ret;
  302. }
  303. static struct pool *current_pool(void)
  304. {
  305. struct pool *pool;
  306. mutex_lock(&control_lock);
  307. pool = currentpool;
  308. mutex_unlock(&control_lock);
  309. return pool;
  310. }
  311. char *set_int_range(const char *arg, int *i, int min, int max)
  312. {
  313. char *err = opt_set_intval(arg, i);
  314. if (err)
  315. return err;
  316. if (*i < min || *i > max)
  317. return "Value out of range";
  318. return NULL;
  319. }
  320. static char *set_int_0_to_9999(const char *arg, int *i)
  321. {
  322. return set_int_range(arg, i, 0, 9999);
  323. }
  324. static char *set_int_1_to_65535(const char *arg, int *i)
  325. {
  326. return set_int_range(arg, i, 1, 65535);
  327. }
  328. static char *set_int_0_to_10(const char *arg, int *i)
  329. {
  330. return set_int_range(arg, i, 0, 10);
  331. }
  332. static char *set_int_1_to_10(const char *arg, int *i)
  333. {
  334. return set_int_range(arg, i, 1, 10);
  335. }
  336. #ifdef USE_BITFORCE
  337. static char *add_serial(char *arg)
  338. {
  339. string_elist_add(arg, &scan_devices);
  340. return NULL;
  341. }
  342. #endif
  343. static char *set_devices(char *arg)
  344. {
  345. int i = strtol(arg, &arg, 0);
  346. if (*arg) {
  347. if (*arg == '?') {
  348. devices_enabled = -1;
  349. return NULL;
  350. }
  351. return "Invalid device number";
  352. }
  353. if (i < 0 || i >= (sizeof(devices_enabled) * 8) - 1)
  354. return "Invalid device number";
  355. devices_enabled |= 1 << i;
  356. return NULL;
  357. }
  358. static char *set_loadbalance(enum pool_strategy *strategy)
  359. {
  360. *strategy = POOL_LOADBALANCE;
  361. return NULL;
  362. }
  363. static char *set_rotate(const char *arg, int *i)
  364. {
  365. pool_strategy = POOL_ROTATE;
  366. return set_int_range(arg, i, 0, 9999);
  367. }
  368. static char *set_rr(enum pool_strategy *strategy)
  369. {
  370. *strategy = POOL_ROUNDROBIN;
  371. return NULL;
  372. }
  373. static char *set_url(char *arg)
  374. {
  375. struct pool *pool;
  376. total_urls++;
  377. if (total_urls > total_pools)
  378. add_pool();
  379. pool = pools[total_urls - 1];
  380. opt_set_charp(arg, &pool->rpc_url);
  381. if (strncmp(arg, "http://", 7) &&
  382. strncmp(arg, "https://", 8)) {
  383. char *httpinput;
  384. httpinput = malloc(255);
  385. if (!httpinput)
  386. quit(1, "Failed to malloc httpinput");
  387. strcpy(httpinput, "http://");
  388. strncat(httpinput, arg, 248);
  389. pool->rpc_url = httpinput;
  390. }
  391. return NULL;
  392. }
  393. static char *set_user(const char *arg)
  394. {
  395. struct pool *pool;
  396. if (total_userpasses)
  397. return "Use only user + pass or userpass, but not both";
  398. total_users++;
  399. if (total_users > total_pools)
  400. add_pool();
  401. pool = pools[total_users - 1];
  402. opt_set_charp(arg, &pool->rpc_user);
  403. return NULL;
  404. }
  405. static char *set_pass(const char *arg)
  406. {
  407. struct pool *pool;
  408. if (total_userpasses)
  409. return "Use only user + pass or userpass, but not both";
  410. total_passes++;
  411. if (total_passes > total_pools)
  412. add_pool();
  413. pool = pools[total_passes - 1];
  414. opt_set_charp(arg, &pool->rpc_pass);
  415. return NULL;
  416. }
  417. static char *set_userpass(const char *arg)
  418. {
  419. struct pool *pool;
  420. if (total_users || total_passes)
  421. return "Use only user + pass or userpass, but not both";
  422. total_userpasses++;
  423. if (total_userpasses > total_pools)
  424. add_pool();
  425. pool = pools[total_userpasses - 1];
  426. opt_set_charp(arg, &pool->rpc_userpass);
  427. return NULL;
  428. }
  429. static char *enable_debug(bool *flag)
  430. {
  431. *flag = true;
  432. /* Turn out verbose output, too. */
  433. opt_log_output = true;
  434. return NULL;
  435. }
  436. static char *set_schedtime(const char *arg, struct schedtime *st)
  437. {
  438. if (sscanf(arg, "%d:%d", &st->tm.tm_hour, &st->tm.tm_min) != 2)
  439. return "Invalid time set, should be HH:MM";
  440. if (st->tm.tm_hour > 23 || st->tm.tm_min > 59 || st->tm.tm_hour < 0 || st->tm.tm_min < 0)
  441. return "Invalid time set.";
  442. st->enable = true;
  443. return NULL;
  444. }
  445. static char *temp_cutoff_str = NULL;
  446. char *set_temp_cutoff(char *arg)
  447. {
  448. int val;
  449. if (!(arg && arg[0]))
  450. return "Invalid parameters for set temp cutoff";
  451. val = atoi(arg);
  452. if (val < 0 || val > 200)
  453. return "Invalid value passed to set temp cutoff";
  454. temp_cutoff_str = arg;
  455. return NULL;
  456. }
  457. static void load_temp_cutoffs()
  458. {
  459. int i, val = 0, device = 0;
  460. char *nextptr;
  461. if (temp_cutoff_str) {
  462. for (device = 0, nextptr = strtok(temp_cutoff_str, ","); nextptr; ++device, nextptr = strtok(NULL, ",")) {
  463. if (device >= total_devices)
  464. quit(1, "Too many values passed to set temp cutoff");
  465. val = atoi(nextptr);
  466. if (val < 0 || val > 200)
  467. quit(1, "Invalid value passed to set temp cutoff");
  468. devices[device]->cutofftemp = val;
  469. }
  470. }
  471. else
  472. val = opt_cutofftemp;
  473. if (device <= 1) {
  474. for (i = device; i < total_devices; ++i)
  475. devices[i]->cutofftemp = val;
  476. }
  477. }
  478. static char *set_api_allow(const char *arg)
  479. {
  480. opt_set_charp(arg, &opt_api_allow);
  481. return NULL;
  482. }
  483. static char *set_api_description(const char *arg)
  484. {
  485. opt_set_charp(arg, &opt_api_description);
  486. return NULL;
  487. }
  488. /* These options are available from config file or commandline */
  489. static struct opt_table opt_config_table[] = {
  490. #ifdef WANT_CPUMINE
  491. OPT_WITH_ARG("--algo|-a",
  492. set_algo, show_algo, &opt_algo,
  493. "Specify sha256 implementation for CPU mining:\n"
  494. "\tauto\t\tBenchmark at startup and pick fastest algorithm"
  495. "\n\tc\t\tLinux kernel sha256, implemented in C"
  496. #ifdef WANT_SSE2_4WAY
  497. "\n\t4way\t\ttcatm's 4-way SSE2 implementation"
  498. #endif
  499. #ifdef WANT_VIA_PADLOCK
  500. "\n\tvia\t\tVIA padlock implementation"
  501. #endif
  502. "\n\tcryptopp\tCrypto++ C/C++ implementation"
  503. #ifdef WANT_CRYPTOPP_ASM32
  504. "\n\tcryptopp_asm32\tCrypto++ 32-bit assembler implementation"
  505. #endif
  506. #ifdef WANT_X8632_SSE2
  507. "\n\tsse2_32\t\tSSE2 32 bit implementation for i386 machines"
  508. #endif
  509. #ifdef WANT_X8664_SSE2
  510. "\n\tsse2_64\t\tSSE2 64 bit implementation for x86_64 machines"
  511. #endif
  512. #ifdef WANT_X8664_SSE4
  513. "\n\tsse4_64\t\tSSE4.1 64 bit implementation for x86_64 machines"
  514. #endif
  515. #ifdef WANT_ALTIVEC_4WAY
  516. "\n\taltivec_4way\tAltivec implementation for PowerPC G4 and G5 machines"
  517. #endif
  518. ),
  519. #endif
  520. OPT_WITH_ARG("--api-allow",
  521. set_api_allow, NULL, NULL,
  522. "Allow API access only to the given list of IP[/Prefix] addresses[/subnets]"),
  523. OPT_WITH_ARG("--api-description",
  524. set_api_description, NULL, NULL,
  525. "Description placed in the API status header, default: cgminer version"),
  526. OPT_WITHOUT_ARG("--api-listen",
  527. opt_set_bool, &opt_api_listen,
  528. "Enable API, default: disabled"),
  529. OPT_WITHOUT_ARG("--api-network",
  530. opt_set_bool, &opt_api_network,
  531. "Allow API (if enabled) to listen on/for any address, default: only 127.0.0.1"),
  532. OPT_WITH_ARG("--api-port",
  533. set_int_1_to_65535, opt_show_intval, &opt_api_port,
  534. "Port number of miner API"),
  535. #ifdef HAVE_ADL
  536. OPT_WITHOUT_ARG("--auto-fan",
  537. opt_set_bool, &opt_autofan,
  538. "Automatically adjust all GPU fan speeds to maintain a target temperature"),
  539. OPT_WITHOUT_ARG("--auto-gpu",
  540. opt_set_bool, &opt_autoengine,
  541. "Automatically adjust all GPU engine clock speeds to maintain a target temperature"),
  542. #endif
  543. #ifdef WANT_CPUMINE
  544. OPT_WITH_ARG("--bench-algo|-b",
  545. set_int_0_to_9999, opt_show_intval, &opt_bench_algo,
  546. opt_hidden),
  547. OPT_WITH_ARG("--cpu-threads|-t",
  548. force_nthreads_int, opt_show_intval, &opt_n_threads,
  549. "Number of miner CPU threads"),
  550. #endif
  551. OPT_WITHOUT_ARG("--debug|-D",
  552. enable_debug, &opt_debug,
  553. "Enable debug output"),
  554. OPT_WITH_ARG("--device|-d",
  555. set_devices, NULL, NULL,
  556. "Select device to use, (Use repeat -d for multiple devices, default: all)"),
  557. #ifdef HAVE_OPENCL
  558. OPT_WITHOUT_ARG("--disable-gpu|-G",
  559. opt_set_bool, &opt_nogpu,
  560. "Disable GPU mining even if suitable devices exist"),
  561. #if defined(WANT_CPUMINE) && (defined(HAVE_OPENCL) || defined(USE_BITFORCE))
  562. OPT_WITHOUT_ARG("--enable-cpu|-C",
  563. opt_set_bool, &opt_usecpu,
  564. "Enable CPU mining with other mining (default: no CPU mining if other devices exist)"),
  565. #endif
  566. #endif
  567. OPT_WITH_ARG("--expiry|-E",
  568. set_int_0_to_9999, opt_show_intval, &opt_expiry,
  569. "Upper bound on how many seconds after getting work we consider a share from it stale"),
  570. OPT_WITHOUT_ARG("--failover-only",
  571. opt_set_bool, &opt_fail_only,
  572. "Don't leak work to backup pools when primary pool is lagging"),
  573. #ifdef HAVE_OPENCL
  574. OPT_WITH_ARG("--gpu-platform",
  575. set_int_0_to_9999, opt_show_intval, &opt_platform_id,
  576. "Select OpenCL platform ID to use for GPU mining"),
  577. OPT_WITH_ARG("--gpu-threads|-g",
  578. set_int_1_to_10, opt_show_intval, &opt_g_threads,
  579. "Number of threads per GPU (1 - 10)"),
  580. #ifdef HAVE_ADL
  581. OPT_WITH_ARG("--gpu-engine",
  582. set_gpu_engine, NULL, NULL,
  583. "GPU engine (over)clock range in Mhz - one value, range and/or comma separated list (e.g. 850-900,900,750-850)"),
  584. OPT_WITH_ARG("--gpu-fan",
  585. set_gpu_fan, NULL, NULL,
  586. "GPU fan percentage range - one value, range and/or comma separated list (e.g. 0-85,85,65)"),
  587. OPT_WITH_ARG("--gpu-memclock",
  588. set_gpu_memclock, NULL, NULL,
  589. "Set the GPU memory (over)clock in Mhz - one value for all or separate by commas for per card"),
  590. OPT_WITH_ARG("--gpu-memdiff",
  591. set_gpu_memdiff, NULL, NULL,
  592. "Set a fixed difference in clock speed between the GPU and memory in auto-gpu mode"),
  593. OPT_WITH_ARG("--gpu-powertune",
  594. set_gpu_powertune, NULL, NULL,
  595. "Set the GPU powertune percentage - one value for all or separate by commas for per card"),
  596. OPT_WITHOUT_ARG("--gpu-reorder",
  597. opt_set_bool, &opt_reorder,
  598. "Attempt to reorder GPU devices according to PCI Bus ID"),
  599. OPT_WITH_ARG("--gpu-vddc",
  600. set_gpu_vddc, NULL, NULL,
  601. "Set the GPU voltage in Volts - one value for all or separate by commas for per card"),
  602. #endif
  603. OPT_WITH_ARG("--intensity|-I",
  604. set_intensity, NULL, NULL,
  605. "Intensity of GPU scanning (d or " _MIN_INTENSITY_STR " -> " _MAX_INTENSITY_STR ", default: d to maintain desktop interactivity)"),
  606. OPT_WITH_ARG("--kernel-path|-K",
  607. opt_set_charp, opt_show_charp, &opt_kernel_path,
  608. "Specify a path to where the kernel .cl files are"),
  609. OPT_WITH_ARG("--kernel|-k",
  610. opt_set_charp, NULL, &opt_kernel,
  611. "Select kernel to use (poclbm or phatk - default: auto)"),
  612. #endif
  613. OPT_WITHOUT_ARG("--load-balance",
  614. set_loadbalance, &pool_strategy,
  615. "Change multipool strategy from failover to even load balance"),
  616. OPT_WITH_ARG("--log|-l",
  617. set_int_0_to_9999, opt_show_intval, &opt_log_interval,
  618. "Interval in seconds between log output"),
  619. #if defined(unix)
  620. OPT_WITH_ARG("--monitor|-m",
  621. opt_set_charp, NULL, &opt_stderr_cmd,
  622. "Use custom pipe cmd for output messages"),
  623. #endif // defined(unix)
  624. OPT_WITHOUT_ARG("--net-delay",
  625. opt_set_bool, &opt_delaynet,
  626. "Impose small delays in networking to not overload slow routers"),
  627. #ifdef HAVE_ADL
  628. OPT_WITHOUT_ARG("--no-adl",
  629. opt_set_bool, &opt_noadl,
  630. "Disable the ATI display library used for monitoring and setting GPU parameters"),
  631. #endif
  632. OPT_WITHOUT_ARG("--no-longpoll",
  633. opt_set_invbool, &want_longpoll,
  634. "Disable X-Long-Polling support"),
  635. #ifdef HAVE_OPENCL
  636. OPT_WITHOUT_ARG("--no-restart",
  637. opt_set_invbool, &opt_restart,
  638. "Do not attempt to restart GPUs that hang"),
  639. #endif
  640. OPT_WITH_ARG("--pass|-p",
  641. set_pass, NULL, NULL,
  642. "Password for bitcoin JSON-RPC server"),
  643. OPT_WITHOUT_ARG("--per-device-stats",
  644. opt_set_bool, &want_per_device_stats,
  645. "Force verbose mode and output per-device statistics"),
  646. OPT_WITHOUT_ARG("--protocol-dump|-P",
  647. opt_set_bool, &opt_protocol,
  648. "Verbose dump of protocol-level activities"),
  649. OPT_WITH_ARG("--queue|-Q",
  650. set_int_0_to_10, opt_show_intval, &opt_queue,
  651. "Minimum number of work items to have queued (0 - 10)"),
  652. OPT_WITHOUT_ARG("--quiet|-q",
  653. opt_set_bool, &opt_quiet,
  654. "Disable logging output, display status and errors"),
  655. OPT_WITHOUT_ARG("--real-quiet",
  656. opt_set_bool, &opt_realquiet,
  657. "Disable all output"),
  658. OPT_WITHOUT_ARG("--remove-disabled",
  659. opt_set_bool, &opt_removedisabled,
  660. "Remove disabled devices entirely, as if they didn't exist"),
  661. OPT_WITH_ARG("--retries|-r",
  662. opt_set_intval, opt_show_intval, &opt_retries,
  663. "Number of times to retry before giving up, if JSON-RPC call fails (-1 means never)"),
  664. OPT_WITH_ARG("--retry-pause|-R",
  665. set_int_0_to_9999, opt_show_intval, &opt_fail_pause,
  666. "Number of seconds to pause, between retries"),
  667. OPT_WITH_ARG("--rotate",
  668. set_rotate, opt_show_intval, &opt_rotate_period,
  669. "Change multipool strategy from failover to regularly rotate at N minutes"),
  670. OPT_WITHOUT_ARG("--round-robin",
  671. set_rr, &pool_strategy,
  672. "Change multipool strategy from failover to round robin on failure"),
  673. #ifdef USE_BITFORCE
  674. OPT_WITH_ARG("--scan-serial|-S",
  675. add_serial, NULL, NULL,
  676. "Serial port to probe for BitForce device"),
  677. #endif
  678. OPT_WITH_ARG("--scan-time|-s",
  679. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  680. "Upper bound on time spent scanning current work, in seconds"),
  681. OPT_WITH_ARG("--sched-start",
  682. set_schedtime, NULL, &schedstart,
  683. "Set a time of day in HH:MM to start mining (a once off without a stop time)"),
  684. OPT_WITH_ARG("--sched-stop",
  685. set_schedtime, NULL, &schedstop,
  686. "Set a time of day in HH:MM to stop mining (will quit without a start time)"),
  687. OPT_WITH_ARG("--shares",
  688. opt_set_intval, NULL, &opt_shares,
  689. "Quit after mining N shares (default: unlimited)"),
  690. OPT_WITH_ARG("--socks-proxy",
  691. opt_set_charp, NULL, &opt_socks_proxy,
  692. "Set socks4 proxy (host:port)"),
  693. OPT_WITHOUT_ARG("--submit-stale",
  694. opt_set_bool, &opt_submit_stale,
  695. "Submit shares even if they would normally be considered stale"),
  696. #ifdef HAVE_SYSLOG_H
  697. OPT_WITHOUT_ARG("--syslog",
  698. opt_set_bool, &use_syslog,
  699. "Use system log for output messages (default: standard error)"),
  700. #endif
  701. #if defined(HAVE_ADL) || defined(USE_BITFORCE)
  702. OPT_WITH_ARG("--temp-cutoff",
  703. set_temp_cutoff, opt_show_intval, &opt_cutofftemp,
  704. "Temperature where a device will be automatically disabled, one value or comma separated list"),
  705. #endif
  706. #ifdef HAVE_ADL
  707. OPT_WITH_ARG("--temp-hysteresis",
  708. set_int_1_to_10, opt_show_intval, &opt_hysteresis,
  709. "Set how much the temperature can fluctuate outside limits when automanaging speeds"),
  710. OPT_WITH_ARG("--temp-overheat",
  711. set_temp_overheat, opt_show_intval, &opt_overheattemp,
  712. "Overheat temperature when automatically managing fan and GPU speeds, one value or comma separated list"),
  713. OPT_WITH_ARG("--temp-target",
  714. set_temp_target, opt_show_intval, &opt_targettemp,
  715. "Target temperature when automatically managing fan and GPU speeds, one value or comma separated list"),
  716. #endif
  717. OPT_WITHOUT_ARG("--text-only|-T",
  718. opt_set_invbool, &use_curses,
  719. "Disable ncurses formatted screen output"),
  720. OPT_WITH_ARG("--url|-o",
  721. set_url, NULL, NULL,
  722. "URL for bitcoin JSON-RPC server"),
  723. OPT_WITH_ARG("--user|-u",
  724. set_user, NULL, NULL,
  725. "Username for bitcoin JSON-RPC server"),
  726. #ifdef HAVE_OPENCL
  727. OPT_WITH_ARG("--vectors|-v",
  728. set_vector, NULL, &opt_vectors,
  729. "Override detected optimal vector width (1, 2 or 4)"),
  730. #endif
  731. OPT_WITHOUT_ARG("--verbose",
  732. opt_set_bool, &opt_log_output,
  733. "Log verbose output to stderr as well as status output"),
  734. #ifdef HAVE_OPENCL
  735. OPT_WITH_ARG("--worksize|-w",
  736. set_int_0_to_9999, opt_show_intval, &opt_worksize,
  737. "Override detected optimal worksize"),
  738. #endif
  739. OPT_WITH_ARG("--userpass|-O",
  740. set_userpass, NULL, NULL,
  741. "Username:Password pair for bitcoin JSON-RPC server"),
  742. OPT_WITH_ARG("--pools",
  743. opt_set_bool, NULL, NULL, opt_hidden),
  744. OPT_ENDTABLE
  745. };
  746. static char *parse_config(json_t *config, bool fileconf)
  747. {
  748. static char err_buf[200];
  749. json_t *val;
  750. struct opt_table *opt;
  751. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  752. char *p, *name;
  753. /* We don't handle subtables. */
  754. assert(!(opt->type & OPT_SUBTABLE));
  755. /* Pull apart the option name(s). */
  756. name = strdup(opt->names);
  757. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  758. char *err = NULL;
  759. /* Ignore short options. */
  760. if (p[1] != '-')
  761. continue;
  762. val = json_object_get(config, p+2);
  763. if (!val)
  764. continue;
  765. if ((opt->type & OPT_HASARG) && json_is_string(val)) {
  766. err = opt->cb_arg(json_string_value(val),
  767. opt->u.arg);
  768. } else if ((opt->type & OPT_HASARG) && json_is_array(val)) {
  769. int n, size = json_array_size(val);
  770. for(n = 0; n < size && !err; n++) {
  771. if (json_is_string(json_array_get(val, n)))
  772. err = opt->cb_arg(json_string_value(json_array_get(val, n)), opt->u.arg);
  773. else if (json_is_object(json_array_get(val, n)))
  774. err = parse_config(json_array_get(val, n), false);
  775. }
  776. } else if ((opt->type&OPT_NOARG) && json_is_true(val)) {
  777. err = opt->cb(opt->u.arg);
  778. } else {
  779. err = "Invalid value";
  780. }
  781. if (err) {
  782. /* Allow invalid values to be in configuration
  783. * file, just skipping over them provided the
  784. * JSON is still valid after that. */
  785. if (fileconf)
  786. applog(LOG_ERR, "Invalid config option %s: %s", p, err);
  787. else {
  788. sprintf(err_buf, "Parsing JSON option %s: %s",
  789. p, err);
  790. return err_buf;
  791. }
  792. }
  793. }
  794. free(name);
  795. }
  796. return NULL;
  797. }
  798. static char *load_config(const char *arg, void __maybe_unused *unused)
  799. {
  800. json_error_t err;
  801. json_t *config;
  802. config = json_load_file(arg, 0, &err);
  803. if (!json_is_object(config))
  804. return "JSON decode of file failed";
  805. config_loaded = true;
  806. /* Parse the config now, so we can override it. That can keep pointers
  807. * so don't free config object. */
  808. return parse_config(config, true);
  809. }
  810. static void load_default_config(void)
  811. {
  812. char buf[PATH_MAX];
  813. #if defined(unix)
  814. strcpy(buf, getenv("HOME"));
  815. if (*buf)
  816. strcat(buf, "/");
  817. else
  818. strcpy(buf, "");
  819. strcat(buf, ".cgminer/");
  820. #else
  821. strcpy(buf, "");
  822. #endif
  823. strcat(buf, def_conf);
  824. if (!access(buf, R_OK))
  825. load_config(buf, NULL);
  826. }
  827. extern const char *opt_argv0;
  828. static char *opt_verusage_and_exit(const char *extra)
  829. {
  830. printf("%s\nBuilt with "
  831. #ifdef HAVE_OPENCL
  832. "GPU "
  833. #endif
  834. #ifdef WANT_CPUMINE
  835. "CPU "
  836. #endif
  837. #ifdef USE_BITFORCE
  838. "bitforce "
  839. #endif
  840. "mining support.\n"
  841. , packagename);
  842. printf("%s", opt_usage(opt_argv0, extra));
  843. fflush(stdout);
  844. exit(0);
  845. }
  846. /* These options are available from commandline only */
  847. static struct opt_table opt_cmdline_table[] = {
  848. OPT_WITH_ARG("--config|-c",
  849. load_config, NULL, NULL,
  850. "Load a JSON-format configuration file\n"
  851. "See example.conf for an example configuration."),
  852. OPT_WITHOUT_ARG("--help|-h",
  853. opt_verusage_and_exit, NULL,
  854. "Print this message"),
  855. #ifdef HAVE_OPENCL
  856. OPT_WITHOUT_ARG("--ndevs|-n",
  857. print_ndevs_and_exit, &nDevs,
  858. "Display number of detected GPUs, OpenCL platform information, and exit"),
  859. #endif
  860. OPT_WITHOUT_ARG("--version|-V",
  861. opt_version_and_exit, packagename,
  862. "Display version and exit"),
  863. OPT_ENDTABLE
  864. };
  865. static bool jobj_binary(const json_t *obj, const char *key,
  866. void *buf, size_t buflen, bool required)
  867. {
  868. const char *hexstr;
  869. json_t *tmp;
  870. tmp = json_object_get(obj, key);
  871. if (unlikely(!tmp)) {
  872. if (unlikely(required))
  873. applog(LOG_ERR, "JSON key '%s' not found", key);
  874. return false;
  875. }
  876. hexstr = json_string_value(tmp);
  877. if (unlikely(!hexstr)) {
  878. applog(LOG_ERR, "JSON key '%s' is not a string", key);
  879. return false;
  880. }
  881. if (!hex2bin(buf, hexstr, buflen))
  882. return false;
  883. return true;
  884. }
  885. static bool work_decode(const json_t *val, struct work *work)
  886. {
  887. if (unlikely(!jobj_binary(val, "data", work->data, sizeof(work->data), true))) {
  888. applog(LOG_ERR, "JSON inval data");
  889. goto err_out;
  890. }
  891. if (likely(!jobj_binary(val, "midstate",
  892. work->midstate, sizeof(work->midstate), false))) {
  893. // Calculate it ourselves
  894. union {
  895. unsigned char c[64];
  896. uint32_t i[16];
  897. } data;
  898. int swapcounter;
  899. for (swapcounter = 0; swapcounter < 16; swapcounter++)
  900. data.i[swapcounter] = swab32(((uint32_t*) (work->data))[swapcounter]);
  901. sha2_context ctx;
  902. sha2_starts( &ctx, 0 );
  903. sha2_update( &ctx, data.c, 64 );
  904. memcpy(work->midstate, ctx.state, sizeof(work->midstate));
  905. }
  906. if (likely(!jobj_binary(val, "hash1", work->hash1, sizeof(work->hash1), false))) {
  907. // Always the same anyway
  908. memcpy(work->hash1, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x80\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\1\0\0", 64);
  909. }
  910. if (unlikely(!jobj_binary(val, "target", work->target, sizeof(work->target), true))) {
  911. applog(LOG_ERR, "JSON inval target");
  912. goto err_out;
  913. }
  914. memset(work->hash, 0, sizeof(work->hash));
  915. #ifdef __BIG_ENDIAN__
  916. int swapcounter = 0;
  917. for (swapcounter = 0; swapcounter < 32; swapcounter++)
  918. (((uint32_t*) (work->data))[swapcounter]) = swab32(((uint32_t*) (work->data))[swapcounter]);
  919. for (swapcounter = 0; swapcounter < 16; swapcounter++)
  920. (((uint32_t*) (work->hash1))[swapcounter]) = swab32(((uint32_t*) (work->hash1))[swapcounter]);
  921. for (swapcounter = 0; swapcounter < 8; swapcounter++)
  922. (((uint32_t*) (work->midstate))[swapcounter]) = swab32(((uint32_t*) (work->midstate))[swapcounter]);
  923. for (swapcounter = 0; swapcounter < 8; swapcounter++)
  924. (((uint32_t*) (work->target))[swapcounter]) = swab32(((uint32_t*) (work->target))[swapcounter]);
  925. #endif
  926. gettimeofday(&work->tv_staged, NULL);
  927. return true;
  928. err_out:
  929. return false;
  930. }
  931. int dev_from_id(int thr_id)
  932. {
  933. return thr_info[thr_id].cgpu->device_id;
  934. }
  935. /* Make the change in the recent value adjust dynamically when the difference
  936. * is large, but damp it when the values are closer together. This allows the
  937. * value to change quickly, but not fluctuate too dramatically when it has
  938. * stabilised. */
  939. void decay_time(double *f, double fadd)
  940. {
  941. double ratio = 0;
  942. if (likely(*f > 0)) {
  943. ratio = fadd / *f;
  944. if (ratio > 1)
  945. ratio = 1 / ratio;
  946. }
  947. if (ratio > 0.9)
  948. *f = (fadd * 0.1 + *f) / 1.1;
  949. else
  950. *f = (fadd + *f * 0.1) / 1.1;
  951. }
  952. static int requests_staged(void)
  953. {
  954. int ret;
  955. mutex_lock(stgd_lock);
  956. ret = HASH_COUNT(staged_work);
  957. mutex_unlock(stgd_lock);
  958. return ret;
  959. }
  960. WINDOW *mainwin, *statuswin, *logwin;
  961. double total_secs = 0.1;
  962. static char statusline[256];
  963. static int devcursor, logstart, logcursor;
  964. struct cgpu_info gpus[MAX_GPUDEVICES]; /* Maximum number apparently possible */
  965. struct cgpu_info *cpus;
  966. static inline void unlock_curses(void)
  967. {
  968. mutex_unlock(&curses_lock);
  969. }
  970. static inline void lock_curses(void)
  971. {
  972. mutex_lock(&curses_lock);
  973. }
  974. static bool curses_active_locked(void)
  975. {
  976. bool ret;
  977. lock_curses();
  978. ret = curses_active;
  979. if (!ret)
  980. unlock_curses();
  981. return ret;
  982. }
  983. void tailsprintf(char *f, const char *fmt, ...)
  984. {
  985. va_list ap;
  986. va_start(ap, fmt);
  987. vsprintf(f + strlen(f), fmt, ap);
  988. va_end(ap);
  989. }
  990. static void get_statline(char *buf, struct cgpu_info *cgpu)
  991. {
  992. sprintf(buf, "%s%d ", cgpu->api->name, cgpu->device_id);
  993. if (cgpu->api->get_statline_before)
  994. cgpu->api->get_statline_before(buf, cgpu);
  995. tailsprintf(buf, "(%ds):%.1f (avg):%.1f Mh/s | A:%d R:%d HW:%d U:%.2f/m",
  996. opt_log_interval,
  997. cgpu->rolling,
  998. cgpu->total_mhashes / total_secs,
  999. cgpu->accepted,
  1000. cgpu->rejected,
  1001. cgpu->hw_errors,
  1002. cgpu->utility);
  1003. if (cgpu->api->get_statline)
  1004. cgpu->api->get_statline(buf, cgpu);
  1005. }
  1006. static void text_print_status(int thr_id)
  1007. {
  1008. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  1009. char logline[255];
  1010. if (cgpu) {
  1011. get_statline(logline, cgpu);
  1012. printf("%s\n", logline);
  1013. }
  1014. }
  1015. /* Must be called with curses mutex lock held and curses_active */
  1016. static void curses_print_status(void)
  1017. {
  1018. struct pool *pool = current_pool();
  1019. wattron(statuswin, A_BOLD);
  1020. mvwprintw(statuswin, 0, 0, " " PACKAGE " version " VERSION " - Started: %s", datestamp);
  1021. #ifdef WANT_CPUMINE
  1022. if (opt_n_threads)
  1023. wprintw(statuswin, " CPU Algo: %s", algo_names[opt_algo]);
  1024. #endif
  1025. wattroff(statuswin, A_BOLD);
  1026. mvwhline(statuswin, 1, 0, '-', 80);
  1027. mvwprintw(statuswin, 2, 0, " %s", statusline);
  1028. wclrtoeol(statuswin);
  1029. mvwprintw(statuswin, 3, 0, " TQ: %d ST: %d SS: %d DW: %d NB: %d LW: %d GF: %d RF: %d",
  1030. total_queued, requests_staged(), total_stale, total_discarded, new_blocks,
  1031. local_work, total_go, total_ro);
  1032. wclrtoeol(statuswin);
  1033. if (pool_strategy == POOL_LOADBALANCE && total_pools > 1)
  1034. mvwprintw(statuswin, 4, 0, " Connected to multiple pools with%s LP",
  1035. have_longpoll ? "": "out");
  1036. else
  1037. mvwprintw(statuswin, 4, 0, " Connected to %s with%s LP as user %s",
  1038. pool->rpc_url, have_longpoll ? "": "out", pool->rpc_user);
  1039. wclrtoeol(statuswin);
  1040. mvwprintw(statuswin, 5, 0, " Block: %s... Started: %s", current_hash, blocktime);
  1041. mvwhline(statuswin, 6, 0, '-', 80);
  1042. mvwhline(statuswin, logstart - 1, 0, '-', 80);
  1043. mvwprintw(statuswin, devcursor - 1, 1, "[P]ool management %s[S]ettings [D]isplay options [Q]uit",
  1044. have_opencl ? "[G]PU management " : "");
  1045. /* The window will be updated once we're done with all the devices */
  1046. wnoutrefresh(statuswin);
  1047. }
  1048. static void adj_width(int var, int *length)
  1049. {
  1050. if ((int)(log10(var) + 1) > *length)
  1051. (*length)++;
  1052. }
  1053. static void curses_print_devstatus(int thr_id)
  1054. {
  1055. static int awidth = 1, rwidth = 1, hwwidth = 1, uwidth = 1;
  1056. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  1057. char logline[255];
  1058. cgpu->utility = cgpu->accepted / ( total_secs ? total_secs : 1 ) * 60;
  1059. mvwprintw(statuswin, devcursor + cgpu->cgminer_id, 0, " %s %d: ", cgpu->api->name, cgpu->device_id);
  1060. if (cgpu->api->get_statline_before) {
  1061. logline[0] = '\0';
  1062. cgpu->api->get_statline_before(logline, cgpu);
  1063. wprintw(statuswin, "%s", logline);
  1064. }
  1065. if (cgpu->status == LIFE_DEAD)
  1066. wprintw(statuswin, "DEAD ");
  1067. else if (cgpu->status == LIFE_SICK)
  1068. wprintw(statuswin, "SICK ");
  1069. else if (!cgpu->enabled)
  1070. wprintw(statuswin, "OFF ");
  1071. else
  1072. wprintw(statuswin, "%5.1f", cgpu->rolling);
  1073. adj_width(cgpu->accepted, &awidth);
  1074. adj_width(cgpu->rejected, &rwidth);
  1075. adj_width(cgpu->hw_errors, &hwwidth);
  1076. adj_width(cgpu->utility, &uwidth);
  1077. wprintw(statuswin, "/%5.1fMh/s | A:%*d R:%*d HW:%*d U:%*.2f/m",
  1078. cgpu->total_mhashes / total_secs,
  1079. awidth, cgpu->accepted,
  1080. rwidth, cgpu->rejected,
  1081. hwwidth, cgpu->hw_errors,
  1082. uwidth + 3, cgpu->utility);
  1083. if (cgpu->api->get_statline) {
  1084. logline[0] = '\0';
  1085. cgpu->api->get_statline(logline, cgpu);
  1086. wprintw(statuswin, "%s", logline);
  1087. }
  1088. wclrtoeol(statuswin);
  1089. wnoutrefresh(statuswin);
  1090. }
  1091. static void print_status(int thr_id)
  1092. {
  1093. if (!curses_active)
  1094. text_print_status(thr_id);
  1095. }
  1096. /* Check for window resize. Called with curses mutex locked */
  1097. static inline bool change_logwinsize(void)
  1098. {
  1099. int x, y, logx, logy;
  1100. getmaxyx(mainwin, y, x);
  1101. getmaxyx(logwin, logy, logx);
  1102. y -= logcursor;
  1103. /* Detect screen size change */
  1104. if ((x != logx || y != logy) && x >= 80 && y >= 25) {
  1105. wresize(logwin, y, x);
  1106. return true;
  1107. }
  1108. return false;
  1109. }
  1110. /* For mandatory printing when mutex is already locked */
  1111. void wlog(const char *f, ...)
  1112. {
  1113. va_list ap;
  1114. va_start(ap, f);
  1115. vw_printw(logwin, f, ap);
  1116. va_end(ap);
  1117. }
  1118. /* Mandatory printing */
  1119. void wlogprint(const char *f, ...)
  1120. {
  1121. va_list ap;
  1122. if (curses_active_locked()) {
  1123. va_start(ap, f);
  1124. vw_printw(logwin, f, ap);
  1125. va_end(ap);
  1126. wrefresh(logwin);
  1127. unlock_curses();
  1128. }
  1129. }
  1130. void log_curses(int prio, const char *f, va_list ap)
  1131. {
  1132. if (opt_quiet && prio != LOG_ERR)
  1133. return;
  1134. if (curses_active_locked()) {
  1135. if (!opt_loginput || prio == LOG_ERR || prio == LOG_WARNING) {
  1136. vw_printw(logwin, f, ap);
  1137. wrefresh(logwin);
  1138. }
  1139. unlock_curses();
  1140. } else
  1141. vprintf(f, ap);
  1142. }
  1143. void clear_logwin(void)
  1144. {
  1145. if (curses_active_locked()) {
  1146. wclear(logwin);
  1147. wrefresh(logwin);
  1148. unlock_curses();
  1149. }
  1150. }
  1151. /* regenerate the full work->hash value and also return true if it's a block */
  1152. bool regeneratehash(const struct work *work)
  1153. {
  1154. uint32_t *data32 = (uint32_t *)(work->data);
  1155. unsigned char swap[128];
  1156. uint32_t *swap32 = (uint32_t *)swap;
  1157. unsigned char hash1[32];
  1158. uint32_t *hash32 = (uint32_t *)(work->hash);
  1159. uint32_t difficulty = 0;
  1160. uint32_t diffbytes = 0;
  1161. uint32_t diffvalue = 0;
  1162. uint32_t diffcmp[8];
  1163. int diffshift = 0;
  1164. int i;
  1165. for (i = 0; i < 80 / 4; i++)
  1166. swap32[i] = swab32(data32[i]);
  1167. sha2(swap, 80, hash1, false);
  1168. sha2(hash1, 32, (unsigned char *)(work->hash), false);
  1169. difficulty = swab32(*((uint32_t *)(work->data + 72)));
  1170. diffbytes = ((difficulty >> 24) & 0xff) - 3;
  1171. diffvalue = difficulty & 0x00ffffff;
  1172. diffshift = (diffbytes % 4) * 8;
  1173. if (diffshift == 0) {
  1174. diffshift = 32;
  1175. diffbytes--;
  1176. }
  1177. memset(diffcmp, 0, 32);
  1178. diffcmp[(diffbytes >> 2) + 1] = diffvalue >> (32 - diffshift);
  1179. diffcmp[diffbytes >> 2] = diffvalue << diffshift;
  1180. for (i = 7; i >= 0; i--) {
  1181. if (hash32[i] > diffcmp[i])
  1182. return false;
  1183. if (hash32[i] < diffcmp[i])
  1184. return true;
  1185. }
  1186. // https://en.bitcoin.it/wiki/Block says: "numerically below"
  1187. // https://en.bitcoin.it/wiki/Target says: "lower than or equal to"
  1188. // code in bitcoind 0.3.24 main.cpp CheckWork() says: if (hash > hashTarget) return false;
  1189. if (hash32[0] == diffcmp[0])
  1190. return true;
  1191. else
  1192. return false;
  1193. }
  1194. static bool submit_upstream_work(const struct work *work)
  1195. {
  1196. char *hexstr = NULL;
  1197. json_t *val, *res;
  1198. char s[345], sd[345];
  1199. bool rc = false;
  1200. int thr_id = work->thr_id;
  1201. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  1202. CURL *curl = curl_easy_init();
  1203. struct pool *pool = work->pool;
  1204. bool rolltime;
  1205. uint32_t *hash32;
  1206. char hashshow[64+1] = "";
  1207. bool isblock;
  1208. if (unlikely(!curl)) {
  1209. applog(LOG_ERR, "CURL initialisation failed");
  1210. return rc;
  1211. }
  1212. #ifdef __BIG_ENDIAN__
  1213. int swapcounter = 0;
  1214. for (swapcounter = 0; swapcounter < 32; swapcounter++)
  1215. (((uint32_t*) (work->data))[swapcounter]) = swab32(((uint32_t*) (work->data))[swapcounter]);
  1216. #endif
  1217. /* build hex string */
  1218. hexstr = bin2hex(work->data, sizeof(work->data));
  1219. if (unlikely(!hexstr)) {
  1220. applog(LOG_ERR, "submit_upstream_work OOM");
  1221. goto out_nofree;
  1222. }
  1223. /* build JSON-RPC request */
  1224. sprintf(s,
  1225. "{\"method\": \"getwork\", \"params\": [ \"%s\" ], \"id\":1}\r\n",
  1226. hexstr);
  1227. sprintf(sd,
  1228. "{\"method\": \"getwork\", \"params\": [ \"%s\" ], \"id\":1}",
  1229. hexstr);
  1230. if (opt_debug)
  1231. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->rpc_url, sd);
  1232. /* Force a fresh connection in case there are dead persistent
  1233. * connections to this pool */
  1234. if (pool_isset(pool, &pool->submit_fail))
  1235. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  1236. /* issue JSON-RPC request */
  1237. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, s, false, false, &rolltime, pool, true);
  1238. if (unlikely(!val)) {
  1239. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  1240. if (!pool_tset(pool, &pool->submit_fail)) {
  1241. total_ro++;
  1242. pool->remotefail_occasions++;
  1243. applog(LOG_WARNING, "Pool %d communication failure, caching submissions", pool->pool_no);
  1244. }
  1245. goto out;
  1246. } else if (pool_tclear(pool, &pool->submit_fail))
  1247. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  1248. res = json_object_get(val, "result");
  1249. if (!QUIET) {
  1250. isblock = regeneratehash(work);
  1251. if (isblock)
  1252. found_blocks++;
  1253. hash32 = (uint32_t *)(work->hash);
  1254. sprintf(hashshow, "%08lx.%08lx.%08lx%s",
  1255. (unsigned long)(hash32[7]), (unsigned long)(hash32[6]), (unsigned long)(hash32[5]),
  1256. isblock ? " BLOCK!" : "");
  1257. }
  1258. /* Theoretically threads could race when modifying accepted and
  1259. * rejected values but the chance of two submits completing at the
  1260. * same time is zero so there is no point adding extra locking */
  1261. if (json_is_true(res)) {
  1262. cgpu->accepted++;
  1263. total_accepted++;
  1264. pool->accepted++;
  1265. cgpu->last_share_pool = pool->pool_no;
  1266. cgpu->last_share_pool_time = time(NULL);
  1267. if (opt_debug)
  1268. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  1269. if (!QUIET) {
  1270. if (total_pools > 1)
  1271. applog(LOG_NOTICE, "Accepted %s %s %d thread %d pool %d",
  1272. hashshow, cgpu->api->name, cgpu->device_id, thr_id, work->pool->pool_no);
  1273. else
  1274. applog(LOG_NOTICE, "Accepted %s %s %d thread %d",
  1275. hashshow, cgpu->api->name, cgpu->device_id, thr_id);
  1276. }
  1277. if (opt_shares && total_accepted >= opt_shares) {
  1278. applog(LOG_WARNING, "Successfully mined %d accepted shares as requested and exiting.", opt_shares);
  1279. kill_work();
  1280. goto out;
  1281. }
  1282. } else {
  1283. cgpu->rejected++;
  1284. total_rejected++;
  1285. pool->rejected++;
  1286. if (opt_debug)
  1287. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  1288. if (!QUIET) {
  1289. if (total_pools > 1)
  1290. applog(LOG_NOTICE, "Rejected %s %s %d thread %d pool %d",
  1291. hashshow, cgpu->api->name, cgpu->device_id, thr_id, work->pool->pool_no);
  1292. else
  1293. applog(LOG_NOTICE, "Rejected %s %s %d thread %d",
  1294. hashshow, cgpu->api->name, cgpu->device_id, thr_id);
  1295. }
  1296. }
  1297. cgpu->utility = cgpu->accepted / ( total_secs ? total_secs : 1 ) * 60;
  1298. if (!opt_realquiet)
  1299. print_status(thr_id);
  1300. if (!want_per_device_stats) {
  1301. char logline[255];
  1302. get_statline(logline, cgpu);
  1303. applog(LOG_INFO, "%s", logline);
  1304. }
  1305. json_decref(val);
  1306. rc = true;
  1307. out:
  1308. free(hexstr);
  1309. out_nofree:
  1310. curl_easy_cleanup(curl);
  1311. return rc;
  1312. }
  1313. static const char *rpc_req =
  1314. "{\"method\": \"getwork\", \"params\": [], \"id\":0}\r\n";
  1315. /* Select any active pool in a rotating fashion when loadbalance is chosen */
  1316. static inline struct pool *select_pool(bool lagging)
  1317. {
  1318. static int rotating_pool = 0;
  1319. struct pool *pool, *cp;
  1320. cp = current_pool();
  1321. if (pool_strategy != POOL_LOADBALANCE && !lagging)
  1322. pool = cp;
  1323. else
  1324. pool = NULL;
  1325. while (!pool) {
  1326. if (++rotating_pool >= total_pools)
  1327. rotating_pool = 0;
  1328. pool = pools[rotating_pool];
  1329. if ((!pool->idle && pool->enabled) || pool == cp)
  1330. break;
  1331. pool = NULL;
  1332. }
  1333. return pool;
  1334. }
  1335. static bool get_upstream_work(struct work *work, bool lagging)
  1336. {
  1337. struct pool *pool;
  1338. json_t *val = NULL;
  1339. bool rc = false;
  1340. int retries = 0;
  1341. CURL *curl;
  1342. curl = curl_easy_init();
  1343. if (unlikely(!curl)) {
  1344. applog(LOG_ERR, "CURL initialisation failed");
  1345. return rc;
  1346. }
  1347. pool = select_pool(lagging);
  1348. if (opt_debug)
  1349. applog(LOG_DEBUG, "DBG: sending %s get RPC call: %s", pool->rpc_url, rpc_req);
  1350. retry:
  1351. /* A single failure response here might be reported as a dead pool and
  1352. * there may be temporary denied messages etc. falsely reporting
  1353. * failure so retry a few times before giving up */
  1354. while (!val && retries++ < 3) {
  1355. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  1356. false, false, &work->rolltime, pool, false);
  1357. }
  1358. if (unlikely(!val)) {
  1359. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  1360. goto out;
  1361. }
  1362. rc = work_decode(json_object_get(val, "result"), work);
  1363. if (!rc && retries < 3) {
  1364. /* Force a fresh connection in case there are dead persistent
  1365. * connections */
  1366. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  1367. goto retry;
  1368. }
  1369. work->pool = pool;
  1370. total_getworks++;
  1371. pool->getwork_requested++;
  1372. json_decref(val);
  1373. out:
  1374. curl_easy_cleanup(curl);
  1375. return rc;
  1376. }
  1377. static struct work *make_work(void)
  1378. {
  1379. struct work *work = calloc(1, sizeof(struct work));
  1380. if (unlikely(!work))
  1381. quit(1, "Failed to calloc work in make_work");
  1382. work->id = total_work++;
  1383. return work;
  1384. }
  1385. static void free_work(struct work *work)
  1386. {
  1387. free(work);
  1388. }
  1389. static void workio_cmd_free(struct workio_cmd *wc)
  1390. {
  1391. if (!wc)
  1392. return;
  1393. switch (wc->cmd) {
  1394. case WC_SUBMIT_WORK:
  1395. free_work(wc->u.work);
  1396. break;
  1397. default: /* do nothing */
  1398. break;
  1399. }
  1400. memset(wc, 0, sizeof(*wc)); /* poison */
  1401. free(wc);
  1402. }
  1403. static void disable_curses(void)
  1404. {
  1405. if (curses_active_locked()) {
  1406. curses_active = false;
  1407. leaveok(logwin, false);
  1408. leaveok(statuswin, false);
  1409. leaveok(mainwin, false);
  1410. nocbreak();
  1411. echo();
  1412. delwin(logwin);
  1413. delwin(statuswin);
  1414. delwin(mainwin);
  1415. endwin();
  1416. refresh();
  1417. #ifdef WIN32
  1418. // Move the cursor to after curses output.
  1419. HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
  1420. CONSOLE_SCREEN_BUFFER_INFO csbi;
  1421. COORD coord;
  1422. if (GetConsoleScreenBufferInfo(hout, &csbi)) {
  1423. coord.X = 0;
  1424. coord.Y = csbi.dwSize.Y - 1;
  1425. SetConsoleCursorPosition(hout, coord);
  1426. }
  1427. #endif
  1428. unlock_curses();
  1429. }
  1430. }
  1431. static void print_summary(void);
  1432. /* This should be the common exit path */
  1433. void kill_work(void)
  1434. {
  1435. struct thr_info *thr;
  1436. unsigned int i;
  1437. disable_curses();
  1438. applog(LOG_INFO, "Received kill message");
  1439. if (opt_debug)
  1440. applog(LOG_DEBUG, "Killing off watchpool thread");
  1441. /* Kill the watchpool thread */
  1442. thr = &thr_info[watchpool_thr_id];
  1443. thr_info_cancel(thr);
  1444. if (opt_debug)
  1445. applog(LOG_DEBUG, "Killing off watchdog thread");
  1446. /* Kill the watchdog thread */
  1447. thr = &thr_info[watchdog_thr_id];
  1448. thr_info_cancel(thr);
  1449. if (opt_debug)
  1450. applog(LOG_DEBUG, "Killing off mining threads");
  1451. /* Stop the mining threads*/
  1452. for (i = 0; i < mining_threads; i++) {
  1453. thr = &thr_info[i];
  1454. thr_info_cancel(thr);
  1455. }
  1456. if (opt_debug)
  1457. applog(LOG_DEBUG, "Killing off stage thread");
  1458. /* Stop the others */
  1459. thr = &thr_info[stage_thr_id];
  1460. thr_info_cancel(thr);
  1461. if (opt_debug)
  1462. applog(LOG_DEBUG, "Killing off longpoll thread");
  1463. thr = &thr_info[longpoll_thr_id];
  1464. if (have_longpoll)
  1465. thr_info_cancel(thr);
  1466. if (opt_debug)
  1467. applog(LOG_DEBUG, "Killing off API thread");
  1468. thr = &thr_info[api_thr_id];
  1469. thr_info_cancel(thr);
  1470. quit(0, "Shutdown signal received.");
  1471. }
  1472. void quit(int status, const char *format, ...);
  1473. static void sighandler(int sig)
  1474. {
  1475. /* Restore signal handlers so we can still quit if kill_work fails */
  1476. sigaction(SIGTERM, &termhandler, NULL);
  1477. sigaction(SIGINT, &inthandler, NULL);
  1478. kill_work();
  1479. }
  1480. static void *get_work_thread(void *userdata)
  1481. {
  1482. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  1483. struct work *ret_work;
  1484. int failures = 0;
  1485. pthread_detach(pthread_self());
  1486. ret_work = make_work();
  1487. if (wc->thr)
  1488. ret_work->thr = wc->thr;
  1489. else
  1490. ret_work->thr = NULL;
  1491. /* obtain new work from bitcoin via JSON-RPC */
  1492. while (!get_upstream_work(ret_work, wc->lagging)) {
  1493. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  1494. applog(LOG_ERR, "json_rpc_call failed, terminating workio thread");
  1495. free_work(ret_work);
  1496. kill_work();
  1497. goto out;
  1498. }
  1499. /* pause, then restart work-request loop */
  1500. applog(LOG_DEBUG, "json_rpc_call failed on get work, retry after %d seconds",
  1501. fail_pause);
  1502. sleep(fail_pause);
  1503. fail_pause += opt_fail_pause;
  1504. }
  1505. fail_pause = opt_fail_pause;
  1506. if (opt_debug)
  1507. applog(LOG_DEBUG, "Pushing work to requesting thread");
  1508. /* send work to requesting thread */
  1509. if (unlikely(!tq_push(thr_info[stage_thr_id].q, ret_work))) {
  1510. applog(LOG_ERR, "Failed to tq_push work in workio_get_work");
  1511. kill_work();
  1512. free_work(ret_work);
  1513. }
  1514. out:
  1515. workio_cmd_free(wc);
  1516. return NULL;
  1517. }
  1518. static bool workio_get_work(struct workio_cmd *wc)
  1519. {
  1520. pthread_t get_thread;
  1521. if (unlikely(pthread_create(&get_thread, NULL, get_work_thread, (void *)wc))) {
  1522. applog(LOG_ERR, "Failed to create get_work_thread");
  1523. return false;
  1524. }
  1525. return true;
  1526. }
  1527. static bool stale_work(struct work *work, bool share)
  1528. {
  1529. struct timeval now;
  1530. gettimeofday(&now, NULL);
  1531. if (share) {
  1532. if ((now.tv_sec - work->tv_staged.tv_sec) >= opt_expiry)
  1533. return true;
  1534. } else if ((now.tv_sec - work->tv_staged.tv_sec) >= opt_scantime)
  1535. return true;
  1536. if (work->work_block != work_block)
  1537. return true;
  1538. if (opt_fail_only && !share && work->pool != current_pool())
  1539. return true;
  1540. return false;
  1541. }
  1542. static void *submit_work_thread(void *userdata)
  1543. {
  1544. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  1545. struct work *work = wc->u.work;
  1546. struct pool *pool = work->pool;
  1547. int failures = 0;
  1548. pthread_detach(pthread_self());
  1549. if (stale_work(work, true)) {
  1550. total_stale++;
  1551. pool->stale_shares++;
  1552. if (!opt_submit_stale && !pool->submit_old) {
  1553. applog(LOG_NOTICE, "Stale share detected, discarding");
  1554. goto out;
  1555. }
  1556. if (opt_submit_stale)
  1557. applog(LOG_NOTICE, "Stale share detected, submitting as user requested");
  1558. else if (pool->submit_old)
  1559. applog(LOG_NOTICE, "Stale share detected, submitting as pool requested");
  1560. }
  1561. /* submit solution to bitcoin via JSON-RPC */
  1562. while (!submit_upstream_work(work)) {
  1563. if (!opt_submit_stale && stale_work(work, true)) {
  1564. applog(LOG_NOTICE, "Stale share detected, discarding");
  1565. total_stale++;
  1566. pool->stale_shares++;
  1567. break;
  1568. }
  1569. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  1570. applog(LOG_ERR, "Failed %d retries ...terminating workio thread", opt_retries);
  1571. kill_work();
  1572. break;
  1573. }
  1574. /* pause, then restart work-request loop */
  1575. applog(LOG_INFO, "json_rpc_call failed on submit_work, retry after %d seconds",
  1576. fail_pause);
  1577. sleep(fail_pause);
  1578. fail_pause += opt_fail_pause;
  1579. }
  1580. fail_pause = opt_fail_pause;
  1581. out:
  1582. workio_cmd_free(wc);
  1583. return NULL;
  1584. }
  1585. static bool workio_submit_work(struct workio_cmd *wc)
  1586. {
  1587. pthread_t submit_thread;
  1588. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, (void *)wc))) {
  1589. applog(LOG_ERR, "Failed to create submit_work_thread");
  1590. return false;
  1591. }
  1592. return true;
  1593. }
  1594. /* Find the pool that currently has the highest priority */
  1595. static struct pool *priority_pool(int choice)
  1596. {
  1597. struct pool *ret = NULL;
  1598. int i;
  1599. for (i = 0; i < total_pools; i++) {
  1600. struct pool *pool = pools[i];
  1601. if (pool->prio == choice) {
  1602. ret = pool;
  1603. break;
  1604. }
  1605. }
  1606. if (unlikely(!ret)) {
  1607. applog(LOG_ERR, "WTF No pool %d found!", choice);
  1608. return pools[choice];
  1609. }
  1610. return ret;
  1611. }
  1612. void switch_pools(struct pool *selected)
  1613. {
  1614. struct pool *pool, *last_pool;
  1615. int i, pool_no;
  1616. mutex_lock(&control_lock);
  1617. last_pool = currentpool;
  1618. pool_no = currentpool->pool_no;
  1619. /* Switch selected to pool number 0 and move the rest down */
  1620. if (selected) {
  1621. if (selected->prio != 0) {
  1622. for (i = 0; i < total_pools; i++) {
  1623. pool = pools[i];
  1624. if (pool->prio < selected->prio)
  1625. pool->prio++;
  1626. }
  1627. selected->prio = 0;
  1628. }
  1629. }
  1630. switch (pool_strategy) {
  1631. /* Both of these set to the master pool */
  1632. case POOL_FAILOVER:
  1633. case POOL_LOADBALANCE:
  1634. for (i = 0; i < total_pools; i++) {
  1635. pool = priority_pool(i);
  1636. if (!pool->idle && pool->enabled) {
  1637. pool_no = pool->pool_no;
  1638. break;
  1639. }
  1640. }
  1641. break;
  1642. /* Both of these simply increment and cycle */
  1643. case POOL_ROUNDROBIN:
  1644. case POOL_ROTATE:
  1645. if (selected) {
  1646. pool_no = selected->pool_no;
  1647. break;
  1648. }
  1649. pool_no++;
  1650. if (pool_no >= total_pools)
  1651. pool_no = 0;
  1652. break;
  1653. default:
  1654. break;
  1655. }
  1656. currentpool = pools[pool_no];
  1657. pool = currentpool;
  1658. mutex_unlock(&control_lock);
  1659. if (pool != last_pool)
  1660. applog(LOG_WARNING, "Switching to %s", pool->rpc_url);
  1661. /* Reset the queued amount to allow more to be queued for the new pool */
  1662. mutex_lock(&qd_lock);
  1663. total_queued = 0;
  1664. mutex_unlock(&qd_lock);
  1665. }
  1666. static void discard_work(struct work *work)
  1667. {
  1668. if (!work->clone && !work->rolls && !work->mined) {
  1669. if (work->pool)
  1670. work->pool->discarded_work++;
  1671. total_discarded++;
  1672. if (opt_debug)
  1673. applog(LOG_DEBUG, "Discarded work");
  1674. } else if (opt_debug)
  1675. applog(LOG_DEBUG, "Discarded cloned or rolled work");
  1676. free_work(work);
  1677. }
  1678. /* This is overkill, but at least we'll know accurately how much work is
  1679. * queued to prevent ever being left without work */
  1680. static void inc_queued(void)
  1681. {
  1682. mutex_lock(&qd_lock);
  1683. total_queued++;
  1684. mutex_unlock(&qd_lock);
  1685. }
  1686. static void dec_queued(void)
  1687. {
  1688. mutex_lock(&qd_lock);
  1689. if (total_queued > 0)
  1690. total_queued--;
  1691. mutex_unlock(&qd_lock);
  1692. }
  1693. static int requests_queued(void)
  1694. {
  1695. int ret;
  1696. mutex_lock(&qd_lock);
  1697. ret = total_queued;
  1698. mutex_unlock(&qd_lock);
  1699. return ret;
  1700. }
  1701. static int discard_stale(void)
  1702. {
  1703. struct work *work, *tmp;
  1704. int i, stale = 0;
  1705. mutex_lock(stgd_lock);
  1706. HASH_ITER(hh, staged_work, work, tmp) {
  1707. if (stale_work(work, false)) {
  1708. HASH_DEL(staged_work, work);
  1709. if (work->clone)
  1710. --staged_clones;
  1711. discard_work(work);
  1712. stale++;
  1713. }
  1714. }
  1715. mutex_unlock(stgd_lock);
  1716. if (opt_debug)
  1717. applog(LOG_DEBUG, "Discarded %d stales that didn't match current hash", stale);
  1718. /* Dec queued outside the loop to not have recursive locks */
  1719. for (i = 0; i < stale; i++)
  1720. dec_queued();
  1721. return stale;
  1722. }
  1723. static bool queue_request(struct thr_info *thr, bool needed);
  1724. static void restart_threads(void)
  1725. {
  1726. int i, stale;
  1727. /* Discard staged work that is now stale */
  1728. stale = discard_stale();
  1729. for (i = 0; i < stale; i++)
  1730. queue_request(NULL, true);
  1731. for (i = 0; i < mining_threads; i++)
  1732. work_restart[i].restart = 1;
  1733. }
  1734. static void set_curblock(char *hexstr, unsigned char *hash)
  1735. {
  1736. unsigned char hash_swap[32];
  1737. char *old_hash = NULL;
  1738. struct timeval tv_now;
  1739. /* Don't free current_hash directly to avoid dereferencing it when
  1740. * we might be accessing its data elsewhere */
  1741. if (current_hash)
  1742. old_hash = current_hash;
  1743. strcpy(current_block, hexstr);
  1744. gettimeofday(&tv_now, NULL);
  1745. get_timestamp(blocktime, &tv_now);
  1746. swap256(hash_swap, hash);
  1747. current_hash = bin2hex(hash_swap, 16);
  1748. if (unlikely(!current_hash))
  1749. quit (1, "set_curblock OOM");
  1750. if (old_hash)
  1751. free(old_hash);
  1752. }
  1753. /* Search to see if this string is from a block that has been seen before */
  1754. static bool block_exists(char *hexstr)
  1755. {
  1756. struct block *s;
  1757. rd_lock(&blk_lock);
  1758. HASH_FIND_STR(blocks, hexstr, s);
  1759. rd_unlock(&blk_lock);
  1760. if (s)
  1761. return true;
  1762. return false;
  1763. }
  1764. /* Tests if this work is from a block that has been seen before */
  1765. static inline bool from_existing_block(struct work *work)
  1766. {
  1767. char *hexstr = bin2hex(work->data, 18);
  1768. bool ret;
  1769. if (unlikely(!hexstr)) {
  1770. applog(LOG_ERR, "from_existing_block OOM");
  1771. return true;
  1772. }
  1773. ret = block_exists(hexstr);
  1774. free(hexstr);
  1775. return ret;
  1776. }
  1777. static void test_work_current(struct work *work, bool longpoll)
  1778. {
  1779. char *hexstr;
  1780. hexstr = bin2hex(work->data, 18);
  1781. if (unlikely(!hexstr)) {
  1782. applog(LOG_ERR, "stage_thread OOM");
  1783. return;
  1784. }
  1785. /* Search to see if this block exists yet and if not, consider it a
  1786. * new block and set the current block details to this one */
  1787. if (!block_exists(hexstr)) {
  1788. struct block *s = calloc(sizeof(struct block), 1);
  1789. if (unlikely(!s))
  1790. quit (1, "test_work_current OOM");
  1791. strcpy(s->hash, hexstr);
  1792. wr_lock(&blk_lock);
  1793. HASH_ADD_STR(blocks, hash, s);
  1794. wr_unlock(&blk_lock);
  1795. set_curblock(hexstr, work->data);
  1796. if (unlikely(++new_blocks == 1))
  1797. goto out_free;
  1798. work_block++;
  1799. if (longpoll)
  1800. applog(LOG_NOTICE, "LONGPOLL detected new block on network, waiting on fresh work");
  1801. else if (have_longpoll)
  1802. applog(LOG_NOTICE, "New block detected on network before longpoll, waiting on fresh work");
  1803. else
  1804. applog(LOG_NOTICE, "New block detected on network, waiting on fresh work");
  1805. restart_threads();
  1806. } else if (longpoll) {
  1807. applog(LOG_NOTICE, "LONGPOLL requested work restart, waiting on fresh work");
  1808. work_block++;
  1809. restart_threads();
  1810. }
  1811. out_free:
  1812. free(hexstr);
  1813. }
  1814. static int tv_sort(struct work *worka, struct work *workb)
  1815. {
  1816. return worka->tv_staged.tv_sec - workb->tv_staged.tv_sec;
  1817. }
  1818. static bool hash_push(struct work *work)
  1819. {
  1820. bool rc = true;
  1821. mutex_lock(stgd_lock);
  1822. if (likely(!getq->frozen)) {
  1823. HASH_ADD_INT(staged_work, id, work);
  1824. HASH_SORT(staged_work, tv_sort);
  1825. if (work->clone)
  1826. ++staged_clones;
  1827. } else
  1828. rc = false;
  1829. pthread_cond_signal(&getq->cond);
  1830. mutex_unlock(stgd_lock);
  1831. return rc;
  1832. }
  1833. static void *stage_thread(void *userdata)
  1834. {
  1835. struct thr_info *mythr = userdata;
  1836. bool ok = true;
  1837. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  1838. while (ok) {
  1839. struct work *work = NULL;
  1840. if (opt_debug)
  1841. applog(LOG_DEBUG, "Popping work to stage thread");
  1842. work = tq_pop(mythr->q, NULL);
  1843. if (unlikely(!work)) {
  1844. applog(LOG_ERR, "Failed to tq_pop in stage_thread");
  1845. ok = false;
  1846. break;
  1847. }
  1848. work->work_block = work_block;
  1849. test_work_current(work, false);
  1850. if (opt_debug)
  1851. applog(LOG_DEBUG, "Pushing work to getwork queue");
  1852. if (unlikely(!hash_push(work))) {
  1853. applog(LOG_WARNING, "Failed to hash_push in stage_thread");
  1854. continue;
  1855. }
  1856. }
  1857. tq_freeze(mythr->q);
  1858. return NULL;
  1859. }
  1860. static bool stage_work(struct work *work)
  1861. {
  1862. if (opt_debug)
  1863. applog(LOG_DEBUG, "Pushing work to stage thread");
  1864. if (unlikely(!tq_push(thr_info[stage_thr_id].q, work))) {
  1865. applog(LOG_ERR, "Could not tq_push work in stage_work");
  1866. return false;
  1867. }
  1868. return true;
  1869. }
  1870. int curses_int(const char *query)
  1871. {
  1872. int ret;
  1873. char *cvar;
  1874. cvar = curses_input(query);
  1875. ret = atoi(cvar);
  1876. free(cvar);
  1877. return ret;
  1878. }
  1879. static bool input_pool(bool live);
  1880. static int active_pools(void)
  1881. {
  1882. int ret = 0;
  1883. int i;
  1884. for (i = 0; i < total_pools; i++) {
  1885. if ((pools[i])->enabled)
  1886. ret++;
  1887. }
  1888. return ret;
  1889. }
  1890. static void display_pool_summary(struct pool *pool)
  1891. {
  1892. double efficiency = 0.0;
  1893. if (curses_active_locked()) {
  1894. wlog("Pool: %s\n", pool->rpc_url);
  1895. wlog("%s long-poll support\n", pool->hdr_path ? "Has" : "Does not have");
  1896. wlog(" Queued work requests: %d\n", pool->getwork_requested);
  1897. wlog(" Share submissions: %d\n", pool->accepted + pool->rejected);
  1898. wlog(" Accepted shares: %d\n", pool->accepted);
  1899. wlog(" Rejected shares: %d\n", pool->rejected);
  1900. if (pool->accepted || pool->rejected)
  1901. wlog(" Reject ratio: %.1f%%\n", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  1902. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  1903. wlog(" Efficiency (accepted / queued): %.0f%%\n", efficiency);
  1904. wlog(" Discarded work due to new blocks: %d\n", pool->discarded_work);
  1905. wlog(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  1906. wlog(" Unable to get work from server occasions: %d\n", pool->getfail_occasions);
  1907. wlog(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  1908. wrefresh(logwin);
  1909. unlock_curses();
  1910. }
  1911. }
  1912. /* We can't remove the memory used for this struct pool because there may
  1913. * still be work referencing it. We just remove it from the pools list */
  1914. static void remove_pool(struct pool *pool)
  1915. {
  1916. int i, last_pool = total_pools - 1;
  1917. struct pool *other;
  1918. /* Boost priority of any lower prio than this one */
  1919. for (i = 0; i < total_pools; i++) {
  1920. other = pools[i];
  1921. if (other->prio > pool->prio)
  1922. other->prio--;
  1923. }
  1924. if (pool->pool_no < last_pool) {
  1925. /* Swap the last pool for this one */
  1926. (pools[last_pool])->pool_no = pool->pool_no;
  1927. pools[pool->pool_no] = pools[last_pool];
  1928. }
  1929. /* Give it an invalid number */
  1930. pool->pool_no = total_pools;
  1931. total_pools--;
  1932. }
  1933. void write_config(FILE *fcfg)
  1934. {
  1935. int i;
  1936. /* Write pool values */
  1937. fputs("{\n\"pools\" : [", fcfg);
  1938. for(i = 0; i < total_pools; i++) {
  1939. fprintf(fcfg, "%s\n\t{\n\t\t\"url\" : \"%s\",", i > 0 ? "," : "", pools[i]->rpc_url);
  1940. fprintf(fcfg, "\n\t\t\"user\" : \"%s\",", pools[i]->rpc_user);
  1941. fprintf(fcfg, "\n\t\t\"pass\" : \"%s\"\n\t}", pools[i]->rpc_pass);
  1942. }
  1943. fputs("\n],\n\n", fcfg);
  1944. if (nDevs) {
  1945. /* Write GPU device values */
  1946. fputs("\"intensity\" : \"", fcfg);
  1947. for(i = 0; i < nDevs; i++)
  1948. fprintf(fcfg, gpus[i].dynamic ? "%sd" : "%s%d", i > 0 ? "," : "", gpus[i].intensity);
  1949. #ifdef HAVE_ADL
  1950. fputs("\",\n\"gpu-engine\" : \"", fcfg);
  1951. for(i = 0; i < nDevs; i++)
  1952. fprintf(fcfg, "%s%d-%d", i > 0 ? "," : "", gpus[i].min_engine, gpus[i].gpu_engine);
  1953. fputs("\",\n\"gpu-fan\" : \"", fcfg);
  1954. for(i = 0; i < nDevs; i++)
  1955. fprintf(fcfg, "%s%d-%d", i > 0 ? "," : "", gpus[i].min_fan, gpus[i].gpu_fan);
  1956. fputs("\",\n\"gpu-memclock\" : \"", fcfg);
  1957. for(i = 0; i < nDevs; i++)
  1958. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_memclock);
  1959. fputs("\",\n\"gpu-memdiff\" : \"", fcfg);
  1960. for(i = 0; i < nDevs; i++)
  1961. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_memdiff);
  1962. fputs("\",\n\"gpu-powertune\" : \"", fcfg);
  1963. for(i = 0; i < nDevs; i++)
  1964. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_powertune);
  1965. fputs("\",\n\"gpu-vddc\" : \"", fcfg);
  1966. for(i = 0; i < nDevs; i++)
  1967. fprintf(fcfg, "%s%1.3f", i > 0 ? "," : "", gpus[i].gpu_vddc);
  1968. fputs("\",\n\"temp-cutoff\" : \"", fcfg);
  1969. for(i = 0; i < nDevs; i++)
  1970. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].cutofftemp);
  1971. fputs("\",\n\"temp-overheat\" : \"", fcfg);
  1972. for(i = 0; i < nDevs; i++)
  1973. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].adl.overtemp);
  1974. fputs("\",\n\"temp-target\" : \"", fcfg);
  1975. for(i = 0; i < nDevs; i++)
  1976. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].adl.targettemp);
  1977. #endif
  1978. fputs("\"", fcfg);
  1979. #ifdef WANT_CPUMINE
  1980. fputs(",\n", fcfg);
  1981. #endif
  1982. }
  1983. #ifdef HAVE_ADL
  1984. if (opt_reorder)
  1985. fprintf(fcfg, ",\n\"gpu-reorder\" : true");
  1986. #endif
  1987. #ifdef WANT_CPUMINE
  1988. fprintf(fcfg, "\n\"algo\" : \"%s\"", algo_names[opt_algo]);
  1989. #endif
  1990. /* Simple bool and int options */
  1991. struct opt_table *opt;
  1992. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  1993. char *p, *name = strdup(opt->names);
  1994. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  1995. if (p[1] != '-')
  1996. continue;
  1997. if (opt->type & OPT_NOARG &&
  1998. ((void *)opt->cb == (void *)opt_set_bool || (void *)opt->cb == (void *)opt_set_invbool) &&
  1999. (*(bool *)opt->u.arg == ((void *)opt->cb == (void *)opt_set_bool)))
  2000. fprintf(fcfg, ",\n\"%s\" : true", p+2);
  2001. if (opt->type & OPT_HASARG &&
  2002. ((void *)opt->cb_arg == (void *)set_int_0_to_9999 ||
  2003. (void *)opt->cb_arg == (void *)set_int_1_to_65535 ||
  2004. (void *)opt->cb_arg == (void *)set_int_0_to_10 ||
  2005. (void *)opt->cb_arg == (void *)set_int_1_to_10) && opt->desc != opt_hidden)
  2006. fprintf(fcfg, ",\n\"%s\" : \"%d\"", p+2, *(int *)opt->u.arg);
  2007. }
  2008. }
  2009. /* Special case options */
  2010. fprintf(fcfg, ",\n\"shares\" : \"%d\"", opt_shares);
  2011. if (pool_strategy == POOL_LOADBALANCE)
  2012. fputs(",\n\"load-balance\" : true", fcfg);
  2013. if (pool_strategy == POOL_ROUNDROBIN)
  2014. fputs(",\n\"round-robin\" : true", fcfg);
  2015. if (pool_strategy == POOL_ROTATE)
  2016. fprintf(fcfg, ",\n\"rotate\" : \"%d\"", opt_rotate_period);
  2017. #if defined(unix)
  2018. if (opt_stderr_cmd && *opt_stderr_cmd)
  2019. fprintf(fcfg, ",\n\"monitor\" : \"%s\"", opt_stderr_cmd);
  2020. #endif // defined(unix)
  2021. if (opt_kernel && *opt_kernel)
  2022. fprintf(fcfg, ",\n\"kernel\" : \"%s\"", opt_kernel);
  2023. if (opt_kernel_path && *opt_kernel_path) {
  2024. char *kpath = strdup(opt_kernel_path);
  2025. if (kpath[strlen(kpath)-1] == '/')
  2026. kpath[strlen(kpath)-1] = 0;
  2027. fprintf(fcfg, ",\n\"kernel-path\" : \"%s\"", kpath);
  2028. }
  2029. if (schedstart.enable)
  2030. fprintf(fcfg, ",\n\"sched-time\" : \"%d:%d\"", schedstart.tm.tm_hour, schedstart.tm.tm_min);
  2031. if (schedstop.enable)
  2032. fprintf(fcfg, ",\n\"stop-time\" : \"%d:%d\"", schedstop.tm.tm_hour, schedstop.tm.tm_min);
  2033. if (opt_socks_proxy && *opt_socks_proxy)
  2034. fprintf(fcfg, ",\n\"socks-proxy\" : \"%s\"", opt_socks_proxy);
  2035. for(i = 0; i < nDevs; i++)
  2036. if (!gpus[i].enabled)
  2037. break;
  2038. if (i < nDevs)
  2039. for (i = 0; i < nDevs; i++)
  2040. if (gpus[i].enabled)
  2041. fprintf(fcfg, ",\n\"device\" : \"%d\"", i);
  2042. if (opt_api_allow != NULL)
  2043. fprintf(fcfg, ",\n\"api-allow\" : \"%s\"", opt_api_allow);
  2044. if (strcmp(opt_api_description, PACKAGE_STRING) != 0)
  2045. fprintf(fcfg, ",\n\"api-description\" : \"%s\"", opt_api_description);
  2046. fputs("\n}", fcfg);
  2047. }
  2048. static void display_pools(void)
  2049. {
  2050. struct pool *pool;
  2051. int selected, i;
  2052. char input;
  2053. opt_loginput = true;
  2054. immedok(logwin, true);
  2055. clear_logwin();
  2056. updated:
  2057. for (i = 0; i < total_pools; i++) {
  2058. pool = pools[i];
  2059. if (pool == current_pool())
  2060. wattron(logwin, A_BOLD);
  2061. if (!pool->enabled)
  2062. wattron(logwin, A_DIM);
  2063. wlogprint("%d: %s %s Priority %d: %s User:%s\n",
  2064. pool->pool_no,
  2065. pool->enabled? "Enabled" : "Disabled",
  2066. pool->idle? "Dead" : "Alive",
  2067. pool->prio,
  2068. pool->rpc_url, pool->rpc_user);
  2069. wattroff(logwin, A_BOLD | A_DIM);
  2070. }
  2071. retry:
  2072. wlogprint("\nCurrent pool management strategy: %s\n",
  2073. strategies[pool_strategy]);
  2074. if (pool_strategy == POOL_ROTATE)
  2075. wlogprint("Set to rotate every %d minutes\n", opt_rotate_period);
  2076. wlogprint("[A]dd pool [R]emove pool [D]isable pool [E]nable pool\n");
  2077. wlogprint("[C]hange management strategy [S]witch pool [I]nformation\n");
  2078. wlogprint("Or press any other key to continue\n");
  2079. input = getch();
  2080. if (!strncasecmp(&input, "a", 1)) {
  2081. input_pool(true);
  2082. goto updated;
  2083. } else if (!strncasecmp(&input, "r", 1)) {
  2084. if (total_pools <= 1) {
  2085. wlogprint("Cannot remove last pool");
  2086. goto retry;
  2087. }
  2088. selected = curses_int("Select pool number");
  2089. if (selected < 0 || selected >= total_pools) {
  2090. wlogprint("Invalid selection\n");
  2091. goto retry;
  2092. }
  2093. pool = pools[selected];
  2094. if (pool == current_pool())
  2095. switch_pools(NULL);
  2096. if (pool == current_pool()) {
  2097. wlogprint("Unable to remove pool due to activity\n");
  2098. goto retry;
  2099. }
  2100. pool->enabled = false;
  2101. remove_pool(pool);
  2102. goto updated;
  2103. } else if (!strncasecmp(&input, "s", 1)) {
  2104. selected = curses_int("Select pool number");
  2105. if (selected < 0 || selected >= total_pools) {
  2106. wlogprint("Invalid selection\n");
  2107. goto retry;
  2108. }
  2109. pool = pools[selected];
  2110. pool->enabled = true;
  2111. switch_pools(pool);
  2112. goto updated;
  2113. } else if (!strncasecmp(&input, "d", 1)) {
  2114. if (active_pools() <= 1) {
  2115. wlogprint("Cannot disable last pool");
  2116. goto retry;
  2117. }
  2118. selected = curses_int("Select pool number");
  2119. if (selected < 0 || selected >= total_pools) {
  2120. wlogprint("Invalid selection\n");
  2121. goto retry;
  2122. }
  2123. pool = pools[selected];
  2124. pool->enabled = false;
  2125. if (pool == current_pool())
  2126. switch_pools(NULL);
  2127. goto updated;
  2128. } else if (!strncasecmp(&input, "e", 1)) {
  2129. selected = curses_int("Select pool number");
  2130. if (selected < 0 || selected >= total_pools) {
  2131. wlogprint("Invalid selection\n");
  2132. goto retry;
  2133. }
  2134. pool = pools[selected];
  2135. pool->enabled = true;
  2136. if (pool->prio < current_pool()->prio)
  2137. switch_pools(pool);
  2138. goto updated;
  2139. } else if (!strncasecmp(&input, "c", 1)) {
  2140. for (i = 0; i <= TOP_STRATEGY; i++)
  2141. wlogprint("%d: %s\n", i, strategies[i]);
  2142. selected = curses_int("Select strategy number type");
  2143. if (selected < 0 || selected > TOP_STRATEGY) {
  2144. wlogprint("Invalid selection\n");
  2145. goto retry;
  2146. }
  2147. if (selected == POOL_ROTATE) {
  2148. opt_rotate_period = curses_int("Select interval in minutes");
  2149. if (opt_rotate_period < 0 || opt_rotate_period > 9999) {
  2150. opt_rotate_period = 0;
  2151. wlogprint("Invalid selection\n");
  2152. goto retry;
  2153. }
  2154. }
  2155. pool_strategy = selected;
  2156. switch_pools(NULL);
  2157. goto updated;
  2158. } else if (!strncasecmp(&input, "i", 1)) {
  2159. selected = curses_int("Select pool number");
  2160. if (selected < 0 || selected >= total_pools) {
  2161. wlogprint("Invalid selection\n");
  2162. goto retry;
  2163. }
  2164. pool = pools[selected];
  2165. display_pool_summary(pool);
  2166. goto retry;
  2167. } else
  2168. clear_logwin();
  2169. immedok(logwin, false);
  2170. opt_loginput = false;
  2171. }
  2172. static void display_options(void)
  2173. {
  2174. int selected;
  2175. char input;
  2176. opt_loginput = true;
  2177. immedok(logwin, true);
  2178. clear_logwin();
  2179. retry:
  2180. wlogprint("[N]ormal [C]lear [S]ilent mode (disable all output)\n");
  2181. wlogprint("[D]ebug:%s\n[P]er-device:%s\n[Q]uiet:%s\n[V]erbose:%s\n[R]PC debug:%s\n[L]og interval:%d\n",
  2182. opt_debug ? "on" : "off",
  2183. want_per_device_stats? "on" : "off",
  2184. opt_quiet ? "on" : "off",
  2185. opt_log_output ? "on" : "off",
  2186. opt_protocol ? "on" : "off",
  2187. opt_log_interval);
  2188. wlogprint("Select an option or any other key to return\n");
  2189. input = getch();
  2190. if (!strncasecmp(&input, "q", 1)) {
  2191. opt_quiet ^= true;
  2192. wlogprint("Quiet mode %s\n", opt_quiet ? "enabled" : "disabled");
  2193. goto retry;
  2194. } else if (!strncasecmp(&input, "v", 1)) {
  2195. opt_log_output ^= true;
  2196. if (opt_log_output)
  2197. opt_quiet = false;
  2198. wlogprint("Verbose mode %s\n", opt_log_output ? "enabled" : "disabled");
  2199. goto retry;
  2200. } else if (!strncasecmp(&input, "n", 1)) {
  2201. opt_log_output = false;
  2202. opt_debug = false;
  2203. opt_quiet = false;
  2204. opt_protocol = false;
  2205. want_per_device_stats = false;
  2206. wlogprint("Output mode reset to normal\n");
  2207. goto retry;
  2208. } else if (!strncasecmp(&input, "d", 1)) {
  2209. opt_debug ^= true;
  2210. opt_log_output = opt_debug;
  2211. if (opt_debug)
  2212. opt_quiet = false;
  2213. wlogprint("Debug mode %s\n", opt_debug ? "enabled" : "disabled");
  2214. goto retry;
  2215. } else if (!strncasecmp(&input, "p", 1)) {
  2216. want_per_device_stats ^= true;
  2217. opt_log_output = want_per_device_stats;
  2218. wlogprint("Per-device stats %s\n", want_per_device_stats ? "enabled" : "disabled");
  2219. goto retry;
  2220. } else if (!strncasecmp(&input, "r", 1)) {
  2221. opt_protocol ^= true;
  2222. if (opt_protocol)
  2223. opt_quiet = false;
  2224. wlogprint("RPC protocol debugging %s\n", opt_protocol ? "enabled" : "disabled");
  2225. goto retry;
  2226. } else if (!strncasecmp(&input, "c", 1))
  2227. clear_logwin();
  2228. else if (!strncasecmp(&input, "l", 1)) {
  2229. selected = curses_int("Interval in seconds");
  2230. if (selected < 0 || selected > 9999) {
  2231. wlogprint("Invalid selection\n");
  2232. goto retry;
  2233. }
  2234. opt_log_interval = selected;
  2235. wlogprint("Log interval set to %d seconds\n", opt_log_interval);
  2236. goto retry;
  2237. } else if (!strncasecmp(&input, "s", 1)) {
  2238. opt_realquiet = true;
  2239. } else
  2240. clear_logwin();
  2241. immedok(logwin, false);
  2242. opt_loginput = false;
  2243. }
  2244. static void start_longpoll(void);
  2245. static void stop_longpoll(void);
  2246. static void set_options(void)
  2247. {
  2248. int selected;
  2249. char input;
  2250. opt_loginput = true;
  2251. immedok(logwin, true);
  2252. clear_logwin();
  2253. retry:
  2254. wlogprint("\n[L]ongpoll: %s\n", want_longpoll ? "On" : "Off");
  2255. wlogprint("[Q]ueue: %d\n[S]cantime: %d\n[E]xpiry: %d\n[R]etries: %d\n[P]ause: %d\n[W]rite config file\n",
  2256. opt_queue, opt_scantime, opt_expiry, opt_retries, opt_fail_pause);
  2257. wlogprint("Select an option or any other key to return\n");
  2258. input = getch();
  2259. if (!strncasecmp(&input, "q", 1)) {
  2260. selected = curses_int("Extra work items to queue");
  2261. if (selected < 0 || selected > 9999) {
  2262. wlogprint("Invalid selection\n");
  2263. goto retry;
  2264. }
  2265. opt_queue = selected;
  2266. goto retry;
  2267. } else if (!strncasecmp(&input, "l", 1)) {
  2268. want_longpoll ^= true;
  2269. applog(LOG_WARNING, "Longpoll %s", want_longpoll ? "enabled" : "disabled");
  2270. if (!want_longpoll) {
  2271. if (have_longpoll)
  2272. stop_longpoll();
  2273. } else
  2274. start_longpoll();
  2275. goto retry;
  2276. } else if (!strncasecmp(&input, "s", 1)) {
  2277. selected = curses_int("Set scantime in seconds");
  2278. if (selected < 0 || selected > 9999) {
  2279. wlogprint("Invalid selection\n");
  2280. goto retry;
  2281. }
  2282. opt_scantime = selected;
  2283. goto retry;
  2284. } else if (!strncasecmp(&input, "e", 1)) {
  2285. selected = curses_int("Set expiry time in seconds");
  2286. if (selected < 0 || selected > 9999) {
  2287. wlogprint("Invalid selection\n");
  2288. goto retry;
  2289. }
  2290. opt_expiry = selected;
  2291. goto retry;
  2292. } else if (!strncasecmp(&input, "r", 1)) {
  2293. selected = curses_int("Retries before failing (-1 infinite)");
  2294. if (selected < -1 || selected > 9999) {
  2295. wlogprint("Invalid selection\n");
  2296. goto retry;
  2297. }
  2298. opt_retries = selected;
  2299. goto retry;
  2300. } else if (!strncasecmp(&input, "p", 1)) {
  2301. selected = curses_int("Seconds to pause before network retries");
  2302. if (selected < 1 || selected > 9999) {
  2303. wlogprint("Invalid selection\n");
  2304. goto retry;
  2305. }
  2306. opt_fail_pause = selected;
  2307. goto retry;
  2308. } else if (!strncasecmp(&input, "w", 1)) {
  2309. FILE *fcfg;
  2310. char *str, filename[PATH_MAX], prompt[PATH_MAX + 50];
  2311. #if defined(unix)
  2312. strcpy(filename, getenv("HOME"));
  2313. if (*filename)
  2314. strcat(filename, "/");
  2315. else
  2316. strcpy(filename, "");
  2317. strcat(filename, ".cgminer/");
  2318. mkdir(filename, 0777);
  2319. #else
  2320. strcpy(filename, "");
  2321. #endif
  2322. strcat(filename, def_conf);
  2323. sprintf(prompt, "Config filename to write (Enter for default) [%s]", filename);
  2324. str = curses_input(prompt);
  2325. if (strcmp(str, "-1")) {
  2326. struct stat statbuf;
  2327. strcpy(filename, str);
  2328. if (!stat(filename, &statbuf)) {
  2329. wlogprint("File exists, overwrite?\n");
  2330. input = getch();
  2331. if (strncasecmp(&input, "y", 1))
  2332. goto retry;
  2333. }
  2334. }
  2335. fcfg = fopen(filename, "w");
  2336. if (!fcfg) {
  2337. wlogprint("Cannot open or create file\n");
  2338. goto retry;
  2339. }
  2340. write_config(fcfg);
  2341. fclose(fcfg);
  2342. goto retry;
  2343. } else
  2344. clear_logwin();
  2345. immedok(logwin, false);
  2346. opt_loginput = false;
  2347. }
  2348. static void *input_thread(void __maybe_unused *userdata)
  2349. {
  2350. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2351. if (!curses_active)
  2352. return NULL;
  2353. while (1) {
  2354. char input;
  2355. input = getch();
  2356. if (!strncasecmp(&input, "q", 1)) {
  2357. kill_work();
  2358. return NULL;
  2359. } else if (!strncasecmp(&input, "d", 1))
  2360. display_options();
  2361. else if (!strncasecmp(&input, "p", 1))
  2362. display_pools();
  2363. else if (!strncasecmp(&input, "s", 1))
  2364. set_options();
  2365. else if (have_opencl && !strncasecmp(&input, "g", 1))
  2366. manage_gpu();
  2367. if (opt_realquiet) {
  2368. disable_curses();
  2369. break;
  2370. }
  2371. }
  2372. return NULL;
  2373. }
  2374. /* This thread should not be shut down unless a problem occurs */
  2375. static void *workio_thread(void *userdata)
  2376. {
  2377. struct thr_info *mythr = userdata;
  2378. bool ok = true;
  2379. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2380. while (ok) {
  2381. struct workio_cmd *wc;
  2382. if (opt_debug)
  2383. applog(LOG_DEBUG, "Popping work to work thread");
  2384. /* wait for workio_cmd sent to us, on our queue */
  2385. wc = tq_pop(mythr->q, NULL);
  2386. if (unlikely(!wc)) {
  2387. applog(LOG_ERR, "Failed to tq_pop in workio_thread");
  2388. ok = false;
  2389. break;
  2390. }
  2391. /* process workio_cmd */
  2392. switch (wc->cmd) {
  2393. case WC_GET_WORK:
  2394. ok = workio_get_work(wc);
  2395. break;
  2396. case WC_SUBMIT_WORK:
  2397. ok = workio_submit_work(wc);
  2398. break;
  2399. default:
  2400. ok = false;
  2401. break;
  2402. }
  2403. }
  2404. tq_freeze(mythr->q);
  2405. return NULL;
  2406. }
  2407. static void *api_thread(void *userdata)
  2408. {
  2409. struct thr_info *mythr = userdata;
  2410. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2411. api();
  2412. PTH(mythr) = 0L;
  2413. return NULL;
  2414. }
  2415. void thread_reportin(struct thr_info *thr)
  2416. {
  2417. gettimeofday(&thr->last, NULL);
  2418. thr->cgpu->status = LIFE_WELL;
  2419. thr->getwork = false;
  2420. }
  2421. static inline void thread_reportout(struct thr_info *thr)
  2422. {
  2423. thr->getwork = true;
  2424. }
  2425. static void hashmeter(int thr_id, struct timeval *diff,
  2426. unsigned long hashes_done)
  2427. {
  2428. struct timeval temp_tv_end, total_diff;
  2429. double secs;
  2430. double local_secs;
  2431. double utility, efficiency = 0.0;
  2432. static double local_mhashes_done = 0;
  2433. static double rolling = 0;
  2434. double local_mhashes = (double)hashes_done / 1000000.0;
  2435. bool showlog = false;
  2436. /* Update the last time this thread reported in */
  2437. if (thr_id >= 0)
  2438. gettimeofday(&thr_info[thr_id].last, NULL);
  2439. /* Don't bother calculating anything if we're not displaying it */
  2440. if (opt_realquiet || !opt_log_interval)
  2441. return;
  2442. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  2443. /* So we can call hashmeter from a non worker thread */
  2444. if (thr_id >= 0) {
  2445. struct thr_info *thr = &thr_info[thr_id];
  2446. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  2447. double thread_rolling = 0.0;
  2448. int i;
  2449. if (opt_debug)
  2450. applog(LOG_DEBUG, "[thread %d: %lu hashes, %.0f khash/sec]",
  2451. thr_id, hashes_done, hashes_done / secs);
  2452. /* Rolling average for each thread and each device */
  2453. decay_time(&thr->rolling, local_mhashes / secs);
  2454. for (i = 0; i < mining_threads; i++) {
  2455. struct thr_info *th = &thr_info[i];
  2456. if (th->cgpu == cgpu)
  2457. thread_rolling += th->rolling;
  2458. }
  2459. decay_time(&cgpu->rolling, thread_rolling);
  2460. cgpu->total_mhashes += local_mhashes;
  2461. // If needed, output detailed, per-device stats
  2462. if (want_per_device_stats) {
  2463. struct timeval now;
  2464. struct timeval elapsed;
  2465. gettimeofday(&now, NULL);
  2466. timeval_subtract(&elapsed, &now, &thr->cgpu->last_message_tv);
  2467. if (opt_log_interval <= elapsed.tv_sec) {
  2468. struct cgpu_info *cgpu = thr->cgpu;
  2469. char logline[255];
  2470. cgpu->last_message_tv = now;
  2471. get_statline(logline, cgpu);
  2472. if (!curses_active) {
  2473. printf("%s \r", logline);
  2474. fflush(stdout);
  2475. } else
  2476. applog(LOG_INFO, "%s", logline);
  2477. }
  2478. }
  2479. }
  2480. /* Totals are updated by all threads so can race without locking */
  2481. mutex_lock(&hash_lock);
  2482. gettimeofday(&temp_tv_end, NULL);
  2483. timeval_subtract(&total_diff, &temp_tv_end, &total_tv_end);
  2484. total_mhashes_done += local_mhashes;
  2485. local_mhashes_done += local_mhashes;
  2486. if (total_diff.tv_sec < opt_log_interval)
  2487. /* Only update the total every opt_log_interval seconds */
  2488. goto out_unlock;
  2489. showlog = true;
  2490. gettimeofday(&total_tv_end, NULL);
  2491. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  2492. decay_time(&rolling, local_mhashes_done / local_secs);
  2493. timeval_subtract(&total_diff, &total_tv_end, &total_tv_start);
  2494. total_secs = (double)total_diff.tv_sec +
  2495. ((double)total_diff.tv_usec / 1000000.0);
  2496. utility = total_accepted / ( total_secs ? total_secs : 1 ) * 60;
  2497. efficiency = total_getworks ? total_accepted * 100.0 / total_getworks : 0.0;
  2498. sprintf(statusline, "%s(%ds):%.1f (avg):%.1f Mh/s | Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m",
  2499. want_per_device_stats ? "ALL " : "",
  2500. opt_log_interval, rolling, total_mhashes_done / total_secs,
  2501. total_getworks, total_accepted, total_rejected, hw_errors, efficiency, utility);
  2502. local_mhashes_done = 0;
  2503. out_unlock:
  2504. mutex_unlock(&hash_lock);
  2505. if (showlog) {
  2506. if (!curses_active) {
  2507. printf("%s \r", statusline);
  2508. fflush(stdout);
  2509. } else
  2510. applog(LOG_INFO, "%s", statusline);
  2511. }
  2512. }
  2513. static bool pool_active(struct pool *pool, bool pinging)
  2514. {
  2515. bool ret = false;
  2516. json_t *val;
  2517. CURL *curl;
  2518. bool rolltime;
  2519. curl = curl_easy_init();
  2520. if (unlikely(!curl)) {
  2521. applog(LOG_ERR, "CURL initialisation failed");
  2522. return false;
  2523. }
  2524. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  2525. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  2526. true, false, &rolltime, pool, false);
  2527. if (val) {
  2528. struct work *work = make_work();
  2529. bool rc;
  2530. rc = work_decode(json_object_get(val, "result"), work);
  2531. if (rc) {
  2532. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  2533. pool->pool_no, pool->rpc_url);
  2534. work->pool = pool;
  2535. work->rolltime = rolltime;
  2536. if (opt_debug)
  2537. applog(LOG_DEBUG, "Pushing pooltest work to base pool");
  2538. tq_push(thr_info[stage_thr_id].q, work);
  2539. total_getworks++;
  2540. pool->getwork_requested++;
  2541. inc_queued();
  2542. ret = true;
  2543. gettimeofday(&pool->tv_idle, NULL);
  2544. } else {
  2545. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher work from pool %u %s",
  2546. pool->pool_no, pool->rpc_url);
  2547. free_work(work);
  2548. }
  2549. json_decref(val);
  2550. } else {
  2551. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  2552. pool->pool_no, pool->rpc_url);
  2553. if (!pinging)
  2554. applog(LOG_WARNING, "Pool %u slow/down or URL or credentials invalid", pool->pool_no);
  2555. }
  2556. curl_easy_cleanup(curl);
  2557. return ret;
  2558. }
  2559. static void pool_died(struct pool *pool)
  2560. {
  2561. if (!pool_tset(pool, &pool->idle)) {
  2562. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  2563. gettimeofday(&pool->tv_idle, NULL);
  2564. switch_pools(NULL);
  2565. }
  2566. }
  2567. static inline int cp_prio(void)
  2568. {
  2569. int prio;
  2570. mutex_lock(&control_lock);
  2571. prio = currentpool->prio;
  2572. mutex_unlock(&control_lock);
  2573. return prio;
  2574. }
  2575. static void pool_resus(struct pool *pool)
  2576. {
  2577. applog(LOG_WARNING, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  2578. if (pool->prio < cp_prio() && pool_strategy == POOL_FAILOVER)
  2579. switch_pools(NULL);
  2580. }
  2581. static long requested_tv_sec;
  2582. static bool queue_request(struct thr_info *thr, bool needed)
  2583. {
  2584. int rq = requests_queued();
  2585. struct workio_cmd *wc;
  2586. struct timeval now;
  2587. gettimeofday(&now, NULL);
  2588. /* Space out retrieval of extra work according to the number of mining
  2589. * threads */
  2590. if (rq >= mining_threads + staged_clones &&
  2591. (now.tv_sec - requested_tv_sec) < opt_scantime / (mining_threads + 1))
  2592. return true;
  2593. /* fill out work request message */
  2594. wc = calloc(1, sizeof(*wc));
  2595. if (unlikely(!wc)) {
  2596. applog(LOG_ERR, "Failed to calloc wc in queue_request");
  2597. return false;
  2598. }
  2599. wc->cmd = WC_GET_WORK;
  2600. if (thr)
  2601. wc->thr = thr;
  2602. else
  2603. wc->thr = NULL;
  2604. /* If we're queueing work faster than we can stage it, consider the
  2605. * system lagging and allow work to be gathered from another pool if
  2606. * possible */
  2607. if (rq && needed && !requests_staged() && !opt_fail_only)
  2608. wc->lagging = true;
  2609. if (opt_debug)
  2610. applog(LOG_DEBUG, "Queueing getwork request to work thread");
  2611. /* send work request to workio thread */
  2612. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  2613. applog(LOG_ERR, "Failed to tq_push in queue_request");
  2614. workio_cmd_free(wc);
  2615. return false;
  2616. }
  2617. requested_tv_sec = now.tv_sec;
  2618. inc_queued();
  2619. return true;
  2620. }
  2621. static struct work *hash_pop(const struct timespec *abstime)
  2622. {
  2623. struct work *work = NULL;
  2624. int rc = 0;
  2625. mutex_lock(stgd_lock);
  2626. while (!getq->frozen && !HASH_COUNT(staged_work) && !rc)
  2627. rc = pthread_cond_timedwait(&getq->cond, stgd_lock, abstime);
  2628. if (HASH_COUNT(staged_work)) {
  2629. work = staged_work;
  2630. HASH_DEL(staged_work, work);
  2631. if (work->clone)
  2632. --staged_clones;
  2633. }
  2634. mutex_unlock(stgd_lock);
  2635. return work;
  2636. }
  2637. static inline bool should_roll(struct work *work)
  2638. {
  2639. if (work->pool == current_pool() || pool_strategy == POOL_LOADBALANCE)
  2640. return true;
  2641. return false;
  2642. }
  2643. static inline bool can_roll(struct work *work)
  2644. {
  2645. return (work->pool && !stale_work(work, false) && work->rolltime &&
  2646. work->rolls < 11 && !work->clone);
  2647. }
  2648. static void roll_work(struct work *work)
  2649. {
  2650. uint32_t *work_ntime;
  2651. uint32_t ntime;
  2652. work_ntime = (uint32_t *)(work->data + 68);
  2653. ntime = be32toh(*work_ntime);
  2654. ntime++;
  2655. *work_ntime = htobe32(ntime);
  2656. local_work++;
  2657. work->rolls++;
  2658. work->blk.nonce = 0;
  2659. if (opt_debug)
  2660. applog(LOG_DEBUG, "Successfully rolled work");
  2661. /* This is now a different work item so it needs a different ID for the
  2662. * hashtable */
  2663. work->id = total_work++;
  2664. }
  2665. static bool reuse_work(struct work *work)
  2666. {
  2667. if (can_roll(work) && should_roll(work)) {
  2668. roll_work(work);
  2669. return true;
  2670. }
  2671. return false;
  2672. }
  2673. static bool get_work(struct work *work, bool requested, struct thr_info *thr,
  2674. const int thr_id)
  2675. {
  2676. bool newreq = false, ret = false;
  2677. struct timespec abstime = {};
  2678. struct timeval now;
  2679. struct work *work_heap;
  2680. struct pool *pool;
  2681. int failures = 0;
  2682. /* Tell the watchdog thread this thread is waiting on getwork and
  2683. * should not be restarted */
  2684. thread_reportout(thr);
  2685. retry:
  2686. pool = current_pool();
  2687. if (!requested || requests_queued() < opt_queue) {
  2688. if (unlikely(!queue_request(thr, true))) {
  2689. applog(LOG_WARNING, "Failed to queue_request in get_work");
  2690. goto out;
  2691. }
  2692. newreq = true;
  2693. }
  2694. if (reuse_work(work)) {
  2695. ret = true;
  2696. goto out;
  2697. }
  2698. if (requested && !newreq && !requests_staged() && requests_queued() >= mining_threads &&
  2699. !pool_tset(pool, &pool->lagging)) {
  2700. applog(LOG_WARNING, "Pool %d not providing work fast enough", pool->pool_no);
  2701. pool->getfail_occasions++;
  2702. total_go++;
  2703. }
  2704. newreq = requested = false;
  2705. gettimeofday(&now, NULL);
  2706. abstime.tv_sec = now.tv_sec + 60;
  2707. if (opt_debug)
  2708. applog(LOG_DEBUG, "Popping work from get queue to get work");
  2709. /* wait for 1st response, or get cached response */
  2710. work_heap = hash_pop(&abstime);
  2711. if (unlikely(!work_heap)) {
  2712. /* Attempt to switch pools if this one times out */
  2713. pool_died(pool);
  2714. goto retry;
  2715. }
  2716. if (stale_work(work_heap, false)) {
  2717. dec_queued();
  2718. discard_work(work_heap);
  2719. goto retry;
  2720. }
  2721. pool = work_heap->pool;
  2722. /* If we make it here we have succeeded in getting fresh work */
  2723. if (!work_heap->mined) {
  2724. pool_tclear(pool, &pool->lagging);
  2725. if (pool_tclear(pool, &pool->idle))
  2726. pool_resus(pool);
  2727. }
  2728. memcpy(work, work_heap, sizeof(*work));
  2729. /* Hand out a clone if we can roll this work item */
  2730. if (reuse_work(work_heap)) {
  2731. if (opt_debug)
  2732. applog(LOG_DEBUG, "Pushing divided work to get queue head");
  2733. stage_work(work_heap);
  2734. work->clone = true;
  2735. } else {
  2736. dec_queued();
  2737. free_work(work_heap);
  2738. }
  2739. ret = true;
  2740. out:
  2741. if (unlikely(ret == false)) {
  2742. if ((opt_retries >= 0) && (++failures > opt_retries)) {
  2743. applog(LOG_ERR, "Failed %d times to get_work");
  2744. return ret;
  2745. }
  2746. applog(LOG_DEBUG, "Retrying after %d seconds", fail_pause);
  2747. sleep(fail_pause);
  2748. fail_pause += opt_fail_pause;
  2749. goto retry;
  2750. }
  2751. fail_pause = opt_fail_pause;
  2752. work->thr_id = thr_id;
  2753. thread_reportin(thr);
  2754. if (ret)
  2755. work->mined = true;
  2756. return ret;
  2757. }
  2758. bool submit_work_sync(struct thr_info *thr, const struct work *work_in)
  2759. {
  2760. struct workio_cmd *wc;
  2761. /* fill out work request message */
  2762. wc = calloc(1, sizeof(*wc));
  2763. if (unlikely(!wc)) {
  2764. applog(LOG_ERR, "Failed to calloc wc in submit_work_sync");
  2765. return false;
  2766. }
  2767. wc->u.work = make_work();
  2768. wc->cmd = WC_SUBMIT_WORK;
  2769. wc->thr = thr;
  2770. memcpy(wc->u.work, work_in, sizeof(*work_in));
  2771. if (opt_debug)
  2772. applog(LOG_DEBUG, "Pushing submit work to work thread");
  2773. /* send solution to workio thread */
  2774. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  2775. applog(LOG_ERR, "Failed to tq_push work in submit_work_sync");
  2776. goto err_out;
  2777. }
  2778. return true;
  2779. err_out:
  2780. workio_cmd_free(wc);
  2781. return false;
  2782. }
  2783. bool hashtest(const struct work *work)
  2784. {
  2785. uint32_t *data32 = (uint32_t *)(work->data);
  2786. unsigned char swap[128];
  2787. uint32_t *swap32 = (uint32_t *)swap;
  2788. unsigned char hash1[32];
  2789. unsigned char hash2[32];
  2790. uint32_t *hash2_32 = (uint32_t *)hash2;
  2791. int i;
  2792. for (i = 0; i < 80 / 4; i++)
  2793. swap32[i] = swab32(data32[i]);
  2794. sha2(swap, 80, hash1, false);
  2795. sha2(hash1, 32, hash2, false);
  2796. for (i = 0; i < 32 / 4; i++)
  2797. hash2_32[i] = swab32(hash2_32[i]);
  2798. memcpy((void*)work->hash, hash2, 32);
  2799. return fulltest(work->hash, work->target);
  2800. }
  2801. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  2802. {
  2803. work->data[64 + 12 + 0] = (nonce >> 0) & 0xff;
  2804. work->data[64 + 12 + 1] = (nonce >> 8) & 0xff;
  2805. work->data[64 + 12 + 2] = (nonce >> 16) & 0xff;
  2806. work->data[64 + 12 + 3] = (nonce >> 24) & 0xff;
  2807. /* Do one last check before attempting to submit the work */
  2808. if (!hashtest(work)) {
  2809. applog(LOG_INFO, "Share below target");
  2810. return true;
  2811. }
  2812. return submit_work_sync(thr, work);
  2813. }
  2814. static inline bool abandon_work(struct work *work, struct timeval *wdiff, uint64_t hashes)
  2815. {
  2816. if (wdiff->tv_sec > opt_scantime ||
  2817. work->blk.nonce >= MAXTHREADS - hashes ||
  2818. hashes >= 0xfffffffe ||
  2819. stale_work(work, false))
  2820. return true;
  2821. return false;
  2822. }
  2823. void *miner_thread(void *userdata)
  2824. {
  2825. struct thr_info *mythr = userdata;
  2826. const int thr_id = mythr->id;
  2827. struct cgpu_info *cgpu = mythr->cgpu;
  2828. struct device_api *api = cgpu->api;
  2829. /* Try to cycle approximately 5 times before each log update */
  2830. const unsigned long def_cycle = opt_log_interval / 5 ? : 1;
  2831. unsigned long cycle;
  2832. struct timeval tv_start, tv_end, tv_workstart, tv_lastupdate;
  2833. struct timeval diff, sdiff, wdiff;
  2834. uint32_t max_nonce = api->can_limit_work ? api->can_limit_work(mythr) : 0xffffffff;
  2835. uint32_t hashes_done = 0;
  2836. uint32_t hashes;
  2837. struct work *work = make_work();
  2838. unsigned const int request_interval = opt_scantime * 2 / 3 ? : 1;
  2839. unsigned const long request_nonce = MAXTHREADS / 3 * 2;
  2840. bool requested = false;
  2841. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2842. if (api->thread_init && !api->thread_init(mythr))
  2843. goto out;
  2844. if (opt_debug)
  2845. applog(LOG_DEBUG, "Popping ping in miner thread");
  2846. tq_pop(mythr->q, NULL); /* Wait for a ping to start */
  2847. sdiff.tv_sec = sdiff.tv_usec = 0;
  2848. gettimeofday(&tv_lastupdate, NULL);
  2849. while (1) {
  2850. work_restart[thr_id].restart = 0;
  2851. if (api->free_work && likely(work->pool))
  2852. api->free_work(mythr, work);
  2853. if (unlikely(!get_work(work, requested, mythr, thr_id))) {
  2854. applog(LOG_ERR, "work retrieval failed, exiting "
  2855. "mining thread %d", thr_id);
  2856. break;
  2857. }
  2858. requested = false;
  2859. cycle = (can_roll(work) && should_roll(work)) ? 1 : def_cycle;
  2860. gettimeofday(&tv_workstart, NULL);
  2861. work->blk.nonce = 0;
  2862. if (api->prepare_work && !api->prepare_work(mythr, work)) {
  2863. applog(LOG_ERR, "work prepare failed, exiting "
  2864. "mining thread %d", thr_id);
  2865. break;
  2866. }
  2867. do {
  2868. gettimeofday(&tv_start, NULL);
  2869. hashes = api->scanhash(mythr, work, work->blk.nonce + max_nonce);
  2870. if (unlikely(work_restart[thr_id].restart)) {
  2871. /* Apart from device_thread 0, we stagger the
  2872. * starting of every next thread to try and get
  2873. * all devices busy before worrying about
  2874. * getting work for their extra threads */
  2875. if (mythr->device_thread) {
  2876. struct timespec rgtp;
  2877. rgtp.tv_sec = 0;
  2878. rgtp.tv_nsec = 250 * mythr->device_thread * 1000000;
  2879. nanosleep(&rgtp, NULL);
  2880. }
  2881. break;
  2882. }
  2883. if (unlikely(!hashes))
  2884. goto out;
  2885. hashes_done += hashes;
  2886. gettimeofday(&tv_end, NULL);
  2887. timeval_subtract(&diff, &tv_end, &tv_start);
  2888. sdiff.tv_sec += diff.tv_sec;
  2889. sdiff.tv_usec += diff.tv_usec;
  2890. if (sdiff.tv_usec > 1000000) {
  2891. ++sdiff.tv_sec;
  2892. sdiff.tv_usec -= 1000000;
  2893. }
  2894. timeval_subtract(&wdiff, &tv_end, &tv_workstart);
  2895. if (!requested) {
  2896. if (wdiff.tv_sec > request_interval || work->blk.nonce > request_nonce) {
  2897. thread_reportout(mythr);
  2898. if (unlikely(!queue_request(mythr, false))) {
  2899. applog(LOG_ERR, "Failed to queue_request in miner_thread %d", thr_id);
  2900. goto out;
  2901. }
  2902. thread_reportin(mythr);
  2903. requested = true;
  2904. }
  2905. }
  2906. if (unlikely(sdiff.tv_sec < cycle)) {
  2907. if (likely(!api->can_limit_work || max_nonce == 0xffffffff))
  2908. continue;
  2909. {
  2910. int mult = 1000000 / ((sdiff.tv_usec + 0x400) / 0x400) + 0x10;
  2911. mult *= cycle;
  2912. if (max_nonce > (0xffffffff * 0x400) / mult)
  2913. max_nonce = 0xffffffff;
  2914. else
  2915. max_nonce = (max_nonce * mult) / 0x400;
  2916. }
  2917. } else if (unlikely(sdiff.tv_sec > cycle) && api->can_limit_work) {
  2918. max_nonce = max_nonce * cycle / sdiff.tv_sec;
  2919. } else if (unlikely(sdiff.tv_usec > 100000) && api->can_limit_work) {
  2920. max_nonce = max_nonce * 0x400 / (((cycle * 1000000) + sdiff.tv_usec) / (cycle * 1000000 / 0x400));
  2921. }
  2922. timeval_subtract(&diff, &tv_end, &tv_lastupdate);
  2923. if (diff.tv_sec >= opt_log_interval) {
  2924. hashmeter(thr_id, &diff, hashes_done);
  2925. hashes_done = 0;
  2926. tv_lastupdate = tv_end;
  2927. }
  2928. if (unlikely(mythr->pause || !cgpu->enabled)) {
  2929. applog(LOG_WARNING, "Thread %d being disabled", thr_id);
  2930. mythr->rolling = mythr->cgpu->rolling = 0;
  2931. if (opt_debug)
  2932. applog(LOG_DEBUG, "Popping wakeup ping in miner thread");
  2933. thread_reportout(mythr);
  2934. tq_pop(mythr->q, NULL); /* Ignore ping that's popped */
  2935. thread_reportin(mythr);
  2936. applog(LOG_WARNING, "Thread %d being re-enabled", thr_id);
  2937. }
  2938. sdiff.tv_sec = sdiff.tv_usec = 0;
  2939. } while (!abandon_work(work, &wdiff, hashes));
  2940. }
  2941. out:
  2942. if (api->thread_shutdown)
  2943. api->thread_shutdown(mythr);
  2944. thread_reportin(mythr);
  2945. applog(LOG_ERR, "Thread %d failure, exiting", thr_id);
  2946. tq_freeze(mythr->q);
  2947. return NULL;
  2948. }
  2949. enum {
  2950. STAT_SLEEP_INTERVAL = 1,
  2951. STAT_CTR_INTERVAL = 10000000,
  2952. FAILURE_INTERVAL = 30,
  2953. };
  2954. /* Stage another work item from the work returned in a longpoll */
  2955. static void convert_to_work(json_t *val, bool rolltime, struct pool *pool)
  2956. {
  2957. struct work *work, *work_clone;
  2958. bool rc;
  2959. work = make_work();
  2960. rc= work_decode(json_object_get(val, "result"), work);
  2961. if (unlikely(!rc)) {
  2962. applog(LOG_ERR, "Could not convert longpoll data to work");
  2963. return;
  2964. }
  2965. work->pool = pool;
  2966. work->rolltime = rolltime;
  2967. /* We'll be checking this work item twice, but we already know it's
  2968. * from a new block so explicitly force the new block detection now
  2969. * rather than waiting for it to hit the stage thread. This also
  2970. * allows testwork to know whether LP discovered the block or not. */
  2971. test_work_current(work, true);
  2972. work_clone = make_work();
  2973. memcpy(work_clone, work, sizeof(struct work));
  2974. while (reuse_work(work)) {
  2975. work_clone->clone = true;
  2976. if (opt_debug)
  2977. applog(LOG_DEBUG, "Pushing rolled converted work to stage thread");
  2978. if (unlikely(!stage_work(work_clone)))
  2979. break;
  2980. work_clone = make_work();
  2981. memcpy(work_clone, work, sizeof(struct work));
  2982. }
  2983. free_work(work_clone);
  2984. if (opt_debug)
  2985. applog(LOG_DEBUG, "Pushing converted work to stage thread");
  2986. if (unlikely(!stage_work(work)))
  2987. free_work(work);
  2988. else if (opt_debug)
  2989. applog(LOG_DEBUG, "Converted longpoll data to work");
  2990. }
  2991. /* If we want longpoll, enable it for the chosen default pool, or, if
  2992. * the pool does not support longpoll, find the first one that does
  2993. * and use its longpoll support */
  2994. static struct pool *select_longpoll_pool(void)
  2995. {
  2996. struct pool *cp = current_pool();
  2997. int i;
  2998. if (cp->hdr_path)
  2999. return cp;
  3000. for (i = 0; i < total_pools; i++) {
  3001. struct pool *pool = pools[i];
  3002. if (pool->hdr_path)
  3003. return pool;
  3004. }
  3005. return NULL;
  3006. }
  3007. static void *longpoll_thread(void *userdata)
  3008. {
  3009. char *copy_start, *hdr_path, *lp_url = NULL;
  3010. struct thr_info *mythr = userdata;
  3011. struct timeval start, end;
  3012. bool need_slash = false;
  3013. struct pool *sp, *pool;
  3014. CURL *curl = NULL;
  3015. int failures = 0;
  3016. bool rolltime;
  3017. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3018. pthread_detach(pthread_self());
  3019. curl = curl_easy_init();
  3020. if (unlikely(!curl)) {
  3021. applog(LOG_ERR, "CURL initialisation failed");
  3022. goto out;
  3023. }
  3024. tq_pop(mythr->q, NULL);
  3025. pool = select_longpoll_pool();
  3026. new_longpoll:
  3027. if (!pool) {
  3028. applog(LOG_WARNING, "No long-poll found on any pool server");
  3029. goto out;
  3030. }
  3031. hdr_path = pool->hdr_path;
  3032. /* full URL */
  3033. if (strstr(hdr_path, "://")) {
  3034. lp_url = hdr_path;
  3035. hdr_path = NULL;
  3036. } else {
  3037. /* absolute path, on current server */
  3038. copy_start = (*hdr_path == '/') ? (hdr_path + 1) : hdr_path;
  3039. if (pool->rpc_url[strlen(pool->rpc_url) - 1] != '/')
  3040. need_slash = true;
  3041. lp_url = malloc(strlen(pool->rpc_url) + strlen(copy_start) + 2);
  3042. if (!lp_url)
  3043. goto out;
  3044. sprintf(lp_url, "%s%s%s", pool->rpc_url, need_slash ? "/" : "", copy_start);
  3045. }
  3046. have_longpoll = true;
  3047. applog(LOG_WARNING, "Long-polling activated for %s", lp_url);
  3048. while (1) {
  3049. json_t *val, *soval;
  3050. gettimeofday(&start, NULL);
  3051. val = json_rpc_call(curl, lp_url, pool->rpc_userpass, rpc_req,
  3052. false, true, &rolltime, pool, false);
  3053. if (likely(val)) {
  3054. soval = json_object_get(json_object_get(val, "result"), "submitold");
  3055. if (soval)
  3056. pool->submit_old = json_is_true(soval);
  3057. else
  3058. pool->submit_old = false;
  3059. convert_to_work(val, rolltime, pool);
  3060. failures = 0;
  3061. json_decref(val);
  3062. } else {
  3063. /* Some pools regularly drop the longpoll request so
  3064. * only see this as longpoll failure if it happens
  3065. * immediately and just restart it the rest of the
  3066. * time. */
  3067. gettimeofday(&end, NULL);
  3068. if (end.tv_sec - start.tv_sec > 30)
  3069. continue;
  3070. if (opt_retries == -1 || failures++ < opt_retries) {
  3071. applog(LOG_WARNING,
  3072. "longpoll failed for %s, sleeping for 30s", lp_url);
  3073. sleep(30);
  3074. } else {
  3075. applog(LOG_ERR,
  3076. "longpoll failed for %s, ending thread", lp_url);
  3077. goto out;
  3078. }
  3079. }
  3080. sp = select_longpoll_pool();
  3081. if (sp != pool) {
  3082. if (likely(lp_url))
  3083. free(lp_url);
  3084. pool = sp;
  3085. goto new_longpoll;
  3086. }
  3087. }
  3088. out:
  3089. if (curl)
  3090. curl_easy_cleanup(curl);
  3091. tq_freeze(mythr->q);
  3092. return NULL;
  3093. }
  3094. static void stop_longpoll(void)
  3095. {
  3096. struct thr_info *thr = &thr_info[longpoll_thr_id];
  3097. thr_info_cancel(thr);
  3098. have_longpoll = false;
  3099. tq_freeze(thr->q);
  3100. }
  3101. static void start_longpoll(void)
  3102. {
  3103. struct thr_info *thr = &thr_info[longpoll_thr_id];
  3104. tq_thaw(thr->q);
  3105. if (unlikely(thr_info_create(thr, NULL, longpoll_thread, thr)))
  3106. quit(1, "longpoll thread create failed");
  3107. if (opt_debug)
  3108. applog(LOG_DEBUG, "Pushing ping to longpoll thread");
  3109. tq_push(thr_info[longpoll_thr_id].q, &ping);
  3110. }
  3111. void reinit_device(struct cgpu_info *cgpu)
  3112. {
  3113. if (cgpu->api->reinit_device)
  3114. cgpu->api->reinit_device(cgpu);
  3115. }
  3116. static struct timeval rotate_tv;
  3117. static void *watchpool_thread(void __maybe_unused *userdata)
  3118. {
  3119. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3120. while (42) {
  3121. struct timeval now;
  3122. int i;
  3123. gettimeofday(&now, NULL);
  3124. for (i = 0; i < total_pools; i++) {
  3125. struct pool *pool = pools[i];
  3126. if (!pool->enabled)
  3127. continue;
  3128. /* Test pool is idle once every minute */
  3129. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 60) {
  3130. gettimeofday(&pool->tv_idle, NULL);
  3131. if (pool_active(pool, true) && pool_tclear(pool, &pool->idle))
  3132. pool_resus(pool);
  3133. }
  3134. }
  3135. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  3136. gettimeofday(&rotate_tv, NULL);
  3137. switch_pools(NULL);
  3138. }
  3139. sleep(10);
  3140. }
  3141. return NULL;
  3142. }
  3143. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  3144. * the screen at regular intervals, and restarts threads if they appear to have
  3145. * died. */
  3146. static void *watchdog_thread(void __maybe_unused *userdata)
  3147. {
  3148. const unsigned int interval = 3;
  3149. struct timeval zero_tv;
  3150. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3151. memset(&zero_tv, 0, sizeof(struct timeval));
  3152. gettimeofday(&rotate_tv, NULL);
  3153. while (1) {
  3154. int i;
  3155. struct timeval now;
  3156. sleep(interval);
  3157. if (requests_queued() < opt_queue)
  3158. queue_request(NULL, false);
  3159. hashmeter(-1, &zero_tv, 0);
  3160. if (curses_active_locked()) {
  3161. change_logwinsize();
  3162. curses_print_status();
  3163. for (i = 0; i < mining_threads; i++)
  3164. curses_print_devstatus(i);
  3165. clearok(statuswin, true);
  3166. doupdate();
  3167. unlock_curses();
  3168. }
  3169. gettimeofday(&now, NULL);
  3170. if (!sched_paused && !should_run()) {
  3171. applog(LOG_WARNING, "Pausing execution as per stop time %02d:%02d scheduled",
  3172. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  3173. if (!schedstart.enable) {
  3174. quit(0, "Terminating execution as planned");
  3175. break;
  3176. }
  3177. applog(LOG_WARNING, "Will restart execution as scheduled at %02d:%02d",
  3178. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  3179. sched_paused = true;
  3180. for (i = 0; i < mining_threads; i++) {
  3181. struct thr_info *thr;
  3182. thr = &thr_info[i];
  3183. thr->pause = true;
  3184. }
  3185. } else if (sched_paused && should_run()) {
  3186. applog(LOG_WARNING, "Restarting execution as per start time %02d:%02d scheduled",
  3187. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  3188. if (schedstop.enable)
  3189. applog(LOG_WARNING, "Will pause execution as scheduled at %02d:%02d",
  3190. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  3191. sched_paused = false;
  3192. for (i = 0; i < mining_threads; i++) {
  3193. struct thr_info *thr;
  3194. thr = &thr_info[i];
  3195. /* Don't touch disabled devices */
  3196. if (!thr->cgpu->enabled)
  3197. continue;
  3198. thr->pause = false;
  3199. tq_push(thr->q, &ping);
  3200. }
  3201. }
  3202. #ifdef HAVE_OPENCL
  3203. for (i = 0; i < total_devices; ++i) {
  3204. struct cgpu_info *cgpu = devices[i];
  3205. struct thr_info *thr = cgpu->thread;
  3206. bool *enable;
  3207. int gpu;
  3208. if (cgpu->api != &opencl_api)
  3209. continue;
  3210. /* Use only one thread per device to determine if the GPU is healthy */
  3211. if (i >= nDevs)
  3212. break;
  3213. gpu = thr->cgpu->device_id;
  3214. enable = &cgpu->enabled;
  3215. #ifdef HAVE_ADL
  3216. if (adl_active && gpus[gpu].has_adl)
  3217. gpu_autotune(gpu, enable);
  3218. if (opt_debug && gpus[gpu].has_adl) {
  3219. int engineclock = 0, memclock = 0, activity = 0, fanspeed = 0, fanpercent = 0, powertune = 0;
  3220. float temp = 0, vddc = 0;
  3221. if (gpu_stats(gpu, &temp, &engineclock, &memclock, &vddc, &activity, &fanspeed, &fanpercent, &powertune))
  3222. applog(LOG_DEBUG, "%.1f C F: %d%%(%dRPM) E: %dMHz M: %dMhz V: %.3fV A: %d%% P: %d%%",
  3223. temp, fanpercent, fanspeed, engineclock, memclock, vddc, activity, powertune);
  3224. }
  3225. #endif
  3226. /* Thread is waiting on getwork or disabled */
  3227. if (thr->getwork || !*enable)
  3228. continue;
  3229. if (gpus[gpu].status != LIFE_WELL && now.tv_sec - thr->last.tv_sec < 60) {
  3230. applog(LOG_ERR, "Device %d recovered, GPU %d declared WELL!", i, gpu);
  3231. gpus[gpu].status = LIFE_WELL;
  3232. } else if (now.tv_sec - thr->last.tv_sec > 60 && gpus[gpu].status == LIFE_WELL) {
  3233. thr->rolling = thr->cgpu->rolling = 0;
  3234. gpus[gpu].status = LIFE_SICK;
  3235. applog(LOG_ERR, "Device %d idle for more than 60 seconds, GPU %d declared SICK!", i, gpu);
  3236. gettimeofday(&thr->sick, NULL);
  3237. #ifdef HAVE_ADL
  3238. if (adl_active && gpus[gpu].has_adl && gpu_activity(gpu) > 50) {
  3239. applog(LOG_ERR, "GPU still showing activity suggesting a hard hang.");
  3240. applog(LOG_ERR, "Will not attempt to auto-restart it.");
  3241. } else
  3242. #endif
  3243. if (opt_restart) {
  3244. applog(LOG_ERR, "Attempting to restart GPU");
  3245. reinit_device(thr->cgpu);
  3246. }
  3247. } else if (now.tv_sec - thr->last.tv_sec > 600 && gpus[i].status == LIFE_SICK) {
  3248. gpus[gpu].status = LIFE_DEAD;
  3249. applog(LOG_ERR, "Device %d not responding for more than 10 minutes, GPU %d declared DEAD!", i, gpu);
  3250. gettimeofday(&thr->sick, NULL);
  3251. } else if (now.tv_sec - thr->sick.tv_sec > 60 &&
  3252. (gpus[i].status == LIFE_SICK || gpus[i].status == LIFE_DEAD)) {
  3253. /* Attempt to restart a GPU that's sick or dead once every minute */
  3254. gettimeofday(&thr->sick, NULL);
  3255. #ifdef HAVE_ADL
  3256. if (adl_active && gpus[gpu].has_adl && gpu_activity(gpu) > 50) {
  3257. /* Again do not attempt to restart a device that may have hard hung */
  3258. } else
  3259. #endif
  3260. if (opt_restart)
  3261. reinit_device(thr->cgpu);
  3262. }
  3263. }
  3264. #endif
  3265. }
  3266. return NULL;
  3267. }
  3268. static void log_print_status(struct cgpu_info *cgpu)
  3269. {
  3270. char logline[255];
  3271. get_statline(logline, cgpu);
  3272. applog(LOG_WARNING, "%s", logline);
  3273. }
  3274. static void print_summary(void)
  3275. {
  3276. struct timeval diff;
  3277. int hours, mins, secs, i;
  3278. double utility, efficiency = 0.0;
  3279. timeval_subtract(&diff, &total_tv_end, &total_tv_start);
  3280. hours = diff.tv_sec / 3600;
  3281. mins = (diff.tv_sec % 3600) / 60;
  3282. secs = diff.tv_sec % 60;
  3283. utility = total_accepted / ( total_secs ? total_secs : 1 ) * 60;
  3284. efficiency = total_getworks ? total_accepted * 100.0 / total_getworks : 0.0;
  3285. applog(LOG_WARNING, "\nSummary of runtime statistics:\n");
  3286. applog(LOG_WARNING, "Started at %s", datestamp);
  3287. if (total_pools == 1)
  3288. applog(LOG_WARNING, "Pool: %s", pools[0]->rpc_url);
  3289. #ifdef WANT_CPUMINE
  3290. if (opt_n_threads)
  3291. applog(LOG_WARNING, "CPU hasher algorithm used: %s", algo_names[opt_algo]);
  3292. #endif
  3293. applog(LOG_WARNING, "Runtime: %d hrs : %d mins : %d secs", hours, mins, secs);
  3294. if (total_secs)
  3295. applog(LOG_WARNING, "Average hashrate: %.1f Megahash/s", total_mhashes_done / total_secs);
  3296. applog(LOG_WARNING, "Solved blocks: %d", found_blocks);
  3297. applog(LOG_WARNING, "Queued work requests: %d", total_getworks);
  3298. applog(LOG_WARNING, "Share submissions: %d", total_accepted + total_rejected);
  3299. applog(LOG_WARNING, "Accepted shares: %d", total_accepted);
  3300. applog(LOG_WARNING, "Rejected shares: %d", total_rejected);
  3301. if (total_accepted || total_rejected)
  3302. applog(LOG_WARNING, "Reject ratio: %.1f%%", (double)(total_rejected * 100) / (double)(total_accepted + total_rejected));
  3303. applog(LOG_WARNING, "Hardware errors: %d", hw_errors);
  3304. applog(LOG_WARNING, "Efficiency (accepted / queued): %.0f%%", efficiency);
  3305. applog(LOG_WARNING, "Utility (accepted shares / min): %.2f/min\n", utility);
  3306. applog(LOG_WARNING, "Discarded work due to new blocks: %d", total_discarded);
  3307. applog(LOG_WARNING, "Stale submissions discarded due to new blocks: %d", total_stale);
  3308. applog(LOG_WARNING, "Unable to get work from server occasions: %d", total_go);
  3309. applog(LOG_WARNING, "Work items generated locally: %d", local_work);
  3310. applog(LOG_WARNING, "Submitting work remotely delay occasions: %d", total_ro);
  3311. applog(LOG_WARNING, "New blocks detected on network: %d\n", new_blocks);
  3312. if (total_pools > 1) {
  3313. for (i = 0; i < total_pools; i++) {
  3314. struct pool *pool = pools[i];
  3315. applog(LOG_WARNING, "Pool: %s", pool->rpc_url);
  3316. applog(LOG_WARNING, " Queued work requests: %d", pool->getwork_requested);
  3317. applog(LOG_WARNING, " Share submissions: %d", pool->accepted + pool->rejected);
  3318. applog(LOG_WARNING, " Accepted shares: %d", pool->accepted);
  3319. applog(LOG_WARNING, " Rejected shares: %d", pool->rejected);
  3320. if (pool->accepted || pool->rejected)
  3321. applog(LOG_WARNING, " Reject ratio: %.1f%%", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  3322. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  3323. applog(LOG_WARNING, " Efficiency (accepted / queued): %.0f%%", efficiency);
  3324. applog(LOG_WARNING, " Discarded work due to new blocks: %d", pool->discarded_work);
  3325. applog(LOG_WARNING, " Stale submissions discarded due to new blocks: %d", pool->stale_shares);
  3326. applog(LOG_WARNING, " Unable to get work from server occasions: %d", pool->getfail_occasions);
  3327. applog(LOG_WARNING, " Submitting work remotely delay occasions: %d\n", pool->remotefail_occasions);
  3328. }
  3329. }
  3330. applog(LOG_WARNING, "Summary of per device statistics:\n");
  3331. for (i = 0; i < total_devices; ++i) {
  3332. if (devices[i]->enabled)
  3333. log_print_status(devices[i]);
  3334. }
  3335. if (opt_shares)
  3336. applog(LOG_WARNING, "Mined %d accepted shares of %d requested\n", total_accepted, opt_shares);
  3337. fflush(stdout);
  3338. fflush(stderr);
  3339. if (opt_shares > total_accepted)
  3340. quit(1, "Did not successfully mine as many shares as were requested.");
  3341. }
  3342. static void clean_up(void)
  3343. {
  3344. gettimeofday(&total_tv_end, NULL);
  3345. disable_curses();
  3346. if (!opt_realquiet && successful_connect)
  3347. print_summary();
  3348. #ifdef HAVE_OPENCL
  3349. clear_adl(nDevs);
  3350. #endif
  3351. if (opt_n_threads)
  3352. free(cpus);
  3353. curl_global_cleanup();
  3354. }
  3355. void quit(int status, const char *format, ...)
  3356. {
  3357. va_list ap;
  3358. clean_up();
  3359. if (format) {
  3360. va_start(ap, format);
  3361. vfprintf(stderr, format, ap);
  3362. va_end(ap);
  3363. }
  3364. fprintf(stderr, "\n");
  3365. fflush(stderr);
  3366. exit(status);
  3367. }
  3368. char *curses_input(const char *query)
  3369. {
  3370. char *input;
  3371. echo();
  3372. input = malloc(255);
  3373. if (!input)
  3374. quit(1, "Failed to malloc input");
  3375. leaveok(logwin, false);
  3376. wlogprint("%s:\n", query);
  3377. wgetnstr(logwin, input, 255);
  3378. if (!strlen(input))
  3379. strcpy(input, "-1");
  3380. leaveok(logwin, true);
  3381. noecho();
  3382. return input;
  3383. }
  3384. static bool input_pool(bool live)
  3385. {
  3386. char *url = NULL, *user = NULL, *pass = NULL;
  3387. struct pool *pool = NULL;
  3388. bool ret = false;
  3389. immedok(logwin, true);
  3390. if (total_pools == MAX_POOLS) {
  3391. wlogprint("Reached maximum number of pools.\n");
  3392. goto out;
  3393. }
  3394. wlogprint("Input server details.\n");
  3395. url = curses_input("URL");
  3396. if (!url)
  3397. goto out;
  3398. if (strncmp(url, "http://", 7) &&
  3399. strncmp(url, "https://", 8)) {
  3400. char *httpinput;
  3401. httpinput = malloc(255);
  3402. if (!httpinput)
  3403. quit(1, "Failed to malloc httpinput");
  3404. strcpy(httpinput, "http://");
  3405. strncat(httpinput, url, 248);
  3406. free(url);
  3407. url = httpinput;
  3408. }
  3409. user = curses_input("Username");
  3410. if (!user)
  3411. goto out;
  3412. pass = curses_input("Password");
  3413. if (!pass)
  3414. goto out;
  3415. pool = calloc(sizeof(struct pool), 1);
  3416. if (!pool)
  3417. quit(1, "Failed to realloc pools in input_pool");
  3418. pool->pool_no = total_pools;
  3419. pool->prio = total_pools;
  3420. if (unlikely(pthread_mutex_init(&pool->pool_lock, NULL)))
  3421. quit (1, "Failed to pthread_mutex_init in input_pool");
  3422. pool->rpc_url = url;
  3423. pool->rpc_user = user;
  3424. pool->rpc_pass = pass;
  3425. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  3426. if (!pool->rpc_userpass)
  3427. quit(1, "Failed to malloc userpass");
  3428. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  3429. pool->tv_idle.tv_sec = ~0UL;
  3430. /* Test the pool is not idle if we're live running, otherwise
  3431. * it will be tested separately */
  3432. ret = true;
  3433. pool->enabled = true;
  3434. if (live && !pool_active(pool, false))
  3435. pool->idle = true;
  3436. pools[total_pools++] = pool;
  3437. out:
  3438. immedok(logwin, false);
  3439. if (!ret) {
  3440. if (url)
  3441. free(url);
  3442. if (user)
  3443. free(user);
  3444. if (pass)
  3445. free(pass);
  3446. if (pool)
  3447. free(pool);
  3448. }
  3449. return ret;
  3450. }
  3451. #if defined(unix)
  3452. static void fork_monitor()
  3453. {
  3454. // Make a pipe: [readFD, writeFD]
  3455. int pfd[2];
  3456. int r = pipe(pfd);
  3457. if (r<0) {
  3458. perror("pipe - failed to create pipe for --monitor");
  3459. exit(1);
  3460. }
  3461. // Make stderr write end of pipe
  3462. fflush(stderr);
  3463. r = dup2(pfd[1], 2);
  3464. if (r<0) {
  3465. perror("dup2 - failed to alias stderr to write end of pipe for --monitor");
  3466. exit(1);
  3467. }
  3468. r = close(pfd[1]);
  3469. if (r<0) {
  3470. perror("close - failed to close write end of pipe for --monitor");
  3471. exit(1);
  3472. }
  3473. // Don't allow a dying monitor to kill the main process
  3474. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  3475. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  3476. if (SIG_ERR==sr0 || SIG_ERR==sr1) {
  3477. perror("signal - failed to edit signal mask for --monitor");
  3478. exit(1);
  3479. }
  3480. // Fork a child process
  3481. r = fork();
  3482. if (r<0) {
  3483. perror("fork - failed to fork child process for --monitor");
  3484. exit(1);
  3485. }
  3486. // Child: launch monitor command
  3487. if (0==r) {
  3488. // Make stdin read end of pipe
  3489. r = dup2(pfd[0], 0);
  3490. if (r<0) {
  3491. perror("dup2 - in child, failed to alias read end of pipe to stdin for --monitor");
  3492. exit(1);
  3493. }
  3494. close(pfd[0]);
  3495. if (r<0) {
  3496. perror("close - in child, failed to close read end of pipe for --monitor");
  3497. exit(1);
  3498. }
  3499. // Launch user specified command
  3500. execl("/bin/bash", "/bin/bash", "-c", opt_stderr_cmd, (char*)NULL);
  3501. perror("execl - in child failed to exec user specified command for --monitor");
  3502. exit(1);
  3503. }
  3504. // Parent: clean up unused fds and bail
  3505. r = close(pfd[0]);
  3506. if (r<0) {
  3507. perror("close - failed to close read end of pipe for --monitor");
  3508. exit(1);
  3509. }
  3510. }
  3511. #endif // defined(unix)
  3512. void enable_curses(void) {
  3513. int x,y;
  3514. lock_curses();
  3515. if (curses_active) {
  3516. unlock_curses();
  3517. return;
  3518. }
  3519. mainwin = initscr();
  3520. getmaxyx(mainwin, y, x);
  3521. statuswin = newwin(logstart, x, 0, 0);
  3522. leaveok(statuswin, true);
  3523. logwin = newwin(y - logcursor, 0, logcursor, 0);
  3524. idlok(logwin, true);
  3525. scrollok(logwin, true);
  3526. leaveok(logwin, true);
  3527. cbreak();
  3528. noecho();
  3529. curses_active = true;
  3530. unlock_curses();
  3531. }
  3532. /* TODO: fix need a dummy CPU device_api even if no support for CPU mining */
  3533. #ifndef WANT_CPUMINE
  3534. struct device_api cpu_api;
  3535. struct device_api cpu_api = {
  3536. .name = "CPU",
  3537. };
  3538. #endif
  3539. #ifdef USE_BITFORCE
  3540. extern struct device_api bitforce_api;
  3541. #endif
  3542. static int cgminer_id_count = 0;
  3543. void enable_device(struct cgpu_info *cgpu)
  3544. {
  3545. cgpu->enabled = true;
  3546. devices[cgpu->cgminer_id = cgminer_id_count++] = cgpu;
  3547. mining_threads += cgpu->threads;
  3548. #ifdef HAVE_OPENCL
  3549. if (cgpu->api == &opencl_api) {
  3550. gpu_threads += cgpu->threads;
  3551. }
  3552. #endif
  3553. }
  3554. int main (int argc, char *argv[])
  3555. {
  3556. struct block *block, *tmpblock;
  3557. struct work *work, *tmpwork;
  3558. bool pools_active = false;
  3559. struct sigaction handler;
  3560. struct thr_info *thr;
  3561. unsigned int i, j, k;
  3562. /* This dangerous functions tramples random dynamically allocated
  3563. * variables so do it before anything at all */
  3564. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  3565. quit(1, "Failed to curl_global_init");
  3566. mutex_init(&hash_lock);
  3567. mutex_init(&qd_lock);
  3568. mutex_init(&curses_lock);
  3569. mutex_init(&control_lock);
  3570. rwlock_init(&blk_lock);
  3571. rwlock_init(&netacc_lock);
  3572. sprintf(packagename, "%s %s", PACKAGE, VERSION);
  3573. #ifdef WANT_CPUMINE
  3574. init_max_name_len();
  3575. #endif
  3576. handler.sa_handler = &sighandler;
  3577. handler.sa_flags = 0;
  3578. sigemptyset(&handler.sa_mask);
  3579. sigaction(SIGTERM, &handler, &termhandler);
  3580. sigaction(SIGINT, &handler, &inthandler);
  3581. opt_kernel_path = alloca(PATH_MAX);
  3582. strcpy(opt_kernel_path, CGMINER_PREFIX);
  3583. cgminer_path = alloca(PATH_MAX);
  3584. strcpy(cgminer_path, dirname(argv[0]));
  3585. strcat(cgminer_path, "/");
  3586. #ifdef WANT_CPUMINE
  3587. // Hack to make cgminer silent when called recursively on WIN32
  3588. int skip_to_bench = 0;
  3589. #if defined(WIN32)
  3590. char buf[32];
  3591. if (GetEnvironmentVariable("CGMINER_BENCH_ALGO", buf, 16))
  3592. skip_to_bench = 1;
  3593. #endif // defined(WIN32)
  3594. #endif
  3595. block = calloc(sizeof(struct block), 1);
  3596. if (unlikely(!block))
  3597. quit (1, "main OOM");
  3598. for (i = 0; i < 36; i++)
  3599. strcat(block->hash, "0");
  3600. HASH_ADD_STR(blocks, hash, block);
  3601. strcpy(current_block, block->hash);
  3602. INIT_LIST_HEAD(&scan_devices);
  3603. memset(gpus, 0, sizeof(gpus));
  3604. for (i = 0; i < MAX_GPUDEVICES; i++)
  3605. gpus[i].dynamic = true;
  3606. memset(devices, 0, sizeof(devices));
  3607. /* parse command line */
  3608. opt_register_table(opt_config_table,
  3609. "Options for both config file and command line");
  3610. opt_register_table(opt_cmdline_table,
  3611. "Options for command line only");
  3612. if (!config_loaded)
  3613. load_default_config();
  3614. opt_parse(&argc, argv, applog_and_exit);
  3615. if (argc != 1)
  3616. quit(1, "Unexpected extra commandline arguments");
  3617. applog(LOG_WARNING, "Started %s", packagename);
  3618. strcat(opt_kernel_path, "/");
  3619. if (want_per_device_stats)
  3620. opt_log_output = true;
  3621. #ifdef WANT_CPUMINE
  3622. if (0<=opt_bench_algo) {
  3623. double rate = bench_algo_stage3(opt_bench_algo);
  3624. if (!skip_to_bench) {
  3625. printf("%.5f (%s)\n", rate, algo_names[opt_bench_algo]);
  3626. } else {
  3627. // Write result to shared memory for parent
  3628. #if defined(WIN32)
  3629. char unique_name[64];
  3630. if (GetEnvironmentVariable("CGMINER_SHARED_MEM", unique_name, 32)) {
  3631. HANDLE map_handle = CreateFileMapping(
  3632. INVALID_HANDLE_VALUE, // use paging file
  3633. NULL, // default security attributes
  3634. PAGE_READWRITE, // read/write access
  3635. 0, // size: high 32-bits
  3636. 4096, // size: low 32-bits
  3637. unique_name // name of map object
  3638. );
  3639. if (NULL!=map_handle) {
  3640. void *shared_mem = MapViewOfFile(
  3641. map_handle, // object to map view of
  3642. FILE_MAP_WRITE, // read/write access
  3643. 0, // high offset: map from
  3644. 0, // low offset: beginning
  3645. 0 // default: map entire file
  3646. );
  3647. if (NULL!=shared_mem)
  3648. CopyMemory(shared_mem, &rate, sizeof(rate));
  3649. (void)UnmapViewOfFile(shared_mem);
  3650. }
  3651. (void)CloseHandle(map_handle);
  3652. }
  3653. #endif
  3654. }
  3655. exit(0);
  3656. }
  3657. #endif
  3658. #ifdef HAVE_OPENCL
  3659. if (!opt_nogpu)
  3660. opencl_api.api_detect();
  3661. #endif
  3662. #ifdef USE_BITFORCE
  3663. bitforce_api.api_detect();
  3664. #endif
  3665. #ifdef WANT_CPUMINE
  3666. cpu_api.api_detect();
  3667. #endif
  3668. if (devices_enabled == -1) {
  3669. applog(LOG_ERR, "Devices detected:");
  3670. for (i = 0; i < total_devices; ++i) {
  3671. applog(LOG_ERR, " %2d. %s%d", i, devices[i]->api->name, devices[i]->device_id);
  3672. }
  3673. quit(0, "%d devices listed", total_devices);
  3674. }
  3675. mining_threads = 0;
  3676. gpu_threads = 0;
  3677. if (devices_enabled) {
  3678. for (i = 0; i < (sizeof(devices_enabled) * 8) - 1; ++i) {
  3679. if (devices_enabled & (1 << i)) {
  3680. if (i >= total_devices)
  3681. quit (1, "Command line options set a device that doesn't exist");
  3682. enable_device(devices[i]);
  3683. } else if (i < total_devices) {
  3684. if (opt_removedisabled) {
  3685. if (devices[i]->api == &cpu_api)
  3686. --opt_n_threads;
  3687. } else {
  3688. enable_device(devices[i]);
  3689. }
  3690. devices[i]->enabled = false;
  3691. }
  3692. }
  3693. total_devices = cgminer_id_count;
  3694. } else {
  3695. for (i = 0; i < total_devices; ++i)
  3696. enable_device(devices[i]);
  3697. }
  3698. if (!total_devices)
  3699. quit(1, "All devices disabled, cannot mine!");
  3700. load_temp_cutoffs();
  3701. devcursor = 8;
  3702. logstart = devcursor + total_devices + 1;
  3703. logcursor = logstart + 1;
  3704. if (opt_realquiet)
  3705. use_curses = false;
  3706. if (!total_pools) {
  3707. if (use_curses)
  3708. enable_curses();
  3709. applog(LOG_WARNING, "Need to specify at least one pool server.");
  3710. if (!use_curses || (use_curses && !input_pool(false)))
  3711. quit(1, "Pool setup failed");
  3712. }
  3713. for (i = 0; i < total_pools; i++) {
  3714. struct pool *pool = pools[i];
  3715. if (!pool->rpc_userpass) {
  3716. if (!pool->rpc_user || !pool->rpc_pass)
  3717. quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  3718. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  3719. if (!pool->rpc_userpass)
  3720. quit(1, "Failed to malloc userpass");
  3721. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  3722. } else {
  3723. pool->rpc_user = malloc(strlen(pool->rpc_userpass) + 1);
  3724. if (!pool->rpc_user)
  3725. quit(1, "Failed to malloc user");
  3726. strcpy(pool->rpc_user, pool->rpc_userpass);
  3727. pool->rpc_user = strtok(pool->rpc_user, ":");
  3728. if (!pool->rpc_user)
  3729. quit(1, "Failed to find colon delimiter in userpass");
  3730. }
  3731. }
  3732. /* Set the currentpool to pool 0 */
  3733. currentpool = pools[0];
  3734. #ifdef HAVE_SYSLOG_H
  3735. if (use_syslog)
  3736. openlog(PACKAGE, LOG_PID, LOG_USER);
  3737. #endif
  3738. #if defined(unix)
  3739. if (opt_stderr_cmd)
  3740. fork_monitor();
  3741. #endif // defined(unix)
  3742. total_threads = mining_threads + 8;
  3743. work_restart = calloc(total_threads, sizeof(*work_restart));
  3744. if (!work_restart)
  3745. quit(1, "Failed to calloc work_restart");
  3746. thr_info = calloc(total_threads, sizeof(*thr));
  3747. if (!thr_info)
  3748. quit(1, "Failed to calloc thr_info");
  3749. /* init workio thread info */
  3750. work_thr_id = mining_threads;
  3751. thr = &thr_info[work_thr_id];
  3752. thr->id = work_thr_id;
  3753. thr->q = tq_new();
  3754. if (!thr->q)
  3755. quit(1, "Failed to tq_new");
  3756. /* start work I/O thread */
  3757. if (thr_info_create(thr, NULL, workio_thread, thr))
  3758. quit(1, "workio thread create failed");
  3759. /* init longpoll thread info */
  3760. longpoll_thr_id = mining_threads + 1;
  3761. thr = &thr_info[longpoll_thr_id];
  3762. thr->id = longpoll_thr_id;
  3763. thr->q = tq_new();
  3764. if (!thr->q)
  3765. quit(1, "Failed to tq_new");
  3766. stage_thr_id = mining_threads + 2;
  3767. thr = &thr_info[stage_thr_id];
  3768. thr->q = tq_new();
  3769. if (!thr->q)
  3770. quit(1, "Failed to tq_new");
  3771. /* start stage thread */
  3772. if (thr_info_create(thr, NULL, stage_thread, thr))
  3773. quit(1, "stage thread create failed");
  3774. pthread_detach(thr->pth);
  3775. /* Create a unique get work queue */
  3776. getq = tq_new();
  3777. if (!getq)
  3778. quit(1, "Failed to create getq");
  3779. /* We use the getq mutex as the staged lock */
  3780. stgd_lock = &getq->mutex;
  3781. for (i = 0; i < total_pools; i++) {
  3782. struct pool *pool = pools[i];
  3783. pool->enabled = true;
  3784. pool->idle = true;
  3785. }
  3786. applog(LOG_NOTICE, "Probing for an alive pool");
  3787. do {
  3788. /* Look for at least one active pool before starting */
  3789. for (i = 0; i < total_pools; i++) {
  3790. struct pool *pool = pools[i];
  3791. if (pool_active(pool, false)) {
  3792. if (!currentpool)
  3793. currentpool = pool;
  3794. applog(LOG_INFO, "Pool %d %s active", pool->pool_no, pool->rpc_url);
  3795. pools_active = true;
  3796. break;
  3797. } else {
  3798. if (pool == currentpool)
  3799. currentpool = NULL;
  3800. applog(LOG_WARNING, "Unable to get work from pool %d %s", pool->pool_no, pool->rpc_url);
  3801. }
  3802. }
  3803. if (!pools_active) {
  3804. if (use_curses)
  3805. enable_curses();
  3806. applog(LOG_ERR, "No servers were found that could be used to get work from.");
  3807. applog(LOG_ERR, "Please check the details from the list below of the servers you have input");
  3808. applog(LOG_ERR, "Most likely you have input the wrong URL, forgotten to add a port, or have not set up workers");
  3809. for (i = 0; i < total_pools; i++) {
  3810. struct pool *pool;
  3811. pool = pools[i];
  3812. applog(LOG_WARNING, "Pool: %d URL: %s User: %s Password: %s",
  3813. i, pool->rpc_url, pool->rpc_user, pool->rpc_pass);
  3814. }
  3815. if (use_curses) {
  3816. halfdelay(150);
  3817. applog(LOG_ERR, "Press any key to exit, or cgminer will try again in 15s.");
  3818. if (getch() != ERR)
  3819. quit(0, "No servers could be used! Exiting.");
  3820. nocbreak();
  3821. } else
  3822. quit(0, "No servers could be used! Exiting.");
  3823. }
  3824. } while (!pools_active);
  3825. if (want_longpoll)
  3826. start_longpoll();
  3827. gettimeofday(&total_tv_start, NULL);
  3828. gettimeofday(&total_tv_end, NULL);
  3829. get_datestamp(datestamp, &total_tv_start);
  3830. #ifndef HAVE_OPENCL
  3831. opt_g_threads = 0;
  3832. #endif
  3833. // Start threads
  3834. k = 0;
  3835. for (i = 0; i < total_devices; ++i) {
  3836. struct cgpu_info *cgpu = devices[i];
  3837. for (j = 0; j < cgpu->threads; ++j, ++k) {
  3838. thr = &thr_info[k];
  3839. thr->id = k;
  3840. thr->cgpu = cgpu;
  3841. thr->device_thread = j;
  3842. thr->q = tq_new();
  3843. if (!thr->q)
  3844. quit(1, "tq_new failed in starting %s%d mining thread (#%d)", cgpu->api->name, cgpu->device_id, i);
  3845. /* Enable threads for devices set not to mine but disable
  3846. * their queue in case we wish to enable them later */
  3847. if (cgpu->enabled) {
  3848. if (opt_debug)
  3849. applog(LOG_DEBUG, "Pushing ping to thread %d", thr->id);
  3850. tq_push(thr->q, &ping);
  3851. }
  3852. if (cgpu->api->thread_prepare && !cgpu->api->thread_prepare(thr))
  3853. continue;
  3854. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  3855. quit(1, "thread %d create failed", thr->id);
  3856. cgpu->thread = thr;
  3857. }
  3858. }
  3859. #ifdef HAVE_OPENCL
  3860. applog(LOG_INFO, "%d gpu miner threads started", gpu_threads);
  3861. for (i = 0; i < nDevs; i++)
  3862. pause_dynamic_threads(i);
  3863. #endif
  3864. #ifdef WANT_CPUMINE
  3865. applog(LOG_INFO, "%d cpu miner threads started, "
  3866. "using SHA256 '%s' algorithm.",
  3867. opt_n_threads,
  3868. algo_names[opt_algo]);
  3869. #endif
  3870. if (use_curses)
  3871. enable_curses();
  3872. watchpool_thr_id = mining_threads + 3;
  3873. thr = &thr_info[watchpool_thr_id];
  3874. /* start watchpool thread */
  3875. if (thr_info_create(thr, NULL, watchpool_thread, NULL))
  3876. quit(1, "watchpool thread create failed");
  3877. pthread_detach(thr->pth);
  3878. watchdog_thr_id = mining_threads + 4;
  3879. thr = &thr_info[watchdog_thr_id];
  3880. /* start watchdog thread */
  3881. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  3882. quit(1, "watchdog thread create failed");
  3883. pthread_detach(thr->pth);
  3884. /* Create reinit gpu thread */
  3885. gpur_thr_id = mining_threads + 5;
  3886. thr = &thr_info[gpur_thr_id];
  3887. thr->q = tq_new();
  3888. if (!thr->q)
  3889. quit(1, "tq_new failed for gpur_thr_id");
  3890. if (thr_info_create(thr, NULL, reinit_gpu, thr))
  3891. quit(1, "reinit_gpu thread create failed");
  3892. /* Create API socket thread */
  3893. api_thr_id = mining_threads + 6;
  3894. thr = &thr_info[api_thr_id];
  3895. if (thr_info_create(thr, NULL, api_thread, thr))
  3896. quit(1, "API thread create failed");
  3897. pthread_detach(thr->pth);
  3898. /* Create curses input thread for keyboard input. Create this last so
  3899. * that we know all threads are created since this can call kill_work
  3900. * to try and shut down ll previous threads. */
  3901. input_thr_id = mining_threads + 7;
  3902. thr = &thr_info[input_thr_id];
  3903. if (thr_info_create(thr, NULL, input_thread, thr))
  3904. quit(1, "input thread create failed");
  3905. pthread_detach(thr->pth);
  3906. /* main loop - simply wait for workio thread to exit. This is not the
  3907. * normal exit path and only occurs should the workio_thread die
  3908. * unexpectedly */
  3909. pthread_join(thr_info[work_thr_id].pth, NULL);
  3910. applog(LOG_INFO, "workio thread dead, exiting.");
  3911. clean_up();
  3912. /* Not really necessary, but let's clean this up too anyway */
  3913. HASH_ITER(hh, staged_work, work, tmpwork) {
  3914. HASH_DEL(staged_work, work);
  3915. free_work(work);
  3916. }
  3917. HASH_ITER(hh, blocks, block, tmpblock) {
  3918. HASH_DEL(blocks, block);
  3919. free(block);
  3920. }
  3921. return 0;
  3922. }