miner.c 130 KB

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