miner.c 256 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075
  1. /*
  2. * Copyright 2011-2013 Con Kolivas
  3. * Copyright 2011-2013 Luke Dashjr
  4. * Copyright 2012-2013 Andrew Smith
  5. * Copyright 2010 Jeff Garzik
  6. *
  7. * This program is free software; you can redistribute it and/or modify it
  8. * under the terms of the GNU General Public License as published by the Free
  9. * Software Foundation; either version 3 of the License, or (at your option)
  10. * any later version. See COPYING for more details.
  11. */
  12. #include "config.h"
  13. #ifdef HAVE_CURSES
  14. #define PDC_WIDE
  15. #include <curses.h>
  16. #ifdef WACS_HLINE
  17. #define USE_UNICODE
  18. #endif
  19. #endif
  20. #include <ctype.h>
  21. #include <limits.h>
  22. #include <locale.h>
  23. #include <stdio.h>
  24. #include <stdlib.h>
  25. #include <string.h>
  26. #include <stdbool.h>
  27. #include <stdint.h>
  28. #include <unistd.h>
  29. #include <sys/time.h>
  30. #include <time.h>
  31. #include <math.h>
  32. #include <stdarg.h>
  33. #include <assert.h>
  34. #include <signal.h>
  35. #include <sys/stat.h>
  36. #include <sys/types.h>
  37. #include <dirent.h>
  38. #ifndef WIN32
  39. #include <sys/resource.h>
  40. #include <sys/socket.h>
  41. #else
  42. #include <winsock2.h>
  43. #endif
  44. #include <ccan/opt/opt.h>
  45. #include <jansson.h>
  46. #include <curl/curl.h>
  47. #include <libgen.h>
  48. #include <sha2.h>
  49. #include <utlist.h>
  50. #include <blkmaker.h>
  51. #include <blkmaker_jansson.h>
  52. #include <blktemplate.h>
  53. #include "compat.h"
  54. #include "deviceapi.h"
  55. #include "miner.h"
  56. #include "findnonce.h"
  57. #include "adl.h"
  58. #include "driver-cpu.h"
  59. #include "driver-opencl.h"
  60. #include "bench_block.h"
  61. #include "scrypt.h"
  62. #ifdef USE_AVALON
  63. #include "driver-avalon.h"
  64. #endif
  65. #ifdef USE_X6500
  66. #include "ft232r.h"
  67. #endif
  68. #if defined(unix) || defined(__APPLE__)
  69. #include <errno.h>
  70. #include <fcntl.h>
  71. #include <sys/wait.h>
  72. #endif
  73. #ifdef USE_SCRYPT
  74. #include "scrypt.h"
  75. #endif
  76. #if defined(USE_AVALON) || defined(USE_BITFORCE) || defined(USE_ICARUS) || defined(USE_MODMINER) || defined(USE_X6500) || defined(USE_ZTEX)
  77. # define USE_FPGA
  78. # define USE_FPGA_SERIAL
  79. #endif
  80. struct strategies strategies[] = {
  81. { "Failover" },
  82. { "Round Robin" },
  83. { "Rotate" },
  84. { "Load Balance" },
  85. { "Balance" },
  86. };
  87. static char packagename[256];
  88. bool opt_protocol;
  89. bool opt_dev_protocol;
  90. static bool opt_benchmark;
  91. static bool want_longpoll = true;
  92. static bool want_gbt = true;
  93. static bool want_getwork = true;
  94. #if BLKMAKER_VERSION > 1
  95. struct _cbscript_t {
  96. char *data;
  97. size_t sz;
  98. };
  99. static struct _cbscript_t opt_coinbase_script;
  100. static uint32_t template_nonce;
  101. #endif
  102. #if BLKMAKER_VERSION < 1
  103. const
  104. #endif
  105. char *opt_coinbase_sig;
  106. char *request_target_str;
  107. float request_pdiff = 1.0;
  108. double request_bdiff;
  109. static bool want_stratum = true;
  110. bool have_longpoll;
  111. int opt_skip_checks;
  112. bool want_per_device_stats;
  113. bool use_syslog;
  114. bool opt_quiet_work_updates;
  115. bool opt_quiet;
  116. bool opt_realquiet;
  117. bool opt_loginput;
  118. bool opt_compact;
  119. bool opt_show_procs;
  120. const int opt_cutofftemp = 95;
  121. int opt_hysteresis = 3;
  122. static int opt_retries = -1;
  123. int opt_fail_pause = 5;
  124. int opt_log_interval = 5;
  125. int opt_queue = 1;
  126. int opt_scantime = 60;
  127. int opt_expiry = 120;
  128. int opt_expiry_lp = 3600;
  129. int opt_bench_algo = -1;
  130. static const bool opt_time = true;
  131. unsigned long long global_hashrate;
  132. #ifdef HAVE_OPENCL
  133. int opt_dynamic_interval = 7;
  134. int nDevs;
  135. int opt_g_threads = -1;
  136. int gpu_threads;
  137. #endif
  138. #ifdef USE_SCRYPT
  139. static char detect_algo = 1;
  140. bool opt_scrypt;
  141. #else
  142. static char detect_algo;
  143. #endif
  144. bool opt_restart = true;
  145. static bool opt_nogpu;
  146. struct string_elist *scan_devices;
  147. bool opt_force_dev_init;
  148. static bool devices_enabled[MAX_DEVICES];
  149. static int opt_devs_enabled;
  150. static bool opt_display_devs;
  151. static bool opt_removedisabled;
  152. int total_devices;
  153. struct cgpu_info **devices;
  154. int total_devices_new;
  155. struct cgpu_info **devices_new;
  156. bool have_opencl;
  157. int opt_n_threads = -1;
  158. int mining_threads;
  159. int num_processors;
  160. #ifdef HAVE_CURSES
  161. bool use_curses = true;
  162. #else
  163. bool use_curses;
  164. #endif
  165. #ifdef HAVE_LIBUSB
  166. bool have_libusb = true;
  167. #else
  168. const bool have_libusb;
  169. #endif
  170. static bool opt_submit_stale = true;
  171. static int opt_shares;
  172. static int opt_submit_threads = 0x40;
  173. bool opt_fail_only;
  174. bool opt_autofan;
  175. bool opt_autoengine;
  176. bool opt_noadl;
  177. char *opt_api_allow = NULL;
  178. char *opt_api_groups;
  179. char *opt_api_description = PACKAGE_STRING;
  180. int opt_api_port = 4028;
  181. bool opt_api_listen;
  182. bool opt_api_network;
  183. bool opt_delaynet;
  184. bool opt_disable_pool;
  185. char *opt_icarus_options = NULL;
  186. char *opt_icarus_timing = NULL;
  187. bool opt_worktime;
  188. #ifdef USE_AVALON
  189. char *opt_avalon_options = NULL;
  190. #endif
  191. char *opt_kernel_path;
  192. char *cgminer_path;
  193. #if defined(USE_BITFORCE)
  194. bool opt_bfl_noncerange;
  195. #endif
  196. #define QUIET (opt_quiet || opt_realquiet)
  197. struct thr_info *control_thr;
  198. struct thr_info **mining_thr;
  199. static int gwsched_thr_id;
  200. static int stage_thr_id;
  201. static int watchpool_thr_id;
  202. static int watchdog_thr_id;
  203. #ifdef HAVE_CURSES
  204. static int input_thr_id;
  205. #endif
  206. int gpur_thr_id;
  207. static int api_thr_id;
  208. static int total_control_threads;
  209. pthread_mutex_t hash_lock;
  210. static pthread_mutex_t *stgd_lock;
  211. pthread_mutex_t console_lock;
  212. cglock_t ch_lock;
  213. static pthread_rwlock_t blk_lock;
  214. static pthread_mutex_t sshare_lock;
  215. pthread_rwlock_t netacc_lock;
  216. pthread_rwlock_t mining_thr_lock;
  217. pthread_rwlock_t devices_lock;
  218. static pthread_mutex_t lp_lock;
  219. static pthread_cond_t lp_cond;
  220. pthread_cond_t gws_cond;
  221. bool shutting_down;
  222. double total_mhashes_done;
  223. static struct timeval total_tv_start, total_tv_end;
  224. static struct timeval miner_started;
  225. cglock_t control_lock;
  226. pthread_mutex_t stats_lock;
  227. static pthread_mutex_t submitting_lock;
  228. static int total_submitting;
  229. static struct work *submit_waiting;
  230. notifier_t submit_waiting_notifier;
  231. int hw_errors;
  232. int total_accepted, total_rejected, total_diff1;
  233. int total_bad_nonces;
  234. int total_getworks, total_stale, total_discarded;
  235. uint64_t total_bytes_rcvd, total_bytes_sent;
  236. double total_diff_accepted, total_diff_rejected, total_diff_stale;
  237. static int staged_rollable;
  238. unsigned int new_blocks;
  239. unsigned int found_blocks;
  240. unsigned int local_work;
  241. unsigned int total_go, total_ro;
  242. struct pool **pools;
  243. static struct pool *currentpool = NULL;
  244. int total_pools, enabled_pools;
  245. enum pool_strategy pool_strategy = POOL_FAILOVER;
  246. int opt_rotate_period;
  247. static int total_urls, total_users, total_passes;
  248. static
  249. #ifndef HAVE_CURSES
  250. const
  251. #endif
  252. bool curses_active;
  253. #ifdef HAVE_CURSES
  254. static
  255. #ifdef USE_UNICODE
  256. bool use_unicode = true;
  257. #else
  258. const bool use_unicode;
  259. #endif
  260. bool selecting_device;
  261. unsigned selected_device;
  262. #endif
  263. static char current_block[40];
  264. /* Protected by ch_lock */
  265. static char *current_hash;
  266. static uint32_t current_block_id;
  267. char *current_fullhash;
  268. static char datestamp[40];
  269. static char blocktime[32];
  270. struct timeval block_timeval;
  271. static char best_share[8] = "0";
  272. double current_diff = 0xFFFFFFFFFFFFFFFFULL;
  273. static char block_diff[8];
  274. static char net_hashrate[10];
  275. uint64_t best_diff = 0;
  276. static bool known_blkheight_current;
  277. static uint32_t known_blkheight;
  278. static uint32_t known_blkheight_blkid;
  279. struct block {
  280. char hash[40];
  281. UT_hash_handle hh;
  282. int block_no;
  283. };
  284. static struct block *blocks = NULL;
  285. int swork_id;
  286. /* For creating a hash database of stratum shares submitted that have not had
  287. * a response yet */
  288. struct stratum_share {
  289. UT_hash_handle hh;
  290. bool block;
  291. struct work *work;
  292. int id;
  293. };
  294. static struct stratum_share *stratum_shares = NULL;
  295. char *opt_socks_proxy = NULL;
  296. static const char def_conf[] = "bfgminer.conf";
  297. static bool config_loaded;
  298. static int include_count;
  299. #define JSON_INCLUDE_CONF "include"
  300. #define JSON_LOAD_ERROR "JSON decode of file '%s' failed\n %s"
  301. #define JSON_LOAD_ERROR_LEN strlen(JSON_LOAD_ERROR)
  302. #define JSON_MAX_DEPTH 10
  303. #define JSON_MAX_DEPTH_ERR "Too many levels of JSON includes (limit 10) or a loop"
  304. #if defined(unix) || defined(__APPLE__)
  305. static char *opt_stderr_cmd = NULL;
  306. static int forkpid;
  307. #endif // defined(unix)
  308. struct sigaction termhandler, inthandler;
  309. struct thread_q *getq;
  310. static int total_work;
  311. static bool staged_full;
  312. struct work *staged_work = NULL;
  313. struct schedtime {
  314. bool enable;
  315. struct tm tm;
  316. };
  317. struct schedtime schedstart;
  318. struct schedtime schedstop;
  319. bool sched_paused;
  320. static bool time_before(struct tm *tm1, struct tm *tm2)
  321. {
  322. if (tm1->tm_hour < tm2->tm_hour)
  323. return true;
  324. if (tm1->tm_hour == tm2->tm_hour && tm1->tm_min < tm2->tm_min)
  325. return true;
  326. return false;
  327. }
  328. static bool should_run(void)
  329. {
  330. struct tm tm;
  331. time_t tt;
  332. bool within_range;
  333. if (!schedstart.enable && !schedstop.enable)
  334. return true;
  335. tt = time(NULL);
  336. localtime_r(&tt, &tm);
  337. // NOTE: This is delicately balanced so that should_run is always false if schedstart==schedstop
  338. if (time_before(&schedstop.tm, &schedstart.tm))
  339. within_range = (time_before(&tm, &schedstop.tm) || !time_before(&tm, &schedstart.tm));
  340. else
  341. within_range = (time_before(&tm, &schedstop.tm) && !time_before(&tm, &schedstart.tm));
  342. if (within_range && !schedstop.enable)
  343. /* This is a once off event with no stop time set */
  344. schedstart.enable = false;
  345. return within_range;
  346. }
  347. void get_datestamp(char *f, time_t tt)
  348. {
  349. struct tm _tm;
  350. struct tm *tm = &_tm;
  351. if (tt == INVALID_TIMESTAMP)
  352. tt = time(NULL);
  353. localtime_r(&tt, tm);
  354. sprintf(f, "[%d-%02d-%02d %02d:%02d:%02d]",
  355. tm->tm_year + 1900,
  356. tm->tm_mon + 1,
  357. tm->tm_mday,
  358. tm->tm_hour,
  359. tm->tm_min,
  360. tm->tm_sec);
  361. }
  362. void get_timestamp(char *f, time_t tt)
  363. {
  364. struct tm _tm;
  365. struct tm *tm = &_tm;
  366. localtime_r(&tt, tm);
  367. sprintf(f, "[%02d:%02d:%02d]",
  368. tm->tm_hour,
  369. tm->tm_min,
  370. tm->tm_sec);
  371. }
  372. static void applog_and_exit(const char *fmt, ...) FORMAT_SYNTAX_CHECK(printf, 1, 2);
  373. static char exit_buf[512];
  374. static void applog_and_exit(const char *fmt, ...)
  375. {
  376. va_list ap;
  377. va_start(ap, fmt);
  378. vsnprintf(exit_buf, sizeof(exit_buf), fmt, ap);
  379. va_end(ap);
  380. _applog(LOG_ERR, exit_buf);
  381. exit(1);
  382. }
  383. static pthread_mutex_t sharelog_lock;
  384. static FILE *sharelog_file = NULL;
  385. struct thr_info *get_thread(int thr_id)
  386. {
  387. struct thr_info *thr;
  388. rd_lock(&mining_thr_lock);
  389. thr = mining_thr[thr_id];
  390. rd_unlock(&mining_thr_lock);
  391. return thr;
  392. }
  393. static struct cgpu_info *get_thr_cgpu(int thr_id)
  394. {
  395. struct thr_info *thr = get_thread(thr_id);
  396. return thr->cgpu;
  397. }
  398. struct cgpu_info *get_devices(int id)
  399. {
  400. struct cgpu_info *cgpu;
  401. rd_lock(&devices_lock);
  402. cgpu = devices[id];
  403. rd_unlock(&devices_lock);
  404. return cgpu;
  405. }
  406. static void sharelog(const char*disposition, const struct work*work)
  407. {
  408. char target[(sizeof(work->target) * 2) + 1];
  409. char hash[(sizeof(work->hash) * 2) + 1];
  410. char data[(sizeof(work->data) * 2) + 1];
  411. struct cgpu_info *cgpu;
  412. unsigned long int t;
  413. struct pool *pool;
  414. int thr_id, rv;
  415. char s[1024];
  416. size_t ret;
  417. if (!sharelog_file)
  418. return;
  419. thr_id = work->thr_id;
  420. cgpu = get_thr_cgpu(thr_id);
  421. pool = work->pool;
  422. t = (unsigned long int)(work->tv_work_found.tv_sec);
  423. bin2hex(target, work->target, sizeof(work->target));
  424. bin2hex(hash, work->hash, sizeof(work->hash));
  425. bin2hex(data, work->data, sizeof(work->data));
  426. // timestamp,disposition,target,pool,dev,thr,sharehash,sharedata
  427. rv = snprintf(s, sizeof(s), "%lu,%s,%s,%s,%s,%u,%s,%s\n", t, disposition, target, pool->rpc_url, cgpu->proc_repr_ns, thr_id, hash, data);
  428. if (rv >= (int)(sizeof(s)))
  429. s[sizeof(s) - 1] = '\0';
  430. else if (rv < 0) {
  431. applog(LOG_ERR, "sharelog printf error");
  432. return;
  433. }
  434. mutex_lock(&sharelog_lock);
  435. ret = fwrite(s, rv, 1, sharelog_file);
  436. fflush(sharelog_file);
  437. mutex_unlock(&sharelog_lock);
  438. if (ret != 1)
  439. applog(LOG_ERR, "sharelog fwrite error");
  440. }
  441. static char *getwork_req = "{\"method\": \"getwork\", \"params\": [], \"id\":0}\n";
  442. /* Return value is ignored if not called from add_pool_details */
  443. struct pool *add_pool(void)
  444. {
  445. struct pool *pool;
  446. pool = calloc(sizeof(struct pool), 1);
  447. if (!pool)
  448. quit(1, "Failed to malloc pool in add_pool");
  449. pool->pool_no = pool->prio = total_pools;
  450. mutex_init(&pool->last_work_lock);
  451. mutex_init(&pool->pool_lock);
  452. if (unlikely(pthread_cond_init(&pool->cr_cond, NULL)))
  453. quit(1, "Failed to pthread_cond_init in add_pool");
  454. cglock_init(&pool->data_lock);
  455. mutex_init(&pool->stratum_lock);
  456. timer_unset(&pool->swork.tv_transparency);
  457. /* Make sure the pool doesn't think we've been idle since time 0 */
  458. pool->tv_idle.tv_sec = ~0UL;
  459. bfg_init_time();
  460. cgtime(&pool->cgminer_stats.start_tv);
  461. pool->rpc_proxy = NULL;
  462. pool->sock = INVSOCK;
  463. pool->lp_socket = CURL_SOCKET_BAD;
  464. pools = realloc(pools, sizeof(struct pool *) * (total_pools + 2));
  465. pools[total_pools++] = pool;
  466. return pool;
  467. }
  468. /* Pool variant of test and set */
  469. static bool pool_tset(struct pool *pool, bool *var)
  470. {
  471. bool ret;
  472. mutex_lock(&pool->pool_lock);
  473. ret = *var;
  474. *var = true;
  475. mutex_unlock(&pool->pool_lock);
  476. return ret;
  477. }
  478. bool pool_tclear(struct pool *pool, bool *var)
  479. {
  480. bool ret;
  481. mutex_lock(&pool->pool_lock);
  482. ret = *var;
  483. *var = false;
  484. mutex_unlock(&pool->pool_lock);
  485. return ret;
  486. }
  487. struct pool *current_pool(void)
  488. {
  489. struct pool *pool;
  490. cg_rlock(&control_lock);
  491. pool = currentpool;
  492. cg_runlock(&control_lock);
  493. return pool;
  494. }
  495. char *set_int_range(const char *arg, int *i, int min, int max)
  496. {
  497. char *err = opt_set_intval(arg, i);
  498. if (err)
  499. return err;
  500. if (*i < min || *i > max)
  501. return "Value out of range";
  502. return NULL;
  503. }
  504. static char *set_int_0_to_9999(const char *arg, int *i)
  505. {
  506. return set_int_range(arg, i, 0, 9999);
  507. }
  508. static char *set_int_1_to_65535(const char *arg, int *i)
  509. {
  510. return set_int_range(arg, i, 1, 65535);
  511. }
  512. static char *set_int_0_to_10(const char *arg, int *i)
  513. {
  514. return set_int_range(arg, i, 0, 10);
  515. }
  516. static char *set_int_1_to_10(const char *arg, int *i)
  517. {
  518. return set_int_range(arg, i, 1, 10);
  519. }
  520. char *set_strdup(const char *arg, char **p)
  521. {
  522. *p = strdup((char *)arg);
  523. return NULL;
  524. }
  525. #if BLKMAKER_VERSION > 1
  526. static char *set_b58addr(const char *arg, struct _cbscript_t *p)
  527. {
  528. size_t scriptsz = blkmk_address_to_script(NULL, 0, arg);
  529. if (!scriptsz)
  530. return "Invalid address";
  531. char *script = malloc(scriptsz);
  532. if (blkmk_address_to_script(script, scriptsz, arg) != scriptsz) {
  533. free(script);
  534. return "Failed to convert address to script";
  535. }
  536. p->data = script;
  537. p->sz = scriptsz;
  538. return NULL;
  539. }
  540. #endif
  541. static void bdiff_target_leadzero(unsigned char *target, double diff);
  542. char *set_request_diff(const char *arg, float *p)
  543. {
  544. unsigned char target[32];
  545. char *e = opt_set_floatval(arg, p);
  546. if (e)
  547. return e;
  548. request_bdiff = (double)*p * 0.9999847412109375;
  549. bdiff_target_leadzero(target, request_bdiff);
  550. request_target_str = malloc(65);
  551. bin2hex(request_target_str, target, 32);
  552. return NULL;
  553. }
  554. #ifdef USE_FPGA_SERIAL
  555. #ifdef HAVE_LIBUDEV
  556. #include <libudev.h>
  557. #endif
  558. static
  559. char* add_serial_all(char*arg, char*p) {
  560. size_t pLen = p - arg;
  561. char dev[pLen + PATH_MAX];
  562. memcpy(dev, arg, pLen);
  563. char *devp = &dev[pLen];
  564. #ifdef HAVE_LIBUDEV
  565. struct udev *udev = udev_new();
  566. struct udev_enumerate *enumerate = udev_enumerate_new(udev);
  567. struct udev_list_entry *list_entry;
  568. udev_enumerate_add_match_subsystem(enumerate, "tty");
  569. udev_enumerate_add_match_property(enumerate, "ID_SERIAL", "*");
  570. udev_enumerate_scan_devices(enumerate);
  571. udev_list_entry_foreach(list_entry, udev_enumerate_get_list_entry(enumerate)) {
  572. struct udev_device *device = udev_device_new_from_syspath(
  573. udev_enumerate_get_udev(enumerate),
  574. udev_list_entry_get_name(list_entry)
  575. );
  576. if (!device)
  577. continue;
  578. const char *devpath = udev_device_get_devnode(device);
  579. if (devpath) {
  580. strcpy(devp, devpath);
  581. applog(LOG_DEBUG, "scan-serial: libudev all-adding %s", dev);
  582. string_elist_add(dev, &scan_devices);
  583. }
  584. udev_device_unref(device);
  585. }
  586. udev_enumerate_unref(enumerate);
  587. udev_unref(udev);
  588. #elif defined(WIN32)
  589. size_t bufLen = 0x100;
  590. tryagain: ;
  591. char buf[bufLen];
  592. if (!QueryDosDevice(NULL, buf, bufLen)) {
  593. if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
  594. bufLen *= 2;
  595. applog(LOG_DEBUG, "scan-serial: QueryDosDevice returned insufficent buffer error; enlarging to %lx", (unsigned long)bufLen);
  596. goto tryagain;
  597. }
  598. return "scan-serial: Error occurred trying to enumerate COM ports with QueryDosDevice";
  599. }
  600. size_t tLen;
  601. memcpy(devp, "\\\\.\\", 4);
  602. devp = &devp[4];
  603. for (char *t = buf; *t; t += tLen) {
  604. tLen = strlen(t) + 1;
  605. if (strncmp("COM", t, 3))
  606. continue;
  607. memcpy(devp, t, tLen);
  608. applog(LOG_DEBUG, "scan-serial: QueryDosDevice all-adding %s", dev);
  609. string_elist_add(dev, &scan_devices);
  610. }
  611. #else
  612. DIR *D;
  613. struct dirent *de;
  614. const char devdir[] = "/dev";
  615. const size_t devdirlen = sizeof(devdir) - 1;
  616. char *devpath = devp;
  617. char *devfile = devpath + devdirlen + 1;
  618. D = opendir(devdir);
  619. if (!D)
  620. return "scan-serial 'all' is not supported on this platform";
  621. memcpy(devpath, devdir, devdirlen);
  622. devpath[devdirlen] = '/';
  623. while ( (de = readdir(D)) ) {
  624. if (!strncmp(de->d_name, "cu.", 3))
  625. goto trydev;
  626. if (strncmp(de->d_name, "tty", 3))
  627. continue;
  628. if (strncmp(&de->d_name[3], "USB", 3) && strncmp(&de->d_name[3], "ACM", 3))
  629. continue;
  630. trydev:
  631. strcpy(devfile, de->d_name);
  632. applog(LOG_DEBUG, "scan-serial: /dev glob all-adding %s", dev);
  633. string_elist_add(dev, &scan_devices);
  634. }
  635. closedir(D);
  636. return NULL;
  637. #endif
  638. return NULL;
  639. }
  640. static char *add_serial(char *arg)
  641. {
  642. char *p = strchr(arg, ':');
  643. if (p)
  644. ++p;
  645. else
  646. p = arg;
  647. if (!strcasecmp(p, "all")) {
  648. return add_serial_all(arg, p);
  649. }
  650. string_elist_add(arg, &scan_devices);
  651. return NULL;
  652. }
  653. #endif
  654. bool get_intrange(const char *arg, int *val1, int *val2)
  655. {
  656. // NOTE: This could be done with sscanf, but its %n is broken in strange ways on Windows
  657. char *p, *p2;
  658. *val1 = strtol(arg, &p, 0);
  659. if (arg == p)
  660. // Zero-length ending number, invalid
  661. return false;
  662. while (true)
  663. {
  664. if (!p[0])
  665. {
  666. *val2 = *val1;
  667. return true;
  668. }
  669. if (p[0] == '-')
  670. break;
  671. if (!isspace(p[0]))
  672. // Garbage, invalid
  673. return false;
  674. ++p;
  675. }
  676. p2 = &p[1];
  677. *val2 = strtol(p2, &p, 0);
  678. if (p2 == p)
  679. // Zero-length ending number, invalid
  680. return false;
  681. while (true)
  682. {
  683. if (!p[0])
  684. return true;
  685. if (!isspace(p[0]))
  686. // Garbage, invalid
  687. return false;
  688. ++p;
  689. }
  690. }
  691. static
  692. void _test_intrange(const char *s, const int v[2])
  693. {
  694. int a[2];
  695. if (!get_intrange(s, &a[0], &a[1]))
  696. applog(LOG_ERR, "Test \"%s\" failed: returned false", s);
  697. for (int i = 0; i < 2; ++i)
  698. if (unlikely(a[i] != v[i]))
  699. applog(LOG_ERR, "Test \"%s\" failed: value %d should be %d but got %d", s, i, v[i], a[i]);
  700. }
  701. #define _test_intrange(s, ...) _test_intrange(s, (int[]){ __VA_ARGS__ })
  702. static
  703. void _test_intrange_fail(const char *s)
  704. {
  705. int a[2];
  706. if (get_intrange(s, &a[0], &a[1]))
  707. applog(LOG_ERR, "Test !\"%s\" failed: returned true with %d and %d", s, a[0], a[1]);
  708. }
  709. static
  710. void test_intrange()
  711. {
  712. _test_intrange("-1--2", -1, -2);
  713. _test_intrange("-1-2", -1, 2);
  714. _test_intrange("1--2", 1, -2);
  715. _test_intrange("1-2", 1, 2);
  716. _test_intrange("111-222", 111, 222);
  717. _test_intrange(" 11 - 22 ", 11, 22);
  718. _test_intrange("+11-+22", 11, 22);
  719. _test_intrange("-1", -1, -1);
  720. _test_intrange_fail("all");
  721. _test_intrange_fail("1-");
  722. _test_intrange_fail("");
  723. _test_intrange_fail("1-54x");
  724. }
  725. static char *set_devices(char *arg)
  726. {
  727. int i, val1 = 0, val2 = 0;
  728. char *nextptr;
  729. if (*arg) {
  730. if (*arg == '?') {
  731. opt_display_devs = true;
  732. return NULL;
  733. }
  734. } else
  735. return "Invalid device parameters";
  736. nextptr = strtok(arg, ",");
  737. if (nextptr == NULL)
  738. return "Invalid parameters for set devices";
  739. if (!get_intrange(nextptr, &val1, &val2))
  740. return "Invalid device number";
  741. if (val1 < 0 || val1 > MAX_DEVICES || val2 < 0 || val2 > MAX_DEVICES ||
  742. val1 > val2) {
  743. return "Invalid value passed to set devices";
  744. }
  745. for (i = val1; i <= val2; i++) {
  746. devices_enabled[i] = true;
  747. opt_devs_enabled++;
  748. }
  749. while ((nextptr = strtok(NULL, ",")) != NULL) {
  750. if (!get_intrange(nextptr, &val1, &val2))
  751. return "Invalid device number";
  752. if (val1 < 0 || val1 > MAX_DEVICES || val2 < 0 || val2 > MAX_DEVICES ||
  753. val1 > val2) {
  754. return "Invalid value passed to set devices";
  755. }
  756. for (i = val1; i <= val2; i++) {
  757. devices_enabled[i] = true;
  758. opt_devs_enabled++;
  759. }
  760. }
  761. return NULL;
  762. }
  763. static char *set_balance(enum pool_strategy *strategy)
  764. {
  765. *strategy = POOL_BALANCE;
  766. return NULL;
  767. }
  768. static char *set_loadbalance(enum pool_strategy *strategy)
  769. {
  770. *strategy = POOL_LOADBALANCE;
  771. return NULL;
  772. }
  773. static char *set_rotate(const char *arg, int *i)
  774. {
  775. pool_strategy = POOL_ROTATE;
  776. return set_int_range(arg, i, 0, 9999);
  777. }
  778. static char *set_rr(enum pool_strategy *strategy)
  779. {
  780. *strategy = POOL_ROUNDROBIN;
  781. return NULL;
  782. }
  783. /* Detect that url is for a stratum protocol either via the presence of
  784. * stratum+tcp or by detecting a stratum server response */
  785. bool detect_stratum(struct pool *pool, char *url)
  786. {
  787. if (!extract_sockaddr(pool, url))
  788. return false;
  789. if (!strncasecmp(url, "stratum+tcp://", 14)) {
  790. pool->rpc_url = strdup(url);
  791. pool->has_stratum = true;
  792. pool->stratum_url = pool->sockaddr_url;
  793. return true;
  794. }
  795. return false;
  796. }
  797. static char *set_url(char *arg)
  798. {
  799. struct pool *pool;
  800. total_urls++;
  801. if (total_urls > total_pools)
  802. add_pool();
  803. pool = pools[total_urls - 1];
  804. if (detect_stratum(pool, arg))
  805. return NULL;
  806. opt_set_charp(arg, &pool->rpc_url);
  807. if (strncmp(arg, "http://", 7) &&
  808. strncmp(arg, "https://", 8)) {
  809. char *httpinput;
  810. httpinput = malloc(255);
  811. if (!httpinput)
  812. quit(1, "Failed to malloc httpinput");
  813. strcpy(httpinput, "http://");
  814. strncat(httpinput, arg, 248);
  815. pool->rpc_url = httpinput;
  816. }
  817. return NULL;
  818. }
  819. static char *set_user(const char *arg)
  820. {
  821. struct pool *pool;
  822. total_users++;
  823. if (total_users > total_pools)
  824. add_pool();
  825. pool = pools[total_users - 1];
  826. opt_set_charp(arg, &pool->rpc_user);
  827. return NULL;
  828. }
  829. static char *set_pass(const char *arg)
  830. {
  831. struct pool *pool;
  832. total_passes++;
  833. if (total_passes > total_pools)
  834. add_pool();
  835. pool = pools[total_passes - 1];
  836. opt_set_charp(arg, &pool->rpc_pass);
  837. return NULL;
  838. }
  839. static char *set_userpass(const char *arg)
  840. {
  841. struct pool *pool;
  842. char *updup;
  843. if (total_users != total_passes)
  844. return "User + pass options must be balanced before userpass";
  845. ++total_users;
  846. ++total_passes;
  847. if (total_users > total_pools)
  848. add_pool();
  849. pool = pools[total_users - 1];
  850. updup = strdup(arg);
  851. opt_set_charp(arg, &pool->rpc_userpass);
  852. pool->rpc_user = strtok(updup, ":");
  853. if (!pool->rpc_user)
  854. return "Failed to find : delimited user info";
  855. pool->rpc_pass = strtok(NULL, ":");
  856. if (!pool->rpc_pass)
  857. pool->rpc_pass = "";
  858. return NULL;
  859. }
  860. static char *set_pool_priority(const char *arg)
  861. {
  862. struct pool *pool;
  863. if (!total_pools)
  864. return "Usage of --pool-priority before pools are defined does not make sense";
  865. pool = pools[total_pools - 1];
  866. opt_set_intval(arg, &pool->prio);
  867. return NULL;
  868. }
  869. static char *set_pool_proxy(const char *arg)
  870. {
  871. struct pool *pool;
  872. if (!total_pools)
  873. return "Usage of --pool-proxy before pools are defined does not make sense";
  874. if (!our_curl_supports_proxy_uris())
  875. return "Your installed cURL library does not support proxy URIs. At least version 7.21.7 is required.";
  876. pool = pools[total_pools - 1];
  877. opt_set_charp(arg, &pool->rpc_proxy);
  878. return NULL;
  879. }
  880. static char *set_pool_force_rollntime(const char *arg)
  881. {
  882. struct pool *pool;
  883. if (!total_pools)
  884. return "Usage of --force-rollntime before pools are defined does not make sense";
  885. pool = pools[total_pools - 1];
  886. opt_set_intval(arg, &pool->force_rollntime);
  887. return NULL;
  888. }
  889. static char *enable_debug(bool *flag)
  890. {
  891. *flag = true;
  892. opt_debug_console = true;
  893. /* Turn on verbose output, too. */
  894. opt_log_output = true;
  895. return NULL;
  896. }
  897. static char *set_schedtime(const char *arg, struct schedtime *st)
  898. {
  899. if (sscanf(arg, "%d:%d", &st->tm.tm_hour, &st->tm.tm_min) != 2)
  900. {
  901. if (strcasecmp(arg, "now"))
  902. return "Invalid time set, should be HH:MM";
  903. } else
  904. schedstop.tm.tm_sec = 0;
  905. if (st->tm.tm_hour > 23 || st->tm.tm_min > 59 || st->tm.tm_hour < 0 || st->tm.tm_min < 0)
  906. return "Invalid time set.";
  907. st->enable = true;
  908. return NULL;
  909. }
  910. static
  911. char *set_log_file(char *arg)
  912. {
  913. char *r = "";
  914. long int i = strtol(arg, &r, 10);
  915. int fd, stderr_fd = fileno(stderr);
  916. if ((!*r) && i >= 0 && i <= INT_MAX)
  917. fd = i;
  918. else
  919. if (!strcmp(arg, "-"))
  920. {
  921. fd = fileno(stdout);
  922. if (unlikely(fd == -1))
  923. return "Standard output missing for log-file";
  924. }
  925. else
  926. {
  927. fd = open(arg, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR);
  928. if (unlikely(fd == -1))
  929. return "Failed to open %s for log-file";
  930. }
  931. close(stderr_fd);
  932. if (unlikely(-1 == dup2(fd, stderr_fd)))
  933. return "Failed to dup2 for log-file";
  934. close(fd);
  935. return NULL;
  936. }
  937. static char* set_sharelog(char *arg)
  938. {
  939. char *r = "";
  940. long int i = strtol(arg, &r, 10);
  941. if ((!*r) && i >= 0 && i <= INT_MAX) {
  942. sharelog_file = fdopen((int)i, "a");
  943. if (!sharelog_file)
  944. applog(LOG_ERR, "Failed to open fd %u for share log", (unsigned int)i);
  945. } else if (!strcmp(arg, "-")) {
  946. sharelog_file = stdout;
  947. if (!sharelog_file)
  948. applog(LOG_ERR, "Standard output missing for share log");
  949. } else {
  950. sharelog_file = fopen(arg, "a");
  951. if (!sharelog_file)
  952. applog(LOG_ERR, "Failed to open %s for share log", arg);
  953. }
  954. return NULL;
  955. }
  956. static char *temp_cutoff_str = "";
  957. static char *temp_target_str = "";
  958. char *set_temp_cutoff(char *arg)
  959. {
  960. int val;
  961. if (!(arg && arg[0]))
  962. return "Invalid parameters for set temp cutoff";
  963. val = atoi(arg);
  964. if (val < 0 || val > 200)
  965. return "Invalid value passed to set temp cutoff";
  966. temp_cutoff_str = arg;
  967. return NULL;
  968. }
  969. char *set_temp_target(char *arg)
  970. {
  971. int val;
  972. if (!(arg && arg[0]))
  973. return "Invalid parameters for set temp target";
  974. val = atoi(arg);
  975. if (val < 0 || val > 200)
  976. return "Invalid value passed to set temp target";
  977. temp_target_str = arg;
  978. return NULL;
  979. }
  980. // For a single element string, this always returns the number (for all calls)
  981. // For multi-element strings, it returns each element as a number in order, and 0 when there are no more
  982. static int temp_strtok(char *base, char **n)
  983. {
  984. char *i = *n;
  985. char *p = strchr(i, ',');
  986. if (p) {
  987. p[0] = '\0';
  988. *n = &p[1];
  989. }
  990. else
  991. if (base != i)
  992. *n = strchr(i, '\0');
  993. return atoi(i);
  994. }
  995. static void load_temp_config_cgpu(struct cgpu_info *cgpu, char **cutoff_np, char **target_np)
  996. {
  997. int target_off, val;
  998. // cutoff default may be specified by driver during probe; otherwise, opt_cutofftemp (const)
  999. if (!cgpu->cutofftemp)
  1000. cgpu->cutofftemp = opt_cutofftemp;
  1001. // target default may be specified by driver, and is moved with offset; otherwise, offset minus 6
  1002. if (cgpu->targettemp)
  1003. target_off = cgpu->targettemp - cgpu->cutofftemp;
  1004. else
  1005. target_off = -6;
  1006. val = temp_strtok(temp_cutoff_str, cutoff_np);
  1007. if (val < 0 || val > 200)
  1008. quit(1, "Invalid value passed to set temp cutoff");
  1009. if (val)
  1010. cgpu->cutofftemp = val;
  1011. val = temp_strtok(temp_target_str, target_np);
  1012. if (val < 0 || val > 200)
  1013. quit(1, "Invalid value passed to set temp target");
  1014. if (val)
  1015. cgpu->targettemp = val;
  1016. else
  1017. cgpu->targettemp = cgpu->cutofftemp + target_off;
  1018. applog(LOG_DEBUG, "%"PRIprepr": Set temperature config: target=%d cutoff=%d",
  1019. cgpu->proc_repr,
  1020. cgpu->targettemp, cgpu->cutofftemp);
  1021. }
  1022. static void load_temp_config()
  1023. {
  1024. int i;
  1025. char *cutoff_n, *target_n;
  1026. struct cgpu_info *cgpu;
  1027. cutoff_n = temp_cutoff_str;
  1028. target_n = temp_target_str;
  1029. for (i = 0; i < total_devices; ++i) {
  1030. cgpu = get_devices(i);
  1031. load_temp_config_cgpu(cgpu, &cutoff_n, &target_n);
  1032. }
  1033. if (cutoff_n != temp_cutoff_str && cutoff_n[0])
  1034. quit(1, "Too many values passed to set temp cutoff");
  1035. if (target_n != temp_target_str && target_n[0])
  1036. quit(1, "Too many values passed to set temp target");
  1037. }
  1038. static char *set_api_allow(const char *arg)
  1039. {
  1040. opt_set_charp(arg, &opt_api_allow);
  1041. return NULL;
  1042. }
  1043. static char *set_api_groups(const char *arg)
  1044. {
  1045. opt_set_charp(arg, &opt_api_groups);
  1046. return NULL;
  1047. }
  1048. static char *set_api_description(const char *arg)
  1049. {
  1050. opt_set_charp(arg, &opt_api_description);
  1051. return NULL;
  1052. }
  1053. #ifdef USE_ICARUS
  1054. static char *set_icarus_options(const char *arg)
  1055. {
  1056. opt_set_charp(arg, &opt_icarus_options);
  1057. return NULL;
  1058. }
  1059. static char *set_icarus_timing(const char *arg)
  1060. {
  1061. opt_set_charp(arg, &opt_icarus_timing);
  1062. return NULL;
  1063. }
  1064. #endif
  1065. #ifdef USE_AVALON
  1066. static char *set_avalon_options(const char *arg)
  1067. {
  1068. opt_set_charp(arg, &opt_avalon_options);
  1069. return NULL;
  1070. }
  1071. #endif
  1072. __maybe_unused
  1073. static char *set_null(const char __maybe_unused *arg)
  1074. {
  1075. return NULL;
  1076. }
  1077. /* These options are available from config file or commandline */
  1078. static struct opt_table opt_config_table[] = {
  1079. #ifdef WANT_CPUMINE
  1080. OPT_WITH_ARG("--algo|-a",
  1081. set_algo, show_algo, &opt_algo,
  1082. "Specify sha256 implementation for CPU mining:\n"
  1083. "\tfastauto*\tQuick benchmark at startup to pick a working algorithm\n"
  1084. "\tauto\t\tBenchmark at startup and pick fastest algorithm"
  1085. "\n\tc\t\tLinux kernel sha256, implemented in C"
  1086. #ifdef WANT_SSE2_4WAY
  1087. "\n\t4way\t\ttcatm's 4-way SSE2 implementation"
  1088. #endif
  1089. #ifdef WANT_VIA_PADLOCK
  1090. "\n\tvia\t\tVIA padlock implementation"
  1091. #endif
  1092. "\n\tcryptopp\tCrypto++ C/C++ implementation"
  1093. #ifdef WANT_CRYPTOPP_ASM32
  1094. "\n\tcryptopp_asm32\tCrypto++ 32-bit assembler implementation"
  1095. #endif
  1096. #ifdef WANT_X8632_SSE2
  1097. "\n\tsse2_32\t\tSSE2 32 bit implementation for i386 machines"
  1098. #endif
  1099. #ifdef WANT_X8664_SSE2
  1100. "\n\tsse2_64\t\tSSE2 64 bit implementation for x86_64 machines"
  1101. #endif
  1102. #ifdef WANT_X8664_SSE4
  1103. "\n\tsse4_64\t\tSSE4.1 64 bit implementation for x86_64 machines"
  1104. #endif
  1105. #ifdef WANT_ALTIVEC_4WAY
  1106. "\n\taltivec_4way\tAltivec implementation for PowerPC G4 and G5 machines"
  1107. #endif
  1108. ),
  1109. #endif
  1110. OPT_WITH_ARG("--api-allow",
  1111. set_api_allow, NULL, NULL,
  1112. "Allow API access only to the given list of [G:]IP[/Prefix] addresses[/subnets]"),
  1113. OPT_WITH_ARG("--api-description",
  1114. set_api_description, NULL, NULL,
  1115. "Description placed in the API status header, default: BFGMiner version"),
  1116. OPT_WITH_ARG("--api-groups",
  1117. set_api_groups, NULL, NULL,
  1118. "API one letter groups G:cmd:cmd[,P:cmd:*...] defining the cmds a groups can use"),
  1119. OPT_WITHOUT_ARG("--api-listen",
  1120. opt_set_bool, &opt_api_listen,
  1121. "Enable API, default: disabled"),
  1122. OPT_WITHOUT_ARG("--api-network",
  1123. opt_set_bool, &opt_api_network,
  1124. "Allow API (if enabled) to listen on/for any address, default: only 127.0.0.1"),
  1125. OPT_WITH_ARG("--api-port",
  1126. set_int_1_to_65535, opt_show_intval, &opt_api_port,
  1127. "Port number of miner API"),
  1128. #ifdef HAVE_ADL
  1129. OPT_WITHOUT_ARG("--auto-fan",
  1130. opt_set_bool, &opt_autofan,
  1131. "Automatically adjust all GPU fan speeds to maintain a target temperature"),
  1132. OPT_WITHOUT_ARG("--auto-gpu",
  1133. opt_set_bool, &opt_autoengine,
  1134. "Automatically adjust all GPU engine clock speeds to maintain a target temperature"),
  1135. #endif
  1136. OPT_WITHOUT_ARG("--balance",
  1137. set_balance, &pool_strategy,
  1138. "Change multipool strategy from failover to even share balance"),
  1139. OPT_WITHOUT_ARG("--benchmark",
  1140. opt_set_bool, &opt_benchmark,
  1141. "Run BFGMiner in benchmark mode - produces no shares"),
  1142. #if defined(USE_BITFORCE)
  1143. OPT_WITHOUT_ARG("--bfl-range",
  1144. opt_set_bool, &opt_bfl_noncerange,
  1145. "Use nonce range on bitforce devices if supported"),
  1146. #endif
  1147. #ifdef WANT_CPUMINE
  1148. OPT_WITH_ARG("--bench-algo|-b",
  1149. set_int_0_to_9999, opt_show_intval, &opt_bench_algo,
  1150. opt_hidden),
  1151. #endif
  1152. #if BLKMAKER_VERSION > 1
  1153. OPT_WITH_ARG("--coinbase-addr",
  1154. set_b58addr, NULL, &opt_coinbase_script,
  1155. "Set coinbase payout address for solo mining"),
  1156. OPT_WITH_ARG("--coinbase-payout|--cbaddr|--cb-addr|--payout",
  1157. set_b58addr, NULL, &opt_coinbase_script,
  1158. opt_hidden),
  1159. #endif
  1160. #if BLKMAKER_VERSION > 0
  1161. OPT_WITH_ARG("--coinbase-sig",
  1162. set_strdup, NULL, &opt_coinbase_sig,
  1163. "Set coinbase signature when possible"),
  1164. OPT_WITH_ARG("--coinbase|--cbsig|--cb-sig|--cb|--prayer",
  1165. set_strdup, NULL, &opt_coinbase_sig,
  1166. opt_hidden),
  1167. #endif
  1168. #ifdef HAVE_CURSES
  1169. OPT_WITHOUT_ARG("--compact",
  1170. opt_set_bool, &opt_compact,
  1171. "Use compact display without per device statistics"),
  1172. #endif
  1173. #ifdef WANT_CPUMINE
  1174. OPT_WITH_ARG("--cpu-threads|-t",
  1175. force_nthreads_int, opt_show_intval, &opt_n_threads,
  1176. "Number of miner CPU threads"),
  1177. #endif
  1178. OPT_WITHOUT_ARG("--debug|-D",
  1179. enable_debug, &opt_debug,
  1180. "Enable debug output"),
  1181. OPT_WITHOUT_ARG("--debuglog",
  1182. opt_set_bool, &opt_debug,
  1183. "Enable debug logging"),
  1184. OPT_WITHOUT_ARG("--device-protocol-dump",
  1185. opt_set_bool, &opt_dev_protocol,
  1186. "Verbose dump of device protocol-level activities"),
  1187. OPT_WITH_ARG("--device|-d",
  1188. set_devices, NULL, NULL,
  1189. "Select device to use, one value, range and/or comma separated (e.g. 0-2,4) default: all"),
  1190. OPT_WITHOUT_ARG("--disable-gpu|-G",
  1191. opt_set_bool, &opt_nogpu,
  1192. opt_hidden
  1193. ),
  1194. OPT_WITHOUT_ARG("--disable-rejecting",
  1195. opt_set_bool, &opt_disable_pool,
  1196. "Automatically disable pools that continually reject shares"),
  1197. #if defined(WANT_CPUMINE) && (defined(HAVE_OPENCL) || defined(USE_FPGA))
  1198. OPT_WITHOUT_ARG("--enable-cpu|-C",
  1199. opt_set_bool, &opt_usecpu,
  1200. opt_hidden),
  1201. #endif
  1202. OPT_WITH_ARG("--expiry|-E",
  1203. set_int_0_to_9999, opt_show_intval, &opt_expiry,
  1204. "Upper bound on how many seconds after getting work we consider a share from it stale (w/o longpoll active)"),
  1205. OPT_WITH_ARG("--expiry-lp",
  1206. set_int_0_to_9999, opt_show_intval, &opt_expiry_lp,
  1207. "Upper bound on how many seconds after getting work we consider a share from it stale (with longpoll active)"),
  1208. OPT_WITHOUT_ARG("--failover-only",
  1209. opt_set_bool, &opt_fail_only,
  1210. "Don't leak work to backup pools when primary pool is lagging"),
  1211. #ifdef USE_FPGA
  1212. OPT_WITHOUT_ARG("--force-dev-init",
  1213. opt_set_bool, &opt_force_dev_init,
  1214. "Always initialize devices when possible (such as bitstream uploads to some FPGAs)"),
  1215. #endif
  1216. #ifdef HAVE_OPENCL
  1217. OPT_WITH_ARG("--gpu-dyninterval",
  1218. set_int_1_to_65535, opt_show_intval, &opt_dynamic_interval,
  1219. "Set the refresh interval in ms for GPUs using dynamic intensity"),
  1220. OPT_WITH_ARG("--gpu-platform",
  1221. set_int_0_to_9999, opt_show_intval, &opt_platform_id,
  1222. "Select OpenCL platform ID to use for GPU mining"),
  1223. OPT_WITH_ARG("--gpu-threads|-g",
  1224. set_int_1_to_10, opt_show_intval, &opt_g_threads,
  1225. "Number of threads per GPU (1 - 10)"),
  1226. #ifdef HAVE_ADL
  1227. OPT_WITH_ARG("--gpu-engine",
  1228. set_gpu_engine, NULL, NULL,
  1229. "GPU engine (over)clock range in MHz - one value, range and/or comma separated list (e.g. 850-900,900,750-850)"),
  1230. OPT_WITH_ARG("--gpu-fan",
  1231. set_gpu_fan, NULL, NULL,
  1232. "GPU fan percentage range - one value, range and/or comma separated list (e.g. 0-85,85,65)"),
  1233. OPT_WITH_ARG("--gpu-map",
  1234. set_gpu_map, NULL, NULL,
  1235. "Map OpenCL to ADL device order manually, paired CSV (e.g. 1:0,2:1 maps OpenCL 1 to ADL 0, 2 to 1)"),
  1236. OPT_WITH_ARG("--gpu-memclock",
  1237. set_gpu_memclock, NULL, NULL,
  1238. "Set the GPU memory (over)clock in MHz - one value for all or separate by commas for per card"),
  1239. OPT_WITH_ARG("--gpu-memdiff",
  1240. set_gpu_memdiff, NULL, NULL,
  1241. "Set a fixed difference in clock speed between the GPU and memory in auto-gpu mode"),
  1242. OPT_WITH_ARG("--gpu-powertune",
  1243. set_gpu_powertune, NULL, NULL,
  1244. "Set the GPU powertune percentage - one value for all or separate by commas for per card"),
  1245. OPT_WITHOUT_ARG("--gpu-reorder",
  1246. opt_set_bool, &opt_reorder,
  1247. "Attempt to reorder GPU devices according to PCI Bus ID"),
  1248. OPT_WITH_ARG("--gpu-vddc",
  1249. set_gpu_vddc, NULL, NULL,
  1250. "Set the GPU voltage in Volts - one value for all or separate by commas for per card"),
  1251. #endif
  1252. #ifdef USE_SCRYPT
  1253. OPT_WITH_ARG("--lookup-gap",
  1254. set_lookup_gap, NULL, NULL,
  1255. "Set GPU lookup gap for scrypt mining, comma separated"),
  1256. #endif
  1257. OPT_WITH_ARG("--intensity|-I",
  1258. set_intensity, NULL, NULL,
  1259. "Intensity of GPU scanning (d or " _MIN_INTENSITY_STR " -> " _MAX_INTENSITY_STR ", default: d to maintain desktop interactivity)"),
  1260. #endif
  1261. #if defined(HAVE_OPENCL) || defined(USE_MODMINER) || defined(USE_X6500) || defined(USE_ZTEX)
  1262. OPT_WITH_ARG("--kernel-path|-K",
  1263. opt_set_charp, opt_show_charp, &opt_kernel_path,
  1264. "Specify a path to where bitstream and kernel files are"),
  1265. #endif
  1266. #ifdef HAVE_OPENCL
  1267. OPT_WITH_ARG("--kernel|-k",
  1268. set_kernel, NULL, NULL,
  1269. "Override sha256 kernel to use (diablo, poclbm, phatk or diakgcn) - one value or comma separated"),
  1270. #endif
  1271. #ifdef USE_ICARUS
  1272. OPT_WITH_ARG("--icarus-options",
  1273. set_icarus_options, NULL, NULL,
  1274. opt_hidden),
  1275. OPT_WITH_ARG("--icarus-timing",
  1276. set_icarus_timing, NULL, NULL,
  1277. opt_hidden),
  1278. #endif
  1279. #ifdef USE_AVALON
  1280. OPT_WITH_ARG("--avalon-options",
  1281. set_avalon_options, NULL, NULL,
  1282. opt_hidden),
  1283. #endif
  1284. OPT_WITHOUT_ARG("--load-balance",
  1285. set_loadbalance, &pool_strategy,
  1286. "Change multipool strategy from failover to efficiency based balance"),
  1287. OPT_WITH_ARG("--log|-l",
  1288. set_int_0_to_9999, opt_show_intval, &opt_log_interval,
  1289. "Interval in seconds between log output"),
  1290. OPT_WITH_ARG("--log-file|-L",
  1291. set_log_file, NULL, NULL,
  1292. "Append log file for output messages"),
  1293. OPT_WITH_ARG("--logfile",
  1294. set_log_file, NULL, NULL,
  1295. opt_hidden),
  1296. OPT_WITHOUT_ARG("--log-microseconds",
  1297. opt_set_bool, &opt_log_microseconds,
  1298. "Include microseconds in log output"),
  1299. #if defined(unix) || defined(__APPLE__)
  1300. OPT_WITH_ARG("--monitor|-m",
  1301. opt_set_charp, NULL, &opt_stderr_cmd,
  1302. "Use custom pipe cmd for output messages"),
  1303. #endif // defined(unix)
  1304. OPT_WITHOUT_ARG("--net-delay",
  1305. opt_set_bool, &opt_delaynet,
  1306. "Impose small delays in networking to not overload slow routers"),
  1307. OPT_WITHOUT_ARG("--no-adl",
  1308. opt_set_bool, &opt_noadl,
  1309. #ifdef HAVE_ADL
  1310. "Disable the ATI display library used for monitoring and setting GPU parameters"
  1311. #else
  1312. opt_hidden
  1313. #endif
  1314. ),
  1315. OPT_WITHOUT_ARG("--no-gbt",
  1316. opt_set_invbool, &want_gbt,
  1317. "Disable getblocktemplate support"),
  1318. OPT_WITHOUT_ARG("--no-getwork",
  1319. opt_set_invbool, &want_getwork,
  1320. "Disable getwork support"),
  1321. OPT_WITHOUT_ARG("--no-longpoll",
  1322. opt_set_invbool, &want_longpoll,
  1323. "Disable X-Long-Polling support"),
  1324. OPT_WITHOUT_ARG("--no-pool-disable",
  1325. opt_set_invbool, &opt_disable_pool,
  1326. opt_hidden),
  1327. OPT_WITHOUT_ARG("--no-restart",
  1328. opt_set_invbool, &opt_restart,
  1329. "Do not attempt to restart devices that hang"
  1330. ),
  1331. OPT_WITHOUT_ARG("--no-show-processors",
  1332. opt_set_invbool, &opt_show_procs,
  1333. opt_hidden),
  1334. OPT_WITHOUT_ARG("--no-show-procs",
  1335. opt_set_invbool, &opt_show_procs,
  1336. opt_hidden),
  1337. OPT_WITHOUT_ARG("--no-stratum",
  1338. opt_set_invbool, &want_stratum,
  1339. "Disable Stratum detection"),
  1340. OPT_WITHOUT_ARG("--no-submit-stale",
  1341. opt_set_invbool, &opt_submit_stale,
  1342. "Don't submit shares if they are detected as stale"),
  1343. #ifdef HAVE_OPENCL
  1344. OPT_WITHOUT_ARG("--no-opencl-binaries",
  1345. opt_set_invbool, &opt_opencl_binaries,
  1346. "Don't attempt to use or save OpenCL kernel binaries"),
  1347. #endif
  1348. OPT_WITHOUT_ARG("--no-unicode",
  1349. opt_set_invbool, &use_unicode,
  1350. #ifdef USE_UNICODE
  1351. "Don't use Unicode characters in TUI"
  1352. #else
  1353. opt_hidden
  1354. #endif
  1355. ),
  1356. OPT_WITH_ARG("--pass|-p",
  1357. set_pass, NULL, NULL,
  1358. "Password for bitcoin JSON-RPC server"),
  1359. OPT_WITHOUT_ARG("--per-device-stats",
  1360. opt_set_bool, &want_per_device_stats,
  1361. "Force verbose mode and output per-device statistics"),
  1362. OPT_WITH_ARG("--pool-priority",
  1363. set_pool_priority, NULL, NULL,
  1364. "Priority for just the previous-defined pool"),
  1365. OPT_WITH_ARG("--pool-proxy|-x",
  1366. set_pool_proxy, NULL, NULL,
  1367. "Proxy URI to use for connecting to just the previous-defined pool"),
  1368. OPT_WITH_ARG("--force-rollntime", // NOTE: must be after --pass for config file ordering
  1369. set_pool_force_rollntime, NULL, NULL,
  1370. opt_hidden),
  1371. OPT_WITHOUT_ARG("--protocol-dump|-P",
  1372. opt_set_bool, &opt_protocol,
  1373. "Verbose dump of protocol-level activities"),
  1374. OPT_WITH_ARG("--queue|-Q",
  1375. set_int_0_to_9999, opt_show_intval, &opt_queue,
  1376. "Minimum number of work items to have queued (0+)"),
  1377. OPT_WITHOUT_ARG("--quiet|-q",
  1378. opt_set_bool, &opt_quiet,
  1379. "Disable logging output, display status and errors"),
  1380. OPT_WITHOUT_ARG("--quiet-work-updates|--quiet-work-update",
  1381. opt_set_bool, &opt_quiet_work_updates,
  1382. opt_hidden),
  1383. OPT_WITHOUT_ARG("--real-quiet",
  1384. opt_set_bool, &opt_realquiet,
  1385. "Disable all output"),
  1386. OPT_WITHOUT_ARG("--remove-disabled",
  1387. opt_set_bool, &opt_removedisabled,
  1388. "Remove disabled devices entirely, as if they didn't exist"),
  1389. OPT_WITH_ARG("--request-diff",
  1390. set_request_diff, opt_show_floatval, &request_pdiff,
  1391. "Request a specific difficulty from pools"),
  1392. OPT_WITH_ARG("--retries",
  1393. opt_set_intval, opt_show_intval, &opt_retries,
  1394. "Number of times to retry failed submissions before giving up (-1 means never)"),
  1395. OPT_WITH_ARG("--retry-pause",
  1396. set_null, NULL, NULL,
  1397. opt_hidden),
  1398. OPT_WITH_ARG("--rotate",
  1399. set_rotate, opt_show_intval, &opt_rotate_period,
  1400. "Change multipool strategy from failover to regularly rotate at N minutes"),
  1401. OPT_WITHOUT_ARG("--round-robin",
  1402. set_rr, &pool_strategy,
  1403. "Change multipool strategy from failover to round robin on failure"),
  1404. #ifdef USE_FPGA_SERIAL
  1405. OPT_WITH_ARG("--scan-serial|-S",
  1406. add_serial, NULL, NULL,
  1407. "Serial port to probe for mining devices"),
  1408. #endif
  1409. OPT_WITH_ARG("--scan-time|-s",
  1410. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  1411. "Upper bound on time spent scanning current work, in seconds"),
  1412. OPT_WITH_ARG("--scantime",
  1413. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  1414. opt_hidden),
  1415. OPT_WITH_ARG("--sched-start",
  1416. set_schedtime, NULL, &schedstart,
  1417. "Set a time of day in HH:MM to start mining (a once off without a stop time)"),
  1418. OPT_WITH_ARG("--sched-stop",
  1419. set_schedtime, NULL, &schedstop,
  1420. "Set a time of day in HH:MM to stop mining (will quit without a start time)"),
  1421. #ifdef USE_SCRYPT
  1422. OPT_WITHOUT_ARG("--scrypt",
  1423. opt_set_bool, &opt_scrypt,
  1424. "Use the scrypt algorithm for mining (non-bitcoin)"),
  1425. #ifdef HAVE_OPENCL
  1426. OPT_WITH_ARG("--shaders",
  1427. set_shaders, NULL, NULL,
  1428. "GPU shaders per card for tuning scrypt, comma separated"),
  1429. #endif
  1430. #endif
  1431. OPT_WITH_ARG("--sharelog",
  1432. set_sharelog, NULL, NULL,
  1433. "Append share log to file"),
  1434. OPT_WITH_ARG("--shares",
  1435. opt_set_intval, NULL, &opt_shares,
  1436. "Quit after mining N shares (default: unlimited)"),
  1437. OPT_WITHOUT_ARG("--show-processors",
  1438. opt_set_bool, &opt_show_procs,
  1439. "Show per processor statistics in summary"),
  1440. OPT_WITHOUT_ARG("--show-procs",
  1441. opt_set_bool, &opt_show_procs,
  1442. opt_hidden),
  1443. OPT_WITH_ARG("--skip-security-checks",
  1444. set_int_0_to_9999, NULL, &opt_skip_checks,
  1445. "Skip security checks sometimes to save bandwidth; only check 1/<arg>th of the time (default: never skip)"),
  1446. OPT_WITH_ARG("--socks-proxy",
  1447. opt_set_charp, NULL, &opt_socks_proxy,
  1448. "Set socks4 proxy (host:port)"),
  1449. OPT_WITHOUT_ARG("--submit-stale",
  1450. opt_set_bool, &opt_submit_stale,
  1451. opt_hidden),
  1452. OPT_WITHOUT_ARG("--submit-threads",
  1453. opt_set_intval, &opt_submit_threads,
  1454. "Minimum number of concurrent share submissions (default: 64)"),
  1455. #ifdef HAVE_SYSLOG_H
  1456. OPT_WITHOUT_ARG("--syslog",
  1457. opt_set_bool, &use_syslog,
  1458. "Use system log for output messages (default: standard error)"),
  1459. #endif
  1460. OPT_WITH_ARG("--temp-cutoff",
  1461. set_temp_cutoff, opt_show_intval, &opt_cutofftemp,
  1462. "Temperature where a device will be automatically disabled, one value or comma separated list"),
  1463. OPT_WITH_ARG("--temp-hysteresis",
  1464. set_int_1_to_10, opt_show_intval, &opt_hysteresis,
  1465. "Set how much the temperature can fluctuate outside limits when automanaging speeds"),
  1466. #ifdef HAVE_ADL
  1467. OPT_WITH_ARG("--temp-overheat",
  1468. set_temp_overheat, opt_show_intval, &opt_overheattemp,
  1469. "Overheat temperature when automatically managing fan and GPU speeds, one value or comma separated list"),
  1470. #endif
  1471. OPT_WITH_ARG("--temp-target",
  1472. set_temp_target, NULL, NULL,
  1473. "Target temperature when automatically managing fan and clock speeds, one value or comma separated list"),
  1474. OPT_WITHOUT_ARG("--text-only|-T",
  1475. opt_set_invbool, &use_curses,
  1476. #ifdef HAVE_CURSES
  1477. "Disable ncurses formatted screen output"
  1478. #else
  1479. opt_hidden
  1480. #endif
  1481. ),
  1482. #if defined(USE_SCRYPT) && defined(HAVE_OPENCL)
  1483. OPT_WITH_ARG("--thread-concurrency",
  1484. set_thread_concurrency, NULL, NULL,
  1485. "Set GPU thread concurrency for scrypt mining, comma separated"),
  1486. #endif
  1487. OPT_WITH_ARG("--url|-o",
  1488. set_url, NULL, NULL,
  1489. "URL for bitcoin JSON-RPC server"),
  1490. OPT_WITH_ARG("--user|-u",
  1491. set_user, NULL, NULL,
  1492. "Username for bitcoin JSON-RPC server"),
  1493. #ifdef HAVE_OPENCL
  1494. OPT_WITH_ARG("--vectors|-v",
  1495. set_vector, NULL, NULL,
  1496. "Override detected optimal vector (1, 2 or 4) - one value or comma separated list"),
  1497. #endif
  1498. OPT_WITHOUT_ARG("--verbose",
  1499. opt_set_bool, &opt_log_output,
  1500. "Log verbose output to stderr as well as status output"),
  1501. #ifdef HAVE_OPENCL
  1502. OPT_WITH_ARG("--worksize|-w",
  1503. set_worksize, NULL, NULL,
  1504. "Override detected optimal worksize - one value or comma separated list"),
  1505. #endif
  1506. OPT_WITH_ARG("--userpass|-O",
  1507. set_userpass, NULL, NULL,
  1508. "Username:Password pair for bitcoin JSON-RPC server"),
  1509. OPT_WITHOUT_ARG("--worktime",
  1510. opt_set_bool, &opt_worktime,
  1511. "Display extra work time debug information"),
  1512. OPT_WITH_ARG("--pools",
  1513. opt_set_bool, NULL, NULL, opt_hidden),
  1514. OPT_ENDTABLE
  1515. };
  1516. static char *load_config(const char *arg, void __maybe_unused *unused);
  1517. static int fileconf_load;
  1518. static char *parse_config(json_t *config, bool fileconf)
  1519. {
  1520. static char err_buf[200];
  1521. struct opt_table *opt;
  1522. json_t *val;
  1523. if (fileconf && !fileconf_load)
  1524. fileconf_load = 1;
  1525. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  1526. char *p, *name, *sp;
  1527. /* We don't handle subtables. */
  1528. assert(!(opt->type & OPT_SUBTABLE));
  1529. /* Pull apart the option name(s). */
  1530. name = strdup(opt->names);
  1531. for (p = strtok_r(name, "|", &sp); p; p = strtok_r(NULL, "|", &sp)) {
  1532. char *err = "Invalid value";
  1533. /* Ignore short options. */
  1534. if (p[1] != '-')
  1535. continue;
  1536. val = json_object_get(config, p+2);
  1537. if (!val)
  1538. continue;
  1539. if (opt->type & OPT_HASARG) {
  1540. if (json_is_string(val)) {
  1541. err = opt->cb_arg(json_string_value(val),
  1542. opt->u.arg);
  1543. } else if (json_is_number(val)) {
  1544. char buf[256], *p, *q;
  1545. snprintf(buf, 256, "%f", json_number_value(val));
  1546. if ( (p = strchr(buf, '.')) ) {
  1547. // Trim /\.0*$/ to work properly with integer-only arguments
  1548. q = p;
  1549. while (*(++q) == '0') {}
  1550. if (*q == '\0')
  1551. *p = '\0';
  1552. }
  1553. err = opt->cb_arg(buf, opt->u.arg);
  1554. } else if (json_is_array(val)) {
  1555. int n, size = json_array_size(val);
  1556. err = NULL;
  1557. for (n = 0; n < size && !err; n++) {
  1558. if (json_is_string(json_array_get(val, n)))
  1559. err = opt->cb_arg(json_string_value(json_array_get(val, n)), opt->u.arg);
  1560. else if (json_is_object(json_array_get(val, n)))
  1561. err = parse_config(json_array_get(val, n), false);
  1562. }
  1563. }
  1564. } else if (opt->type & OPT_NOARG) {
  1565. if (json_is_true(val))
  1566. err = opt->cb(opt->u.arg);
  1567. else if (json_is_boolean(val)) {
  1568. if (opt->cb == (void*)opt_set_bool)
  1569. err = opt_set_invbool(opt->u.arg);
  1570. else if (opt->cb == (void*)opt_set_invbool)
  1571. err = opt_set_bool(opt->u.arg);
  1572. }
  1573. }
  1574. if (err) {
  1575. /* Allow invalid values to be in configuration
  1576. * file, just skipping over them provided the
  1577. * JSON is still valid after that. */
  1578. if (fileconf) {
  1579. applog(LOG_ERR, "Invalid config option %s: %s", p, err);
  1580. fileconf_load = -1;
  1581. } else {
  1582. sprintf(err_buf, "Parsing JSON option %s: %s",
  1583. p, err);
  1584. return err_buf;
  1585. }
  1586. }
  1587. }
  1588. free(name);
  1589. }
  1590. val = json_object_get(config, JSON_INCLUDE_CONF);
  1591. if (val && json_is_string(val))
  1592. return load_config(json_string_value(val), NULL);
  1593. return NULL;
  1594. }
  1595. char *cnfbuf = NULL;
  1596. static char *load_config(const char *arg, void __maybe_unused *unused)
  1597. {
  1598. json_error_t err;
  1599. json_t *config;
  1600. char *json_error;
  1601. if (!cnfbuf)
  1602. cnfbuf = strdup(arg);
  1603. if (++include_count > JSON_MAX_DEPTH)
  1604. return JSON_MAX_DEPTH_ERR;
  1605. #if JANSSON_MAJOR_VERSION > 1
  1606. config = json_load_file(arg, 0, &err);
  1607. #else
  1608. config = json_load_file(arg, &err);
  1609. #endif
  1610. if (!json_is_object(config)) {
  1611. json_error = malloc(JSON_LOAD_ERROR_LEN + strlen(arg) + strlen(err.text));
  1612. if (!json_error)
  1613. quit(1, "Malloc failure in json error");
  1614. sprintf(json_error, JSON_LOAD_ERROR, arg, err.text);
  1615. return json_error;
  1616. }
  1617. config_loaded = true;
  1618. /* Parse the config now, so we can override it. That can keep pointers
  1619. * so don't free config object. */
  1620. return parse_config(config, true);
  1621. }
  1622. static void load_default_config(void)
  1623. {
  1624. cnfbuf = malloc(PATH_MAX);
  1625. #if defined(unix)
  1626. if (getenv("HOME") && *getenv("HOME")) {
  1627. strcpy(cnfbuf, getenv("HOME"));
  1628. strcat(cnfbuf, "/");
  1629. } else
  1630. strcpy(cnfbuf, "");
  1631. char *dirp = cnfbuf + strlen(cnfbuf);
  1632. strcpy(dirp, ".bfgminer/");
  1633. strcat(dirp, def_conf);
  1634. if (access(cnfbuf, R_OK))
  1635. // No BFGMiner config, try Cgminer's...
  1636. strcpy(dirp, ".cgminer/cgminer.conf");
  1637. #else
  1638. strcpy(cnfbuf, "");
  1639. strcat(cnfbuf, def_conf);
  1640. #endif
  1641. if (!access(cnfbuf, R_OK))
  1642. load_config(cnfbuf, NULL);
  1643. else {
  1644. free(cnfbuf);
  1645. cnfbuf = NULL;
  1646. }
  1647. }
  1648. extern const char *opt_argv0;
  1649. static char *opt_verusage_and_exit(const char *extra)
  1650. {
  1651. printf("%s\nBuilt with "
  1652. #ifdef HAVE_OPENCL
  1653. "GPU "
  1654. #endif
  1655. #ifdef WANT_CPUMINE
  1656. "CPU "
  1657. #endif
  1658. #ifdef USE_BITFORCE
  1659. "bitforce "
  1660. #endif
  1661. #ifdef USE_ICARUS
  1662. "icarus "
  1663. #endif
  1664. #ifdef USE_AVALON
  1665. "avalon "
  1666. #endif
  1667. #ifdef USE_MODMINER
  1668. "modminer "
  1669. #endif
  1670. #ifdef USE_X6500
  1671. "x6500 "
  1672. #endif
  1673. #ifdef USE_ZTEX
  1674. "ztex "
  1675. #endif
  1676. #ifdef USE_SCRYPT
  1677. "scrypt "
  1678. #endif
  1679. "mining support.\n"
  1680. , packagename);
  1681. printf("%s", opt_usage(opt_argv0, extra));
  1682. fflush(stdout);
  1683. exit(0);
  1684. }
  1685. /* These options are available from commandline only */
  1686. static struct opt_table opt_cmdline_table[] = {
  1687. OPT_WITH_ARG("--config|-c",
  1688. load_config, NULL, NULL,
  1689. "Load a JSON-format configuration file\n"
  1690. "See example.conf for an example configuration."),
  1691. OPT_WITHOUT_ARG("--help|-h",
  1692. opt_verusage_and_exit, NULL,
  1693. "Print this message"),
  1694. #ifdef HAVE_OPENCL
  1695. OPT_WITHOUT_ARG("--ndevs|-n",
  1696. print_ndevs_and_exit, &nDevs,
  1697. "Display number of detected GPUs, OpenCL platform information, and exit"),
  1698. #endif
  1699. OPT_WITHOUT_ARG("--version|-V",
  1700. opt_version_and_exit, packagename,
  1701. "Display version and exit"),
  1702. OPT_ENDTABLE
  1703. };
  1704. static bool jobj_binary(const json_t *obj, const char *key,
  1705. void *buf, size_t buflen, bool required)
  1706. {
  1707. const char *hexstr;
  1708. json_t *tmp;
  1709. tmp = json_object_get(obj, key);
  1710. if (unlikely(!tmp)) {
  1711. if (unlikely(required))
  1712. applog(LOG_ERR, "JSON key '%s' not found", key);
  1713. return false;
  1714. }
  1715. hexstr = json_string_value(tmp);
  1716. if (unlikely(!hexstr)) {
  1717. applog(LOG_ERR, "JSON key '%s' is not a string", key);
  1718. return false;
  1719. }
  1720. if (!hex2bin(buf, hexstr, buflen))
  1721. return false;
  1722. return true;
  1723. }
  1724. static void calc_midstate(struct work *work)
  1725. {
  1726. union {
  1727. unsigned char c[64];
  1728. uint32_t i[16];
  1729. } data;
  1730. swap32yes(&data.i[0], work->data, 16);
  1731. sha2_context ctx;
  1732. sha2_starts(&ctx);
  1733. sha2_update(&ctx, data.c, 64);
  1734. memcpy(work->midstate, ctx.state, sizeof(work->midstate));
  1735. swap32tole(work->midstate, work->midstate, 8);
  1736. }
  1737. static struct work *make_work(void)
  1738. {
  1739. struct work *work = calloc(1, sizeof(struct work));
  1740. if (unlikely(!work))
  1741. quit(1, "Failed to calloc work in make_work");
  1742. cg_wlock(&control_lock);
  1743. work->id = total_work++;
  1744. cg_wunlock(&control_lock);
  1745. return work;
  1746. }
  1747. /* This is the central place all work that is about to be retired should be
  1748. * cleaned to remove any dynamically allocated arrays within the struct */
  1749. void clean_work(struct work *work)
  1750. {
  1751. free(work->job_id);
  1752. bytes_free(&work->nonce2);
  1753. free(work->nonce1);
  1754. if (work->tmpl) {
  1755. struct pool *pool = work->pool;
  1756. mutex_lock(&pool->pool_lock);
  1757. bool free_tmpl = !--*work->tmpl_refcount;
  1758. mutex_unlock(&pool->pool_lock);
  1759. if (free_tmpl) {
  1760. blktmpl_free(work->tmpl);
  1761. free(work->tmpl_refcount);
  1762. }
  1763. }
  1764. memset(work, 0, sizeof(struct work));
  1765. }
  1766. /* All dynamically allocated work structs should be freed here to not leak any
  1767. * ram from arrays allocated within the work struct */
  1768. void free_work(struct work *work)
  1769. {
  1770. clean_work(work);
  1771. free(work);
  1772. }
  1773. static const char *workpadding_bin = "\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\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x80\x02\0\0";
  1774. // Must only be called with ch_lock held!
  1775. static
  1776. void __update_block_title(const unsigned char *hash_swap)
  1777. {
  1778. if (hash_swap) {
  1779. char tmp[17];
  1780. // Only provided when the block has actually changed
  1781. free(current_hash);
  1782. current_hash = malloc(3 /* ... */ + 16 /* block hash segment */ + 1);
  1783. bin2hex(tmp, &hash_swap[24], 8);
  1784. sprintf(current_hash, "...%s", tmp);
  1785. known_blkheight_current = false;
  1786. } else if (likely(known_blkheight_current)) {
  1787. return;
  1788. }
  1789. if (current_block_id == known_blkheight_blkid) {
  1790. // FIXME: The block number will overflow this sometime around AD 2025-2027
  1791. if (known_blkheight < 1000000) {
  1792. memmove(&current_hash[3], &current_hash[11], 8);
  1793. sprintf(&current_hash[11], " #%6u", known_blkheight);
  1794. }
  1795. known_blkheight_current = true;
  1796. }
  1797. }
  1798. static
  1799. void have_block_height(uint32_t block_id, uint32_t blkheight)
  1800. {
  1801. if (known_blkheight == blkheight)
  1802. return;
  1803. applog(LOG_DEBUG, "Learned that block id %08" PRIx32 " is height %" PRIu32, be32toh(block_id), blkheight);
  1804. cg_wlock(&ch_lock);
  1805. known_blkheight = blkheight;
  1806. known_blkheight_blkid = block_id;
  1807. if (block_id == current_block_id)
  1808. __update_block_title(NULL);
  1809. cg_wunlock(&ch_lock);
  1810. }
  1811. static
  1812. void pool_set_opaque(struct pool *pool, bool opaque)
  1813. {
  1814. if (pool->swork.opaque == opaque)
  1815. return;
  1816. pool->swork.opaque = opaque;
  1817. if (opaque)
  1818. applog(LOG_WARNING, "Pool %u is hiding block contents from us",
  1819. pool->pool_no);
  1820. else
  1821. applog(LOG_NOTICE, "Pool %u now providing block contents to us",
  1822. pool->pool_no);
  1823. }
  1824. static bool work_decode(struct pool *pool, struct work *work, json_t *val)
  1825. {
  1826. json_t *res_val = json_object_get(val, "result");
  1827. json_t *tmp_val;
  1828. bool ret = false;
  1829. if (unlikely(detect_algo == 1)) {
  1830. json_t *tmp = json_object_get(res_val, "algorithm");
  1831. const char *v = tmp ? json_string_value(tmp) : "";
  1832. if (strncasecmp(v, "scrypt", 6))
  1833. detect_algo = 2;
  1834. }
  1835. if (work->tmpl) {
  1836. struct timeval tv_now;
  1837. cgtime(&tv_now);
  1838. const char *err = blktmpl_add_jansson(work->tmpl, res_val, tv_now.tv_sec);
  1839. if (err) {
  1840. applog(LOG_ERR, "blktmpl error: %s", err);
  1841. return false;
  1842. }
  1843. work->rolltime = blkmk_time_left(work->tmpl, tv_now.tv_sec);
  1844. #if BLKMAKER_VERSION > 1
  1845. if (opt_coinbase_script.sz)
  1846. {
  1847. bool newcb;
  1848. #if BLKMAKER_VERSION > 2
  1849. blkmk_init_generation2(work->tmpl, opt_coinbase_script.data, opt_coinbase_script.sz, &newcb);
  1850. #else
  1851. newcb = !work->tmpl->cbtxn;
  1852. blkmk_init_generation(work->tmpl, opt_coinbase_script.data, opt_coinbase_script.sz);
  1853. #endif
  1854. if (newcb)
  1855. {
  1856. ssize_t ae = blkmk_append_coinbase_safe(work->tmpl, &template_nonce, sizeof(template_nonce));
  1857. if (ae < (ssize_t)sizeof(template_nonce))
  1858. applog(LOG_WARNING, "Cannot append template-nonce to coinbase on pool %u (%"PRId64") - you might be wasting hashing!", work->pool->pool_no, (int64_t)ae);
  1859. ++template_nonce;
  1860. }
  1861. }
  1862. #endif
  1863. #if BLKMAKER_VERSION > 0
  1864. {
  1865. ssize_t ae = blkmk_append_coinbase_safe(work->tmpl, opt_coinbase_sig, 101);
  1866. static bool appenderr = false;
  1867. if (ae <= 0) {
  1868. if (opt_coinbase_sig) {
  1869. applog((appenderr ? LOG_DEBUG : LOG_WARNING), "Cannot append coinbase signature at all on pool %u (%"PRId64")", pool->pool_no, (int64_t)ae);
  1870. appenderr = true;
  1871. }
  1872. } else if (ae >= 3 || opt_coinbase_sig) {
  1873. const char *cbappend = opt_coinbase_sig;
  1874. if (!cbappend) {
  1875. const char full[] = PACKAGE " " VERSION;
  1876. if ((size_t)ae >= sizeof(full) - 1)
  1877. cbappend = full;
  1878. else if ((size_t)ae >= sizeof(PACKAGE) - 1)
  1879. cbappend = PACKAGE;
  1880. else
  1881. cbappend = "BFG";
  1882. }
  1883. size_t cbappendsz = strlen(cbappend);
  1884. static bool truncatewarning = false;
  1885. if (cbappendsz <= (size_t)ae) {
  1886. if (cbappendsz < (size_t)ae)
  1887. // If we have space, include the trailing \0
  1888. ++cbappendsz;
  1889. ae = cbappendsz;
  1890. truncatewarning = false;
  1891. } else {
  1892. char *tmp = malloc(ae + 1);
  1893. memcpy(tmp, opt_coinbase_sig, ae);
  1894. tmp[ae] = '\0';
  1895. applog((truncatewarning ? LOG_DEBUG : LOG_WARNING),
  1896. "Pool %u truncating appended coinbase signature at %"PRId64" bytes: %s(%s)",
  1897. pool->pool_no, (int64_t)ae, tmp, &opt_coinbase_sig[ae]);
  1898. free(tmp);
  1899. truncatewarning = true;
  1900. }
  1901. ae = blkmk_append_coinbase_safe(work->tmpl, cbappend, ae);
  1902. if (ae <= 0) {
  1903. applog((appenderr ? LOG_DEBUG : LOG_WARNING), "Error appending coinbase signature (%"PRId64")", (int64_t)ae);
  1904. appenderr = true;
  1905. } else
  1906. appenderr = false;
  1907. }
  1908. }
  1909. #endif
  1910. if (blkmk_get_data(work->tmpl, work->data, 80, tv_now.tv_sec, NULL, &work->dataid) < 76)
  1911. return false;
  1912. swap32yes(work->data, work->data, 80 / 4);
  1913. memcpy(&work->data[80], workpadding_bin, 48);
  1914. const struct blktmpl_longpoll_req *lp;
  1915. if ((lp = blktmpl_get_longpoll(work->tmpl)) && ((!pool->lp_id) || strcmp(lp->id, pool->lp_id))) {
  1916. free(pool->lp_id);
  1917. pool->lp_id = strdup(lp->id);
  1918. #if 0 /* This just doesn't work :( */
  1919. curl_socket_t sock = pool->lp_socket;
  1920. if (sock != CURL_SOCKET_BAD) {
  1921. pool->lp_socket = CURL_SOCKET_BAD;
  1922. applog(LOG_WARNING, "Pool %u long poll request hanging, reconnecting", pool->pool_no);
  1923. shutdown(sock, SHUT_RDWR);
  1924. }
  1925. #endif
  1926. }
  1927. }
  1928. else
  1929. if (unlikely(!jobj_binary(res_val, "data", work->data, sizeof(work->data), true))) {
  1930. applog(LOG_ERR, "JSON inval data");
  1931. return false;
  1932. }
  1933. if (!jobj_binary(res_val, "midstate", work->midstate, sizeof(work->midstate), false)) {
  1934. // Calculate it ourselves
  1935. applog(LOG_DEBUG, "Calculating midstate locally");
  1936. calc_midstate(work);
  1937. }
  1938. if (unlikely(!jobj_binary(res_val, "target", work->target, sizeof(work->target), true))) {
  1939. applog(LOG_ERR, "JSON inval target");
  1940. return false;
  1941. }
  1942. if (work->tmpl) {
  1943. for (size_t i = 0; i < sizeof(work->target) / 2; ++i)
  1944. {
  1945. int p = (sizeof(work->target) - 1) - i;
  1946. unsigned char c = work->target[i];
  1947. work->target[i] = work->target[p];
  1948. work->target[p] = c;
  1949. }
  1950. }
  1951. if ( (tmp_val = json_object_get(res_val, "height")) ) {
  1952. uint32_t blkheight = json_number_value(tmp_val);
  1953. uint32_t block_id = ((uint32_t*)work->data)[1];
  1954. have_block_height(block_id, blkheight);
  1955. }
  1956. memset(work->hash, 0, sizeof(work->hash));
  1957. cgtime(&work->tv_staged);
  1958. pool_set_opaque(pool, !work->tmpl);
  1959. ret = true;
  1960. return ret;
  1961. }
  1962. /* Returns whether the pool supports local work generation or not. */
  1963. static bool pool_localgen(struct pool *pool)
  1964. {
  1965. return (pool->last_work_copy || pool->has_stratum);
  1966. }
  1967. int dev_from_id(int thr_id)
  1968. {
  1969. struct cgpu_info *cgpu = get_thr_cgpu(thr_id);
  1970. return cgpu->device_id;
  1971. }
  1972. /* Make the change in the recent value adjust dynamically when the difference
  1973. * is large, but damp it when the values are closer together. This allows the
  1974. * value to change quickly, but not fluctuate too dramatically when it has
  1975. * stabilised. */
  1976. void decay_time(double *f, double fadd)
  1977. {
  1978. double ratio = 0;
  1979. if (likely(*f > 0)) {
  1980. ratio = fadd / *f;
  1981. if (ratio > 1)
  1982. ratio = 1 / ratio;
  1983. }
  1984. if (ratio > 0.63)
  1985. *f = (fadd * 0.58 + *f) / 1.58;
  1986. else
  1987. *f = (fadd + *f * 0.58) / 1.58;
  1988. }
  1989. static int __total_staged(void)
  1990. {
  1991. return HASH_COUNT(staged_work);
  1992. }
  1993. static int total_staged(void)
  1994. {
  1995. int ret;
  1996. mutex_lock(stgd_lock);
  1997. ret = __total_staged();
  1998. mutex_unlock(stgd_lock);
  1999. return ret;
  2000. }
  2001. #ifdef HAVE_CURSES
  2002. WINDOW *mainwin, *statuswin, *logwin;
  2003. #endif
  2004. double total_secs = 1.0;
  2005. static char statusline[256];
  2006. /* logstart is where the log window should start */
  2007. static int devcursor, logstart, logcursor;
  2008. #ifdef HAVE_CURSES
  2009. /* statusy is where the status window goes up to in cases where it won't fit at startup */
  2010. static int statusy;
  2011. static int devsummaryYOffset;
  2012. static int total_lines;
  2013. #endif
  2014. #ifdef HAVE_OPENCL
  2015. struct cgpu_info gpus[MAX_GPUDEVICES]; /* Maximum number apparently possible */
  2016. #endif
  2017. struct cgpu_info *cpus;
  2018. bool _bfg_console_cancel_disabled;
  2019. int _bfg_console_prev_cancelstate;
  2020. #ifdef HAVE_CURSES
  2021. #define lock_curses() bfg_console_lock()
  2022. #define unlock_curses() bfg_console_unlock()
  2023. static bool curses_active_locked(void)
  2024. {
  2025. bool ret;
  2026. lock_curses();
  2027. ret = curses_active;
  2028. if (!ret)
  2029. unlock_curses();
  2030. return ret;
  2031. }
  2032. // Cancellable getch
  2033. int my_cancellable_getch(void)
  2034. {
  2035. // This only works because the macro only hits direct getch() calls
  2036. typedef int (*real_getch_t)(void);
  2037. const real_getch_t real_getch = __real_getch;
  2038. int type, rv;
  2039. bool sct;
  2040. sct = !pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &type);
  2041. rv = real_getch();
  2042. if (sct)
  2043. pthread_setcanceltype(type, &type);
  2044. return rv;
  2045. }
  2046. #endif
  2047. void tailsprintf(char *f, const char *fmt, ...)
  2048. {
  2049. va_list ap;
  2050. va_start(ap, fmt);
  2051. vsprintf(f + strlen(f), fmt, ap);
  2052. va_end(ap);
  2053. }
  2054. double stats_elapsed(struct cgminer_stats *stats)
  2055. {
  2056. struct timeval now;
  2057. double elapsed;
  2058. if (stats->start_tv.tv_sec == 0)
  2059. elapsed = total_secs;
  2060. else {
  2061. cgtime(&now);
  2062. elapsed = tdiff(&now, &stats->start_tv);
  2063. }
  2064. if (elapsed < 1.0)
  2065. elapsed = 1.0;
  2066. return elapsed;
  2067. }
  2068. bool drv_ready(struct cgpu_info *cgpu)
  2069. {
  2070. switch (cgpu->status) {
  2071. case LIFE_INIT:
  2072. case LIFE_DEAD2:
  2073. return false;
  2074. default:
  2075. return true;
  2076. }
  2077. }
  2078. double cgpu_utility(struct cgpu_info *cgpu)
  2079. {
  2080. double dev_runtime = cgpu_runtime(cgpu);
  2081. return cgpu->utility = cgpu->accepted / dev_runtime * 60;
  2082. }
  2083. /* Convert a uint64_t value into a truncated string for displaying with its
  2084. * associated suitable for Mega, Giga etc. Buf array needs to be long enough */
  2085. static void suffix_string(uint64_t val, char *buf, int sigdigits)
  2086. {
  2087. const double dkilo = 1000.0;
  2088. const uint64_t kilo = 1000ull;
  2089. const uint64_t mega = 1000000ull;
  2090. const uint64_t giga = 1000000000ull;
  2091. const uint64_t tera = 1000000000000ull;
  2092. const uint64_t peta = 1000000000000000ull;
  2093. const uint64_t exa = 1000000000000000000ull;
  2094. char suffix[2] = "";
  2095. bool decimal = true;
  2096. double dval;
  2097. if (val >= exa) {
  2098. val /= peta;
  2099. dval = (double)val / dkilo;
  2100. sprintf(suffix, "E");
  2101. } else if (val >= peta) {
  2102. val /= tera;
  2103. dval = (double)val / dkilo;
  2104. sprintf(suffix, "P");
  2105. } else if (val >= tera) {
  2106. val /= giga;
  2107. dval = (double)val / dkilo;
  2108. sprintf(suffix, "T");
  2109. } else if (val >= giga) {
  2110. val /= mega;
  2111. dval = (double)val / dkilo;
  2112. sprintf(suffix, "G");
  2113. } else if (val >= mega) {
  2114. val /= kilo;
  2115. dval = (double)val / dkilo;
  2116. sprintf(suffix, "M");
  2117. } else if (val >= kilo) {
  2118. dval = (double)val / dkilo;
  2119. sprintf(suffix, "k");
  2120. } else {
  2121. dval = val;
  2122. decimal = false;
  2123. }
  2124. if (!sigdigits) {
  2125. if (decimal)
  2126. sprintf(buf, "%.3g%s", dval, suffix);
  2127. else
  2128. sprintf(buf, "%d%s", (unsigned int)dval, suffix);
  2129. } else {
  2130. /* Always show sigdigits + 1, padded on right with zeroes
  2131. * followed by suffix */
  2132. int ndigits = sigdigits - 1 - (dval > 0.0 ? floor(log10(dval)) : 0);
  2133. sprintf(buf, "%*.*f%s", sigdigits + 1, ndigits, dval, suffix);
  2134. }
  2135. }
  2136. static float
  2137. utility_to_hashrate(double utility)
  2138. {
  2139. return utility * 0x4444444;
  2140. }
  2141. static const char*_unitchar = " kMGTPEZY?";
  2142. static
  2143. void pick_unit(float hashrate, unsigned char *unit)
  2144. {
  2145. unsigned char i;
  2146. for (i = 0; i < *unit; ++i)
  2147. hashrate /= 1e3;
  2148. while (hashrate >= 1000)
  2149. {
  2150. hashrate /= 1e3;
  2151. if (likely(_unitchar[*unit] != '?'))
  2152. ++*unit;
  2153. }
  2154. }
  2155. #define hashrate_pick_unit(hashrate, unit) pick_unit(hashrate, unit)
  2156. enum h2bs_fmt {
  2157. H2B_NOUNIT, // "xxx.x"
  2158. H2B_SHORT, // "xxx.xMH/s"
  2159. H2B_SPACED, // "xxx.x MH/s"
  2160. };
  2161. static const size_t h2bs_fmt_size[] = {6, 10, 11};
  2162. static
  2163. char *format_unit(char *buf, bool floatprec, const char *measurement, enum h2bs_fmt fmt, float hashrate, signed char unitin)
  2164. {
  2165. unsigned char prec, i, unit;
  2166. if (unitin == -1)
  2167. {
  2168. unit = 0;
  2169. hashrate_pick_unit(hashrate, &unit);
  2170. }
  2171. else
  2172. unit = unitin;
  2173. for (i = 0; i < unit; ++i)
  2174. hashrate /= 1000;
  2175. if (floatprec)
  2176. {
  2177. if (hashrate >= 100 || unit < 2)
  2178. prec = 1;
  2179. else
  2180. prec = 2;
  2181. sprintf(buf, "%5.*f", prec, hashrate);
  2182. i = 5;
  2183. }
  2184. else
  2185. {
  2186. sprintf(buf, "%3d", (int)hashrate);
  2187. i = 3;
  2188. }
  2189. switch (fmt) {
  2190. case H2B_SPACED:
  2191. buf[i++] = ' ';
  2192. case H2B_SHORT:
  2193. buf[i++] = _unitchar[unit];
  2194. strcpy(&buf[i], measurement);
  2195. default:
  2196. break;
  2197. }
  2198. return buf;
  2199. }
  2200. static
  2201. char *_multi_format_unit(char **buflist, bool floatprec, const char *measurement, enum h2bs_fmt fmt, const char *delim, int count, const float *numbers, bool isarray)
  2202. {
  2203. unsigned char unit = 0;
  2204. int i;
  2205. size_t delimsz;
  2206. char *buf = buflist[0];
  2207. size_t itemwidth = (floatprec ? 5 : 3);
  2208. if (!isarray)
  2209. delimsz = strlen(delim);
  2210. for (i = 0; i < count; ++i)
  2211. pick_unit(numbers[i], &unit);
  2212. --count;
  2213. for (i = 0; i < count; ++i)
  2214. {
  2215. format_unit(buf, floatprec, NULL, H2B_NOUNIT, numbers[i], unit);
  2216. if (isarray)
  2217. buf = buflist[i + 1];
  2218. else
  2219. {
  2220. buf += itemwidth;
  2221. memcpy(buf, delim, delimsz);
  2222. buf += delimsz;
  2223. }
  2224. }
  2225. // Last entry has the unit
  2226. format_unit(buf, floatprec, measurement, fmt, numbers[count], unit);
  2227. return buflist[0];
  2228. }
  2229. #define multi_format_unit(buf, floatprec, measurement, fmt, delim, count, ...) _multi_format_unit((char *[]){buf}, floatprec, measurement, fmt, delim, count, (float[]){ __VA_ARGS__ }, false)
  2230. #define multi_format_unit_array(buflist, floatprec, measurement, fmt, count, ...) (void)_multi_format_unit(buflist, floatprec, measurement, fmt, NULL, count, (float[]){ __VA_ARGS__ }, true)
  2231. static const char *
  2232. percentf2(double p, double t, char *buf)
  2233. {
  2234. if (!p)
  2235. return "none";
  2236. if (t <= p)
  2237. return "100%";
  2238. p /= t;
  2239. if (p < 0.01)
  2240. sprintf(buf, ".%02.0f%%", p * 10000); // ".01%"
  2241. else
  2242. if (p < 0.1)
  2243. sprintf(buf, "%.1f%%", p * 100); // "9.1%"
  2244. else
  2245. sprintf(buf, "%3.0f%%", p * 100); // " 99%"
  2246. return buf;
  2247. }
  2248. #define percentf(p, t, buf) percentf2(p, p + t, buf)
  2249. #ifdef HAVE_CURSES
  2250. static void adj_width(int var, int *length);
  2251. #endif
  2252. #ifdef HAVE_CURSES
  2253. static int awidth = 1, rwidth = 1, swidth = 1, hwwidth = 1;
  2254. static
  2255. void format_statline(char *buf, const char *cHr, const char *aHr, const char *uHr, int accepted, int rejected, int stale, int wnotaccepted, int waccepted, int hwerrs, int badnonces, int allnonces)
  2256. {
  2257. char rejpcbuf[6];
  2258. char bnbuf[6];
  2259. adj_width(accepted, &awidth);
  2260. adj_width(rejected, &rwidth);
  2261. adj_width(stale, &swidth);
  2262. adj_width(hwerrs, &hwwidth);
  2263. tailsprintf(buf, "%s/%s/%s | A:%*d R:%*d+%*d(%s) HW:%*d/%s",
  2264. cHr, aHr, uHr,
  2265. awidth, accepted,
  2266. rwidth, rejected,
  2267. swidth, stale,
  2268. percentf(wnotaccepted, waccepted, rejpcbuf),
  2269. hwwidth, hwerrs,
  2270. percentf2(badnonces, allnonces, bnbuf)
  2271. );
  2272. }
  2273. #endif
  2274. static inline
  2275. void temperature_column_tail(char *buf, bool maybe_unicode, const float * const temp)
  2276. {
  2277. if (!use_unicode)
  2278. maybe_unicode = false;
  2279. if (temp && *temp > 0.)
  2280. sprintf(buf, "%4.1fC", *temp);
  2281. else
  2282. {
  2283. if (temp)
  2284. strcpy(buf, " ");
  2285. }
  2286. strcat(buf, " | ");
  2287. }
  2288. void get_statline3(char *buf, struct cgpu_info *cgpu, bool for_curses, bool opt_show_procs)
  2289. {
  2290. #ifndef HAVE_CURSES
  2291. assert(for_curses == false);
  2292. #endif
  2293. struct device_drv *drv = cgpu->drv;
  2294. enum h2bs_fmt hashrate_style = for_curses ? H2B_SHORT : H2B_SPACED;
  2295. char cHr[h2bs_fmt_size[H2B_NOUNIT]], aHr[h2bs_fmt_size[H2B_NOUNIT]], uHr[h2bs_fmt_size[hashrate_style]];
  2296. char rejpcbuf[6];
  2297. char bnbuf[6];
  2298. double dev_runtime;
  2299. if (!opt_show_procs)
  2300. cgpu = cgpu->device;
  2301. dev_runtime = cgpu_runtime(cgpu);
  2302. cgpu_utility(cgpu);
  2303. cgpu->utility_diff1 = cgpu->diff_accepted / dev_runtime * 60;
  2304. double rolling = cgpu->rolling;
  2305. double mhashes = cgpu->total_mhashes;
  2306. double wutil = cgpu->utility_diff1;
  2307. int accepted = cgpu->accepted;
  2308. int rejected = cgpu->rejected;
  2309. int stale = cgpu->stale;
  2310. double waccepted = cgpu->diff_accepted;
  2311. double wnotaccepted = cgpu->diff_rejected + cgpu->diff_stale;
  2312. int hwerrs = cgpu->hw_errors;
  2313. int badnonces = cgpu->bad_nonces;
  2314. int allnonces = cgpu->diff1;
  2315. if (!opt_show_procs)
  2316. for (struct cgpu_info *slave = cgpu; (slave = slave->next_proc); )
  2317. {
  2318. slave->utility = slave->accepted / dev_runtime * 60;
  2319. slave->utility_diff1 = slave->diff_accepted / dev_runtime * 60;
  2320. rolling += slave->rolling;
  2321. mhashes += slave->total_mhashes;
  2322. wutil += slave->utility_diff1;
  2323. accepted += slave->accepted;
  2324. rejected += slave->rejected;
  2325. stale += slave->stale;
  2326. waccepted += slave->diff_accepted;
  2327. wnotaccepted += slave->diff_rejected + slave->diff_stale;
  2328. hwerrs += slave->hw_errors;
  2329. badnonces += slave->bad_nonces;
  2330. allnonces += slave->diff1;
  2331. }
  2332. multi_format_unit_array(
  2333. ((char*[]){cHr, aHr, uHr}),
  2334. true, "h/s", hashrate_style,
  2335. 3,
  2336. 1e6*rolling,
  2337. 1e6*mhashes / dev_runtime,
  2338. utility_to_hashrate(wutil));
  2339. // Processor representation
  2340. #ifdef HAVE_CURSES
  2341. if (for_curses)
  2342. {
  2343. if (opt_show_procs)
  2344. sprintf(buf, " %"PRIprepr": ", cgpu->proc_repr);
  2345. else
  2346. sprintf(buf, " %s: ", cgpu->dev_repr);
  2347. }
  2348. else
  2349. #endif
  2350. sprintf(buf, "%s ", opt_show_procs ? cgpu->proc_repr_ns : cgpu->dev_repr_ns);
  2351. if (unlikely(cgpu->status == LIFE_INIT))
  2352. {
  2353. tailsprintf(buf, "Initializing...");
  2354. return;
  2355. }
  2356. if (likely(cgpu->status != LIFE_DEAD2) && drv->override_statline_temp && drv->override_statline_temp(buf, cgpu, opt_show_procs))
  2357. temperature_column_tail(&buf[strlen(buf)], for_curses, NULL);
  2358. else
  2359. {
  2360. float temp = cgpu->temp;
  2361. if (!opt_show_procs)
  2362. {
  2363. // Find the highest temperature of all processors
  2364. for (struct cgpu_info *proc = cgpu; proc; proc = proc->next_proc)
  2365. if (proc->temp > temp)
  2366. temp = proc->temp;
  2367. }
  2368. temperature_column_tail(&buf[strlen(buf)], for_curses, &temp);
  2369. }
  2370. #ifdef HAVE_CURSES
  2371. if (for_curses)
  2372. {
  2373. const char *cHrStatsOpt[] = {"DEAD ", "SICK ", "OFF ", "REST ", " ERR ", "WAIT ", cHr};
  2374. int cHrStatsI = (sizeof(cHrStatsOpt) / sizeof(*cHrStatsOpt)) - 1;
  2375. bool all_dead = true, all_off = true;
  2376. for (struct cgpu_info *proc = cgpu; proc; proc = proc->next_proc)
  2377. {
  2378. switch (cHrStatsI) {
  2379. default:
  2380. if (proc->status == LIFE_WAIT)
  2381. cHrStatsI = 5;
  2382. case 5:
  2383. if (proc->deven == DEV_RECOVER_ERR)
  2384. cHrStatsI = 4;
  2385. case 4:
  2386. if (proc->deven == DEV_RECOVER)
  2387. cHrStatsI = 3;
  2388. case 3:
  2389. if (proc->status == LIFE_SICK || proc->status == LIFE_DEAD || proc->status == LIFE_DEAD2)
  2390. {
  2391. cHrStatsI = 1;
  2392. all_off = false;
  2393. }
  2394. else
  2395. if (likely(proc->deven != DEV_DISABLED))
  2396. all_off = false;
  2397. case 1:
  2398. break;
  2399. }
  2400. if (likely(proc->status != LIFE_DEAD && proc->status != LIFE_DEAD2))
  2401. all_dead = false;
  2402. if (opt_show_procs)
  2403. break;
  2404. }
  2405. if (unlikely(all_dead))
  2406. cHrStatsI = 0;
  2407. else
  2408. if (unlikely(all_off))
  2409. cHrStatsI = 2;
  2410. format_statline(buf,
  2411. cHrStatsOpt[cHrStatsI],
  2412. aHr, uHr,
  2413. accepted, rejected, stale,
  2414. wnotaccepted, waccepted,
  2415. hwerrs,
  2416. badnonces, allnonces);
  2417. }
  2418. else
  2419. #endif
  2420. {
  2421. tailsprintf(buf, "%ds:%s avg:%s u:%s | A:%d R:%d+%d(%s) HW:%d/%s",
  2422. opt_log_interval,
  2423. cHr, aHr, uHr,
  2424. accepted,
  2425. rejected,
  2426. stale,
  2427. percentf(wnotaccepted, waccepted, rejpcbuf),
  2428. hwerrs,
  2429. percentf2(badnonces, allnonces, bnbuf)
  2430. );
  2431. }
  2432. }
  2433. #define get_statline(buf, cgpu) get_statline3(buf, cgpu, false, opt_show_procs)
  2434. #define get_statline2(buf, cgpu, for_curses) get_statline3(buf, cgpu, for_curses, opt_show_procs)
  2435. static void text_print_status(int thr_id)
  2436. {
  2437. struct cgpu_info *cgpu;
  2438. char logline[256];
  2439. cgpu = get_thr_cgpu(thr_id);
  2440. if (cgpu) {
  2441. get_statline(logline, cgpu);
  2442. printf("%s\n", logline);
  2443. }
  2444. }
  2445. #ifdef HAVE_CURSES
  2446. #ifdef USE_UNICODE
  2447. static
  2448. void bfg_waddstr(WINDOW *win, const char *s)
  2449. {
  2450. const char *p = s;
  2451. wchar_t buf[2] = {0, 0};
  2452. #define PREP_ADDCH do { \
  2453. if (p != s) \
  2454. waddnstr(win, s, p - s); \
  2455. s = ++p; \
  2456. }while(0)
  2457. while (true)
  2458. {
  2459. next:
  2460. switch(p[0])
  2461. {
  2462. case '\0':
  2463. goto done;
  2464. default:
  2465. ++p;
  2466. goto next;
  2467. case '\xb0': // Degrees symbol
  2468. buf[0] = ((unsigned char *)p)[0];
  2469. }
  2470. PREP_ADDCH;
  2471. waddwstr(win, buf);
  2472. }
  2473. done:
  2474. PREP_ADDCH;
  2475. return;
  2476. #undef PREP_ADDCH
  2477. }
  2478. #define bfg_waddstr(win, s) do { \
  2479. if (use_unicode) \
  2480. bfg_waddstr(win, s); \
  2481. else \
  2482. waddstr(win, s); \
  2483. }while(0)
  2484. #else
  2485. #define bfg_waddstr(win, s) waddstr(win, s)
  2486. #endif
  2487. static inline
  2488. void bfg_hline(WINDOW *win, int y)
  2489. {
  2490. if (use_unicode)
  2491. mvwhline_set(win, y, 0, WACS_HLINE, 80);
  2492. else
  2493. mvwhline(win, y, 0, '-', 80);
  2494. }
  2495. static int menu_attr = A_REVERSE;
  2496. /* Must be called with curses mutex lock held and curses_active */
  2497. static void curses_print_status(void)
  2498. {
  2499. struct pool *pool = currentpool;
  2500. struct timeval now, tv;
  2501. float efficiency;
  2502. double utility;
  2503. efficiency = total_bytes_xfer ? total_diff_accepted * 2048. / total_bytes_xfer : 0.0;
  2504. wattron(statuswin, A_BOLD);
  2505. mvwprintw(statuswin, 0, 0, " " PACKAGE " version " VERSION " - Started: %s", datestamp);
  2506. timer_set_now(&now);
  2507. {
  2508. unsigned int days, hours;
  2509. div_t d;
  2510. timersub(&now, &miner_started, &tv);
  2511. d = div(tv.tv_sec, 86400);
  2512. days = d.quot;
  2513. d = div(d.rem, 3600);
  2514. hours = d.quot;
  2515. d = div(d.rem, 60);
  2516. wprintw(statuswin, " - [%3u day%c %02d:%02d:%02d]"
  2517. , days
  2518. , (days == 1) ? ' ' : 's'
  2519. , hours
  2520. , d.quot
  2521. , d.rem
  2522. );
  2523. }
  2524. wattroff(statuswin, A_BOLD);
  2525. wmove(statuswin, 5, 1);
  2526. bfg_waddstr(statuswin, statusline);
  2527. wclrtoeol(statuswin);
  2528. utility = total_accepted / total_secs * 60;
  2529. char bwstr[12];
  2530. mvwprintw(statuswin, 4, 0, " ST:%d F:%d NB:%d AS:%d BW:[%s] E:%.2f U:%.1f/m BS:%s",
  2531. __total_staged(),
  2532. total_go + total_ro,
  2533. new_blocks,
  2534. total_submitting,
  2535. multi_format_unit(bwstr, false, "B/s", H2B_SHORT, "/", 2,
  2536. (float)(total_bytes_rcvd / total_secs),
  2537. (float)(total_bytes_sent / total_secs)),
  2538. efficiency,
  2539. utility,
  2540. best_share);
  2541. wclrtoeol(statuswin);
  2542. if ((pool_strategy == POOL_LOADBALANCE || pool_strategy == POOL_BALANCE) && total_pools > 1) {
  2543. mvwprintw(statuswin, 2, 0, " Connected to multiple pools with%s LP",
  2544. have_longpoll ? "": "out");
  2545. } else if (pool->has_stratum) {
  2546. mvwprintw(statuswin, 2, 0, " Connected to %s diff %s with stratum as user %s",
  2547. pool->sockaddr_url, pool->diff, pool->rpc_user);
  2548. } else {
  2549. mvwprintw(statuswin, 2, 0, " Connected to %s diff %s with%s LP as user %s",
  2550. pool->sockaddr_url, pool->diff, have_longpoll ? "": "out", pool->rpc_user);
  2551. }
  2552. wclrtoeol(statuswin);
  2553. mvwprintw(statuswin, 3, 0, " Block: %s Diff:%s (%s) Started: %s",
  2554. current_hash, block_diff, net_hashrate, blocktime);
  2555. bfg_hline(statuswin, 6);
  2556. bfg_hline(statuswin, statusy - 1);
  2557. wattron(statuswin, menu_attr);
  2558. mvwprintw(statuswin, 1, 0, " [M]anage devices [P]ool management [S]ettings [D]isplay options [H]elp [Q]uit ");
  2559. wattroff(statuswin, menu_attr);
  2560. }
  2561. static void adj_width(int var, int *length)
  2562. {
  2563. if ((int)(log10(var) + 1) > *length)
  2564. (*length)++;
  2565. }
  2566. static int dev_width;
  2567. static void curses_print_devstatus(struct cgpu_info *cgpu)
  2568. {
  2569. char logline[256];
  2570. int ypos;
  2571. if (opt_compact)
  2572. return;
  2573. /* Check this isn't out of the window size */
  2574. if (opt_show_procs)
  2575. ypos = cgpu->cgminer_id;
  2576. else
  2577. {
  2578. if (cgpu->proc_id)
  2579. return;
  2580. ypos = cgpu->device_line_id;
  2581. }
  2582. ypos += devsummaryYOffset;
  2583. if (ypos < 0)
  2584. return;
  2585. ypos += devcursor - 1;
  2586. if (ypos >= statusy - 1)
  2587. return;
  2588. if (wmove(statuswin, ypos, 0) == ERR)
  2589. return;
  2590. get_statline2(logline, cgpu, true);
  2591. if (selecting_device && (opt_show_procs ? (selected_device == cgpu->cgminer_id) : (devices[selected_device]->device == cgpu)))
  2592. wattron(statuswin, A_REVERSE);
  2593. bfg_waddstr(statuswin, logline);
  2594. wattroff(statuswin, A_REVERSE);
  2595. wclrtoeol(statuswin);
  2596. }
  2597. static
  2598. void refresh_devstatus() {
  2599. if (curses_active_locked()) {
  2600. int i;
  2601. for (i = 0; i < total_devices; i++)
  2602. curses_print_devstatus(get_devices(i));
  2603. touchwin(statuswin);
  2604. wrefresh(statuswin);
  2605. unlock_curses();
  2606. }
  2607. }
  2608. #endif
  2609. static void print_status(int thr_id)
  2610. {
  2611. if (!curses_active)
  2612. text_print_status(thr_id);
  2613. }
  2614. #ifdef HAVE_CURSES
  2615. /* Check for window resize. Called with curses mutex locked */
  2616. static inline void change_logwinsize(void)
  2617. {
  2618. int x, y, logx, logy;
  2619. getmaxyx(mainwin, y, x);
  2620. if (x < 80 || y < 25)
  2621. return;
  2622. if (y > statusy + 2 && statusy < logstart) {
  2623. if (y - 2 < logstart)
  2624. statusy = y - 2;
  2625. else
  2626. statusy = logstart;
  2627. logcursor = statusy;
  2628. mvwin(logwin, logcursor, 0);
  2629. wresize(statuswin, statusy, x);
  2630. }
  2631. y -= logcursor;
  2632. getmaxyx(logwin, logy, logx);
  2633. /* Detect screen size change */
  2634. if (x != logx || y != logy)
  2635. wresize(logwin, y, x);
  2636. }
  2637. static void check_winsizes(void)
  2638. {
  2639. if (!use_curses)
  2640. return;
  2641. if (curses_active_locked()) {
  2642. int y, x;
  2643. erase();
  2644. x = getmaxx(statuswin);
  2645. if (logstart > LINES - 2)
  2646. statusy = LINES - 2;
  2647. else
  2648. statusy = logstart;
  2649. logcursor = statusy;
  2650. wresize(statuswin, statusy, x);
  2651. getmaxyx(mainwin, y, x);
  2652. y -= logcursor;
  2653. wresize(logwin, y, x);
  2654. mvwin(logwin, logcursor, 0);
  2655. unlock_curses();
  2656. }
  2657. }
  2658. static int device_line_id_count;
  2659. static void switch_logsize(void)
  2660. {
  2661. if (curses_active_locked()) {
  2662. if (opt_compact) {
  2663. logstart = devcursor - 1;
  2664. logcursor = logstart + 1;
  2665. } else {
  2666. total_lines = (opt_show_procs ? total_devices : device_line_id_count);
  2667. logstart = devcursor + total_lines;
  2668. logcursor = logstart;
  2669. }
  2670. unlock_curses();
  2671. }
  2672. check_winsizes();
  2673. }
  2674. /* For mandatory printing when mutex is already locked */
  2675. void _wlog(const char *str)
  2676. {
  2677. static bool newline;
  2678. size_t end = strlen(str) - 1;
  2679. if (newline)
  2680. bfg_waddstr(logwin, "\n");
  2681. if (str[end] == '\n')
  2682. {
  2683. char *s;
  2684. newline = true;
  2685. s = alloca(end);
  2686. memcpy(s, str, end);
  2687. s[end] = '\0';
  2688. str = s;
  2689. }
  2690. else
  2691. newline = false;
  2692. bfg_waddstr(logwin, str);
  2693. }
  2694. /* Mandatory printing */
  2695. void _wlogprint(const char *str)
  2696. {
  2697. if (curses_active_locked()) {
  2698. _wlog(str);
  2699. unlock_curses();
  2700. }
  2701. }
  2702. #endif
  2703. #ifdef HAVE_CURSES
  2704. bool _log_curses_only(int prio, const char *datetime, const char *str)
  2705. {
  2706. bool high_prio;
  2707. high_prio = (prio == LOG_WARNING || prio == LOG_ERR);
  2708. if (curses_active)
  2709. {
  2710. if (!opt_loginput || high_prio) {
  2711. wlog(" %s %s\n", datetime, str);
  2712. if (high_prio) {
  2713. touchwin(logwin);
  2714. wrefresh(logwin);
  2715. }
  2716. }
  2717. return true;
  2718. }
  2719. return false;
  2720. }
  2721. void clear_logwin(void)
  2722. {
  2723. if (curses_active_locked()) {
  2724. wclear(logwin);
  2725. unlock_curses();
  2726. }
  2727. }
  2728. void logwin_update(void)
  2729. {
  2730. if (curses_active_locked()) {
  2731. touchwin(logwin);
  2732. wrefresh(logwin);
  2733. unlock_curses();
  2734. }
  2735. }
  2736. #endif
  2737. static void enable_pool(struct pool *pool)
  2738. {
  2739. if (pool->enabled != POOL_ENABLED) {
  2740. enabled_pools++;
  2741. pool->enabled = POOL_ENABLED;
  2742. }
  2743. }
  2744. #ifdef HAVE_CURSES
  2745. static void disable_pool(struct pool *pool)
  2746. {
  2747. if (pool->enabled == POOL_ENABLED)
  2748. enabled_pools--;
  2749. pool->enabled = POOL_DISABLED;
  2750. }
  2751. #endif
  2752. static void reject_pool(struct pool *pool)
  2753. {
  2754. if (pool->enabled == POOL_ENABLED)
  2755. enabled_pools--;
  2756. pool->enabled = POOL_REJECTING;
  2757. }
  2758. static uint64_t share_diff(const struct work *);
  2759. static
  2760. void share_result_msg(const struct work *work, const char *disp, const char *reason, bool resubmit, const char *worktime) {
  2761. struct cgpu_info *cgpu;
  2762. const unsigned char *hashpart = &work->hash[opt_scrypt ? 26 : 24];
  2763. char shrdiffdisp[16];
  2764. int tgtdiff = floor(work->work_difficulty);
  2765. char tgtdiffdisp[16];
  2766. char where[20];
  2767. cgpu = get_thr_cgpu(work->thr_id);
  2768. suffix_string(work->share_diff, shrdiffdisp, 0);
  2769. suffix_string(tgtdiff, tgtdiffdisp, 0);
  2770. if (total_pools > 1)
  2771. sprintf(where, " pool %d", work->pool->pool_no);
  2772. else
  2773. where[0] = '\0';
  2774. applog(LOG_NOTICE, "%s %02x%02x%02x%02x %"PRIprepr"%s Diff %s/%s%s %s%s",
  2775. disp,
  2776. (unsigned)hashpart[3], (unsigned)hashpart[2], (unsigned)hashpart[1], (unsigned)hashpart[0],
  2777. cgpu->proc_repr,
  2778. where,
  2779. shrdiffdisp, tgtdiffdisp,
  2780. reason,
  2781. resubmit ? "(resubmit)" : "",
  2782. worktime
  2783. );
  2784. }
  2785. static bool test_work_current(struct work *);
  2786. static void _submit_work_async(struct work *);
  2787. static
  2788. void maybe_local_submit(const struct work *work)
  2789. {
  2790. #if BLKMAKER_VERSION > 3
  2791. if (unlikely(work->block && work->tmpl))
  2792. {
  2793. // This is a block with a full template (GBT)
  2794. // Regardless of the result, submit to local bitcoind(s) as well
  2795. struct work *work_cp;
  2796. char *p;
  2797. for (int i = 0; i < total_pools; ++i)
  2798. {
  2799. p = strchr(pools[i]->rpc_url, '#');
  2800. if (likely(!(p && strstr(&p[1], "allblocks"))))
  2801. continue;
  2802. work_cp = copy_work(work);
  2803. work_cp->pool = pools[i];
  2804. work_cp->do_foreign_submit = true;
  2805. _submit_work_async(work_cp);
  2806. }
  2807. }
  2808. #endif
  2809. }
  2810. /* Theoretically threads could race when modifying accepted and
  2811. * rejected values but the chance of two submits completing at the
  2812. * same time is zero so there is no point adding extra locking */
  2813. static void
  2814. share_result(json_t *val, json_t *res, json_t *err, const struct work *work,
  2815. /*char *hashshow,*/ bool resubmit, char *worktime)
  2816. {
  2817. struct pool *pool = work->pool;
  2818. struct cgpu_info *cgpu;
  2819. cgpu = get_thr_cgpu(work->thr_id);
  2820. if ((json_is_null(err) || !err) && (json_is_null(res) || json_is_true(res))) {
  2821. mutex_lock(&stats_lock);
  2822. cgpu->accepted++;
  2823. total_accepted++;
  2824. pool->accepted++;
  2825. cgpu->diff_accepted += work->work_difficulty;
  2826. total_diff_accepted += work->work_difficulty;
  2827. pool->diff_accepted += work->work_difficulty;
  2828. mutex_unlock(&stats_lock);
  2829. pool->seq_rejects = 0;
  2830. cgpu->last_share_pool = pool->pool_no;
  2831. cgpu->last_share_pool_time = time(NULL);
  2832. cgpu->last_share_diff = work->work_difficulty;
  2833. pool->last_share_time = cgpu->last_share_pool_time;
  2834. pool->last_share_diff = work->work_difficulty;
  2835. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  2836. if (!QUIET) {
  2837. share_result_msg(work, "Accepted", "", resubmit, worktime);
  2838. }
  2839. sharelog("accept", work);
  2840. if (opt_shares && total_accepted >= opt_shares) {
  2841. applog(LOG_WARNING, "Successfully mined %d accepted shares as requested and exiting.", opt_shares);
  2842. kill_work();
  2843. return;
  2844. }
  2845. /* Detect if a pool that has been temporarily disabled for
  2846. * continually rejecting shares has started accepting shares.
  2847. * This will only happen with the work returned from a
  2848. * longpoll */
  2849. if (unlikely(pool->enabled == POOL_REJECTING)) {
  2850. applog(LOG_WARNING, "Rejecting pool %d now accepting shares, re-enabling!", pool->pool_no);
  2851. enable_pool(pool);
  2852. switch_pools(NULL);
  2853. }
  2854. if (unlikely(work->block)) {
  2855. // Force moving on to this new block :)
  2856. struct work fakework;
  2857. memset(&fakework, 0, sizeof(fakework));
  2858. fakework.pool = work->pool;
  2859. // Copy block version, bits, and time from share
  2860. memcpy(&fakework.data[ 0], &work->data[ 0], 4);
  2861. memcpy(&fakework.data[68], &work->data[68], 8);
  2862. // Set prevblock to winning hash (swap32'd)
  2863. swap32yes(&fakework.data[4], &work->hash[0], 32 / 4);
  2864. test_work_current(&fakework);
  2865. }
  2866. } else {
  2867. mutex_lock(&stats_lock);
  2868. cgpu->rejected++;
  2869. total_rejected++;
  2870. pool->rejected++;
  2871. cgpu->diff_rejected += work->work_difficulty;
  2872. total_diff_rejected += work->work_difficulty;
  2873. pool->diff_rejected += work->work_difficulty;
  2874. pool->seq_rejects++;
  2875. mutex_unlock(&stats_lock);
  2876. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  2877. if (!QUIET) {
  2878. char where[20];
  2879. char disposition[36] = "reject";
  2880. char reason[32];
  2881. strcpy(reason, "");
  2882. if (total_pools > 1)
  2883. sprintf(where, "pool %d", work->pool->pool_no);
  2884. else
  2885. strcpy(where, "");
  2886. if (!json_is_string(res))
  2887. res = json_object_get(val, "reject-reason");
  2888. if (res) {
  2889. const char *reasontmp = json_string_value(res);
  2890. size_t reasonLen = strlen(reasontmp);
  2891. if (reasonLen > 28)
  2892. reasonLen = 28;
  2893. reason[0] = ' '; reason[1] = '(';
  2894. memcpy(2 + reason, reasontmp, reasonLen);
  2895. reason[reasonLen + 2] = ')'; reason[reasonLen + 3] = '\0';
  2896. memcpy(disposition + 7, reasontmp, reasonLen);
  2897. disposition[6] = ':'; disposition[reasonLen + 7] = '\0';
  2898. } else if (work->stratum && err && json_is_array(err)) {
  2899. json_t *reason_val = json_array_get(err, 1);
  2900. char *reason_str;
  2901. if (reason_val && json_is_string(reason_val)) {
  2902. reason_str = (char *)json_string_value(reason_val);
  2903. snprintf(reason, 31, " (%s)", reason_str);
  2904. }
  2905. }
  2906. share_result_msg(work, "Rejected", reason, resubmit, worktime);
  2907. sharelog(disposition, work);
  2908. }
  2909. /* Once we have more than a nominal amount of sequential rejects,
  2910. * at least 10 and more than 3 mins at the current utility,
  2911. * disable the pool because some pool error is likely to have
  2912. * ensued. Do not do this if we know the share just happened to
  2913. * be stale due to networking delays.
  2914. */
  2915. if (pool->seq_rejects > 10 && !work->stale && opt_disable_pool && enabled_pools > 1) {
  2916. double utility = total_accepted / total_secs * 60;
  2917. if (pool->seq_rejects > utility * 3) {
  2918. applog(LOG_WARNING, "Pool %d rejected %d sequential shares, disabling!",
  2919. pool->pool_no, pool->seq_rejects);
  2920. reject_pool(pool);
  2921. if (pool == current_pool())
  2922. switch_pools(NULL);
  2923. pool->seq_rejects = 0;
  2924. }
  2925. }
  2926. }
  2927. maybe_local_submit(work);
  2928. }
  2929. static char *submit_upstream_work_request(struct work *work)
  2930. {
  2931. char *hexstr = NULL;
  2932. char *s, *sd;
  2933. struct pool *pool = work->pool;
  2934. if (work->tmpl) {
  2935. json_t *req;
  2936. unsigned char data[80];
  2937. swap32yes(data, work->data, 80 / 4);
  2938. #if BLKMAKER_VERSION > 3
  2939. if (work->do_foreign_submit)
  2940. req = blkmk_submit_foreign_jansson(work->tmpl, data, work->dataid, le32toh(*((uint32_t*)&work->data[76])));
  2941. else
  2942. #endif
  2943. req = blkmk_submit_jansson(work->tmpl, data, work->dataid, le32toh(*((uint32_t*)&work->data[76])));
  2944. s = json_dumps(req, 0);
  2945. json_decref(req);
  2946. sd = malloc(161);
  2947. bin2hex(sd, data, 80);
  2948. } else {
  2949. /* build hex string */
  2950. hexstr = malloc((sizeof(work->data) * 2) + 1);
  2951. bin2hex(hexstr, work->data, sizeof(work->data));
  2952. /* build JSON-RPC request */
  2953. s = strdup("{\"method\": \"getwork\", \"params\": [ \"");
  2954. s = realloc_strcat(s, hexstr);
  2955. s = realloc_strcat(s, "\" ], \"id\":1}");
  2956. free(hexstr);
  2957. sd = s;
  2958. }
  2959. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->rpc_url, sd);
  2960. if (work->tmpl)
  2961. free(sd);
  2962. else
  2963. s = realloc_strcat(s, "\n");
  2964. return s;
  2965. }
  2966. static bool submit_upstream_work_completed(struct work *work, bool resubmit, struct timeval *ptv_submit, json_t *val) {
  2967. json_t *res, *err;
  2968. bool rc = false;
  2969. int thr_id = work->thr_id;
  2970. struct pool *pool = work->pool;
  2971. struct timeval tv_submit_reply;
  2972. time_t ts_submit_reply;
  2973. char worktime[200] = "";
  2974. cgtime(&tv_submit_reply);
  2975. ts_submit_reply = time(NULL);
  2976. if (unlikely(!val)) {
  2977. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  2978. if (!pool_tset(pool, &pool->submit_fail)) {
  2979. total_ro++;
  2980. pool->remotefail_occasions++;
  2981. applog(LOG_WARNING, "Pool %d communication failure, caching submissions", pool->pool_no);
  2982. }
  2983. goto out;
  2984. } else if (pool_tclear(pool, &pool->submit_fail))
  2985. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  2986. res = json_object_get(val, "result");
  2987. err = json_object_get(val, "error");
  2988. if (!QUIET) {
  2989. if (opt_worktime) {
  2990. char workclone[20];
  2991. struct tm _tm;
  2992. struct tm *tm, tm_getwork, tm_submit_reply;
  2993. tm = &_tm;
  2994. double getwork_time = tdiff((struct timeval *)&(work->tv_getwork_reply),
  2995. (struct timeval *)&(work->tv_getwork));
  2996. double getwork_to_work = tdiff((struct timeval *)&(work->tv_work_start),
  2997. (struct timeval *)&(work->tv_getwork_reply));
  2998. double work_time = tdiff((struct timeval *)&(work->tv_work_found),
  2999. (struct timeval *)&(work->tv_work_start));
  3000. double work_to_submit = tdiff(ptv_submit,
  3001. (struct timeval *)&(work->tv_work_found));
  3002. double submit_time = tdiff(&tv_submit_reply, ptv_submit);
  3003. int diffplaces = 3;
  3004. localtime_r(&work->ts_getwork, tm);
  3005. memcpy(&tm_getwork, tm, sizeof(struct tm));
  3006. localtime_r(&ts_submit_reply, tm);
  3007. memcpy(&tm_submit_reply, tm, sizeof(struct tm));
  3008. if (work->clone) {
  3009. sprintf(workclone, "C:%1.3f",
  3010. tdiff((struct timeval *)&(work->tv_cloned),
  3011. (struct timeval *)&(work->tv_getwork_reply)));
  3012. }
  3013. else
  3014. strcpy(workclone, "O");
  3015. if (work->work_difficulty < 1)
  3016. diffplaces = 6;
  3017. sprintf(worktime, " <-%08lx.%08lx M:%c D:%1.*f G:%02d:%02d:%02d:%1.3f %s (%1.3f) W:%1.3f (%1.3f) S:%1.3f R:%02d:%02d:%02d",
  3018. (unsigned long)swab32(*(uint32_t *)&(work->data[opt_scrypt ? 32 : 28])),
  3019. (unsigned long)swab32(*(uint32_t *)&(work->data[opt_scrypt ? 28 : 24])),
  3020. work->getwork_mode, diffplaces, work->work_difficulty,
  3021. tm_getwork.tm_hour, tm_getwork.tm_min,
  3022. tm_getwork.tm_sec, getwork_time, workclone,
  3023. getwork_to_work, work_time, work_to_submit, submit_time,
  3024. tm_submit_reply.tm_hour, tm_submit_reply.tm_min,
  3025. tm_submit_reply.tm_sec);
  3026. }
  3027. }
  3028. share_result(val, res, err, work, resubmit, worktime);
  3029. if (!opt_realquiet)
  3030. print_status(thr_id);
  3031. if (!want_per_device_stats) {
  3032. char logline[256];
  3033. struct cgpu_info *cgpu;
  3034. cgpu = get_thr_cgpu(thr_id);
  3035. get_statline(logline, cgpu);
  3036. applog(LOG_INFO, "%s", logline);
  3037. }
  3038. json_decref(val);
  3039. rc = true;
  3040. out:
  3041. return rc;
  3042. }
  3043. /* Specifies whether we can use this pool for work or not. */
  3044. static bool pool_unworkable(struct pool *pool)
  3045. {
  3046. if (pool->idle)
  3047. return true;
  3048. if (pool->enabled != POOL_ENABLED)
  3049. return true;
  3050. if (pool->has_stratum && !pool->stratum_active)
  3051. return true;
  3052. return false;
  3053. }
  3054. /* In balanced mode, the amount of diff1 solutions per pool is monitored as a
  3055. * rolling average per 10 minutes and if pools start getting more, it biases
  3056. * away from them to distribute work evenly. The share count is reset to the
  3057. * rolling average every 10 minutes to not send all work to one pool after it
  3058. * has been disabled/out for an extended period. */
  3059. static struct pool *select_balanced(struct pool *cp)
  3060. {
  3061. int i, lowest = cp->shares;
  3062. struct pool *ret = cp;
  3063. for (i = 0; i < total_pools; i++) {
  3064. struct pool *pool = pools[i];
  3065. if (pool_unworkable(pool))
  3066. continue;
  3067. if (pool->shares < lowest) {
  3068. lowest = pool->shares;
  3069. ret = pool;
  3070. }
  3071. }
  3072. ret->shares++;
  3073. return ret;
  3074. }
  3075. static bool pool_active(struct pool *, bool pinging);
  3076. static void pool_died(struct pool *);
  3077. /* Select any active pool in a rotating fashion when loadbalance is chosen */
  3078. static inline struct pool *select_pool(bool lagging)
  3079. {
  3080. static int rotating_pool = 0;
  3081. struct pool *pool, *cp;
  3082. int tested;
  3083. cp = current_pool();
  3084. retry:
  3085. if (pool_strategy == POOL_BALANCE)
  3086. {
  3087. pool = select_balanced(cp);
  3088. goto have_pool;
  3089. }
  3090. if (pool_strategy != POOL_LOADBALANCE && (!lagging || opt_fail_only))
  3091. pool = cp;
  3092. else
  3093. pool = NULL;
  3094. /* Try to find the first pool in the rotation that is usable */
  3095. tested = 0;
  3096. while (!pool && tested++ < total_pools) {
  3097. if (++rotating_pool >= total_pools)
  3098. rotating_pool = 0;
  3099. pool = pools[rotating_pool];
  3100. if (!pool_unworkable(pool))
  3101. break;
  3102. pool = NULL;
  3103. }
  3104. /* If still nothing is usable, use the current pool */
  3105. if (!pool)
  3106. pool = cp;
  3107. have_pool:
  3108. if (cp != pool)
  3109. {
  3110. if (!pool_active(pool, false))
  3111. {
  3112. pool_died(pool);
  3113. goto retry;
  3114. }
  3115. pool_tclear(pool, &pool->idle);
  3116. }
  3117. return pool;
  3118. }
  3119. static double DIFFEXACTONE = 26959946667150639794667015087019630673637144422540572481103610249215.0;
  3120. static const uint64_t diffone = 0xFFFF000000000000ull;
  3121. static double target_diff(const unsigned char *target)
  3122. {
  3123. double targ = 0;
  3124. signed int i;
  3125. for (i = 31; i >= 0; --i)
  3126. targ = (targ * 0x100) + target[i];
  3127. return DIFFEXACTONE / (targ ?: 1);
  3128. }
  3129. /*
  3130. * Calculate the work share difficulty
  3131. */
  3132. static void calc_diff(struct work *work, int known)
  3133. {
  3134. struct cgminer_pool_stats *pool_stats = &(work->pool->cgminer_pool_stats);
  3135. double difficulty;
  3136. if (!known) {
  3137. work->work_difficulty = target_diff(work->target);
  3138. } else
  3139. work->work_difficulty = known;
  3140. difficulty = work->work_difficulty;
  3141. pool_stats->last_diff = difficulty;
  3142. suffix_string((uint64_t)difficulty, work->pool->diff, 0);
  3143. if (difficulty == pool_stats->min_diff)
  3144. pool_stats->min_diff_count++;
  3145. else if (difficulty < pool_stats->min_diff || pool_stats->min_diff == 0) {
  3146. pool_stats->min_diff = difficulty;
  3147. pool_stats->min_diff_count = 1;
  3148. }
  3149. if (difficulty == pool_stats->max_diff)
  3150. pool_stats->max_diff_count++;
  3151. else if (difficulty > pool_stats->max_diff) {
  3152. pool_stats->max_diff = difficulty;
  3153. pool_stats->max_diff_count = 1;
  3154. }
  3155. }
  3156. static void get_benchmark_work(struct work *work)
  3157. {
  3158. // Use a random work block pulled from a pool
  3159. static uint8_t bench_block[] = { CGMINER_BENCHMARK_BLOCK };
  3160. size_t bench_size = sizeof(*work);
  3161. size_t work_size = sizeof(bench_block);
  3162. size_t min_size = (work_size < bench_size ? work_size : bench_size);
  3163. memset(work, 0, sizeof(*work));
  3164. memcpy(work, &bench_block, min_size);
  3165. work->mandatory = true;
  3166. work->pool = pools[0];
  3167. cgtime(&work->tv_getwork);
  3168. copy_time(&work->tv_getwork_reply, &work->tv_getwork);
  3169. work->getwork_mode = GETWORK_MODE_BENCHMARK;
  3170. calc_diff(work, 0);
  3171. }
  3172. static void wake_gws(void);
  3173. static void update_last_work(struct work *work)
  3174. {
  3175. if (!work->tmpl)
  3176. // Only save GBT jobs, since rollntime isn't coordinated well yet
  3177. return;
  3178. struct pool *pool = work->pool;
  3179. mutex_lock(&pool->last_work_lock);
  3180. if (pool->last_work_copy)
  3181. free_work(pool->last_work_copy);
  3182. pool->last_work_copy = copy_work(work);
  3183. pool->last_work_copy->work_restart_id = pool->work_restart_id;
  3184. mutex_unlock(&pool->last_work_lock);
  3185. }
  3186. static
  3187. void gbt_req_target(json_t *req)
  3188. {
  3189. json_t *j;
  3190. json_t *n;
  3191. if (!request_target_str)
  3192. return;
  3193. j = json_object_get(req, "params");
  3194. if (!j)
  3195. {
  3196. n = json_array();
  3197. if (!n)
  3198. return;
  3199. if (json_object_set_new(req, "params", n))
  3200. goto erradd;
  3201. j = n;
  3202. }
  3203. n = json_array_get(j, 0);
  3204. if (!n)
  3205. {
  3206. n = json_object();
  3207. if (!n)
  3208. return;
  3209. if (json_array_append_new(j, n))
  3210. goto erradd;
  3211. }
  3212. j = n;
  3213. n = json_string(request_target_str);
  3214. if (!n)
  3215. return;
  3216. if (json_object_set_new(j, "target", n))
  3217. goto erradd;
  3218. return;
  3219. erradd:
  3220. json_decref(n);
  3221. }
  3222. static char *prepare_rpc_req2(struct work *work, enum pool_protocol proto, const char *lpid, bool probe)
  3223. {
  3224. char *rpc_req;
  3225. clean_work(work);
  3226. switch (proto) {
  3227. case PLP_GETWORK:
  3228. work->getwork_mode = GETWORK_MODE_POOL;
  3229. return strdup(getwork_req);
  3230. case PLP_GETBLOCKTEMPLATE:
  3231. work->getwork_mode = GETWORK_MODE_GBT;
  3232. work->tmpl_refcount = malloc(sizeof(*work->tmpl_refcount));
  3233. if (!work->tmpl_refcount)
  3234. return NULL;
  3235. work->tmpl = blktmpl_create();
  3236. if (!work->tmpl)
  3237. goto gbtfail2;
  3238. *work->tmpl_refcount = 1;
  3239. gbt_capabilities_t caps = blktmpl_addcaps(work->tmpl);
  3240. if (!caps)
  3241. goto gbtfail;
  3242. caps |= GBT_LONGPOLL;
  3243. json_t *req = blktmpl_request_jansson(caps, lpid);
  3244. if (!req)
  3245. goto gbtfail;
  3246. if (probe)
  3247. gbt_req_target(req);
  3248. rpc_req = json_dumps(req, 0);
  3249. if (!rpc_req)
  3250. goto gbtfail;
  3251. json_decref(req);
  3252. return rpc_req;
  3253. default:
  3254. return NULL;
  3255. }
  3256. return NULL;
  3257. gbtfail:
  3258. blktmpl_free(work->tmpl);
  3259. work->tmpl = NULL;
  3260. gbtfail2:
  3261. free(work->tmpl_refcount);
  3262. work->tmpl_refcount = NULL;
  3263. return NULL;
  3264. }
  3265. #define prepare_rpc_req(work, proto, lpid) prepare_rpc_req2(work, proto, lpid, false)
  3266. #define prepare_rpc_req_probe(work, proto, lpid) prepare_rpc_req2(work, proto, lpid, true)
  3267. static const char *pool_protocol_name(enum pool_protocol proto)
  3268. {
  3269. switch (proto) {
  3270. case PLP_GETBLOCKTEMPLATE:
  3271. return "getblocktemplate";
  3272. case PLP_GETWORK:
  3273. return "getwork";
  3274. default:
  3275. return "UNKNOWN";
  3276. }
  3277. }
  3278. static enum pool_protocol pool_protocol_fallback(enum pool_protocol proto)
  3279. {
  3280. switch (proto) {
  3281. case PLP_GETBLOCKTEMPLATE:
  3282. if (want_getwork)
  3283. return PLP_GETWORK;
  3284. default:
  3285. return PLP_NONE;
  3286. }
  3287. }
  3288. static bool get_upstream_work(struct work *work, CURL *curl)
  3289. {
  3290. struct pool *pool = work->pool;
  3291. struct cgminer_pool_stats *pool_stats = &(pool->cgminer_pool_stats);
  3292. struct timeval tv_elapsed;
  3293. json_t *val = NULL;
  3294. bool rc = false;
  3295. char *url;
  3296. enum pool_protocol proto;
  3297. char *rpc_req;
  3298. if (pool->proto == PLP_NONE)
  3299. pool->proto = PLP_GETBLOCKTEMPLATE;
  3300. tryagain:
  3301. rpc_req = prepare_rpc_req(work, pool->proto, NULL);
  3302. work->pool = pool;
  3303. if (!rpc_req)
  3304. return false;
  3305. applog(LOG_DEBUG, "DBG: sending %s get RPC call: %s", pool->rpc_url, rpc_req);
  3306. url = pool->rpc_url;
  3307. cgtime(&work->tv_getwork);
  3308. val = json_rpc_call(curl, url, pool->rpc_userpass, rpc_req, false,
  3309. false, &work->rolltime, pool, false);
  3310. pool_stats->getwork_attempts++;
  3311. free(rpc_req);
  3312. if (likely(val)) {
  3313. rc = work_decode(pool, work, val);
  3314. if (unlikely(!rc))
  3315. applog(LOG_DEBUG, "Failed to decode work in get_upstream_work");
  3316. } else if (PLP_NONE != (proto = pool_protocol_fallback(pool->proto))) {
  3317. applog(LOG_WARNING, "Pool %u failed getblocktemplate request; falling back to getwork protocol", pool->pool_no);
  3318. pool->proto = proto;
  3319. goto tryagain;
  3320. } else
  3321. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  3322. cgtime(&work->tv_getwork_reply);
  3323. timersub(&(work->tv_getwork_reply), &(work->tv_getwork), &tv_elapsed);
  3324. pool_stats->getwork_wait_rolling += ((double)tv_elapsed.tv_sec + ((double)tv_elapsed.tv_usec / 1000000)) * 0.63;
  3325. pool_stats->getwork_wait_rolling /= 1.63;
  3326. timeradd(&tv_elapsed, &(pool_stats->getwork_wait), &(pool_stats->getwork_wait));
  3327. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_max), >)) {
  3328. pool_stats->getwork_wait_max.tv_sec = tv_elapsed.tv_sec;
  3329. pool_stats->getwork_wait_max.tv_usec = tv_elapsed.tv_usec;
  3330. }
  3331. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_min), <)) {
  3332. pool_stats->getwork_wait_min.tv_sec = tv_elapsed.tv_sec;
  3333. pool_stats->getwork_wait_min.tv_usec = tv_elapsed.tv_usec;
  3334. }
  3335. pool_stats->getwork_calls++;
  3336. work->pool = pool;
  3337. work->longpoll = false;
  3338. calc_diff(work, 0);
  3339. total_getworks++;
  3340. pool->getwork_requested++;
  3341. if (rc)
  3342. update_last_work(work);
  3343. if (likely(val))
  3344. json_decref(val);
  3345. return rc;
  3346. }
  3347. #ifdef HAVE_CURSES
  3348. static void disable_curses(void)
  3349. {
  3350. if (curses_active_locked()) {
  3351. use_curses = false;
  3352. curses_active = false;
  3353. leaveok(logwin, false);
  3354. leaveok(statuswin, false);
  3355. leaveok(mainwin, false);
  3356. nocbreak();
  3357. echo();
  3358. delwin(logwin);
  3359. delwin(statuswin);
  3360. delwin(mainwin);
  3361. endwin();
  3362. #ifdef WIN32
  3363. // Move the cursor to after curses output.
  3364. HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
  3365. CONSOLE_SCREEN_BUFFER_INFO csbi;
  3366. COORD coord;
  3367. if (GetConsoleScreenBufferInfo(hout, &csbi)) {
  3368. coord.X = 0;
  3369. coord.Y = csbi.dwSize.Y - 1;
  3370. SetConsoleCursorPosition(hout, coord);
  3371. }
  3372. #endif
  3373. unlock_curses();
  3374. }
  3375. }
  3376. #endif
  3377. static void __kill_work(void)
  3378. {
  3379. struct thr_info *thr;
  3380. int i;
  3381. if (!successful_connect)
  3382. return;
  3383. applog(LOG_INFO, "Received kill message");
  3384. shutting_down = true;
  3385. applog(LOG_DEBUG, "Prompting submit_work thread to finish");
  3386. notifier_wake(submit_waiting_notifier);
  3387. applog(LOG_DEBUG, "Killing off watchpool thread");
  3388. /* Kill the watchpool thread */
  3389. thr = &control_thr[watchpool_thr_id];
  3390. thr_info_cancel(thr);
  3391. applog(LOG_DEBUG, "Killing off watchdog thread");
  3392. /* Kill the watchdog thread */
  3393. thr = &control_thr[watchdog_thr_id];
  3394. thr_info_cancel(thr);
  3395. applog(LOG_DEBUG, "Shutting down mining threads");
  3396. for (i = 0; i < mining_threads; i++) {
  3397. struct cgpu_info *cgpu;
  3398. thr = get_thread(i);
  3399. if (!thr)
  3400. continue;
  3401. cgpu = thr->cgpu;
  3402. if (!cgpu)
  3403. continue;
  3404. if (!cgpu->threads)
  3405. continue;
  3406. cgpu->shutdown = true;
  3407. thr->work_restart = true;
  3408. notifier_wake(thr->notifier);
  3409. notifier_wake(thr->work_restart_notifier);
  3410. }
  3411. sleep(1);
  3412. applog(LOG_DEBUG, "Killing off mining threads");
  3413. /* Kill the mining threads*/
  3414. for (i = 0; i < mining_threads; i++) {
  3415. thr = get_thread(i);
  3416. if (!(thr && thr->cgpu->threads))
  3417. continue;
  3418. applog(LOG_WARNING, "Killing %"PRIpreprv, thr->cgpu->proc_repr);
  3419. thr_info_cancel(thr);
  3420. pthread_join(thr->pth, NULL);
  3421. }
  3422. applog(LOG_DEBUG, "Killing off stage thread");
  3423. /* Stop the others */
  3424. thr = &control_thr[stage_thr_id];
  3425. thr_info_cancel(thr);
  3426. applog(LOG_DEBUG, "Killing off API thread");
  3427. thr = &control_thr[api_thr_id];
  3428. thr_info_cancel(thr);
  3429. }
  3430. /* This should be the common exit path */
  3431. void kill_work(void)
  3432. {
  3433. __kill_work();
  3434. quit(0, "Shutdown signal received.");
  3435. }
  3436. static
  3437. #ifdef WIN32
  3438. #ifndef _WIN64
  3439. const
  3440. #endif
  3441. #endif
  3442. char **initial_args;
  3443. void _bfg_clean_up(void);
  3444. void app_restart(void)
  3445. {
  3446. applog(LOG_WARNING, "Attempting to restart %s", packagename);
  3447. __kill_work();
  3448. _bfg_clean_up();
  3449. #if defined(unix) || defined(__APPLE__)
  3450. if (forkpid > 0) {
  3451. kill(forkpid, SIGTERM);
  3452. forkpid = 0;
  3453. }
  3454. #endif
  3455. execv(initial_args[0], initial_args);
  3456. applog(LOG_WARNING, "Failed to restart application");
  3457. }
  3458. static void sighandler(int __maybe_unused sig)
  3459. {
  3460. /* Restore signal handlers so we can still quit if kill_work fails */
  3461. sigaction(SIGTERM, &termhandler, NULL);
  3462. sigaction(SIGINT, &inthandler, NULL);
  3463. kill_work();
  3464. }
  3465. static void start_longpoll(void);
  3466. static void stop_longpoll(void);
  3467. /* Called with pool_lock held. Recruit an extra curl if none are available for
  3468. * this pool. */
  3469. static void recruit_curl(struct pool *pool)
  3470. {
  3471. struct curl_ent *ce = calloc(sizeof(struct curl_ent), 1);
  3472. if (unlikely(!ce))
  3473. quit(1, "Failed to calloc in recruit_curl");
  3474. ce->curl = curl_easy_init();
  3475. if (unlikely(!ce->curl))
  3476. quit(1, "Failed to init in recruit_curl");
  3477. LL_PREPEND(pool->curllist, ce);
  3478. pool->curls++;
  3479. }
  3480. /* Grab an available curl if there is one. If not, then recruit extra curls
  3481. * unless we are in a submit_fail situation, or we have opt_delaynet enabled
  3482. * and there are already 5 curls in circulation. Limit total number to the
  3483. * number of mining threads per pool as well to prevent blasting a pool during
  3484. * network delays/outages. */
  3485. static struct curl_ent *pop_curl_entry3(struct pool *pool, int blocking)
  3486. {
  3487. int curl_limit = opt_delaynet ? 5 : (mining_threads + opt_queue) * 2;
  3488. bool recruited = false;
  3489. struct curl_ent *ce;
  3490. mutex_lock(&pool->pool_lock);
  3491. retry:
  3492. if (!pool->curls) {
  3493. recruit_curl(pool);
  3494. recruited = true;
  3495. } else if (!pool->curllist) {
  3496. if (blocking < 2 && pool->curls >= curl_limit && (blocking || pool->curls >= opt_submit_threads)) {
  3497. if (!blocking) {
  3498. mutex_unlock(&pool->pool_lock);
  3499. return NULL;
  3500. }
  3501. pthread_cond_wait(&pool->cr_cond, &pool->pool_lock);
  3502. goto retry;
  3503. } else {
  3504. recruit_curl(pool);
  3505. recruited = true;
  3506. }
  3507. }
  3508. ce = pool->curllist;
  3509. LL_DELETE(pool->curllist, ce);
  3510. mutex_unlock(&pool->pool_lock);
  3511. if (recruited)
  3512. applog(LOG_DEBUG, "Recruited curl for pool %d", pool->pool_no);
  3513. return ce;
  3514. }
  3515. static struct curl_ent *pop_curl_entry2(struct pool *pool, bool blocking)
  3516. {
  3517. return pop_curl_entry3(pool, blocking ? 1 : 0);
  3518. }
  3519. __maybe_unused
  3520. static struct curl_ent *pop_curl_entry(struct pool *pool)
  3521. {
  3522. return pop_curl_entry3(pool, 1);
  3523. }
  3524. static void push_curl_entry(struct curl_ent *ce, struct pool *pool)
  3525. {
  3526. mutex_lock(&pool->pool_lock);
  3527. if (!ce || !ce->curl)
  3528. quit(1, "Attempted to add NULL in push_curl_entry");
  3529. LL_PREPEND(pool->curllist, ce);
  3530. cgtime(&ce->tv);
  3531. pthread_cond_broadcast(&pool->cr_cond);
  3532. mutex_unlock(&pool->pool_lock);
  3533. }
  3534. bool stale_work(struct work *work, bool share);
  3535. static inline bool should_roll(struct work *work)
  3536. {
  3537. struct timeval now;
  3538. time_t expiry;
  3539. if (work->pool != current_pool() && pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE)
  3540. return false;
  3541. if (stale_work(work, false))
  3542. return false;
  3543. if (work->rolltime > opt_scantime)
  3544. expiry = work->rolltime;
  3545. else
  3546. expiry = opt_scantime;
  3547. expiry = expiry * 2 / 3;
  3548. /* We shouldn't roll if we're unlikely to get one shares' duration
  3549. * work out of doing so */
  3550. cgtime(&now);
  3551. if (now.tv_sec - work->tv_staged.tv_sec > expiry)
  3552. return false;
  3553. return true;
  3554. }
  3555. /* Limit rolls to 7000 to not beyond 2 hours in the future where bitcoind will
  3556. * reject blocks as invalid. */
  3557. static inline bool can_roll(struct work *work)
  3558. {
  3559. if (work->stratum)
  3560. return false;
  3561. if (!(work->pool && !work->clone))
  3562. return false;
  3563. if (work->tmpl) {
  3564. if (stale_work(work, false))
  3565. return false;
  3566. return blkmk_work_left(work->tmpl);
  3567. }
  3568. return (work->rolltime &&
  3569. work->rolls < 7000 && !stale_work(work, false));
  3570. }
  3571. static void roll_work(struct work *work)
  3572. {
  3573. if (work->tmpl) {
  3574. struct timeval tv_now;
  3575. cgtime(&tv_now);
  3576. if (blkmk_get_data(work->tmpl, work->data, 80, tv_now.tv_sec, NULL, &work->dataid) < 76)
  3577. applog(LOG_ERR, "Failed to get next data from template; spinning wheels!");
  3578. swap32yes(work->data, work->data, 80 / 4);
  3579. calc_midstate(work);
  3580. applog(LOG_DEBUG, "Successfully rolled extranonce to dataid %u", work->dataid);
  3581. } else {
  3582. uint32_t *work_ntime;
  3583. uint32_t ntime;
  3584. work_ntime = (uint32_t *)(work->data + 68);
  3585. ntime = be32toh(*work_ntime);
  3586. ntime++;
  3587. *work_ntime = htobe32(ntime);
  3588. applog(LOG_DEBUG, "Successfully rolled time header in work");
  3589. }
  3590. local_work++;
  3591. work->rolls++;
  3592. work->blk.nonce = 0;
  3593. /* This is now a different work item so it needs a different ID for the
  3594. * hashtable */
  3595. work->id = total_work++;
  3596. }
  3597. /* Duplicates any dynamically allocated arrays within the work struct to
  3598. * prevent a copied work struct from freeing ram belonging to another struct */
  3599. void __copy_work(struct work *work, const struct work *base_work)
  3600. {
  3601. int id = work->id;
  3602. clean_work(work);
  3603. memcpy(work, base_work, sizeof(struct work));
  3604. /* Keep the unique new id assigned during make_work to prevent copied
  3605. * work from having the same id. */
  3606. work->id = id;
  3607. if (base_work->job_id)
  3608. work->job_id = strdup(base_work->job_id);
  3609. if (base_work->nonce1)
  3610. work->nonce1 = strdup(base_work->nonce1);
  3611. bytes_cpy(&work->nonce2, &base_work->nonce2);
  3612. if (base_work->tmpl) {
  3613. struct pool *pool = work->pool;
  3614. mutex_lock(&pool->pool_lock);
  3615. ++*work->tmpl_refcount;
  3616. mutex_unlock(&pool->pool_lock);
  3617. }
  3618. }
  3619. /* Generates a copy of an existing work struct, creating fresh heap allocations
  3620. * for all dynamically allocated arrays within the struct */
  3621. struct work *copy_work(const struct work *base_work)
  3622. {
  3623. struct work *work = make_work();
  3624. __copy_work(work, base_work);
  3625. return work;
  3626. }
  3627. static struct work *make_clone(struct work *work)
  3628. {
  3629. struct work *work_clone = copy_work(work);
  3630. work_clone->clone = true;
  3631. cgtime((struct timeval *)&(work_clone->tv_cloned));
  3632. work_clone->longpoll = false;
  3633. work_clone->mandatory = false;
  3634. /* Make cloned work appear slightly older to bias towards keeping the
  3635. * master work item which can be further rolled */
  3636. work_clone->tv_staged.tv_sec -= 1;
  3637. return work_clone;
  3638. }
  3639. static void stage_work(struct work *work);
  3640. static bool clone_available(void)
  3641. {
  3642. struct work *work_clone = NULL, *work, *tmp;
  3643. bool cloned = false;
  3644. mutex_lock(stgd_lock);
  3645. if (!staged_rollable)
  3646. goto out_unlock;
  3647. HASH_ITER(hh, staged_work, work, tmp) {
  3648. if (can_roll(work) && should_roll(work)) {
  3649. roll_work(work);
  3650. work_clone = make_clone(work);
  3651. roll_work(work);
  3652. cloned = true;
  3653. break;
  3654. }
  3655. }
  3656. out_unlock:
  3657. mutex_unlock(stgd_lock);
  3658. if (cloned) {
  3659. applog(LOG_DEBUG, "Pushing cloned available work to stage thread");
  3660. stage_work(work_clone);
  3661. }
  3662. return cloned;
  3663. }
  3664. static void pool_died(struct pool *pool)
  3665. {
  3666. if (!pool_tset(pool, &pool->idle)) {
  3667. cgtime(&pool->tv_idle);
  3668. if (pool == current_pool()) {
  3669. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  3670. switch_pools(NULL);
  3671. } else
  3672. applog(LOG_INFO, "Pool %d %s failed to return work", pool->pool_no, pool->rpc_url);
  3673. }
  3674. }
  3675. bool stale_work(struct work *work, bool share)
  3676. {
  3677. unsigned work_expiry;
  3678. struct pool *pool;
  3679. uint32_t block_id;
  3680. unsigned getwork_delay;
  3681. if (opt_benchmark)
  3682. return false;
  3683. block_id = ((uint32_t*)work->data)[1];
  3684. pool = work->pool;
  3685. /* Technically the rolltime should be correct but some pools
  3686. * advertise a broken expire= that is lower than a meaningful
  3687. * scantime */
  3688. if (work->rolltime >= opt_scantime || work->tmpl)
  3689. work_expiry = work->rolltime;
  3690. else
  3691. work_expiry = opt_expiry;
  3692. unsigned max_expiry = (have_longpoll ? opt_expiry_lp : opt_expiry);
  3693. if (work_expiry > max_expiry)
  3694. work_expiry = max_expiry;
  3695. if (share) {
  3696. /* If the share isn't on this pool's latest block, it's stale */
  3697. if (pool->block_id && pool->block_id != block_id)
  3698. {
  3699. applog(LOG_DEBUG, "Share stale due to block mismatch (%08lx != %08lx)", (long)block_id, (long)pool->block_id);
  3700. return true;
  3701. }
  3702. /* If the pool doesn't want old shares, then any found in work before
  3703. * the most recent longpoll is stale */
  3704. if ((!pool->submit_old) && work->work_restart_id != pool->work_restart_id)
  3705. {
  3706. applog(LOG_DEBUG, "Share stale due to mandatory work update (%02x != %02x)", work->work_restart_id, pool->work_restart_id);
  3707. return true;
  3708. }
  3709. } else {
  3710. /* If this work isn't for the latest Bitcoin block, it's stale */
  3711. /* But only care about the current pool if failover-only */
  3712. if (enabled_pools <= 1 || opt_fail_only) {
  3713. if (pool->block_id && block_id != pool->block_id)
  3714. {
  3715. applog(LOG_DEBUG, "Work stale due to block mismatch (%08lx != 1 ? %08lx : %08lx)", (long)block_id, (long)pool->block_id, (long)current_block_id);
  3716. return true;
  3717. }
  3718. } else {
  3719. if (block_id != current_block_id)
  3720. {
  3721. applog(LOG_DEBUG, "Work stale due to block mismatch (%08lx != 0 ? %08lx : %08lx)", (long)block_id, (long)pool->block_id, (long)current_block_id);
  3722. return true;
  3723. }
  3724. }
  3725. /* If the pool has asked us to restart since this work, it's stale */
  3726. if (work->work_restart_id != pool->work_restart_id)
  3727. {
  3728. applog(LOG_DEBUG, "Work stale due to work update (%02x != %02x)", work->work_restart_id, pool->work_restart_id);
  3729. return true;
  3730. }
  3731. if (pool->has_stratum && work->job_id) {
  3732. bool same_job;
  3733. if (!pool->stratum_active || !pool->stratum_notify) {
  3734. applog(LOG_DEBUG, "Work stale due to stratum inactive");
  3735. return true;
  3736. }
  3737. same_job = true;
  3738. cg_rlock(&pool->data_lock);
  3739. if (strcmp(work->job_id, pool->swork.job_id))
  3740. same_job = false;
  3741. cg_runlock(&pool->data_lock);
  3742. if (!same_job) {
  3743. applog(LOG_DEBUG, "Work stale due to stratum job_id mismatch");
  3744. return true;
  3745. }
  3746. }
  3747. /* Factor in the average getwork delay of this pool, rounding it up to
  3748. * the nearest second */
  3749. getwork_delay = pool->cgminer_pool_stats.getwork_wait_rolling * 5 + 1;
  3750. if (unlikely(work_expiry <= getwork_delay + 5))
  3751. work_expiry = 5;
  3752. else
  3753. work_expiry -= getwork_delay;
  3754. }
  3755. int elapsed_since_staged = timer_elapsed(&work->tv_staged, NULL);
  3756. if (elapsed_since_staged > work_expiry) {
  3757. applog(LOG_DEBUG, "%s stale due to expiry (%d >= %u)", share?"Share":"Work", elapsed_since_staged, work_expiry);
  3758. return true;
  3759. }
  3760. /* If the user only wants strict failover, any work from a pool other than
  3761. * the current one is always considered stale */
  3762. if (opt_fail_only && !share && pool != current_pool() && !work->mandatory &&
  3763. pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  3764. applog(LOG_DEBUG, "Work stale due to fail only pool mismatch (pool %u vs %u)", pool->pool_no, current_pool()->pool_no);
  3765. return true;
  3766. }
  3767. return false;
  3768. }
  3769. static uint64_t share_diff(const struct work *work)
  3770. {
  3771. uint64_t ret;
  3772. bool new_best = false;
  3773. ret = target_diff(work->hash);
  3774. cg_wlock(&control_lock);
  3775. if (unlikely(ret > best_diff)) {
  3776. new_best = true;
  3777. best_diff = ret;
  3778. suffix_string(best_diff, best_share, 0);
  3779. }
  3780. if (unlikely(ret > work->pool->best_diff))
  3781. work->pool->best_diff = ret;
  3782. cg_wunlock(&control_lock);
  3783. if (unlikely(new_best))
  3784. applog(LOG_INFO, "New best share: %s", best_share);
  3785. return ret;
  3786. }
  3787. static void regen_hash(struct work *work)
  3788. {
  3789. hash_data(work->hash, work->data);
  3790. }
  3791. static void rebuild_hash(struct work *work)
  3792. {
  3793. if (opt_scrypt)
  3794. scrypt_regenhash(work);
  3795. else
  3796. regen_hash(work);
  3797. work->share_diff = share_diff(work);
  3798. if (unlikely(work->share_diff >= current_diff)) {
  3799. work->block = true;
  3800. work->pool->solved++;
  3801. found_blocks++;
  3802. work->mandatory = true;
  3803. applog(LOG_NOTICE, "Found block for pool %d!", work->pool->pool_no);
  3804. }
  3805. }
  3806. static void submit_discard_share2(const char *reason, struct work *work)
  3807. {
  3808. struct cgpu_info *cgpu = get_thr_cgpu(work->thr_id);
  3809. sharelog(reason, work);
  3810. mutex_lock(&stats_lock);
  3811. ++total_stale;
  3812. ++cgpu->stale;
  3813. ++(work->pool->stale_shares);
  3814. total_diff_stale += work->work_difficulty;
  3815. cgpu->diff_stale += work->work_difficulty;
  3816. work->pool->diff_stale += work->work_difficulty;
  3817. mutex_unlock(&stats_lock);
  3818. }
  3819. static void submit_discard_share(struct work *work)
  3820. {
  3821. submit_discard_share2("discard", work);
  3822. }
  3823. struct submit_work_state {
  3824. struct work *work;
  3825. bool resubmit;
  3826. struct curl_ent *ce;
  3827. int failures;
  3828. struct timeval tv_staleexpire;
  3829. char *s;
  3830. struct timeval tv_submit;
  3831. struct submit_work_state *next;
  3832. };
  3833. static int my_curl_timer_set(__maybe_unused CURLM *curlm, long timeout_ms, void *userp)
  3834. {
  3835. long *p_timeout_us = userp;
  3836. const long max_ms = LONG_MAX / 1000;
  3837. if (max_ms < timeout_ms)
  3838. timeout_ms = max_ms;
  3839. *p_timeout_us = timeout_ms * 1000;
  3840. return 0;
  3841. }
  3842. static void sws_has_ce(struct submit_work_state *sws)
  3843. {
  3844. struct pool *pool = sws->work->pool;
  3845. sws->s = submit_upstream_work_request(sws->work);
  3846. cgtime(&sws->tv_submit);
  3847. json_rpc_call_async(sws->ce->curl, pool->rpc_url, pool->rpc_userpass, sws->s, false, pool, true, sws);
  3848. }
  3849. static struct submit_work_state *begin_submission(struct work *work)
  3850. {
  3851. struct pool *pool;
  3852. struct submit_work_state *sws = NULL;
  3853. pool = work->pool;
  3854. sws = malloc(sizeof(*sws));
  3855. *sws = (struct submit_work_state){
  3856. .work = work,
  3857. };
  3858. rebuild_hash(work);
  3859. if (stale_work(work, true)) {
  3860. work->stale = true;
  3861. if (opt_submit_stale)
  3862. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as user requested", pool->pool_no);
  3863. else if (pool->submit_old)
  3864. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as pool requested", pool->pool_no);
  3865. else {
  3866. applog(LOG_NOTICE, "Pool %d stale share detected, discarding", pool->pool_no);
  3867. submit_discard_share(work);
  3868. goto out;
  3869. }
  3870. timer_set_delay_from_now(&sws->tv_staleexpire, 300000000);
  3871. }
  3872. if (work->stratum) {
  3873. char *s;
  3874. s = malloc(1024);
  3875. sws->s = s;
  3876. } else {
  3877. /* submit solution to bitcoin via JSON-RPC */
  3878. sws->ce = pop_curl_entry2(pool, false);
  3879. if (sws->ce) {
  3880. sws_has_ce(sws);
  3881. } else {
  3882. sws->next = pool->sws_waiting_on_curl;
  3883. pool->sws_waiting_on_curl = sws;
  3884. if (sws->next)
  3885. applog(LOG_DEBUG, "submit_thread queuing submission");
  3886. else
  3887. applog(LOG_WARNING, "submit_thread queuing submissions (see --submit-threads)");
  3888. }
  3889. }
  3890. return sws;
  3891. out:
  3892. free(sws);
  3893. return NULL;
  3894. }
  3895. static bool retry_submission(struct submit_work_state *sws)
  3896. {
  3897. struct work *work = sws->work;
  3898. struct pool *pool = work->pool;
  3899. sws->resubmit = true;
  3900. if ((!work->stale) && stale_work(work, true)) {
  3901. work->stale = true;
  3902. if (opt_submit_stale)
  3903. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, will retry as user requested", pool->pool_no);
  3904. else if (pool->submit_old)
  3905. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, will retry as pool requested", pool->pool_no);
  3906. else {
  3907. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, discarding", pool->pool_no);
  3908. submit_discard_share(work);
  3909. return false;
  3910. }
  3911. timer_set_delay_from_now(&sws->tv_staleexpire, 300000000);
  3912. }
  3913. if (unlikely((opt_retries >= 0) && (++sws->failures > opt_retries))) {
  3914. applog(LOG_ERR, "Pool %d failed %d submission retries, discarding", pool->pool_no, opt_retries);
  3915. submit_discard_share(work);
  3916. return false;
  3917. }
  3918. else if (work->stale) {
  3919. if (unlikely(opt_retries < 0 && timer_passed(&sws->tv_staleexpire, NULL)))
  3920. {
  3921. applog(LOG_NOTICE, "Pool %d stale share failed to submit for 5 minutes, discarding", pool->pool_no);
  3922. submit_discard_share(work);
  3923. return false;
  3924. }
  3925. }
  3926. /* pause, then restart work-request loop */
  3927. applog(LOG_INFO, "json_rpc_call failed on submit_work, retrying");
  3928. cgtime(&sws->tv_submit);
  3929. json_rpc_call_async(sws->ce->curl, pool->rpc_url, pool->rpc_userpass, sws->s, false, pool, true, sws);
  3930. return true;
  3931. }
  3932. static void free_sws(struct submit_work_state *sws)
  3933. {
  3934. free(sws->s);
  3935. free_work(sws->work);
  3936. free(sws);
  3937. }
  3938. static void *submit_work_thread(__maybe_unused void *userdata)
  3939. {
  3940. int wip = 0;
  3941. CURLM *curlm;
  3942. long curlm_timeout_us = -1;
  3943. struct timeval curlm_timer;
  3944. struct submit_work_state *sws, **swsp;
  3945. struct submit_work_state *write_sws = NULL;
  3946. unsigned tsreduce = 0;
  3947. pthread_detach(pthread_self());
  3948. RenameThread("submit_work");
  3949. applog(LOG_DEBUG, "Creating extra submit work thread");
  3950. curlm = curl_multi_init();
  3951. curlm_timeout_us = -1;
  3952. curl_multi_setopt(curlm, CURLMOPT_TIMERDATA, &curlm_timeout_us);
  3953. curl_multi_setopt(curlm, CURLMOPT_TIMERFUNCTION, my_curl_timer_set);
  3954. fd_set rfds, wfds, efds;
  3955. int maxfd;
  3956. struct timeval tv_timeout, tv_now;
  3957. int n;
  3958. CURLMsg *cm;
  3959. FD_ZERO(&rfds);
  3960. while (1) {
  3961. mutex_lock(&submitting_lock);
  3962. total_submitting -= tsreduce;
  3963. tsreduce = 0;
  3964. if (FD_ISSET(submit_waiting_notifier[0], &rfds)) {
  3965. notifier_read(submit_waiting_notifier);
  3966. }
  3967. // Receive any new submissions
  3968. while (submit_waiting) {
  3969. struct work *work = submit_waiting;
  3970. DL_DELETE(submit_waiting, work);
  3971. if ( (sws = begin_submission(work)) ) {
  3972. if (sws->ce)
  3973. curl_multi_add_handle(curlm, sws->ce->curl);
  3974. else if (sws->s) {
  3975. sws->next = write_sws;
  3976. write_sws = sws;
  3977. }
  3978. ++wip;
  3979. }
  3980. else {
  3981. --total_submitting;
  3982. free_work(work);
  3983. }
  3984. }
  3985. if (unlikely(shutting_down && !wip))
  3986. break;
  3987. mutex_unlock(&submitting_lock);
  3988. FD_ZERO(&rfds);
  3989. FD_ZERO(&wfds);
  3990. FD_ZERO(&efds);
  3991. tv_timeout.tv_sec = -1;
  3992. // Setup cURL with select
  3993. // Need to call perform to ensure the timeout gets updated
  3994. curl_multi_perform(curlm, &n);
  3995. curl_multi_fdset(curlm, &rfds, &wfds, &efds, &maxfd);
  3996. if (curlm_timeout_us >= 0)
  3997. {
  3998. timer_set_delay_from_now(&curlm_timer, curlm_timeout_us);
  3999. reduce_timeout_to(&tv_timeout, &curlm_timer);
  4000. }
  4001. // Setup waiting stratum submissions with select
  4002. for (sws = write_sws; sws; sws = sws->next)
  4003. {
  4004. struct pool *pool = sws->work->pool;
  4005. int fd = pool->sock;
  4006. if (fd == INVSOCK || (!pool->stratum_init) || !pool->stratum_notify)
  4007. continue;
  4008. FD_SET(fd, &wfds);
  4009. set_maxfd(&maxfd, fd);
  4010. }
  4011. // Setup "submit waiting" notifier with select
  4012. FD_SET(submit_waiting_notifier[0], &rfds);
  4013. set_maxfd(&maxfd, submit_waiting_notifier[0]);
  4014. // Wait for something interesting to happen :)
  4015. cgtime(&tv_now);
  4016. if (select(maxfd+1, &rfds, &wfds, &efds, select_timeout(&tv_timeout, &tv_now)) < 0) {
  4017. FD_ZERO(&rfds);
  4018. continue;
  4019. }
  4020. // Handle any stratum ready-to-write results
  4021. for (swsp = &write_sws; (sws = *swsp); ) {
  4022. struct work *work = sws->work;
  4023. struct pool *pool = work->pool;
  4024. int fd = pool->sock;
  4025. bool sessionid_match;
  4026. if (fd == INVSOCK || (!pool->stratum_init) || (!pool->stratum_notify) || !FD_ISSET(fd, &wfds)) {
  4027. next_write_sws:
  4028. // TODO: Check if stale, possibly discard etc
  4029. swsp = &sws->next;
  4030. continue;
  4031. }
  4032. cg_rlock(&pool->data_lock);
  4033. // NOTE: cgminer only does this check on retries, but BFGMiner does it for even the first/normal submit; therefore, it needs to be such that it always is true on the same connection regardless of session management
  4034. // NOTE: Worst case scenario for a false positive: the pool rejects it as H-not-zero
  4035. sessionid_match = (!pool->nonce1) || !strcmp(work->nonce1, pool->nonce1);
  4036. cg_runlock(&pool->data_lock);
  4037. if (!sessionid_match)
  4038. {
  4039. applog(LOG_DEBUG, "No matching session id for resubmitting stratum share");
  4040. submit_discard_share2("disconnect", work);
  4041. ++tsreduce;
  4042. next_write_sws_del:
  4043. // Clear the fd from wfds, to avoid potentially blocking on other submissions to the same socket
  4044. FD_CLR(fd, &wfds);
  4045. // Delete sws for this submission, since we're done with it
  4046. *swsp = sws->next;
  4047. free_sws(sws);
  4048. --wip;
  4049. continue;
  4050. }
  4051. char *s = sws->s;
  4052. struct stratum_share *sshare = calloc(sizeof(struct stratum_share), 1);
  4053. int sshare_id;
  4054. uint32_t nonce;
  4055. char nonce2hex[(bytes_len(&work->nonce2) * 2) + 1];
  4056. char noncehex[9];
  4057. char ntimehex[9];
  4058. sshare->work = copy_work(work);
  4059. bin2hex(nonce2hex, bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  4060. nonce = *((uint32_t *)(work->data + 76));
  4061. bin2hex(noncehex, (const unsigned char *)&nonce, 4);
  4062. bin2hex(ntimehex, (void *)&work->data[68], 4);
  4063. mutex_lock(&sshare_lock);
  4064. /* Give the stratum share a unique id */
  4065. sshare_id =
  4066. sshare->id = swork_id++;
  4067. HASH_ADD_INT(stratum_shares, id, sshare);
  4068. sprintf(s, "{\"params\": [\"%s\", \"%s\", \"%s\", \"%s\", \"%s\"], \"id\": %d, \"method\": \"mining.submit\"}",
  4069. pool->rpc_user, work->job_id, nonce2hex, ntimehex, noncehex, sshare->id);
  4070. mutex_unlock(&sshare_lock);
  4071. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->stratum_url, s);
  4072. if (likely(stratum_send(pool, s, strlen(s)))) {
  4073. if (pool_tclear(pool, &pool->submit_fail))
  4074. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  4075. applog(LOG_DEBUG, "Successfully submitted, adding to stratum_shares db");
  4076. goto next_write_sws_del;
  4077. } else if (!pool_tset(pool, &pool->submit_fail)) {
  4078. // Undo stuff
  4079. mutex_lock(&sshare_lock);
  4080. // NOTE: Need to find it again in case something else has consumed it already (like the stratum-disconnect resubmitter...)
  4081. HASH_FIND_INT(stratum_shares, &sshare_id, sshare);
  4082. if (sshare)
  4083. HASH_DEL(stratum_shares, sshare);
  4084. mutex_unlock(&sshare_lock);
  4085. if (sshare)
  4086. {
  4087. free_work(sshare->work);
  4088. free(sshare);
  4089. }
  4090. applog(LOG_WARNING, "Pool %d stratum share submission failure", pool->pool_no);
  4091. total_ro++;
  4092. pool->remotefail_occasions++;
  4093. if (!sshare)
  4094. goto next_write_sws_del;
  4095. goto next_write_sws;
  4096. }
  4097. }
  4098. // Handle any cURL activities
  4099. curl_multi_perform(curlm, &n);
  4100. while( (cm = curl_multi_info_read(curlm, &n)) ) {
  4101. if (cm->msg == CURLMSG_DONE)
  4102. {
  4103. bool finished;
  4104. json_t *val = json_rpc_call_completed(cm->easy_handle, cm->data.result, false, NULL, &sws);
  4105. curl_multi_remove_handle(curlm, cm->easy_handle);
  4106. finished = submit_upstream_work_completed(sws->work, sws->resubmit, &sws->tv_submit, val);
  4107. if (!finished) {
  4108. if (retry_submission(sws))
  4109. curl_multi_add_handle(curlm, sws->ce->curl);
  4110. else
  4111. finished = true;
  4112. }
  4113. if (finished) {
  4114. --wip;
  4115. ++tsreduce;
  4116. struct pool *pool = sws->work->pool;
  4117. if (pool->sws_waiting_on_curl) {
  4118. pool->sws_waiting_on_curl->ce = sws->ce;
  4119. sws_has_ce(pool->sws_waiting_on_curl);
  4120. pool->sws_waiting_on_curl = pool->sws_waiting_on_curl->next;
  4121. curl_multi_add_handle(curlm, sws->ce->curl);
  4122. } else {
  4123. push_curl_entry(sws->ce, sws->work->pool);
  4124. }
  4125. free_sws(sws);
  4126. }
  4127. }
  4128. }
  4129. }
  4130. assert(!write_sws);
  4131. mutex_unlock(&submitting_lock);
  4132. curl_multi_cleanup(curlm);
  4133. applog(LOG_DEBUG, "submit_work thread exiting");
  4134. return NULL;
  4135. }
  4136. /* Find the pool that currently has the highest priority */
  4137. static struct pool *priority_pool(int choice)
  4138. {
  4139. struct pool *ret = NULL;
  4140. int i;
  4141. for (i = 0; i < total_pools; i++) {
  4142. struct pool *pool = pools[i];
  4143. if (pool->prio == choice) {
  4144. ret = pool;
  4145. break;
  4146. }
  4147. }
  4148. if (unlikely(!ret)) {
  4149. applog(LOG_ERR, "WTF No pool %d found!", choice);
  4150. return pools[choice];
  4151. }
  4152. return ret;
  4153. }
  4154. int prioritize_pools(char *param, int *pid)
  4155. {
  4156. char *ptr, *next;
  4157. int i, pr, prio = 0;
  4158. if (total_pools == 0) {
  4159. return MSG_NOPOOL;
  4160. }
  4161. if (param == NULL || *param == '\0') {
  4162. return MSG_MISPID;
  4163. }
  4164. bool pools_changed[total_pools];
  4165. int new_prio[total_pools];
  4166. for (i = 0; i < total_pools; ++i)
  4167. pools_changed[i] = false;
  4168. next = param;
  4169. while (next && *next) {
  4170. ptr = next;
  4171. next = strchr(ptr, ',');
  4172. if (next)
  4173. *(next++) = '\0';
  4174. i = atoi(ptr);
  4175. if (i < 0 || i >= total_pools) {
  4176. *pid = i;
  4177. return MSG_INVPID;
  4178. }
  4179. if (pools_changed[i]) {
  4180. *pid = i;
  4181. return MSG_DUPPID;
  4182. }
  4183. pools_changed[i] = true;
  4184. new_prio[i] = prio++;
  4185. }
  4186. // Only change them if no errors
  4187. for (i = 0; i < total_pools; i++) {
  4188. if (pools_changed[i])
  4189. pools[i]->prio = new_prio[i];
  4190. }
  4191. // In priority order, cycle through the unchanged pools and append them
  4192. for (pr = 0; pr < total_pools; pr++)
  4193. for (i = 0; i < total_pools; i++) {
  4194. if (!pools_changed[i] && pools[i]->prio == pr) {
  4195. pools[i]->prio = prio++;
  4196. pools_changed[i] = true;
  4197. break;
  4198. }
  4199. }
  4200. if (current_pool()->prio)
  4201. switch_pools(NULL);
  4202. return MSG_POOLPRIO;
  4203. }
  4204. void validate_pool_priorities(void)
  4205. {
  4206. // TODO: this should probably do some sort of logging
  4207. int i, j;
  4208. bool used[total_pools];
  4209. bool valid[total_pools];
  4210. for (i = 0; i < total_pools; i++)
  4211. used[i] = valid[i] = false;
  4212. for (i = 0; i < total_pools; i++) {
  4213. if (pools[i]->prio >=0 && pools[i]->prio < total_pools) {
  4214. if (!used[pools[i]->prio]) {
  4215. valid[i] = true;
  4216. used[pools[i]->prio] = true;
  4217. }
  4218. }
  4219. }
  4220. for (i = 0; i < total_pools; i++) {
  4221. if (!valid[i]) {
  4222. for (j = 0; j < total_pools; j++) {
  4223. if (!used[j]) {
  4224. applog(LOG_WARNING, "Pool %d priority changed from %d to %d", i, pools[i]->prio, j);
  4225. pools[i]->prio = j;
  4226. used[j] = true;
  4227. break;
  4228. }
  4229. }
  4230. }
  4231. }
  4232. }
  4233. static void clear_pool_work(struct pool *pool);
  4234. /* Specifies whether we can switch to this pool or not. */
  4235. static bool pool_unusable(struct pool *pool)
  4236. {
  4237. if (pool->idle)
  4238. return true;
  4239. if (pool->enabled != POOL_ENABLED)
  4240. return true;
  4241. return false;
  4242. }
  4243. void switch_pools(struct pool *selected)
  4244. {
  4245. struct pool *pool, *last_pool;
  4246. int i, pool_no, next_pool;
  4247. cg_wlock(&control_lock);
  4248. last_pool = currentpool;
  4249. pool_no = currentpool->pool_no;
  4250. /* Switch selected to pool number 0 and move the rest down */
  4251. if (selected) {
  4252. if (selected->prio != 0) {
  4253. for (i = 0; i < total_pools; i++) {
  4254. pool = pools[i];
  4255. if (pool->prio < selected->prio)
  4256. pool->prio++;
  4257. }
  4258. selected->prio = 0;
  4259. }
  4260. }
  4261. switch (pool_strategy) {
  4262. /* Both of these set to the master pool */
  4263. case POOL_BALANCE:
  4264. case POOL_FAILOVER:
  4265. case POOL_LOADBALANCE:
  4266. for (i = 0; i < total_pools; i++) {
  4267. pool = priority_pool(i);
  4268. if (pool_unusable(pool))
  4269. continue;
  4270. pool_no = pool->pool_no;
  4271. break;
  4272. }
  4273. break;
  4274. /* Both of these simply increment and cycle */
  4275. case POOL_ROUNDROBIN:
  4276. case POOL_ROTATE:
  4277. if (selected && !selected->idle) {
  4278. pool_no = selected->pool_no;
  4279. break;
  4280. }
  4281. next_pool = pool_no;
  4282. /* Select the next alive pool */
  4283. for (i = 1; i < total_pools; i++) {
  4284. next_pool++;
  4285. if (next_pool >= total_pools)
  4286. next_pool = 0;
  4287. pool = pools[next_pool];
  4288. if (pool_unusable(pool))
  4289. continue;
  4290. pool_no = next_pool;
  4291. break;
  4292. }
  4293. break;
  4294. default:
  4295. break;
  4296. }
  4297. currentpool = pools[pool_no];
  4298. pool = currentpool;
  4299. cg_wunlock(&control_lock);
  4300. /* Set the lagging flag to avoid pool not providing work fast enough
  4301. * messages in failover only mode since we have to get all fresh work
  4302. * as in restart_threads */
  4303. if (opt_fail_only)
  4304. pool_tset(pool, &pool->lagging);
  4305. if (pool != last_pool)
  4306. {
  4307. pool->block_id = 0;
  4308. if (pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  4309. applog(LOG_WARNING, "Switching to pool %d %s", pool->pool_no, pool->rpc_url);
  4310. if (pool_localgen(pool) || opt_fail_only)
  4311. clear_pool_work(last_pool);
  4312. }
  4313. }
  4314. mutex_lock(&lp_lock);
  4315. pthread_cond_broadcast(&lp_cond);
  4316. mutex_unlock(&lp_lock);
  4317. }
  4318. static void discard_work(struct work *work)
  4319. {
  4320. if (!work->clone && !work->rolls && !work->mined) {
  4321. if (work->pool)
  4322. work->pool->discarded_work++;
  4323. total_discarded++;
  4324. applog(LOG_DEBUG, "Discarded work");
  4325. } else
  4326. applog(LOG_DEBUG, "Discarded cloned or rolled work");
  4327. free_work(work);
  4328. }
  4329. static void wake_gws(void)
  4330. {
  4331. mutex_lock(stgd_lock);
  4332. pthread_cond_signal(&gws_cond);
  4333. mutex_unlock(stgd_lock);
  4334. }
  4335. static void discard_stale(void)
  4336. {
  4337. struct work *work, *tmp;
  4338. int stale = 0;
  4339. mutex_lock(stgd_lock);
  4340. HASH_ITER(hh, staged_work, work, tmp) {
  4341. if (stale_work(work, false)) {
  4342. HASH_DEL(staged_work, work);
  4343. discard_work(work);
  4344. stale++;
  4345. staged_full = false;
  4346. }
  4347. }
  4348. pthread_cond_signal(&gws_cond);
  4349. mutex_unlock(stgd_lock);
  4350. if (stale)
  4351. applog(LOG_DEBUG, "Discarded %d stales that didn't match current hash", stale);
  4352. }
  4353. bool stale_work_future(struct work *work, bool share, unsigned long ustime)
  4354. {
  4355. bool rv;
  4356. struct timeval tv, orig;
  4357. ldiv_t d;
  4358. d = ldiv(ustime, 1000000);
  4359. tv = (struct timeval){
  4360. .tv_sec = d.quot,
  4361. .tv_usec = d.rem,
  4362. };
  4363. orig = work->tv_staged;
  4364. timersub(&orig, &tv, &work->tv_staged);
  4365. rv = stale_work(work, share);
  4366. work->tv_staged = orig;
  4367. return rv;
  4368. }
  4369. static void restart_threads(void)
  4370. {
  4371. struct pool *cp = current_pool();
  4372. int i;
  4373. struct thr_info *thr;
  4374. /* Artificially set the lagging flag to avoid pool not providing work
  4375. * fast enough messages after every long poll */
  4376. pool_tset(cp, &cp->lagging);
  4377. /* Discard staged work that is now stale */
  4378. discard_stale();
  4379. rd_lock(&mining_thr_lock);
  4380. for (i = 0; i < mining_threads; i++)
  4381. {
  4382. thr = mining_thr[i];
  4383. thr->work_restart = true;
  4384. }
  4385. for (i = 0; i < mining_threads; i++)
  4386. {
  4387. thr = mining_thr[i];
  4388. notifier_wake(thr->work_restart_notifier);
  4389. }
  4390. rd_unlock(&mining_thr_lock);
  4391. }
  4392. static
  4393. void blkhashstr(char *rv, const unsigned char *hash)
  4394. {
  4395. unsigned char hash_swap[32];
  4396. swap256(hash_swap, hash);
  4397. swap32tole(hash_swap, hash_swap, 32 / 4);
  4398. bin2hex(rv, hash_swap, 32);
  4399. }
  4400. static void set_curblock(char *hexstr, unsigned char *hash)
  4401. {
  4402. unsigned char hash_swap[32];
  4403. current_block_id = ((uint32_t*)hash)[0];
  4404. strcpy(current_block, hexstr);
  4405. swap256(hash_swap, hash);
  4406. swap32tole(hash_swap, hash_swap, 32 / 4);
  4407. cg_wlock(&ch_lock);
  4408. cgtime(&block_timeval);
  4409. __update_block_title(hash_swap);
  4410. free(current_fullhash);
  4411. current_fullhash = malloc(65);
  4412. bin2hex(current_fullhash, hash_swap, 32);
  4413. get_timestamp(blocktime, block_timeval.tv_sec);
  4414. cg_wunlock(&ch_lock);
  4415. applog(LOG_INFO, "New block: %s diff %s (%s)", current_hash, block_diff, net_hashrate);
  4416. }
  4417. /* Search to see if this string is from a block that has been seen before */
  4418. static bool block_exists(char *hexstr)
  4419. {
  4420. struct block *s;
  4421. rd_lock(&blk_lock);
  4422. HASH_FIND_STR(blocks, hexstr, s);
  4423. rd_unlock(&blk_lock);
  4424. if (s)
  4425. return true;
  4426. return false;
  4427. }
  4428. /* Tests if this work is from a block that has been seen before */
  4429. static inline bool from_existing_block(struct work *work)
  4430. {
  4431. char hexstr[37];
  4432. bool ret;
  4433. bin2hex(hexstr, work->data + 8, 18);
  4434. ret = block_exists(hexstr);
  4435. return ret;
  4436. }
  4437. static int block_sort(struct block *blocka, struct block *blockb)
  4438. {
  4439. return blocka->block_no - blockb->block_no;
  4440. }
  4441. static void set_blockdiff(const struct work *work)
  4442. {
  4443. unsigned char target[32];
  4444. double diff;
  4445. uint64_t diff64;
  4446. real_block_target(target, work->data);
  4447. diff = target_diff(target);
  4448. diff64 = diff;
  4449. suffix_string(diff64, block_diff, 0);
  4450. format_unit(net_hashrate, true, "h/s", H2B_SHORT, diff * 7158278, -1);
  4451. if (unlikely(current_diff != diff))
  4452. applog(LOG_NOTICE, "Network difficulty changed to %s (%s)", block_diff, net_hashrate);
  4453. current_diff = diff;
  4454. }
  4455. static bool test_work_current(struct work *work)
  4456. {
  4457. bool ret = true;
  4458. char hexstr[37];
  4459. if (work->mandatory)
  4460. return ret;
  4461. uint32_t block_id = ((uint32_t*)(work->data))[1];
  4462. /* Hack to work around dud work sneaking into test */
  4463. bin2hex(hexstr, work->data + 8, 18);
  4464. if (!strncmp(hexstr, "000000000000000000000000000000000000", 36))
  4465. goto out_free;
  4466. /* Search to see if this block exists yet and if not, consider it a
  4467. * new block and set the current block details to this one */
  4468. if (!block_exists(hexstr)) {
  4469. struct block *s = calloc(sizeof(struct block), 1);
  4470. int deleted_block = 0;
  4471. ret = false;
  4472. if (unlikely(!s))
  4473. quit (1, "test_work_current OOM");
  4474. strcpy(s->hash, hexstr);
  4475. s->block_no = new_blocks++;
  4476. wr_lock(&blk_lock);
  4477. /* Only keep the last hour's worth of blocks in memory since
  4478. * work from blocks before this is virtually impossible and we
  4479. * want to prevent memory usage from continually rising */
  4480. if (HASH_COUNT(blocks) > 6) {
  4481. struct block *oldblock;
  4482. HASH_SORT(blocks, block_sort);
  4483. oldblock = blocks;
  4484. deleted_block = oldblock->block_no;
  4485. HASH_DEL(blocks, oldblock);
  4486. free(oldblock);
  4487. }
  4488. HASH_ADD_STR(blocks, hash, s);
  4489. set_blockdiff(work);
  4490. wr_unlock(&blk_lock);
  4491. work->pool->block_id = block_id;
  4492. if (deleted_block)
  4493. applog(LOG_DEBUG, "Deleted block %d from database", deleted_block);
  4494. template_nonce = 0;
  4495. set_curblock(hexstr, &work->data[4]);
  4496. if (unlikely(new_blocks == 1))
  4497. goto out_free;
  4498. if (!work->stratum) {
  4499. if (work->longpoll) {
  4500. applog(LOG_NOTICE, "Longpoll from pool %d detected new block",
  4501. work->pool->pool_no);
  4502. } else if (have_longpoll)
  4503. applog(LOG_NOTICE, "New block detected on network before longpoll");
  4504. else
  4505. applog(LOG_NOTICE, "New block detected on network");
  4506. }
  4507. restart_threads();
  4508. } else {
  4509. bool restart = false;
  4510. struct pool *curpool = NULL;
  4511. if (unlikely(work->pool->block_id != block_id)) {
  4512. bool was_active = work->pool->block_id != 0;
  4513. work->pool->block_id = block_id;
  4514. if (!work->longpoll)
  4515. update_last_work(work);
  4516. if (was_active) { // Pool actively changed block
  4517. if (work->pool == (curpool = current_pool()))
  4518. restart = true;
  4519. if (block_id == current_block_id) {
  4520. // Caught up, only announce if this pool is the one in use
  4521. if (restart)
  4522. applog(LOG_NOTICE, "%s %d caught up to new block",
  4523. work->longpoll ? "Longpoll from pool" : "Pool",
  4524. work->pool->pool_no);
  4525. } else {
  4526. // Switched to a block we know, but not the latest... why?
  4527. // This might detect pools trying to double-spend or 51%,
  4528. // but let's not make any accusations until it's had time
  4529. // in the real world.
  4530. blkhashstr(hexstr, &work->data[4]);
  4531. applog(LOG_WARNING, "%s %d is issuing work for an old block: %s",
  4532. work->longpoll ? "Longpoll from pool" : "Pool",
  4533. work->pool->pool_no,
  4534. hexstr);
  4535. }
  4536. }
  4537. }
  4538. if (work->longpoll) {
  4539. ++work->pool->work_restart_id;
  4540. update_last_work(work);
  4541. if ((!restart) && work->pool == current_pool()) {
  4542. applog(
  4543. (opt_quiet_work_updates ? LOG_DEBUG : LOG_NOTICE),
  4544. "Longpoll from pool %d requested work update",
  4545. work->pool->pool_no);
  4546. restart = true;
  4547. }
  4548. }
  4549. if (restart)
  4550. restart_threads();
  4551. }
  4552. work->longpoll = false;
  4553. out_free:
  4554. return ret;
  4555. }
  4556. static int tv_sort(struct work *worka, struct work *workb)
  4557. {
  4558. return worka->tv_staged.tv_sec - workb->tv_staged.tv_sec;
  4559. }
  4560. static bool work_rollable(struct work *work)
  4561. {
  4562. return (!work->clone && work->rolltime);
  4563. }
  4564. static bool hash_push(struct work *work)
  4565. {
  4566. bool rc = true;
  4567. mutex_lock(stgd_lock);
  4568. if (work_rollable(work))
  4569. staged_rollable++;
  4570. if (likely(!getq->frozen)) {
  4571. HASH_ADD_INT(staged_work, id, work);
  4572. HASH_SORT(staged_work, tv_sort);
  4573. } else
  4574. rc = false;
  4575. pthread_cond_broadcast(&getq->cond);
  4576. mutex_unlock(stgd_lock);
  4577. return rc;
  4578. }
  4579. static void *stage_thread(void *userdata)
  4580. {
  4581. struct thr_info *mythr = userdata;
  4582. bool ok = true;
  4583. #ifndef HAVE_PTHREAD_CANCEL
  4584. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  4585. #endif
  4586. RenameThread("stage");
  4587. while (ok) {
  4588. struct work *work = NULL;
  4589. applog(LOG_DEBUG, "Popping work to stage thread");
  4590. work = tq_pop(mythr->q, NULL);
  4591. if (unlikely(!work)) {
  4592. applog(LOG_ERR, "Failed to tq_pop in stage_thread");
  4593. ok = false;
  4594. break;
  4595. }
  4596. work->work_restart_id = work->pool->work_restart_id;
  4597. test_work_current(work);
  4598. applog(LOG_DEBUG, "Pushing work to getwork queue (queued=%c)", work->queued?'Y':'N');
  4599. if (unlikely(!hash_push(work))) {
  4600. applog(LOG_WARNING, "Failed to hash_push in stage_thread");
  4601. continue;
  4602. }
  4603. }
  4604. tq_freeze(mythr->q);
  4605. return NULL;
  4606. }
  4607. static void stage_work(struct work *work)
  4608. {
  4609. applog(LOG_DEBUG, "Pushing work from pool %d to hash queue", work->pool->pool_no);
  4610. work->work_restart_id = work->pool->work_restart_id;
  4611. work->pool->last_work_time = time(NULL);
  4612. cgtime(&work->pool->tv_last_work_time);
  4613. test_work_current(work);
  4614. hash_push(work);
  4615. }
  4616. #ifdef HAVE_CURSES
  4617. int curses_int(const char *query)
  4618. {
  4619. int ret;
  4620. char *cvar;
  4621. cvar = curses_input(query);
  4622. ret = atoi(cvar);
  4623. free(cvar);
  4624. return ret;
  4625. }
  4626. #endif
  4627. #ifdef HAVE_CURSES
  4628. static bool input_pool(bool live);
  4629. #endif
  4630. #ifdef HAVE_CURSES
  4631. static void display_pool_summary(struct pool *pool)
  4632. {
  4633. double efficiency = 0.0;
  4634. char xfer[17], bw[19];
  4635. int pool_secs;
  4636. if (curses_active_locked()) {
  4637. wlog("Pool: %s\n", pool->rpc_url);
  4638. if (pool->solved)
  4639. wlog("SOLVED %d BLOCK%s!\n", pool->solved, pool->solved > 1 ? "S" : "");
  4640. wlog("%s own long-poll support\n", pool->lp_url ? "Has" : "Does not have");
  4641. wlog(" Queued work requests: %d\n", pool->getwork_requested);
  4642. wlog(" Share submissions: %d\n", pool->accepted + pool->rejected);
  4643. wlog(" Accepted shares: %d\n", pool->accepted);
  4644. wlog(" Rejected shares: %d + %d stale (%.2f%%)\n",
  4645. pool->rejected, pool->stale_shares,
  4646. (float)(pool->rejected + pool->stale_shares) / (float)(pool->rejected + pool->stale_shares + pool->accepted)
  4647. );
  4648. wlog(" Accepted difficulty shares: %1.f\n", pool->diff_accepted);
  4649. wlog(" Rejected difficulty shares: %1.f\n", pool->diff_rejected);
  4650. pool_secs = timer_elapsed(&pool->cgminer_stats.start_tv, NULL);
  4651. wlog(" Network transfer: %s (%s)\n",
  4652. multi_format_unit(xfer, true, "B", H2B_SPACED, " / ", 2,
  4653. (float)pool->cgminer_pool_stats.net_bytes_received,
  4654. (float)pool->cgminer_pool_stats.net_bytes_sent),
  4655. multi_format_unit(bw, true, "B/s", H2B_SPACED, " / ", 2,
  4656. (float)(pool->cgminer_pool_stats.net_bytes_received / pool_secs),
  4657. (float)(pool->cgminer_pool_stats.net_bytes_sent / pool_secs)));
  4658. uint64_t pool_bytes_xfer = pool->cgminer_pool_stats.net_bytes_received + pool->cgminer_pool_stats.net_bytes_sent;
  4659. efficiency = pool_bytes_xfer ? pool->diff_accepted * 2048. / pool_bytes_xfer : 0.0;
  4660. wlog(" Efficiency (accepted * difficulty / 2 KB): %.2f\n", efficiency);
  4661. wlog(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  4662. wlog(" Unable to get work from server occasions: %d\n", pool->getfail_occasions);
  4663. wlog(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  4664. unlock_curses();
  4665. }
  4666. }
  4667. #endif
  4668. /* We can't remove the memory used for this struct pool because there may
  4669. * still be work referencing it. We just remove it from the pools list */
  4670. void remove_pool(struct pool *pool)
  4671. {
  4672. int i, last_pool = total_pools - 1;
  4673. struct pool *other;
  4674. /* Boost priority of any lower prio than this one */
  4675. for (i = 0; i < total_pools; i++) {
  4676. other = pools[i];
  4677. if (other->prio > pool->prio)
  4678. other->prio--;
  4679. }
  4680. if (pool->pool_no < last_pool) {
  4681. /* Swap the last pool for this one */
  4682. (pools[last_pool])->pool_no = pool->pool_no;
  4683. pools[pool->pool_no] = pools[last_pool];
  4684. }
  4685. /* Give it an invalid number */
  4686. pool->pool_no = total_pools;
  4687. pool->removed = true;
  4688. pool->has_stratum = false;
  4689. total_pools--;
  4690. }
  4691. /* add a mutex if this needs to be thread safe in the future */
  4692. static struct JE {
  4693. char *buf;
  4694. struct JE *next;
  4695. } *jedata = NULL;
  4696. static void json_escape_free()
  4697. {
  4698. struct JE *jeptr = jedata;
  4699. struct JE *jenext;
  4700. jedata = NULL;
  4701. while (jeptr) {
  4702. jenext = jeptr->next;
  4703. free(jeptr->buf);
  4704. free(jeptr);
  4705. jeptr = jenext;
  4706. }
  4707. }
  4708. static char *json_escape(char *str)
  4709. {
  4710. struct JE *jeptr;
  4711. char *buf, *ptr;
  4712. /* 2x is the max, may as well just allocate that */
  4713. ptr = buf = malloc(strlen(str) * 2 + 1);
  4714. jeptr = malloc(sizeof(*jeptr));
  4715. jeptr->buf = buf;
  4716. jeptr->next = jedata;
  4717. jedata = jeptr;
  4718. while (*str) {
  4719. if (*str == '\\' || *str == '"')
  4720. *(ptr++) = '\\';
  4721. *(ptr++) = *(str++);
  4722. }
  4723. *ptr = '\0';
  4724. return buf;
  4725. }
  4726. void write_config(FILE *fcfg)
  4727. {
  4728. int i;
  4729. /* Write pool values */
  4730. fputs("{\n\"pools\" : [", fcfg);
  4731. for(i = 0; i < total_pools; i++) {
  4732. fprintf(fcfg, "%s\n\t{\n\t\t\"url\" : \"%s\",", i > 0 ? "," : "", json_escape(pools[i]->rpc_url));
  4733. if (pools[i]->rpc_proxy)
  4734. fprintf(fcfg, "\n\t\t\"pool-proxy\" : \"%s\",", json_escape(pools[i]->rpc_proxy));
  4735. fprintf(fcfg, "\n\t\t\"user\" : \"%s\",", json_escape(pools[i]->rpc_user));
  4736. fprintf(fcfg, "\n\t\t\"pass\" : \"%s\",", json_escape(pools[i]->rpc_pass));
  4737. fprintf(fcfg, "\n\t\t\"pool-priority\" : \"%d\"", pools[i]->prio);
  4738. if (pools[i]->force_rollntime)
  4739. fprintf(fcfg, ",\n\t\t\"force-rollntime\" : %d", pools[i]->force_rollntime);
  4740. fprintf(fcfg, "\n\t}");
  4741. }
  4742. fputs("\n]\n", fcfg);
  4743. fputs(",\n\"temp-cutoff\" : \"", fcfg);
  4744. for (i = 0; i < total_devices; ++i)
  4745. fprintf(fcfg, "%s%d", i > 0 ? "," : "", devices[i]->cutofftemp);
  4746. fputs("\",\n\"temp-target\" : \"", fcfg);
  4747. for (i = 0; i < total_devices; ++i)
  4748. fprintf(fcfg, "%s%d", i > 0 ? "," : "", devices[i]->targettemp);
  4749. fputs("\"", fcfg);
  4750. #ifdef HAVE_OPENCL
  4751. if (nDevs) {
  4752. /* Write GPU device values */
  4753. fputs(",\n\"intensity\" : \"", fcfg);
  4754. for(i = 0; i < nDevs; i++)
  4755. fprintf(fcfg, gpus[i].dynamic ? "%sd" : "%s%d", i > 0 ? "," : "", gpus[i].intensity);
  4756. fputs("\",\n\"vectors\" : \"", fcfg);
  4757. for(i = 0; i < nDevs; i++)
  4758. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  4759. gpus[i].vwidth);
  4760. fputs("\",\n\"worksize\" : \"", fcfg);
  4761. for(i = 0; i < nDevs; i++)
  4762. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  4763. (int)gpus[i].work_size);
  4764. fputs("\",\n\"kernel\" : \"", fcfg);
  4765. for(i = 0; i < nDevs; i++) {
  4766. fprintf(fcfg, "%s", i > 0 ? "," : "");
  4767. switch (gpus[i].kernel) {
  4768. case KL_NONE: // Shouldn't happen
  4769. break;
  4770. case KL_POCLBM:
  4771. fprintf(fcfg, "poclbm");
  4772. break;
  4773. case KL_PHATK:
  4774. fprintf(fcfg, "phatk");
  4775. break;
  4776. case KL_DIAKGCN:
  4777. fprintf(fcfg, "diakgcn");
  4778. break;
  4779. case KL_DIABLO:
  4780. fprintf(fcfg, "diablo");
  4781. break;
  4782. case KL_SCRYPT:
  4783. fprintf(fcfg, "scrypt");
  4784. break;
  4785. }
  4786. }
  4787. #ifdef USE_SCRYPT
  4788. fputs("\",\n\"lookup-gap\" : \"", fcfg);
  4789. for(i = 0; i < nDevs; i++)
  4790. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  4791. (int)gpus[i].opt_lg);
  4792. fputs("\",\n\"thread-concurrency\" : \"", fcfg);
  4793. for(i = 0; i < nDevs; i++)
  4794. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  4795. (int)gpus[i].opt_tc);
  4796. fputs("\",\n\"shaders\" : \"", fcfg);
  4797. for(i = 0; i < nDevs; i++)
  4798. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  4799. (int)gpus[i].shaders);
  4800. #endif
  4801. #ifdef HAVE_ADL
  4802. fputs("\",\n\"gpu-engine\" : \"", fcfg);
  4803. for(i = 0; i < nDevs; i++)
  4804. fprintf(fcfg, "%s%d-%d", i > 0 ? "," : "", gpus[i].min_engine, gpus[i].gpu_engine);
  4805. fputs("\",\n\"gpu-fan\" : \"", fcfg);
  4806. for(i = 0; i < nDevs; i++)
  4807. fprintf(fcfg, "%s%d-%d", i > 0 ? "," : "", gpus[i].min_fan, gpus[i].gpu_fan);
  4808. fputs("\",\n\"gpu-memclock\" : \"", fcfg);
  4809. for(i = 0; i < nDevs; i++)
  4810. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_memclock);
  4811. fputs("\",\n\"gpu-memdiff\" : \"", fcfg);
  4812. for(i = 0; i < nDevs; i++)
  4813. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_memdiff);
  4814. fputs("\",\n\"gpu-powertune\" : \"", fcfg);
  4815. for(i = 0; i < nDevs; i++)
  4816. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_powertune);
  4817. fputs("\",\n\"gpu-vddc\" : \"", fcfg);
  4818. for(i = 0; i < nDevs; i++)
  4819. fprintf(fcfg, "%s%1.3f", i > 0 ? "," : "", gpus[i].gpu_vddc);
  4820. fputs("\",\n\"temp-overheat\" : \"", fcfg);
  4821. for(i = 0; i < nDevs; i++)
  4822. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].adl.overtemp);
  4823. #endif
  4824. fputs("\"", fcfg);
  4825. }
  4826. #endif
  4827. #ifdef HAVE_ADL
  4828. if (opt_reorder)
  4829. fprintf(fcfg, ",\n\"gpu-reorder\" : true");
  4830. #endif
  4831. #ifdef WANT_CPUMINE
  4832. fprintf(fcfg, ",\n\"algo\" : \"%s\"", algo_names[opt_algo]);
  4833. #endif
  4834. /* Simple bool and int options */
  4835. struct opt_table *opt;
  4836. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  4837. char *p, *name = strdup(opt->names);
  4838. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  4839. if (p[1] != '-')
  4840. continue;
  4841. if (opt->type & OPT_NOARG &&
  4842. ((void *)opt->cb == (void *)opt_set_bool || (void *)opt->cb == (void *)opt_set_invbool) &&
  4843. (*(bool *)opt->u.arg == ((void *)opt->cb == (void *)opt_set_bool)))
  4844. fprintf(fcfg, ",\n\"%s\" : true", p+2);
  4845. if (opt->type & OPT_HASARG &&
  4846. ((void *)opt->cb_arg == (void *)set_int_0_to_9999 ||
  4847. (void *)opt->cb_arg == (void *)set_int_1_to_65535 ||
  4848. (void *)opt->cb_arg == (void *)set_int_0_to_10 ||
  4849. (void *)opt->cb_arg == (void *)set_int_1_to_10) &&
  4850. opt->desc != opt_hidden &&
  4851. 0 <= *(int *)opt->u.arg)
  4852. fprintf(fcfg, ",\n\"%s\" : \"%d\"", p+2, *(int *)opt->u.arg);
  4853. }
  4854. }
  4855. /* Special case options */
  4856. fprintf(fcfg, ",\n\"shares\" : \"%d\"", opt_shares);
  4857. if (pool_strategy == POOL_BALANCE)
  4858. fputs(",\n\"balance\" : true", fcfg);
  4859. if (pool_strategy == POOL_LOADBALANCE)
  4860. fputs(",\n\"load-balance\" : true", fcfg);
  4861. if (pool_strategy == POOL_ROUNDROBIN)
  4862. fputs(",\n\"round-robin\" : true", fcfg);
  4863. if (pool_strategy == POOL_ROTATE)
  4864. fprintf(fcfg, ",\n\"rotate\" : \"%d\"", opt_rotate_period);
  4865. #if defined(unix) || defined(__APPLE__)
  4866. if (opt_stderr_cmd && *opt_stderr_cmd)
  4867. fprintf(fcfg, ",\n\"monitor\" : \"%s\"", json_escape(opt_stderr_cmd));
  4868. #endif // defined(unix)
  4869. if (opt_kernel_path && *opt_kernel_path) {
  4870. char *kpath = strdup(opt_kernel_path);
  4871. if (kpath[strlen(kpath)-1] == '/')
  4872. kpath[strlen(kpath)-1] = 0;
  4873. fprintf(fcfg, ",\n\"kernel-path\" : \"%s\"", json_escape(kpath));
  4874. }
  4875. if (schedstart.enable)
  4876. fprintf(fcfg, ",\n\"sched-time\" : \"%d:%d\"", schedstart.tm.tm_hour, schedstart.tm.tm_min);
  4877. if (schedstop.enable)
  4878. fprintf(fcfg, ",\n\"stop-time\" : \"%d:%d\"", schedstop.tm.tm_hour, schedstop.tm.tm_min);
  4879. if (opt_socks_proxy && *opt_socks_proxy)
  4880. fprintf(fcfg, ",\n\"socks-proxy\" : \"%s\"", json_escape(opt_socks_proxy));
  4881. // We can only remove devices or disable them by default, but not both...
  4882. if (!(opt_removedisabled && opt_devs_enabled))
  4883. {
  4884. // Don't need to remove any, so we can set defaults here
  4885. for (i = 0; i < total_devices; ++i)
  4886. if (devices[i]->deven == DEV_DISABLED)
  4887. {
  4888. // At least one device is in fact disabled, so include device params
  4889. fprintf(fcfg, ",\n\"device\" : [");
  4890. bool first = true;
  4891. for (i = 0; i < total_devices; ++i)
  4892. if (devices[i]->deven != DEV_DISABLED)
  4893. {
  4894. fprintf(fcfg, "%s\n\t%d", first ? "" : ",", i);
  4895. first = false;
  4896. }
  4897. fprintf(fcfg, "\n]");
  4898. break;
  4899. }
  4900. }
  4901. else
  4902. if (opt_devs_enabled) {
  4903. // Mark original device params and remove-disabled
  4904. fprintf(fcfg, ",\n\"device\" : [");
  4905. bool first = true;
  4906. for (i = 0; i < MAX_DEVICES; i++) {
  4907. if (devices_enabled[i]) {
  4908. fprintf(fcfg, "%s\n\t%d", first ? "" : ",", i);
  4909. first = false;
  4910. }
  4911. }
  4912. fprintf(fcfg, "\n]");
  4913. fprintf(fcfg, ",\n\"remove-disabled\" : true");
  4914. }
  4915. if (opt_api_allow)
  4916. fprintf(fcfg, ",\n\"api-allow\" : \"%s\"", json_escape(opt_api_allow));
  4917. if (strcmp(opt_api_description, PACKAGE_STRING) != 0)
  4918. fprintf(fcfg, ",\n\"api-description\" : \"%s\"", json_escape(opt_api_description));
  4919. if (opt_api_groups)
  4920. fprintf(fcfg, ",\n\"api-groups\" : \"%s\"", json_escape(opt_api_groups));
  4921. if (opt_icarus_options)
  4922. fprintf(fcfg, ",\n\"icarus-options\" : \"%s\"", json_escape(opt_icarus_options));
  4923. if (opt_icarus_timing)
  4924. fprintf(fcfg, ",\n\"icarus-timing\" : \"%s\"", json_escape(opt_icarus_timing));
  4925. fputs("\n}\n", fcfg);
  4926. json_escape_free();
  4927. }
  4928. void zero_bestshare(void)
  4929. {
  4930. int i;
  4931. best_diff = 0;
  4932. memset(best_share, 0, 8);
  4933. suffix_string(best_diff, best_share, 0);
  4934. for (i = 0; i < total_pools; i++) {
  4935. struct pool *pool = pools[i];
  4936. pool->best_diff = 0;
  4937. }
  4938. }
  4939. void zero_stats(void)
  4940. {
  4941. int i;
  4942. cgtime(&total_tv_start);
  4943. miner_started = total_tv_start;
  4944. total_mhashes_done = 0;
  4945. total_getworks = 0;
  4946. total_accepted = 0;
  4947. total_rejected = 0;
  4948. hw_errors = 0;
  4949. total_stale = 0;
  4950. total_discarded = 0;
  4951. total_bytes_rcvd = total_bytes_sent = 0;
  4952. new_blocks = 0;
  4953. local_work = 0;
  4954. total_go = 0;
  4955. total_ro = 0;
  4956. total_secs = 1.0;
  4957. total_diff1 = 0;
  4958. total_bad_nonces = 0;
  4959. found_blocks = 0;
  4960. total_diff_accepted = 0;
  4961. total_diff_rejected = 0;
  4962. total_diff_stale = 0;
  4963. #ifdef HAVE_CURSES
  4964. awidth = rwidth = swidth = hwwidth = 1;
  4965. #endif
  4966. for (i = 0; i < total_pools; i++) {
  4967. struct pool *pool = pools[i];
  4968. pool->getwork_requested = 0;
  4969. pool->accepted = 0;
  4970. pool->rejected = 0;
  4971. pool->solved = 0;
  4972. pool->getwork_requested = 0;
  4973. pool->stale_shares = 0;
  4974. pool->discarded_work = 0;
  4975. pool->getfail_occasions = 0;
  4976. pool->remotefail_occasions = 0;
  4977. pool->last_share_time = 0;
  4978. pool->diff1 = 0;
  4979. pool->diff_accepted = 0;
  4980. pool->diff_rejected = 0;
  4981. pool->diff_stale = 0;
  4982. pool->last_share_diff = 0;
  4983. pool->cgminer_stats.start_tv = total_tv_start;
  4984. pool->cgminer_stats.getwork_calls = 0;
  4985. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  4986. pool->cgminer_stats.getwork_wait_max.tv_sec = 0;
  4987. pool->cgminer_stats.getwork_wait_max.tv_usec = 0;
  4988. pool->cgminer_pool_stats.getwork_calls = 0;
  4989. pool->cgminer_pool_stats.getwork_attempts = 0;
  4990. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  4991. pool->cgminer_pool_stats.getwork_wait_max.tv_sec = 0;
  4992. pool->cgminer_pool_stats.getwork_wait_max.tv_usec = 0;
  4993. pool->cgminer_pool_stats.min_diff = 0;
  4994. pool->cgminer_pool_stats.max_diff = 0;
  4995. pool->cgminer_pool_stats.min_diff_count = 0;
  4996. pool->cgminer_pool_stats.max_diff_count = 0;
  4997. pool->cgminer_pool_stats.times_sent = 0;
  4998. pool->cgminer_pool_stats.bytes_sent = 0;
  4999. pool->cgminer_pool_stats.net_bytes_sent = 0;
  5000. pool->cgminer_pool_stats.times_received = 0;
  5001. pool->cgminer_pool_stats.bytes_received = 0;
  5002. pool->cgminer_pool_stats.net_bytes_received = 0;
  5003. }
  5004. zero_bestshare();
  5005. for (i = 0; i < total_devices; ++i) {
  5006. struct cgpu_info *cgpu = get_devices(i);
  5007. mutex_lock(&hash_lock);
  5008. cgpu->total_mhashes = 0;
  5009. cgpu->accepted = 0;
  5010. cgpu->rejected = 0;
  5011. cgpu->stale = 0;
  5012. cgpu->hw_errors = 0;
  5013. cgpu->utility = 0.0;
  5014. cgpu->utility_diff1 = 0;
  5015. cgpu->last_share_pool_time = 0;
  5016. cgpu->diff1 = 0;
  5017. cgpu->diff_accepted = 0;
  5018. cgpu->diff_rejected = 0;
  5019. cgpu->last_share_diff = 0;
  5020. cgpu->thread_fail_init_count = 0;
  5021. cgpu->thread_zero_hash_count = 0;
  5022. cgpu->thread_fail_queue_count = 0;
  5023. cgpu->dev_sick_idle_60_count = 0;
  5024. cgpu->dev_dead_idle_600_count = 0;
  5025. cgpu->dev_nostart_count = 0;
  5026. cgpu->dev_over_heat_count = 0;
  5027. cgpu->dev_thermal_cutoff_count = 0;
  5028. cgpu->dev_comms_error_count = 0;
  5029. cgpu->dev_throttle_count = 0;
  5030. cgpu->cgminer_stats.start_tv = total_tv_start;
  5031. cgpu->cgminer_stats.getwork_calls = 0;
  5032. cgpu->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  5033. cgpu->cgminer_stats.getwork_wait_max.tv_sec = 0;
  5034. cgpu->cgminer_stats.getwork_wait_max.tv_usec = 0;
  5035. mutex_unlock(&hash_lock);
  5036. }
  5037. }
  5038. #ifdef HAVE_CURSES
  5039. static void display_pools(void)
  5040. {
  5041. struct pool *pool;
  5042. int selected, i, j;
  5043. char input;
  5044. opt_loginput = true;
  5045. immedok(logwin, true);
  5046. clear_logwin();
  5047. updated:
  5048. for (j = 0; j < total_pools; j++) {
  5049. for (i = 0; i < total_pools; i++) {
  5050. pool = pools[i];
  5051. if (pool->prio != j)
  5052. continue;
  5053. if (pool == current_pool())
  5054. wattron(logwin, A_BOLD);
  5055. if (pool->enabled != POOL_ENABLED)
  5056. wattron(logwin, A_DIM);
  5057. wlogprint("%d: ", pool->prio);
  5058. switch (pool->enabled) {
  5059. case POOL_ENABLED:
  5060. wlogprint("Enabled ");
  5061. break;
  5062. case POOL_DISABLED:
  5063. wlogprint("Disabled ");
  5064. break;
  5065. case POOL_REJECTING:
  5066. wlogprint("Rejectin ");
  5067. break;
  5068. }
  5069. if (pool->idle)
  5070. wlogprint("Dead ");
  5071. else
  5072. if (pool->has_stratum)
  5073. wlogprint("Strtm");
  5074. else
  5075. if (pool->lp_url && pool->proto != pool->lp_proto)
  5076. wlogprint("Mixed");
  5077. else
  5078. switch (pool->proto) {
  5079. case PLP_GETBLOCKTEMPLATE:
  5080. wlogprint(" GBT ");
  5081. break;
  5082. case PLP_GETWORK:
  5083. wlogprint("GWork");
  5084. break;
  5085. default:
  5086. wlogprint("Alive");
  5087. }
  5088. wlogprint(" Pool %d: %s User:%s\n",
  5089. pool->pool_no,
  5090. pool->rpc_url, pool->rpc_user);
  5091. wattroff(logwin, A_BOLD | A_DIM);
  5092. break; //for (i = 0; i < total_pools; i++)
  5093. }
  5094. }
  5095. retry:
  5096. wlogprint("\nCurrent pool management strategy: %s\n",
  5097. strategies[pool_strategy].s);
  5098. if (pool_strategy == POOL_ROTATE)
  5099. wlogprint("Set to rotate every %d minutes\n", opt_rotate_period);
  5100. wlogprint("[F]ailover only %s\n", opt_fail_only ? "enabled" : "disabled");
  5101. wlogprint("[A]dd pool [R]emove pool [D]isable pool [E]nable pool [P]rioritize pool\n");
  5102. wlogprint("[C]hange management strategy [S]witch pool [I]nformation\n");
  5103. wlogprint("Or press any other key to continue\n");
  5104. logwin_update();
  5105. input = getch();
  5106. if (!strncasecmp(&input, "a", 1)) {
  5107. input_pool(true);
  5108. goto updated;
  5109. } else if (!strncasecmp(&input, "r", 1)) {
  5110. if (total_pools <= 1) {
  5111. wlogprint("Cannot remove last pool");
  5112. goto retry;
  5113. }
  5114. selected = curses_int("Select pool number");
  5115. if (selected < 0 || selected >= total_pools) {
  5116. wlogprint("Invalid selection\n");
  5117. goto retry;
  5118. }
  5119. pool = pools[selected];
  5120. if (pool == current_pool())
  5121. switch_pools(NULL);
  5122. if (pool == current_pool()) {
  5123. wlogprint("Unable to remove pool due to activity\n");
  5124. goto retry;
  5125. }
  5126. disable_pool(pool);
  5127. remove_pool(pool);
  5128. goto updated;
  5129. } else if (!strncasecmp(&input, "s", 1)) {
  5130. selected = curses_int("Select pool number");
  5131. if (selected < 0 || selected >= total_pools) {
  5132. wlogprint("Invalid selection\n");
  5133. goto retry;
  5134. }
  5135. pool = pools[selected];
  5136. enable_pool(pool);
  5137. switch_pools(pool);
  5138. goto updated;
  5139. } else if (!strncasecmp(&input, "d", 1)) {
  5140. if (enabled_pools <= 1) {
  5141. wlogprint("Cannot disable last pool");
  5142. goto retry;
  5143. }
  5144. selected = curses_int("Select pool number");
  5145. if (selected < 0 || selected >= total_pools) {
  5146. wlogprint("Invalid selection\n");
  5147. goto retry;
  5148. }
  5149. pool = pools[selected];
  5150. disable_pool(pool);
  5151. if (pool == current_pool())
  5152. switch_pools(NULL);
  5153. goto updated;
  5154. } else if (!strncasecmp(&input, "e", 1)) {
  5155. selected = curses_int("Select pool number");
  5156. if (selected < 0 || selected >= total_pools) {
  5157. wlogprint("Invalid selection\n");
  5158. goto retry;
  5159. }
  5160. pool = pools[selected];
  5161. enable_pool(pool);
  5162. if (pool->prio < current_pool()->prio)
  5163. switch_pools(pool);
  5164. goto updated;
  5165. } else if (!strncasecmp(&input, "c", 1)) {
  5166. for (i = 0; i <= TOP_STRATEGY; i++)
  5167. wlogprint("%d: %s\n", i, strategies[i].s);
  5168. selected = curses_int("Select strategy number type");
  5169. if (selected < 0 || selected > TOP_STRATEGY) {
  5170. wlogprint("Invalid selection\n");
  5171. goto retry;
  5172. }
  5173. if (selected == POOL_ROTATE) {
  5174. opt_rotate_period = curses_int("Select interval in minutes");
  5175. if (opt_rotate_period < 0 || opt_rotate_period > 9999) {
  5176. opt_rotate_period = 0;
  5177. wlogprint("Invalid selection\n");
  5178. goto retry;
  5179. }
  5180. }
  5181. pool_strategy = selected;
  5182. switch_pools(NULL);
  5183. goto updated;
  5184. } else if (!strncasecmp(&input, "i", 1)) {
  5185. selected = curses_int("Select pool number");
  5186. if (selected < 0 || selected >= total_pools) {
  5187. wlogprint("Invalid selection\n");
  5188. goto retry;
  5189. }
  5190. pool = pools[selected];
  5191. display_pool_summary(pool);
  5192. goto retry;
  5193. } else if (!strncasecmp(&input, "f", 1)) {
  5194. opt_fail_only ^= true;
  5195. goto updated;
  5196. } else if (!strncasecmp(&input, "p", 1)) {
  5197. char *prilist = curses_input("Enter new pool priority (comma separated list)");
  5198. int res = prioritize_pools(prilist, &i);
  5199. free(prilist);
  5200. switch (res) {
  5201. case MSG_NOPOOL:
  5202. wlogprint("No pools\n");
  5203. goto retry;
  5204. case MSG_MISPID:
  5205. wlogprint("Missing pool id parameter\n");
  5206. goto retry;
  5207. case MSG_INVPID:
  5208. wlogprint("Invalid pool id %d - range is 0 - %d\n", i, total_pools - 1);
  5209. goto retry;
  5210. case MSG_DUPPID:
  5211. wlogprint("Duplicate pool specified %d\n", i);
  5212. goto retry;
  5213. case MSG_POOLPRIO:
  5214. default:
  5215. goto updated;
  5216. }
  5217. } else
  5218. clear_logwin();
  5219. immedok(logwin, false);
  5220. opt_loginput = false;
  5221. }
  5222. static const char *summary_detail_level_str(void)
  5223. {
  5224. if (opt_compact)
  5225. return "compact";
  5226. if (opt_show_procs)
  5227. return "processors";
  5228. return "devices";
  5229. }
  5230. static void display_options(void)
  5231. {
  5232. int selected;
  5233. char input;
  5234. opt_loginput = true;
  5235. immedok(logwin, true);
  5236. retry:
  5237. clear_logwin();
  5238. wlogprint("[N]ormal [C]lear [S]ilent mode (disable all output)\n");
  5239. wlogprint("[D]ebug:%s\n[P]er-device:%s\n[Q]uiet:%s\n[V]erbose:%s\n"
  5240. "[R]PC debug:%s\n[W]orkTime details:%s\nsu[M]mary detail level:%s\n"
  5241. "[L]og interval:%d\n[Z]ero statistics\n",
  5242. opt_debug_console ? "on" : "off",
  5243. want_per_device_stats? "on" : "off",
  5244. opt_quiet ? "on" : "off",
  5245. opt_log_output ? "on" : "off",
  5246. opt_protocol ? "on" : "off",
  5247. opt_worktime ? "on" : "off",
  5248. summary_detail_level_str(),
  5249. opt_log_interval);
  5250. wlogprint("Select an option or any other key to return\n");
  5251. logwin_update();
  5252. input = getch();
  5253. if (!strncasecmp(&input, "q", 1)) {
  5254. opt_quiet ^= true;
  5255. wlogprint("Quiet mode %s\n", opt_quiet ? "enabled" : "disabled");
  5256. goto retry;
  5257. } else if (!strncasecmp(&input, "v", 1)) {
  5258. opt_log_output ^= true;
  5259. if (opt_log_output)
  5260. opt_quiet = false;
  5261. wlogprint("Verbose mode %s\n", opt_log_output ? "enabled" : "disabled");
  5262. goto retry;
  5263. } else if (!strncasecmp(&input, "n", 1)) {
  5264. opt_log_output = false;
  5265. opt_debug_console = false;
  5266. opt_quiet = false;
  5267. opt_protocol = false;
  5268. opt_compact = false;
  5269. opt_show_procs = false;
  5270. devsummaryYOffset = 0;
  5271. want_per_device_stats = false;
  5272. wlogprint("Output mode reset to normal\n");
  5273. switch_logsize();
  5274. goto retry;
  5275. } else if (!strncasecmp(&input, "d", 1)) {
  5276. opt_debug = true;
  5277. opt_debug_console ^= true;
  5278. opt_log_output = opt_debug_console;
  5279. if (opt_debug_console)
  5280. opt_quiet = false;
  5281. wlogprint("Debug mode %s\n", opt_debug_console ? "enabled" : "disabled");
  5282. goto retry;
  5283. } else if (!strncasecmp(&input, "m", 1)) {
  5284. if (opt_compact)
  5285. opt_compact = false;
  5286. else
  5287. if (!opt_show_procs)
  5288. opt_show_procs = true;
  5289. else
  5290. {
  5291. opt_compact = true;
  5292. opt_show_procs = false;
  5293. devsummaryYOffset = 0;
  5294. }
  5295. wlogprint("su[M]mary detail level changed to: %s\n", summary_detail_level_str());
  5296. switch_logsize();
  5297. goto retry;
  5298. } else if (!strncasecmp(&input, "p", 1)) {
  5299. want_per_device_stats ^= true;
  5300. opt_log_output = want_per_device_stats;
  5301. wlogprint("Per-device stats %s\n", want_per_device_stats ? "enabled" : "disabled");
  5302. goto retry;
  5303. } else if (!strncasecmp(&input, "r", 1)) {
  5304. opt_protocol ^= true;
  5305. if (opt_protocol)
  5306. opt_quiet = false;
  5307. wlogprint("RPC protocol debugging %s\n", opt_protocol ? "enabled" : "disabled");
  5308. goto retry;
  5309. } else if (!strncasecmp(&input, "c", 1))
  5310. clear_logwin();
  5311. else if (!strncasecmp(&input, "l", 1)) {
  5312. selected = curses_int("Interval in seconds");
  5313. if (selected < 0 || selected > 9999) {
  5314. wlogprint("Invalid selection\n");
  5315. goto retry;
  5316. }
  5317. opt_log_interval = selected;
  5318. wlogprint("Log interval set to %d seconds\n", opt_log_interval);
  5319. goto retry;
  5320. } else if (!strncasecmp(&input, "s", 1)) {
  5321. opt_realquiet = true;
  5322. } else if (!strncasecmp(&input, "w", 1)) {
  5323. opt_worktime ^= true;
  5324. wlogprint("WorkTime details %s\n", opt_worktime ? "enabled" : "disabled");
  5325. goto retry;
  5326. } else if (!strncasecmp(&input, "z", 1)) {
  5327. zero_stats();
  5328. goto retry;
  5329. } else
  5330. clear_logwin();
  5331. immedok(logwin, false);
  5332. opt_loginput = false;
  5333. }
  5334. #endif
  5335. void default_save_file(char *filename)
  5336. {
  5337. #if defined(unix) || defined(__APPLE__)
  5338. if (getenv("HOME") && *getenv("HOME")) {
  5339. strcpy(filename, getenv("HOME"));
  5340. strcat(filename, "/");
  5341. }
  5342. else
  5343. strcpy(filename, "");
  5344. strcat(filename, ".bfgminer/");
  5345. mkdir(filename, 0777);
  5346. #else
  5347. strcpy(filename, "");
  5348. #endif
  5349. strcat(filename, def_conf);
  5350. }
  5351. #ifdef HAVE_CURSES
  5352. static void set_options(void)
  5353. {
  5354. int selected;
  5355. char input;
  5356. opt_loginput = true;
  5357. immedok(logwin, true);
  5358. clear_logwin();
  5359. retry:
  5360. wlogprint("\n[L]ongpoll: %s\n", want_longpoll ? "On" : "Off");
  5361. wlogprint("[Q]ueue: %d\n[S]cantime: %d\n[E]xpiry: %d\n[R]etries: %d\n"
  5362. "[W]rite config file\n[B]FGMiner restart\n",
  5363. opt_queue, opt_scantime, opt_expiry, opt_retries);
  5364. wlogprint("Select an option or any other key to return\n");
  5365. logwin_update();
  5366. input = getch();
  5367. if (!strncasecmp(&input, "q", 1)) {
  5368. selected = curses_int("Extra work items to queue");
  5369. if (selected < 0 || selected > 9999) {
  5370. wlogprint("Invalid selection\n");
  5371. goto retry;
  5372. }
  5373. opt_queue = selected;
  5374. goto retry;
  5375. } else if (!strncasecmp(&input, "l", 1)) {
  5376. if (want_longpoll)
  5377. stop_longpoll();
  5378. else
  5379. start_longpoll();
  5380. applog(LOG_WARNING, "Longpoll %s", want_longpoll ? "enabled" : "disabled");
  5381. goto retry;
  5382. } else if (!strncasecmp(&input, "s", 1)) {
  5383. selected = curses_int("Set scantime in seconds");
  5384. if (selected < 0 || selected > 9999) {
  5385. wlogprint("Invalid selection\n");
  5386. goto retry;
  5387. }
  5388. opt_scantime = selected;
  5389. goto retry;
  5390. } else if (!strncasecmp(&input, "e", 1)) {
  5391. selected = curses_int("Set expiry time in seconds");
  5392. if (selected < 0 || selected > 9999) {
  5393. wlogprint("Invalid selection\n");
  5394. goto retry;
  5395. }
  5396. opt_expiry = selected;
  5397. goto retry;
  5398. } else if (!strncasecmp(&input, "r", 1)) {
  5399. selected = curses_int("Retries before failing (-1 infinite)");
  5400. if (selected < -1 || selected > 9999) {
  5401. wlogprint("Invalid selection\n");
  5402. goto retry;
  5403. }
  5404. opt_retries = selected;
  5405. goto retry;
  5406. } else if (!strncasecmp(&input, "w", 1)) {
  5407. FILE *fcfg;
  5408. char *str, filename[PATH_MAX], prompt[PATH_MAX + 50];
  5409. default_save_file(filename);
  5410. sprintf(prompt, "Config filename to write (Enter for default) [%s]", filename);
  5411. str = curses_input(prompt);
  5412. if (strcmp(str, "-1")) {
  5413. struct stat statbuf;
  5414. strcpy(filename, str);
  5415. free(str);
  5416. if (!stat(filename, &statbuf)) {
  5417. wlogprint("File exists, overwrite?\n");
  5418. input = getch();
  5419. if (strncasecmp(&input, "y", 1))
  5420. goto retry;
  5421. }
  5422. }
  5423. else
  5424. free(str);
  5425. fcfg = fopen(filename, "w");
  5426. if (!fcfg) {
  5427. wlogprint("Cannot open or create file\n");
  5428. goto retry;
  5429. }
  5430. write_config(fcfg);
  5431. fclose(fcfg);
  5432. goto retry;
  5433. } else if (!strncasecmp(&input, "b", 1)) {
  5434. wlogprint("Are you sure?\n");
  5435. input = getch();
  5436. if (!strncasecmp(&input, "y", 1))
  5437. app_restart();
  5438. else
  5439. clear_logwin();
  5440. } else
  5441. clear_logwin();
  5442. immedok(logwin, false);
  5443. opt_loginput = false;
  5444. }
  5445. void manage_device(void)
  5446. {
  5447. char logline[256];
  5448. const char *msg = NULL;
  5449. struct cgpu_info *cgpu;
  5450. const struct device_drv *drv;
  5451. opt_loginput = true;
  5452. selecting_device = true;
  5453. immedok(logwin, true);
  5454. devchange:
  5455. cgpu = devices[selected_device];
  5456. drv = cgpu->drv;
  5457. refresh_devstatus();
  5458. refresh:
  5459. clear_logwin();
  5460. wlogprint("Select processor to manage using up/down arrow keys\n");
  5461. get_statline3(logline, cgpu, true, true);
  5462. wattron(logwin, A_BOLD);
  5463. wlogprint("%s", logline);
  5464. wattroff(logwin, A_BOLD);
  5465. wlogprint("\n");
  5466. if (cgpu->dev_manufacturer)
  5467. wlogprint(" %s from %s\n", (cgpu->dev_product ?: "Device"), cgpu->dev_manufacturer);
  5468. else
  5469. if (cgpu->dev_product)
  5470. wlogprint(" %s\n", cgpu->dev_product);
  5471. if (cgpu->dev_serial)
  5472. wlogprint("Serial: %s\n", cgpu->dev_serial);
  5473. if (cgpu->kname)
  5474. wlogprint("Kernel: %s\n", cgpu->kname);
  5475. if (drv->proc_wlogprint_status && likely(cgpu->status != LIFE_INIT))
  5476. drv->proc_wlogprint_status(cgpu);
  5477. wlogprint("\n");
  5478. // TODO: Last share at TIMESTAMP on pool N
  5479. // TODO: Custom device info/commands
  5480. if (cgpu->deven != DEV_ENABLED)
  5481. wlogprint("[E]nable ");
  5482. if (cgpu->deven != DEV_DISABLED)
  5483. wlogprint("[D]isable ");
  5484. if (drv->identify_device)
  5485. wlogprint("[I]dentify ");
  5486. if (drv->proc_tui_wlogprint_choices && likely(cgpu->status != LIFE_INIT))
  5487. drv->proc_tui_wlogprint_choices(cgpu);
  5488. wlogprint("\n");
  5489. wlogprint("Or press Enter when done\n");
  5490. if (msg)
  5491. {
  5492. applog(LOG_DEBUG, "ManageTUI: %"PRIpreprv": %s", cgpu->proc_repr, msg);
  5493. wattron(logwin, A_BOLD);
  5494. wlogprint("%s", msg);
  5495. wattroff(logwin, A_BOLD);
  5496. msg = NULL;
  5497. }
  5498. logwin_update();
  5499. while (true)
  5500. {
  5501. int input = getch();
  5502. applog(LOG_DEBUG, "ManageTUI: %"PRIpreprv": (choice %d)", cgpu->proc_repr, input);
  5503. switch (input) {
  5504. case 'd': case 'D':
  5505. if (cgpu->deven == DEV_DISABLED)
  5506. msg = "Processor already disabled\n";
  5507. else
  5508. {
  5509. cgpu->deven = DEV_DISABLED;
  5510. msg = "Processor being disabled\n";
  5511. }
  5512. goto refresh;
  5513. case 'e': case 'E':
  5514. if (cgpu->deven == DEV_ENABLED)
  5515. msg = "Processor already enabled\n";
  5516. else
  5517. {
  5518. proc_enable(cgpu);
  5519. msg = "Processor being enabled\n";
  5520. }
  5521. goto refresh;
  5522. case 'i': case 'I':
  5523. if (drv->identify_device && drv->identify_device(cgpu))
  5524. msg = "Identify command sent\n";
  5525. else
  5526. goto key_default;
  5527. goto refresh;
  5528. case KEY_DOWN:
  5529. if (selected_device >= total_devices - 1)
  5530. break;
  5531. ++selected_device;
  5532. goto devchange;
  5533. case KEY_UP:
  5534. if (selected_device <= 0)
  5535. break;
  5536. --selected_device;
  5537. goto devchange;
  5538. case KEY_NPAGE:
  5539. {
  5540. if (selected_device >= total_devices - 1)
  5541. break;
  5542. struct cgpu_info *mdev = devices[selected_device]->device;
  5543. do {
  5544. ++selected_device;
  5545. } while (devices[selected_device]->device == mdev && selected_device < total_devices - 1);
  5546. goto devchange;
  5547. }
  5548. case KEY_PPAGE:
  5549. {
  5550. if (selected_device <= 0)
  5551. break;
  5552. struct cgpu_info *mdev = devices[selected_device]->device;
  5553. do {
  5554. --selected_device;
  5555. } while (devices[selected_device]->device == mdev && selected_device > 0);
  5556. goto devchange;
  5557. }
  5558. case 'Q': case 'q':
  5559. case KEY_BREAK: case KEY_BACKSPACE: case KEY_CANCEL: case KEY_CLOSE: case KEY_EXIT:
  5560. case '\x1b': // ESC
  5561. case KEY_ENTER:
  5562. case '\r': // Ctrl-M on Windows, with nonl
  5563. #ifdef PADENTER
  5564. case PADENTER: // pdcurses, used by Enter key on Windows with nonl
  5565. #endif
  5566. case '\n':
  5567. goto out;
  5568. default:
  5569. ;
  5570. key_default:
  5571. if (drv->proc_tui_handle_choice && likely(drv_ready(cgpu)))
  5572. {
  5573. msg = drv->proc_tui_handle_choice(cgpu, input);
  5574. if (msg)
  5575. goto refresh;
  5576. }
  5577. }
  5578. }
  5579. out:
  5580. selecting_device = false;
  5581. clear_logwin();
  5582. immedok(logwin, false);
  5583. opt_loginput = false;
  5584. }
  5585. void show_help(void)
  5586. {
  5587. opt_loginput = true;
  5588. clear_logwin();
  5589. // NOTE: wlogprint is a macro with a buffer limit
  5590. _wlogprint(
  5591. "ST: work in queue | F: network fails | NB: new blocks detected\n"
  5592. "AS: shares being submitted | BW: bandwidth (up/down)\n"
  5593. "E: # shares * diff per 2kB bw | U: shares/minute | BS: best share ever found\n"
  5594. "--------------------------------------------------------------------------------\n"
  5595. "devices/processors hashing (only for totals line), hottest temperature\n"
  5596. );
  5597. wlogprint(
  5598. "hashrates: %ds decaying / all-time average / all-time average (effective)\n"
  5599. , opt_log_interval);
  5600. _wlogprint(
  5601. "A: accepted shares | R: rejected+discarded(%% of total)\n"
  5602. "HW: hardware errors / %% nonces invalid\n"
  5603. "\n"
  5604. "Press any key to clear"
  5605. );
  5606. logwin_update();
  5607. getch();
  5608. clear_logwin();
  5609. opt_loginput = false;
  5610. }
  5611. static void *input_thread(void __maybe_unused *userdata)
  5612. {
  5613. RenameThread("input");
  5614. if (!curses_active)
  5615. return NULL;
  5616. while (1) {
  5617. int input;
  5618. input = getch();
  5619. switch (input) {
  5620. case 'h': case 'H': case '?':
  5621. show_help();
  5622. break;
  5623. case 'q': case 'Q':
  5624. kill_work();
  5625. return NULL;
  5626. case 'd': case 'D':
  5627. display_options();
  5628. break;
  5629. case 'm': case 'M':
  5630. manage_device();
  5631. break;
  5632. case 'p': case 'P':
  5633. display_pools();
  5634. break;
  5635. case 's': case 'S':
  5636. set_options();
  5637. break;
  5638. #ifdef HAVE_CURSES
  5639. case KEY_DOWN:
  5640. if (devsummaryYOffset < -(total_lines + devcursor - statusy))
  5641. break;
  5642. devsummaryYOffset -= 2;
  5643. case KEY_UP:
  5644. if (devsummaryYOffset == 0)
  5645. break;
  5646. ++devsummaryYOffset;
  5647. refresh_devstatus();
  5648. break;
  5649. #endif
  5650. }
  5651. if (opt_realquiet) {
  5652. disable_curses();
  5653. break;
  5654. }
  5655. }
  5656. return NULL;
  5657. }
  5658. #endif
  5659. static void *api_thread(void *userdata)
  5660. {
  5661. struct thr_info *mythr = userdata;
  5662. pthread_detach(pthread_self());
  5663. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  5664. RenameThread("rpc");
  5665. api(api_thr_id);
  5666. mythr->has_pth = false;
  5667. return NULL;
  5668. }
  5669. void thread_reportin(struct thr_info *thr)
  5670. {
  5671. cgtime(&thr->last);
  5672. thr->cgpu->status = LIFE_WELL;
  5673. thr->getwork = 0;
  5674. thr->cgpu->device_last_well = time(NULL);
  5675. }
  5676. void thread_reportout(struct thr_info *thr)
  5677. {
  5678. thr->getwork = time(NULL);
  5679. }
  5680. static void hashmeter(int thr_id, struct timeval *diff,
  5681. uint64_t hashes_done)
  5682. {
  5683. char logstatusline[256];
  5684. struct timeval temp_tv_end, total_diff;
  5685. double secs;
  5686. double local_secs;
  5687. static double local_mhashes_done = 0;
  5688. static double rolling = 0;
  5689. double local_mhashes = (double)hashes_done / 1000000.0;
  5690. bool showlog = false;
  5691. char cHr[h2bs_fmt_size[H2B_NOUNIT]], aHr[h2bs_fmt_size[H2B_NOUNIT]], uHr[h2bs_fmt_size[H2B_SPACED]];
  5692. char rejpcbuf[6];
  5693. char bnbuf[6];
  5694. struct thr_info *thr;
  5695. /* Update the last time this thread reported in */
  5696. if (thr_id >= 0) {
  5697. thr = get_thread(thr_id);
  5698. cgtime(&(thr->last));
  5699. thr->cgpu->device_last_well = time(NULL);
  5700. }
  5701. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  5702. /* So we can call hashmeter from a non worker thread */
  5703. if (thr_id >= 0) {
  5704. struct cgpu_info *cgpu = thr->cgpu;
  5705. int threadobj = cgpu->threads ?: 1;
  5706. double thread_rolling = 0.0;
  5707. int i;
  5708. applog(LOG_DEBUG, "[thread %d: %"PRIu64" hashes, %.1f khash/sec]",
  5709. thr_id, hashes_done, hashes_done / 1000 / secs);
  5710. /* Rolling average for each thread and each device */
  5711. decay_time(&thr->rolling, local_mhashes / secs);
  5712. for (i = 0; i < threadobj; i++)
  5713. thread_rolling += cgpu->thr[i]->rolling;
  5714. mutex_lock(&hash_lock);
  5715. decay_time(&cgpu->rolling, thread_rolling);
  5716. cgpu->total_mhashes += local_mhashes;
  5717. mutex_unlock(&hash_lock);
  5718. // If needed, output detailed, per-device stats
  5719. if (want_per_device_stats) {
  5720. struct timeval now;
  5721. struct timeval elapsed;
  5722. struct timeval *last_msg_tv = opt_show_procs ? &thr->cgpu->last_message_tv : &thr->cgpu->device->last_message_tv;
  5723. cgtime(&now);
  5724. timersub(&now, last_msg_tv, &elapsed);
  5725. if (opt_log_interval <= elapsed.tv_sec) {
  5726. struct cgpu_info *cgpu = thr->cgpu;
  5727. char logline[255];
  5728. *last_msg_tv = now;
  5729. get_statline(logline, cgpu);
  5730. if (!curses_active) {
  5731. printf("%s \r", logline);
  5732. fflush(stdout);
  5733. } else
  5734. applog(LOG_INFO, "%s", logline);
  5735. }
  5736. }
  5737. }
  5738. /* Totals are updated by all threads so can race without locking */
  5739. mutex_lock(&hash_lock);
  5740. cgtime(&temp_tv_end);
  5741. timersub(&temp_tv_end, &total_tv_end, &total_diff);
  5742. total_mhashes_done += local_mhashes;
  5743. local_mhashes_done += local_mhashes;
  5744. /* Only update with opt_log_interval */
  5745. if (total_diff.tv_sec < opt_log_interval)
  5746. goto out_unlock;
  5747. showlog = true;
  5748. cgtime(&total_tv_end);
  5749. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  5750. decay_time(&rolling, local_mhashes_done / local_secs);
  5751. global_hashrate = roundl(rolling) * 1000000;
  5752. timersub(&total_tv_end, &total_tv_start, &total_diff);
  5753. total_secs = (double)total_diff.tv_sec +
  5754. ((double)total_diff.tv_usec / 1000000.0);
  5755. multi_format_unit_array(
  5756. ((char*[]){cHr, aHr, uHr}),
  5757. true, "h/s", H2B_SHORT,
  5758. 3,
  5759. 1e6*rolling,
  5760. 1e6*total_mhashes_done / total_secs,
  5761. utility_to_hashrate(total_diff_accepted / (total_secs ?: 1) * 60));
  5762. #ifdef HAVE_CURSES
  5763. if (curses_active_locked()) {
  5764. float temp = 0;
  5765. struct cgpu_info *proc;
  5766. int i, working_devs = 0, working_procs = 0;
  5767. int divx;
  5768. // Find the highest temperature of all processors
  5769. for (i = 0; i < total_devices; ++i)
  5770. {
  5771. proc = get_devices(i);
  5772. if (proc->temp > temp)
  5773. temp = proc->temp;
  5774. if (likely(proc->status == LIFE_WELL && proc->deven == DEV_ENABLED && proc->rolling > .1))
  5775. {
  5776. ++working_procs;
  5777. if (proc->device == proc)
  5778. ++working_devs;
  5779. }
  5780. }
  5781. if (working_devs == working_procs)
  5782. sprintf(statusline, "%d ", working_devs);
  5783. else
  5784. sprintf(statusline, "%d/%d ", working_devs, working_procs);
  5785. divx = 7;
  5786. if (opt_show_procs && !opt_compact)
  5787. ++divx;
  5788. temperature_column_tail(&statusline[divx], true, &temp);
  5789. format_statline(&statusline[15],
  5790. cHr, aHr,
  5791. uHr,
  5792. total_accepted,
  5793. total_rejected,
  5794. total_stale,
  5795. total_diff_rejected + total_diff_stale, total_diff_accepted,
  5796. hw_errors, total_bad_nonces, total_diff1);
  5797. unlock_curses();
  5798. }
  5799. #endif
  5800. // Add a space
  5801. memmove(&uHr[6], &uHr[5], strlen(&uHr[5]) + 1);
  5802. uHr[5] = ' ';
  5803. sprintf(logstatusline, "%s%ds:%s avg:%s u:%s | A:%d R:%d+%d(%s) HW:%d/%s",
  5804. want_per_device_stats ? "ALL " : "",
  5805. opt_log_interval,
  5806. cHr, aHr,
  5807. uHr,
  5808. total_accepted,
  5809. total_rejected,
  5810. total_stale,
  5811. percentf(total_diff_rejected + total_diff_stale, total_diff_accepted, rejpcbuf),
  5812. hw_errors,
  5813. percentf2(total_bad_nonces, total_diff1, bnbuf)
  5814. );
  5815. local_mhashes_done = 0;
  5816. out_unlock:
  5817. mutex_unlock(&hash_lock);
  5818. if (showlog) {
  5819. if (!curses_active) {
  5820. printf("%s \r", logstatusline);
  5821. fflush(stdout);
  5822. } else
  5823. applog(LOG_INFO, "%s", logstatusline);
  5824. }
  5825. }
  5826. void hashmeter2(struct thr_info *thr)
  5827. {
  5828. struct timeval tv_now, tv_elapsed;
  5829. timerclear(&thr->tv_hashes_done);
  5830. cgtime(&tv_now);
  5831. timersub(&tv_now, &thr->tv_lastupdate, &tv_elapsed);
  5832. /* Update the hashmeter at most 5 times per second */
  5833. if (tv_elapsed.tv_sec > 0 || tv_elapsed.tv_usec > 200) {
  5834. hashmeter(thr->id, &tv_elapsed, thr->hashes_done);
  5835. thr->hashes_done = 0;
  5836. thr->tv_lastupdate = tv_now;
  5837. }
  5838. }
  5839. static void stratum_share_result(json_t *val, json_t *res_val, json_t *err_val,
  5840. struct stratum_share *sshare)
  5841. {
  5842. struct work *work = sshare->work;
  5843. share_result(val, res_val, err_val, work, false, "");
  5844. }
  5845. /* Parses stratum json responses and tries to find the id that the request
  5846. * matched to and treat it accordingly. */
  5847. bool parse_stratum_response(struct pool *pool, char *s)
  5848. {
  5849. json_t *val = NULL, *err_val, *res_val, *id_val;
  5850. struct stratum_share *sshare;
  5851. json_error_t err;
  5852. bool ret = false;
  5853. int id;
  5854. val = JSON_LOADS(s, &err);
  5855. if (!val) {
  5856. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  5857. goto out;
  5858. }
  5859. res_val = json_object_get(val, "result");
  5860. err_val = json_object_get(val, "error");
  5861. id_val = json_object_get(val, "id");
  5862. if (json_is_null(id_val) || !id_val) {
  5863. char *ss;
  5864. if (err_val)
  5865. ss = json_dumps(err_val, JSON_INDENT(3));
  5866. else
  5867. ss = strdup("(unknown reason)");
  5868. applog(LOG_INFO, "JSON-RPC non method decode failed: %s", ss);
  5869. free(ss);
  5870. goto out;
  5871. }
  5872. if (!json_is_integer(id_val)) {
  5873. if (json_is_string(id_val)
  5874. && !strncmp(json_string_value(id_val), "txlist", 6)
  5875. && !strcmp(json_string_value(id_val) + 6, pool->swork.job_id)
  5876. && json_is_array(res_val)) {
  5877. // Check that the transactions actually hash to the merkle links
  5878. {
  5879. unsigned maxtx = 1 << pool->swork.merkles;
  5880. unsigned mintx = maxtx >> 1;
  5881. --maxtx;
  5882. unsigned acttx = (unsigned)json_array_size(res_val);
  5883. if (acttx < mintx || acttx > maxtx) {
  5884. applog(LOG_WARNING, "Pool %u is sending mismatched block contents to us (%u is not %u-%u)",
  5885. pool->pool_no, acttx, mintx, maxtx);
  5886. goto fishy;
  5887. }
  5888. // TODO: Check hashes match actual merkle links
  5889. }
  5890. pool_set_opaque(pool, false);
  5891. timer_unset(&pool->swork.tv_transparency);
  5892. fishy:
  5893. ret = true;
  5894. }
  5895. goto out;
  5896. }
  5897. id = json_integer_value(id_val);
  5898. mutex_lock(&sshare_lock);
  5899. HASH_FIND_INT(stratum_shares, &id, sshare);
  5900. if (sshare)
  5901. HASH_DEL(stratum_shares, sshare);
  5902. mutex_unlock(&sshare_lock);
  5903. if (!sshare) {
  5904. double pool_diff;
  5905. /* Since the share is untracked, we can only guess at what the
  5906. * work difficulty is based on the current pool diff. */
  5907. cg_rlock(&pool->data_lock);
  5908. pool_diff = pool->swork.diff;
  5909. cg_runlock(&pool->data_lock);
  5910. if (json_is_true(res_val)) {
  5911. applog(LOG_NOTICE, "Accepted untracked stratum share from pool %d", pool->pool_no);
  5912. /* We don't know what device this came from so we can't
  5913. * attribute the work to the relevant cgpu */
  5914. mutex_lock(&stats_lock);
  5915. total_accepted++;
  5916. pool->accepted++;
  5917. total_diff_accepted += pool_diff;
  5918. pool->diff_accepted += pool_diff;
  5919. mutex_unlock(&stats_lock);
  5920. } else {
  5921. applog(LOG_NOTICE, "Rejected untracked stratum share from pool %d", pool->pool_no);
  5922. mutex_lock(&stats_lock);
  5923. total_rejected++;
  5924. pool->rejected++;
  5925. total_diff_rejected += pool_diff;
  5926. pool->diff_rejected += pool_diff;
  5927. mutex_unlock(&stats_lock);
  5928. }
  5929. goto out;
  5930. }
  5931. else {
  5932. mutex_lock(&submitting_lock);
  5933. --total_submitting;
  5934. mutex_unlock(&submitting_lock);
  5935. }
  5936. stratum_share_result(val, res_val, err_val, sshare);
  5937. free_work(sshare->work);
  5938. free(sshare);
  5939. ret = true;
  5940. out:
  5941. if (val)
  5942. json_decref(val);
  5943. return ret;
  5944. }
  5945. static void shutdown_stratum(struct pool *pool)
  5946. {
  5947. // Shut down Stratum as if we never had it
  5948. pool->stratum_active = false;
  5949. pool->stratum_init = false;
  5950. pool->has_stratum = false;
  5951. shutdown(pool->sock, SHUT_RDWR);
  5952. free(pool->stratum_url);
  5953. if (pool->sockaddr_url == pool->stratum_url)
  5954. pool->sockaddr_url = NULL;
  5955. pool->stratum_url = NULL;
  5956. }
  5957. void clear_stratum_shares(struct pool *pool)
  5958. {
  5959. int my_mining_threads = mining_threads; // Cached outside of locking
  5960. struct stratum_share *sshare, *tmpshare;
  5961. struct work *work;
  5962. struct cgpu_info *cgpu;
  5963. double diff_cleared = 0;
  5964. double thr_diff_cleared[my_mining_threads];
  5965. int cleared = 0;
  5966. int thr_cleared[my_mining_threads];
  5967. // NOTE: This is per-thread rather than per-device to avoid getting devices lock in stratum_shares loop
  5968. for (int i = 0; i < my_mining_threads; ++i)
  5969. {
  5970. thr_diff_cleared[i] = 0;
  5971. thr_cleared[i] = 0;
  5972. }
  5973. mutex_lock(&sshare_lock);
  5974. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  5975. if (sshare->work->pool == pool && work->thr_id < my_mining_threads) {
  5976. HASH_DEL(stratum_shares, sshare);
  5977. work = sshare->work;
  5978. sharelog("disconnect", work);
  5979. diff_cleared += sshare->work->work_difficulty;
  5980. thr_diff_cleared[work->thr_id] += work->work_difficulty;
  5981. ++thr_cleared[work->thr_id];
  5982. free_work(sshare->work);
  5983. free(sshare);
  5984. cleared++;
  5985. }
  5986. }
  5987. mutex_unlock(&sshare_lock);
  5988. if (cleared) {
  5989. applog(LOG_WARNING, "Lost %d shares due to stratum disconnect on pool %d", cleared, pool->pool_no);
  5990. mutex_lock(&stats_lock);
  5991. pool->stale_shares += cleared;
  5992. total_stale += cleared;
  5993. pool->diff_stale += diff_cleared;
  5994. total_diff_stale += diff_cleared;
  5995. for (int i = 0; i < my_mining_threads; ++i)
  5996. if (thr_cleared[i])
  5997. {
  5998. cgpu = get_thr_cgpu(i);
  5999. cgpu->diff_stale += thr_diff_cleared[i];
  6000. cgpu->stale += thr_cleared[i];
  6001. }
  6002. mutex_unlock(&stats_lock);
  6003. mutex_lock(&submitting_lock);
  6004. total_submitting -= cleared;
  6005. mutex_unlock(&submitting_lock);
  6006. }
  6007. }
  6008. static void resubmit_stratum_shares(struct pool *pool)
  6009. {
  6010. struct stratum_share *sshare, *tmpshare;
  6011. struct work *work;
  6012. unsigned resubmitted = 0;
  6013. mutex_lock(&sshare_lock);
  6014. mutex_lock(&submitting_lock);
  6015. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  6016. if (sshare->work->pool != pool)
  6017. continue;
  6018. HASH_DEL(stratum_shares, sshare);
  6019. work = sshare->work;
  6020. DL_APPEND(submit_waiting, work);
  6021. free(sshare);
  6022. ++resubmitted;
  6023. }
  6024. mutex_unlock(&submitting_lock);
  6025. mutex_unlock(&sshare_lock);
  6026. if (resubmitted) {
  6027. notifier_wake(submit_waiting_notifier);
  6028. applog(LOG_DEBUG, "Resubmitting %u shares due to stratum disconnect on pool %u", resubmitted, pool->pool_no);
  6029. }
  6030. }
  6031. static void clear_pool_work(struct pool *pool)
  6032. {
  6033. struct work *work, *tmp;
  6034. int cleared = 0;
  6035. mutex_lock(stgd_lock);
  6036. HASH_ITER(hh, staged_work, work, tmp) {
  6037. if (work->pool == pool) {
  6038. HASH_DEL(staged_work, work);
  6039. free_work(work);
  6040. cleared++;
  6041. staged_full = false;
  6042. }
  6043. }
  6044. mutex_unlock(stgd_lock);
  6045. }
  6046. static int cp_prio(void)
  6047. {
  6048. int prio;
  6049. cg_rlock(&control_lock);
  6050. prio = currentpool->prio;
  6051. cg_runlock(&control_lock);
  6052. return prio;
  6053. }
  6054. /* We only need to maintain a secondary pool connection when we need the
  6055. * capacity to get work from the backup pools while still on the primary */
  6056. static bool cnx_needed(struct pool *pool)
  6057. {
  6058. struct pool *cp;
  6059. if (pool->enabled != POOL_ENABLED)
  6060. return false;
  6061. /* Balance strategies need all pools online */
  6062. if (pool_strategy == POOL_BALANCE)
  6063. return true;
  6064. if (pool_strategy == POOL_LOADBALANCE)
  6065. return true;
  6066. /* Idle stratum pool needs something to kick it alive again */
  6067. if (pool->has_stratum && pool->idle)
  6068. return true;
  6069. /* Getwork pools without opt_fail_only need backup pools up to be able
  6070. * to leak shares */
  6071. cp = current_pool();
  6072. if (cp == pool)
  6073. return true;
  6074. if (!pool_localgen(cp) && (!opt_fail_only || !cp->hdr_path))
  6075. return true;
  6076. /* Keep the connection open to allow any stray shares to be submitted
  6077. * on switching pools for 2 minutes. */
  6078. if (!timer_passed(&pool->tv_last_work_time, NULL))
  6079. return true;
  6080. /* If the pool has only just come to life and is higher priority than
  6081. * the current pool keep the connection open so we can fail back to
  6082. * it. */
  6083. if (pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  6084. return true;
  6085. if (pool_unworkable(cp))
  6086. return true;
  6087. return false;
  6088. }
  6089. static void wait_lpcurrent(struct pool *pool);
  6090. static void pool_resus(struct pool *pool);
  6091. static void gen_stratum_work(struct pool *pool, struct work *work);
  6092. static void stratum_resumed(struct pool *pool)
  6093. {
  6094. if (!pool->stratum_notify)
  6095. return;
  6096. if (pool_tclear(pool, &pool->idle)) {
  6097. applog(LOG_INFO, "Stratum connection to pool %d resumed", pool->pool_no);
  6098. pool_resus(pool);
  6099. }
  6100. }
  6101. static bool supports_resume(struct pool *pool)
  6102. {
  6103. bool ret;
  6104. cg_rlock(&pool->data_lock);
  6105. ret = (pool->sessionid != NULL);
  6106. cg_runlock(&pool->data_lock);
  6107. return ret;
  6108. }
  6109. /* One stratum thread per pool that has stratum waits on the socket checking
  6110. * for new messages and for the integrity of the socket connection. We reset
  6111. * the connection based on the integrity of the receive side only as the send
  6112. * side will eventually expire data it fails to send. */
  6113. static void *stratum_thread(void *userdata)
  6114. {
  6115. struct pool *pool = (struct pool *)userdata;
  6116. pthread_detach(pthread_self());
  6117. char threadname[20];
  6118. snprintf(threadname, 20, "stratum%u", pool->pool_no);
  6119. RenameThread(threadname);
  6120. srand(time(NULL) + (intptr_t)userdata);
  6121. while (42) {
  6122. struct timeval timeout;
  6123. int sel_ret;
  6124. fd_set rd;
  6125. char *s;
  6126. if (unlikely(!pool->has_stratum))
  6127. break;
  6128. /* Check to see whether we need to maintain this connection
  6129. * indefinitely or just bring it up when we switch to this
  6130. * pool */
  6131. if (!sock_full(pool) && !cnx_needed(pool)) {
  6132. suspend_stratum(pool);
  6133. clear_stratum_shares(pool);
  6134. clear_pool_work(pool);
  6135. wait_lpcurrent(pool);
  6136. if (!restart_stratum(pool)) {
  6137. pool_died(pool);
  6138. while (!restart_stratum(pool)) {
  6139. if (pool->removed)
  6140. goto out;
  6141. nmsleep(30000);
  6142. }
  6143. }
  6144. }
  6145. FD_ZERO(&rd);
  6146. FD_SET(pool->sock, &rd);
  6147. timeout.tv_sec = 120;
  6148. timeout.tv_usec = 0;
  6149. /* If we fail to receive any notify messages for 2 minutes we
  6150. * assume the connection has been dropped and treat this pool
  6151. * as dead */
  6152. if (!sock_full(pool) && (sel_ret = select(pool->sock + 1, &rd, NULL, NULL, &timeout)) < 1) {
  6153. applog(LOG_DEBUG, "Stratum select failed on pool %d with value %d", pool->pool_no, sel_ret);
  6154. s = NULL;
  6155. } else
  6156. s = recv_line(pool);
  6157. if (!s) {
  6158. if (!pool->has_stratum)
  6159. break;
  6160. applog(LOG_NOTICE, "Stratum connection to pool %d interrupted", pool->pool_no);
  6161. pool->getfail_occasions++;
  6162. total_go++;
  6163. mutex_lock(&pool->stratum_lock);
  6164. pool->stratum_active = pool->stratum_notify = false;
  6165. pool->sock = INVSOCK;
  6166. mutex_unlock(&pool->stratum_lock);
  6167. /* If the socket to our stratum pool disconnects, all
  6168. * submissions need to be discarded or resent. */
  6169. if (!supports_resume(pool))
  6170. clear_stratum_shares(pool);
  6171. else
  6172. resubmit_stratum_shares(pool);
  6173. clear_pool_work(pool);
  6174. if (pool == current_pool())
  6175. restart_threads();
  6176. if (restart_stratum(pool))
  6177. continue;
  6178. shutdown_stratum(pool);
  6179. pool_died(pool);
  6180. break;
  6181. }
  6182. /* Check this pool hasn't died while being a backup pool and
  6183. * has not had its idle flag cleared */
  6184. stratum_resumed(pool);
  6185. if (!parse_method(pool, s) && !parse_stratum_response(pool, s))
  6186. applog(LOG_INFO, "Unknown stratum msg: %s", s);
  6187. free(s);
  6188. if (pool->swork.clean) {
  6189. struct work *work = make_work();
  6190. /* Generate a single work item to update the current
  6191. * block database */
  6192. pool->swork.clean = false;
  6193. gen_stratum_work(pool, work);
  6194. /* Try to extract block height from coinbase scriptSig */
  6195. uint8_t *bin_height = &bytes_buf(&pool->swork.coinbase)[4 /*version*/ + 1 /*txin count*/ + 36 /*prevout*/ + 1 /*scriptSig len*/ + 1 /*push opcode*/];
  6196. unsigned char cb_height_sz;
  6197. cb_height_sz = bin_height[-1];
  6198. if (cb_height_sz == 3) {
  6199. // FIXME: The block number will overflow this by AD 2173
  6200. uint32_t block_id = ((uint32_t*)work->data)[1];
  6201. uint32_t height = 0;
  6202. memcpy(&height, bin_height, 3);
  6203. height = le32toh(height);
  6204. have_block_height(block_id, height);
  6205. }
  6206. ++pool->work_restart_id;
  6207. if (test_work_current(work)) {
  6208. /* Only accept a work update if this stratum
  6209. * connection is from the current pool */
  6210. if (pool == current_pool()) {
  6211. restart_threads();
  6212. applog(
  6213. (opt_quiet_work_updates ? LOG_DEBUG : LOG_NOTICE),
  6214. "Stratum from pool %d requested work update", pool->pool_no);
  6215. }
  6216. } else
  6217. applog(LOG_NOTICE, "Stratum from pool %d detected new block", pool->pool_no);
  6218. free_work(work);
  6219. }
  6220. if (timer_passed(&pool->swork.tv_transparency, NULL)) {
  6221. // More than 4 timmills past since requested transactions
  6222. timer_unset(&pool->swork.tv_transparency);
  6223. pool_set_opaque(pool, true);
  6224. }
  6225. }
  6226. out:
  6227. return NULL;
  6228. }
  6229. static void init_stratum_thread(struct pool *pool)
  6230. {
  6231. if (unlikely(pthread_create(&pool->stratum_thread, NULL, stratum_thread, (void *)pool)))
  6232. quit(1, "Failed to create stratum thread");
  6233. }
  6234. static void *longpoll_thread(void *userdata);
  6235. static bool stratum_works(struct pool *pool)
  6236. {
  6237. applog(LOG_INFO, "Testing pool %d stratum %s", pool->pool_no, pool->stratum_url);
  6238. if (!extract_sockaddr(pool, pool->stratum_url))
  6239. return false;
  6240. if (pool->stratum_active)
  6241. return true;
  6242. if (!initiate_stratum(pool))
  6243. return false;
  6244. return true;
  6245. }
  6246. static bool pool_active(struct pool *pool, bool pinging)
  6247. {
  6248. struct timeval tv_getwork, tv_getwork_reply;
  6249. bool ret = false;
  6250. json_t *val;
  6251. CURL *curl;
  6252. int rolltime;
  6253. char *rpc_req;
  6254. struct work *work;
  6255. enum pool_protocol proto;
  6256. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  6257. /* This is the central point we activate stratum when we can */
  6258. curl = curl_easy_init();
  6259. if (unlikely(!curl)) {
  6260. applog(LOG_ERR, "CURL initialisation failed");
  6261. return false;
  6262. }
  6263. if (!(want_gbt || want_getwork))
  6264. goto nohttp;
  6265. work = make_work();
  6266. /* Probe for GBT support on first pass */
  6267. proto = want_gbt ? PLP_GETBLOCKTEMPLATE : PLP_GETWORK;
  6268. tryagain:
  6269. rpc_req = prepare_rpc_req_probe(work, proto, NULL);
  6270. work->pool = pool;
  6271. if (!rpc_req)
  6272. goto out;
  6273. pool->probed = false;
  6274. cgtime(&tv_getwork);
  6275. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  6276. true, false, &rolltime, pool, false);
  6277. cgtime(&tv_getwork_reply);
  6278. free(rpc_req);
  6279. /* Detect if a http getwork pool has an X-Stratum header at startup,
  6280. * and if so, switch to that in preference to getwork if it works */
  6281. if (pool->stratum_url && want_stratum && (pool->has_stratum || stratum_works(pool))) {
  6282. if (!pool->has_stratum) {
  6283. applog(LOG_NOTICE, "Switching pool %d %s to %s", pool->pool_no, pool->rpc_url, pool->stratum_url);
  6284. if (!pool->rpc_url)
  6285. pool->rpc_url = strdup(pool->stratum_url);
  6286. pool->has_stratum = true;
  6287. }
  6288. free_work(work);
  6289. if (val)
  6290. json_decref(val);
  6291. retry_stratum:
  6292. curl_easy_cleanup(curl);
  6293. /* We create the stratum thread for each pool just after
  6294. * successful authorisation. Once the init flag has been set
  6295. * we never unset it and the stratum thread is responsible for
  6296. * setting/unsetting the active flag */
  6297. bool init = pool_tset(pool, &pool->stratum_init);
  6298. if (!init) {
  6299. bool ret = initiate_stratum(pool) && auth_stratum(pool);
  6300. if (ret)
  6301. {
  6302. detect_algo = 2;
  6303. init_stratum_thread(pool);
  6304. }
  6305. else
  6306. pool_tclear(pool, &pool->stratum_init);
  6307. return ret;
  6308. }
  6309. return pool->stratum_active;
  6310. }
  6311. else if (pool->has_stratum)
  6312. shutdown_stratum(pool);
  6313. if (val) {
  6314. bool rc;
  6315. json_t *res;
  6316. res = json_object_get(val, "result");
  6317. if ((!json_is_object(res)) || (proto == PLP_GETBLOCKTEMPLATE && !json_object_get(res, "bits")))
  6318. goto badwork;
  6319. work->rolltime = rolltime;
  6320. rc = work_decode(pool, work, val);
  6321. if (rc) {
  6322. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  6323. pool->pool_no, pool->rpc_url);
  6324. work->pool = pool;
  6325. copy_time(&work->tv_getwork, &tv_getwork);
  6326. copy_time(&work->tv_getwork_reply, &tv_getwork_reply);
  6327. work->getwork_mode = GETWORK_MODE_TESTPOOL;
  6328. calc_diff(work, 0);
  6329. update_last_work(work);
  6330. applog(LOG_DEBUG, "Pushing pooltest work to base pool");
  6331. tq_push(control_thr[stage_thr_id].q, work);
  6332. total_getworks++;
  6333. pool->getwork_requested++;
  6334. ret = true;
  6335. cgtime(&pool->tv_idle);
  6336. } else {
  6337. badwork:
  6338. json_decref(val);
  6339. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher work from pool %u %s",
  6340. pool->pool_no, pool->rpc_url);
  6341. pool->proto = proto = pool_protocol_fallback(proto);
  6342. if (PLP_NONE != proto)
  6343. goto tryagain;
  6344. free_work(work);
  6345. goto out;
  6346. }
  6347. json_decref(val);
  6348. if (proto != pool->proto) {
  6349. pool->proto = proto;
  6350. applog(LOG_INFO, "Selected %s protocol for pool %u", pool_protocol_name(proto), pool->pool_no);
  6351. }
  6352. if (pool->lp_url)
  6353. goto out;
  6354. /* Decipher the longpoll URL, if any, and store it in ->lp_url */
  6355. const struct blktmpl_longpoll_req *lp;
  6356. if (work->tmpl && (lp = blktmpl_get_longpoll(work->tmpl))) {
  6357. // NOTE: work_decode takes care of lp id
  6358. pool->lp_url = lp->uri ? absolute_uri(lp->uri, pool->rpc_url) : pool->rpc_url;
  6359. if (!pool->lp_url)
  6360. {
  6361. ret = false;
  6362. goto out;
  6363. }
  6364. pool->lp_proto = PLP_GETBLOCKTEMPLATE;
  6365. }
  6366. else
  6367. if (pool->hdr_path && want_getwork) {
  6368. pool->lp_url = absolute_uri(pool->hdr_path, pool->rpc_url);
  6369. if (!pool->lp_url)
  6370. {
  6371. ret = false;
  6372. goto out;
  6373. }
  6374. pool->lp_proto = PLP_GETWORK;
  6375. } else
  6376. pool->lp_url = NULL;
  6377. if (want_longpoll && !pool->lp_started) {
  6378. pool->lp_started = true;
  6379. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  6380. quit(1, "Failed to create pool longpoll thread");
  6381. }
  6382. } else if (PLP_NONE != (proto = pool_protocol_fallback(proto))) {
  6383. pool->proto = proto;
  6384. goto tryagain;
  6385. } else {
  6386. free_work(work);
  6387. nohttp:
  6388. /* If we failed to parse a getwork, this could be a stratum
  6389. * url without the prefix stratum+tcp:// so let's check it */
  6390. if (extract_sockaddr(pool, pool->rpc_url) && initiate_stratum(pool)) {
  6391. pool->has_stratum = true;
  6392. goto retry_stratum;
  6393. }
  6394. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  6395. pool->pool_no, pool->rpc_url);
  6396. if (!pinging)
  6397. applog(LOG_WARNING, "Pool %u slow/down or URL or credentials invalid", pool->pool_no);
  6398. }
  6399. out:
  6400. curl_easy_cleanup(curl);
  6401. return ret;
  6402. }
  6403. static void pool_resus(struct pool *pool)
  6404. {
  6405. if (pool_strategy == POOL_FAILOVER && pool->prio < cp_prio()) {
  6406. applog(LOG_WARNING, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  6407. switch_pools(NULL);
  6408. } else
  6409. applog(LOG_INFO, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  6410. }
  6411. static struct work *hash_pop(void)
  6412. {
  6413. struct work *work = NULL, *tmp;
  6414. int hc;
  6415. retry:
  6416. mutex_lock(stgd_lock);
  6417. while (!getq->frozen && !HASH_COUNT(staged_work))
  6418. {
  6419. if (unlikely(staged_full))
  6420. {
  6421. if (likely(opt_queue < 10 + mining_threads))
  6422. {
  6423. ++opt_queue;
  6424. applog(LOG_WARNING, "Staged work underrun; increasing queue minimum to %d", opt_queue);
  6425. }
  6426. else
  6427. applog(LOG_WARNING, "Staged work underrun; not automatically increasing above %d", opt_queue);
  6428. staged_full = false; // Let it fill up before triggering an underrun again
  6429. }
  6430. pthread_cond_wait(&getq->cond, stgd_lock);
  6431. }
  6432. hc = HASH_COUNT(staged_work);
  6433. /* Find clone work if possible, to allow masters to be reused */
  6434. if (hc > staged_rollable) {
  6435. HASH_ITER(hh, staged_work, work, tmp) {
  6436. if (!work_rollable(work))
  6437. break;
  6438. }
  6439. } else
  6440. work = staged_work;
  6441. if (can_roll(work) && should_roll(work))
  6442. {
  6443. // Instead of consuming it, force it to be cloned and grab the clone
  6444. mutex_unlock(stgd_lock);
  6445. clone_available();
  6446. goto retry;
  6447. }
  6448. HASH_DEL(staged_work, work);
  6449. if (work_rollable(work))
  6450. staged_rollable--;
  6451. /* Signal the getwork scheduler to look for more work */
  6452. pthread_cond_signal(&gws_cond);
  6453. /* Signal hash_pop again in case there are mutliple hash_pop waiters */
  6454. pthread_cond_signal(&getq->cond);
  6455. mutex_unlock(stgd_lock);
  6456. work->pool->last_work_time = time(NULL);
  6457. cgtime(&work->pool->tv_last_work_time);
  6458. return work;
  6459. }
  6460. /* Clones work by rolling it if possible, and returning a clone instead of the
  6461. * original work item which gets staged again to possibly be rolled again in
  6462. * the future */
  6463. static struct work *clone_work(struct work *work)
  6464. {
  6465. int mrs = mining_threads + opt_queue - total_staged();
  6466. struct work *work_clone;
  6467. bool cloned;
  6468. if (mrs < 1)
  6469. return work;
  6470. cloned = false;
  6471. work_clone = make_clone(work);
  6472. while (mrs-- > 0 && can_roll(work) && should_roll(work)) {
  6473. applog(LOG_DEBUG, "Pushing rolled converted work to stage thread");
  6474. stage_work(work_clone);
  6475. roll_work(work);
  6476. work_clone = make_clone(work);
  6477. /* Roll it again to prevent duplicates should this be used
  6478. * directly later on */
  6479. roll_work(work);
  6480. cloned = true;
  6481. }
  6482. if (cloned) {
  6483. stage_work(work);
  6484. return work_clone;
  6485. }
  6486. free_work(work_clone);
  6487. return work;
  6488. }
  6489. void gen_hash(unsigned char *data, unsigned char *hash, int len)
  6490. {
  6491. unsigned char hash1[32];
  6492. sha2(data, len, hash1);
  6493. sha2(hash1, 32, hash);
  6494. }
  6495. /* Diff 1 is a 256 bit unsigned integer of
  6496. * 0x00000000ffff0000000000000000000000000000000000000000000000000000
  6497. * so we use a big endian 64 bit unsigned integer centred on the 5th byte to
  6498. * cover a huge range of difficulty targets, though not all 256 bits' worth */
  6499. static void bdiff_target_leadzero(unsigned char *target, double diff)
  6500. {
  6501. uint64_t *data64, h64;
  6502. double d64;
  6503. d64 = diffone;
  6504. d64 /= diff;
  6505. d64 = ceil(d64);
  6506. h64 = d64;
  6507. memset(target, 0, 32);
  6508. if (d64 < 18446744073709551616.0) {
  6509. unsigned char *rtarget = target;
  6510. memset(rtarget, 0, 32);
  6511. if (opt_scrypt)
  6512. data64 = (uint64_t *)(rtarget + 2);
  6513. else
  6514. data64 = (uint64_t *)(rtarget + 4);
  6515. *data64 = htobe64(h64);
  6516. } else {
  6517. /* Support for the classic all FFs just-below-1 diff */
  6518. if (opt_scrypt)
  6519. memset(&target[2], 0xff, 30);
  6520. else
  6521. memset(&target[4], 0xff, 28);
  6522. }
  6523. }
  6524. void set_target(unsigned char *dest_target, double diff)
  6525. {
  6526. unsigned char rtarget[32];
  6527. bdiff_target_leadzero(rtarget, diff);
  6528. swab256(dest_target, rtarget);
  6529. if (opt_debug) {
  6530. char htarget[65];
  6531. bin2hex(htarget, rtarget, 32);
  6532. applog(LOG_DEBUG, "Generated target %s", htarget);
  6533. }
  6534. }
  6535. /* Generates stratum based work based on the most recent notify information
  6536. * from the pool. This will keep generating work while a pool is down so we use
  6537. * other means to detect when the pool has died in stratum_thread */
  6538. static void gen_stratum_work(struct pool *pool, struct work *work)
  6539. {
  6540. unsigned char *coinbase, merkle_root[32], merkle_sha[64];
  6541. uint8_t *merkle_bin;
  6542. uint32_t *data32, *swap32;
  6543. int i;
  6544. coinbase = bytes_buf(&pool->swork.coinbase);
  6545. clean_work(work);
  6546. /* Use intermediate lock to update the one pool variable */
  6547. cg_ilock(&pool->data_lock);
  6548. /* Generate coinbase */
  6549. bytes_resize(&work->nonce2, pool->n2size);
  6550. #ifndef __OPTIMIZE__
  6551. if (pool->nonce2sz < pool->n2size)
  6552. memset(&bytes_buf(&work->nonce2)[pool->nonce2sz], 0, pool->n2size - pool->nonce2sz);
  6553. #endif
  6554. memcpy(bytes_buf(&work->nonce2),
  6555. #ifdef WORDS_BIGENDIAN
  6556. // NOTE: On big endian, the most significant bits are stored at the end, so skip the LSBs
  6557. &((char*)&pool->nonce2)[pool->nonce2off],
  6558. #else
  6559. &pool->nonce2,
  6560. #endif
  6561. pool->nonce2sz);
  6562. memcpy(&coinbase[pool->swork.nonce2_offset], bytes_buf(&work->nonce2), pool->n2size);
  6563. pool->nonce2++;
  6564. /* Downgrade to a read lock to read off the pool variables */
  6565. cg_dlock(&pool->data_lock);
  6566. /* Generate merkle root */
  6567. gen_hash(coinbase, merkle_root, bytes_len(&pool->swork.coinbase));
  6568. memcpy(merkle_sha, merkle_root, 32);
  6569. merkle_bin = bytes_buf(&pool->swork.merkle_bin);
  6570. for (i = 0; i < pool->swork.merkles; ++i, merkle_bin += 32) {
  6571. memcpy(merkle_sha + 32, merkle_bin, 32);
  6572. gen_hash(merkle_sha, merkle_root, 64);
  6573. memcpy(merkle_sha, merkle_root, 32);
  6574. }
  6575. data32 = (uint32_t *)merkle_sha;
  6576. swap32 = (uint32_t *)merkle_root;
  6577. flip32(swap32, data32);
  6578. memcpy(&work->data[0], pool->swork.header1, 36);
  6579. memcpy(&work->data[36], merkle_root, 32);
  6580. *((uint32_t*)&work->data[68]) = htobe32(pool->swork.ntime + timer_elapsed(&pool->swork.tv_received, NULL));
  6581. memcpy(&work->data[72], pool->swork.diffbits, 4);
  6582. memset(&work->data[76], 0, 4); // nonce
  6583. memcpy(&work->data[80], workpadding_bin, 48);
  6584. /* Store the stratum work diff to check it still matches the pool's
  6585. * stratum diff when submitting shares */
  6586. work->sdiff = pool->swork.diff;
  6587. /* Copy parameters required for share submission */
  6588. work->job_id = strdup(pool->swork.job_id);
  6589. work->nonce1 = strdup(pool->nonce1);
  6590. cg_runlock(&pool->data_lock);
  6591. if (opt_debug)
  6592. {
  6593. char header[161];
  6594. char nonce2hex[(bytes_len(&work->nonce2) * 2) + 1];
  6595. bin2hex(header, work->data, 80);
  6596. bin2hex(nonce2hex, bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  6597. applog(LOG_DEBUG, "Generated stratum header %s", header);
  6598. applog(LOG_DEBUG, "Work job_id %s nonce2 %s", work->job_id, nonce2hex);
  6599. }
  6600. calc_midstate(work);
  6601. set_target(work->target, work->sdiff);
  6602. local_work++;
  6603. work->pool = pool;
  6604. work->stratum = true;
  6605. work->blk.nonce = 0;
  6606. work->id = total_work++;
  6607. work->longpoll = false;
  6608. work->getwork_mode = GETWORK_MODE_STRATUM;
  6609. work->work_restart_id = work->pool->work_restart_id;
  6610. calc_diff(work, 0);
  6611. cgtime(&work->tv_staged);
  6612. }
  6613. void request_work(struct thr_info *thr)
  6614. {
  6615. struct cgpu_info *cgpu = thr->cgpu;
  6616. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  6617. /* Tell the watchdog thread this thread is waiting on getwork and
  6618. * should not be restarted */
  6619. thread_reportout(thr);
  6620. // HACK: Since get_work still blocks, reportout all processors dependent on this thread
  6621. for (struct cgpu_info *proc = thr->cgpu->next_proc; proc; proc = proc->next_proc)
  6622. {
  6623. if (proc->threads)
  6624. break;
  6625. thread_reportout(proc->thr[0]);
  6626. }
  6627. cgtime(&dev_stats->_get_start);
  6628. }
  6629. // FIXME: Make this non-blocking (and remove HACK above)
  6630. struct work *get_work(struct thr_info *thr)
  6631. {
  6632. const int thr_id = thr->id;
  6633. struct cgpu_info *cgpu = thr->cgpu;
  6634. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  6635. struct cgminer_stats *pool_stats;
  6636. struct timeval tv_get;
  6637. struct work *work = NULL;
  6638. applog(LOG_DEBUG, "%"PRIpreprv": Popping work from get queue to get work", cgpu->proc_repr);
  6639. while (!work) {
  6640. work = hash_pop();
  6641. if (stale_work(work, false)) {
  6642. staged_full = false; // It wasn't really full, since it was stale :(
  6643. discard_work(work);
  6644. work = NULL;
  6645. wake_gws();
  6646. }
  6647. }
  6648. applog(LOG_DEBUG, "%"PRIpreprv": Got work from get queue to get work for thread %d", cgpu->proc_repr, thr_id);
  6649. work->thr_id = thr_id;
  6650. thread_reportin(thr);
  6651. // HACK: Since get_work still blocks, reportin all processors dependent on this thread
  6652. for (struct cgpu_info *proc = thr->cgpu->next_proc; proc; proc = proc->next_proc)
  6653. {
  6654. if (proc->threads)
  6655. break;
  6656. thread_reportin(proc->thr[0]);
  6657. }
  6658. work->mined = true;
  6659. work->blk.nonce = 0;
  6660. cgtime(&tv_get);
  6661. timersub(&tv_get, &dev_stats->_get_start, &tv_get);
  6662. timeradd(&tv_get, &dev_stats->getwork_wait, &dev_stats->getwork_wait);
  6663. if (timercmp(&tv_get, &dev_stats->getwork_wait_max, >))
  6664. dev_stats->getwork_wait_max = tv_get;
  6665. if (timercmp(&tv_get, &dev_stats->getwork_wait_min, <))
  6666. dev_stats->getwork_wait_min = tv_get;
  6667. ++dev_stats->getwork_calls;
  6668. pool_stats = &(work->pool->cgminer_stats);
  6669. timeradd(&tv_get, &pool_stats->getwork_wait, &pool_stats->getwork_wait);
  6670. if (timercmp(&tv_get, &pool_stats->getwork_wait_max, >))
  6671. pool_stats->getwork_wait_max = tv_get;
  6672. if (timercmp(&tv_get, &pool_stats->getwork_wait_min, <))
  6673. pool_stats->getwork_wait_min = tv_get;
  6674. ++pool_stats->getwork_calls;
  6675. return work;
  6676. }
  6677. static
  6678. void _submit_work_async(struct work *work)
  6679. {
  6680. applog(LOG_DEBUG, "Pushing submit work to work thread");
  6681. mutex_lock(&submitting_lock);
  6682. ++total_submitting;
  6683. DL_APPEND(submit_waiting, work);
  6684. mutex_unlock(&submitting_lock);
  6685. notifier_wake(submit_waiting_notifier);
  6686. }
  6687. static void submit_work_async(struct work *work_in, struct timeval *tv_work_found)
  6688. {
  6689. struct work *work = copy_work(work_in);
  6690. if (tv_work_found)
  6691. copy_time(&work->tv_work_found, tv_work_found);
  6692. _submit_work_async(work);
  6693. }
  6694. void inc_hw_errors(struct thr_info *thr, const struct work *work, const uint32_t bad_nonce)
  6695. {
  6696. struct cgpu_info * const cgpu = thr->cgpu;
  6697. if (work)
  6698. applog(LOG_DEBUG, "%"PRIpreprv": invalid nonce (%08lx) - HW error",
  6699. cgpu->proc_repr, (unsigned long)be32toh(bad_nonce));
  6700. mutex_lock(&stats_lock);
  6701. hw_errors++;
  6702. ++cgpu->hw_errors;
  6703. if (work)
  6704. {
  6705. ++total_diff1;
  6706. ++cgpu->diff1;
  6707. ++work->pool->diff1;
  6708. ++total_bad_nonces;
  6709. ++cgpu->bad_nonces;
  6710. }
  6711. mutex_unlock(&stats_lock);
  6712. if (thr->cgpu->drv->hw_error)
  6713. thr->cgpu->drv->hw_error(thr);
  6714. }
  6715. enum test_nonce2_result hashtest2(struct work *work, bool checktarget)
  6716. {
  6717. uint32_t *hash2_32 = (uint32_t *)&work->hash[0];
  6718. hash_data(work->hash, work->data);
  6719. if (hash2_32[7] != 0)
  6720. return TNR_BAD;
  6721. if (!checktarget)
  6722. return TNR_GOOD;
  6723. if (!hash_target_check_v(work->hash, work->target))
  6724. return TNR_HIGH;
  6725. return TNR_GOOD;
  6726. }
  6727. enum test_nonce2_result _test_nonce2(struct work *work, uint32_t nonce, bool checktarget)
  6728. {
  6729. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  6730. *work_nonce = htole32(nonce);
  6731. #ifdef USE_SCRYPT
  6732. if (opt_scrypt)
  6733. // NOTE: Depends on scrypt_test return matching enum values
  6734. return scrypt_test(work->data, work->target, nonce);
  6735. #endif
  6736. return hashtest2(work, checktarget);
  6737. }
  6738. /* Returns true if nonce for work was a valid share */
  6739. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  6740. {
  6741. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  6742. uint32_t bak_nonce = *work_nonce;
  6743. struct timeval tv_work_found;
  6744. enum test_nonce2_result res;
  6745. bool ret = true;
  6746. thread_reportout(thr);
  6747. cgtime(&tv_work_found);
  6748. *work_nonce = htole32(nonce);
  6749. work->thr_id = thr->id;
  6750. /* Do one last check before attempting to submit the work */
  6751. /* Side effect: sets work->data for us */
  6752. res = test_nonce2(work, nonce);
  6753. if (unlikely(res == TNR_BAD))
  6754. {
  6755. inc_hw_errors(thr, work, nonce);
  6756. ret = false;
  6757. goto out;
  6758. }
  6759. mutex_lock(&stats_lock);
  6760. total_diff1++;
  6761. thr->cgpu->diff1++;
  6762. work->pool->diff1++;
  6763. thr->cgpu->last_device_valid_work = time(NULL);
  6764. mutex_unlock(&stats_lock);
  6765. if (res == TNR_HIGH)
  6766. {
  6767. // Share above target, normal
  6768. /* Check the diff of the share, even if it didn't reach the
  6769. * target, just to set the best share value if it's higher. */
  6770. share_diff(work);
  6771. goto out;
  6772. }
  6773. submit_work_async(work, &tv_work_found);
  6774. out:
  6775. *work_nonce = bak_nonce;
  6776. thread_reportin(thr);
  6777. return ret;
  6778. }
  6779. bool abandon_work(struct work *work, struct timeval *wdiff, uint64_t hashes)
  6780. {
  6781. if (wdiff->tv_sec > opt_scantime ||
  6782. work->blk.nonce >= MAXTHREADS - hashes ||
  6783. hashes >= 0xfffffffe ||
  6784. stale_work(work, false))
  6785. return true;
  6786. return false;
  6787. }
  6788. void __thr_being_msg(int prio, struct thr_info *thr, const char *being)
  6789. {
  6790. struct cgpu_info *proc = thr->cgpu;
  6791. if (proc->threads > 1)
  6792. applog(prio, "%"PRIpreprv" (thread %d) %s", proc->proc_repr, thr->id, being);
  6793. else
  6794. applog(prio, "%"PRIpreprv" %s", proc->proc_repr, being);
  6795. }
  6796. void mt_disable_start(struct thr_info *mythr)
  6797. {
  6798. struct cgpu_info *cgpu = mythr->cgpu;
  6799. struct device_drv *drv = cgpu->drv;
  6800. if (drv->thread_disable)
  6801. drv->thread_disable(mythr);
  6802. hashmeter2(mythr);
  6803. if (mythr->prev_work)
  6804. free_work(mythr->prev_work);
  6805. mythr->prev_work = mythr->work;
  6806. mythr->work = NULL;
  6807. mythr->_job_transition_in_progress = false;
  6808. __thr_being_msg(LOG_WARNING, mythr, "being disabled");
  6809. mythr->rolling = mythr->cgpu->rolling = 0;
  6810. thread_reportout(mythr);
  6811. }
  6812. /* Create a hashtable of work items for devices with a queue. The device
  6813. * driver must have a custom queue_full function or it will default to true
  6814. * and put only one work item in the queue. Work items should not be removed
  6815. * from this hashtable until they are no longer in use anywhere. Once a work
  6816. * item is physically queued on the device itself, the work->queued flag
  6817. * should be set under cgpu->qlock write lock to prevent it being dereferenced
  6818. * while still in use. */
  6819. static void fill_queue(struct thr_info *mythr, struct cgpu_info *cgpu, struct device_drv *drv, const int thr_id)
  6820. {
  6821. thread_reportout(mythr);
  6822. do {
  6823. bool need_work;
  6824. rd_lock(&cgpu->qlock);
  6825. need_work = (HASH_COUNT(cgpu->queued_work) == cgpu->queued_count);
  6826. rd_unlock(&cgpu->qlock);
  6827. if (need_work) {
  6828. struct work *work = get_work(mythr);
  6829. wr_lock(&cgpu->qlock);
  6830. HASH_ADD_INT(cgpu->queued_work, id, work);
  6831. wr_unlock(&cgpu->qlock);
  6832. }
  6833. /* The queue_full function should be used by the driver to
  6834. * actually place work items on the physical device if it
  6835. * does have a queue. */
  6836. } while (drv->queue_full && !drv->queue_full(cgpu));
  6837. }
  6838. /* This function is for retrieving one work item from the queued hashtable of
  6839. * available work items that are not yet physically on a device (which is
  6840. * flagged with the work->queued bool). Code using this function must be able
  6841. * to handle NULL as a return which implies there is no work available. */
  6842. struct work *get_queued(struct cgpu_info *cgpu)
  6843. {
  6844. struct work *work, *tmp, *ret = NULL;
  6845. wr_lock(&cgpu->qlock);
  6846. HASH_ITER(hh, cgpu->queued_work, work, tmp) {
  6847. if (!work->queued) {
  6848. work->queued = true;
  6849. cgpu->queued_count++;
  6850. ret = work;
  6851. break;
  6852. }
  6853. }
  6854. wr_unlock(&cgpu->qlock);
  6855. return ret;
  6856. }
  6857. /* This function is for finding an already queued work item in the
  6858. * given que hashtable. Code using this function must be able
  6859. * to handle NULL as a return which implies there is no matching work.
  6860. * The calling function must lock access to the que if it is required.
  6861. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  6862. struct work *__find_work_bymidstate(struct work *que, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  6863. {
  6864. struct work *work, *tmp, *ret = NULL;
  6865. HASH_ITER(hh, que, work, tmp) {
  6866. if (work->queued &&
  6867. memcmp(work->midstate, midstate, midstatelen) == 0 &&
  6868. memcmp(work->data + offset, data, datalen) == 0) {
  6869. ret = work;
  6870. break;
  6871. }
  6872. }
  6873. return ret;
  6874. }
  6875. /* This function is for finding an already queued work item in the
  6876. * device's queued_work hashtable. Code using this function must be able
  6877. * to handle NULL as a return which implies there is no matching work.
  6878. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  6879. struct work *find_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  6880. {
  6881. struct work *ret;
  6882. rd_lock(&cgpu->qlock);
  6883. ret = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  6884. rd_unlock(&cgpu->qlock);
  6885. return ret;
  6886. }
  6887. /* This function should be used by queued device drivers when they're sure
  6888. * the work struct is no longer in use. */
  6889. void work_completed(struct cgpu_info *cgpu, struct work *work)
  6890. {
  6891. wr_lock(&cgpu->qlock);
  6892. if (work->queued)
  6893. cgpu->queued_count--;
  6894. HASH_DEL(cgpu->queued_work, work);
  6895. wr_unlock(&cgpu->qlock);
  6896. free_work(work);
  6897. }
  6898. static void flush_queue(struct cgpu_info *cgpu)
  6899. {
  6900. struct work *work, *tmp;
  6901. int discarded = 0;
  6902. wr_lock(&cgpu->qlock);
  6903. HASH_ITER(hh, cgpu->queued_work, work, tmp) {
  6904. /* Can only discard the work items if they're not physically
  6905. * queued on the device. */
  6906. if (!work->queued) {
  6907. HASH_DEL(cgpu->queued_work, work);
  6908. discard_work(work);
  6909. discarded++;
  6910. }
  6911. }
  6912. wr_unlock(&cgpu->qlock);
  6913. if (discarded)
  6914. applog(LOG_DEBUG, "Discarded %d queued work items", discarded);
  6915. }
  6916. /* This version of hash work is for devices that are fast enough to always
  6917. * perform a full nonce range and need a queue to maintain the device busy.
  6918. * Work creation and destruction is not done from within this function
  6919. * directly. */
  6920. void hash_queued_work(struct thr_info *mythr)
  6921. {
  6922. const long cycle = opt_log_interval / 5 ? : 1;
  6923. struct timeval tv_start = {0, 0}, tv_end;
  6924. struct cgpu_info *cgpu = mythr->cgpu;
  6925. struct device_drv *drv = cgpu->drv;
  6926. const int thr_id = mythr->id;
  6927. int64_t hashes_done = 0;
  6928. while (likely(!cgpu->shutdown)) {
  6929. struct timeval diff;
  6930. int64_t hashes;
  6931. mythr->work_restart = false;
  6932. fill_queue(mythr, cgpu, drv, thr_id);
  6933. thread_reportin(mythr);
  6934. hashes = drv->scanwork(mythr);
  6935. if (unlikely(hashes == -1 )) {
  6936. applog(LOG_ERR, "%s %d failure, disabling!", drv->name, cgpu->device_id);
  6937. cgpu->deven = DEV_DISABLED;
  6938. dev_error(cgpu, REASON_THREAD_ZERO_HASH);
  6939. mt_disable(mythr);
  6940. }
  6941. hashes_done += hashes;
  6942. cgtime(&tv_end);
  6943. timersub(&tv_end, &tv_start, &diff);
  6944. if (diff.tv_sec >= cycle) {
  6945. hashmeter(thr_id, &diff, hashes_done);
  6946. hashes_done = 0;
  6947. copy_time(&tv_start, &tv_end);
  6948. }
  6949. if (unlikely(mythr->pause || cgpu->deven != DEV_ENABLED))
  6950. mt_disable(mythr);
  6951. if (unlikely(mythr->work_restart)) {
  6952. flush_queue(cgpu);
  6953. if (drv->flush_work)
  6954. drv->flush_work(cgpu);
  6955. }
  6956. }
  6957. // cgpu->deven = DEV_DISABLED; set in miner_thread
  6958. }
  6959. void mt_disable_finish(struct thr_info *mythr)
  6960. {
  6961. struct device_drv *drv = mythr->cgpu->drv;
  6962. thread_reportin(mythr);
  6963. __thr_being_msg(LOG_WARNING, mythr, "being re-enabled");
  6964. if (drv->thread_enable)
  6965. drv->thread_enable(mythr);
  6966. }
  6967. void mt_disable(struct thr_info *mythr)
  6968. {
  6969. mt_disable_start(mythr);
  6970. applog(LOG_DEBUG, "Waiting for wakeup notification in miner thread");
  6971. do {
  6972. notifier_read(mythr->notifier);
  6973. } while (mythr->pause);
  6974. mt_disable_finish(mythr);
  6975. }
  6976. enum {
  6977. STAT_SLEEP_INTERVAL = 1,
  6978. STAT_CTR_INTERVAL = 10000000,
  6979. FAILURE_INTERVAL = 30,
  6980. };
  6981. /* Stage another work item from the work returned in a longpoll */
  6982. static void convert_to_work(json_t *val, int rolltime, struct pool *pool, struct work *work, struct timeval *tv_lp, struct timeval *tv_lp_reply)
  6983. {
  6984. bool rc;
  6985. work->rolltime = rolltime;
  6986. rc = work_decode(pool, work, val);
  6987. if (unlikely(!rc)) {
  6988. applog(LOG_ERR, "Could not convert longpoll data to work");
  6989. free_work(work);
  6990. return;
  6991. }
  6992. total_getworks++;
  6993. pool->getwork_requested++;
  6994. work->pool = pool;
  6995. copy_time(&work->tv_getwork, tv_lp);
  6996. copy_time(&work->tv_getwork_reply, tv_lp_reply);
  6997. calc_diff(work, 0);
  6998. if (pool->enabled == POOL_REJECTING)
  6999. work->mandatory = true;
  7000. work->longpoll = true;
  7001. work->getwork_mode = GETWORK_MODE_LP;
  7002. update_last_work(work);
  7003. /* We'll be checking this work item twice, but we already know it's
  7004. * from a new block so explicitly force the new block detection now
  7005. * rather than waiting for it to hit the stage thread. This also
  7006. * allows testwork to know whether LP discovered the block or not. */
  7007. test_work_current(work);
  7008. /* Don't use backup LPs as work if we have failover-only enabled. Use
  7009. * the longpoll work from a pool that has been rejecting shares as a
  7010. * way to detect when the pool has recovered.
  7011. */
  7012. if (pool != current_pool() && opt_fail_only && pool->enabled != POOL_REJECTING) {
  7013. free_work(work);
  7014. return;
  7015. }
  7016. work = clone_work(work);
  7017. applog(LOG_DEBUG, "Pushing converted work to stage thread");
  7018. stage_work(work);
  7019. applog(LOG_DEBUG, "Converted longpoll data to work");
  7020. }
  7021. /* If we want longpoll, enable it for the chosen default pool, or, if
  7022. * the pool does not support longpoll, find the first one that does
  7023. * and use its longpoll support */
  7024. static struct pool *select_longpoll_pool(struct pool *cp)
  7025. {
  7026. int i;
  7027. if (cp->lp_url)
  7028. return cp;
  7029. for (i = 0; i < total_pools; i++) {
  7030. struct pool *pool = pools[i];
  7031. if (pool->has_stratum || pool->lp_url)
  7032. return pool;
  7033. }
  7034. return NULL;
  7035. }
  7036. /* This will make the longpoll thread wait till it's the current pool, or it
  7037. * has been flagged as rejecting, before attempting to open any connections.
  7038. */
  7039. static void wait_lpcurrent(struct pool *pool)
  7040. {
  7041. if (cnx_needed(pool))
  7042. return;
  7043. while (pool->enabled == POOL_DISABLED ||
  7044. (pool != current_pool() && pool_strategy != POOL_LOADBALANCE &&
  7045. pool_strategy != POOL_BALANCE)) {
  7046. mutex_lock(&lp_lock);
  7047. pthread_cond_wait(&lp_cond, &lp_lock);
  7048. mutex_unlock(&lp_lock);
  7049. }
  7050. }
  7051. static curl_socket_t save_curl_socket(void *vpool, __maybe_unused curlsocktype purpose, struct curl_sockaddr *addr) {
  7052. struct pool *pool = vpool;
  7053. curl_socket_t sock = socket(addr->family, addr->socktype, addr->protocol);
  7054. pool->lp_socket = sock;
  7055. return sock;
  7056. }
  7057. static void *longpoll_thread(void *userdata)
  7058. {
  7059. struct pool *cp = (struct pool *)userdata;
  7060. /* This *pool is the source of the actual longpoll, not the pool we've
  7061. * tied it to */
  7062. struct timeval start, reply, end;
  7063. struct pool *pool = NULL;
  7064. char threadname[20];
  7065. CURL *curl = NULL;
  7066. int failures = 0;
  7067. char *lp_url;
  7068. int rolltime;
  7069. #ifndef HAVE_PTHREAD_CANCEL
  7070. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  7071. #endif
  7072. snprintf(threadname, 20, "longpoll%u", cp->pool_no);
  7073. RenameThread(threadname);
  7074. curl = curl_easy_init();
  7075. if (unlikely(!curl)) {
  7076. applog(LOG_ERR, "CURL initialisation failed");
  7077. return NULL;
  7078. }
  7079. retry_pool:
  7080. pool = select_longpoll_pool(cp);
  7081. if (!pool) {
  7082. applog(LOG_WARNING, "No suitable long-poll found for %s", cp->rpc_url);
  7083. while (!pool) {
  7084. nmsleep(60000);
  7085. pool = select_longpoll_pool(cp);
  7086. }
  7087. }
  7088. if (pool->has_stratum) {
  7089. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  7090. cp->rpc_url, pool->rpc_url);
  7091. goto out;
  7092. }
  7093. /* Any longpoll from any pool is enough for this to be true */
  7094. have_longpoll = true;
  7095. wait_lpcurrent(cp);
  7096. {
  7097. lp_url = pool->lp_url;
  7098. if (cp == pool)
  7099. applog(LOG_WARNING, "Long-polling activated for %s (%s)", lp_url, pool_protocol_name(pool->lp_proto));
  7100. else
  7101. applog(LOG_WARNING, "Long-polling activated for %s via %s (%s)", cp->rpc_url, lp_url, pool_protocol_name(pool->lp_proto));
  7102. }
  7103. while (42) {
  7104. json_t *val, *soval;
  7105. struct work *work = make_work();
  7106. char *lpreq;
  7107. lpreq = prepare_rpc_req(work, pool->lp_proto, pool->lp_id);
  7108. work->pool = pool;
  7109. if (!lpreq)
  7110. {
  7111. free_work(work);
  7112. goto lpfail;
  7113. }
  7114. wait_lpcurrent(cp);
  7115. cgtime(&start);
  7116. /* Longpoll connections can be persistent for a very long time
  7117. * and any number of issues could have come up in the meantime
  7118. * so always establish a fresh connection instead of relying on
  7119. * a persistent one. */
  7120. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  7121. curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, save_curl_socket);
  7122. curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, pool);
  7123. val = json_rpc_call(curl, lp_url, pool->rpc_userpass,
  7124. lpreq, false, true, &rolltime, pool, false);
  7125. pool->lp_socket = CURL_SOCKET_BAD;
  7126. cgtime(&reply);
  7127. free(lpreq);
  7128. if (likely(val)) {
  7129. soval = json_object_get(json_object_get(val, "result"), "submitold");
  7130. if (soval)
  7131. pool->submit_old = json_is_true(soval);
  7132. else
  7133. pool->submit_old = false;
  7134. convert_to_work(val, rolltime, pool, work, &start, &reply);
  7135. failures = 0;
  7136. json_decref(val);
  7137. } else {
  7138. /* Some pools regularly drop the longpoll request so
  7139. * only see this as longpoll failure if it happens
  7140. * immediately and just restart it the rest of the
  7141. * time. */
  7142. cgtime(&end);
  7143. free_work(work);
  7144. if (end.tv_sec - start.tv_sec > 30)
  7145. continue;
  7146. if (failures == 1)
  7147. applog(LOG_WARNING, "longpoll failed for %s, retrying every 30s", lp_url);
  7148. lpfail:
  7149. nmsleep(30000);
  7150. }
  7151. if (pool != cp) {
  7152. pool = select_longpoll_pool(cp);
  7153. if (pool->has_stratum) {
  7154. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  7155. cp->rpc_url, pool->rpc_url);
  7156. break;
  7157. }
  7158. if (unlikely(!pool))
  7159. goto retry_pool;
  7160. }
  7161. if (unlikely(pool->removed))
  7162. break;
  7163. }
  7164. out:
  7165. curl_easy_cleanup(curl);
  7166. return NULL;
  7167. }
  7168. static void stop_longpoll(void)
  7169. {
  7170. int i;
  7171. want_longpoll = false;
  7172. for (i = 0; i < total_pools; ++i)
  7173. {
  7174. struct pool *pool = pools[i];
  7175. if (unlikely(!pool->lp_started))
  7176. continue;
  7177. pool->lp_started = false;
  7178. pthread_cancel(pool->longpoll_thread);
  7179. }
  7180. have_longpoll = false;
  7181. }
  7182. static void start_longpoll(void)
  7183. {
  7184. int i;
  7185. want_longpoll = true;
  7186. for (i = 0; i < total_pools; ++i)
  7187. {
  7188. struct pool *pool = pools[i];
  7189. if (unlikely(pool->removed || pool->lp_started || !pool->lp_url))
  7190. continue;
  7191. pool->lp_started = true;
  7192. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  7193. quit(1, "Failed to create pool longpoll thread");
  7194. }
  7195. }
  7196. void reinit_device(struct cgpu_info *cgpu)
  7197. {
  7198. if (cgpu->drv->reinit_device)
  7199. cgpu->drv->reinit_device(cgpu);
  7200. }
  7201. static struct timeval rotate_tv;
  7202. /* We reap curls if they are unused for over a minute */
  7203. static void reap_curl(struct pool *pool)
  7204. {
  7205. struct curl_ent *ent, *iter;
  7206. struct timeval now;
  7207. int reaped = 0;
  7208. cgtime(&now);
  7209. mutex_lock(&pool->pool_lock);
  7210. LL_FOREACH_SAFE(pool->curllist, ent, iter) {
  7211. if (pool->curls < 2)
  7212. break;
  7213. if (now.tv_sec - ent->tv.tv_sec > 300) {
  7214. reaped++;
  7215. pool->curls--;
  7216. LL_DELETE(pool->curllist, ent);
  7217. curl_easy_cleanup(ent->curl);
  7218. free(ent);
  7219. }
  7220. }
  7221. mutex_unlock(&pool->pool_lock);
  7222. if (reaped)
  7223. applog(LOG_DEBUG, "Reaped %d curl%s from pool %d", reaped, reaped > 1 ? "s" : "", pool->pool_no);
  7224. }
  7225. static void *watchpool_thread(void __maybe_unused *userdata)
  7226. {
  7227. int intervals = 0;
  7228. #ifndef HAVE_PTHREAD_CANCEL
  7229. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  7230. #endif
  7231. RenameThread("watchpool");
  7232. while (42) {
  7233. struct timeval now;
  7234. int i;
  7235. if (++intervals > 20)
  7236. intervals = 0;
  7237. cgtime(&now);
  7238. for (i = 0; i < total_pools; i++) {
  7239. struct pool *pool = pools[i];
  7240. if (!opt_benchmark)
  7241. reap_curl(pool);
  7242. /* Get a rolling utility per pool over 10 mins */
  7243. if (intervals > 19) {
  7244. int shares = pool->diff1 - pool->last_shares;
  7245. pool->last_shares = pool->diff1;
  7246. pool->utility = (pool->utility + (double)shares * 0.63) / 1.63;
  7247. pool->shares = pool->utility;
  7248. }
  7249. if (pool->enabled == POOL_DISABLED)
  7250. continue;
  7251. /* Don't start testing any pools if the test threads
  7252. * from startup are still doing their first attempt. */
  7253. if (unlikely(pool->testing)) {
  7254. pthread_join(pool->test_thread, NULL);
  7255. pool->testing = false;
  7256. }
  7257. /* Test pool is idle once every minute */
  7258. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 30) {
  7259. cgtime(&pool->tv_idle);
  7260. if (pool_active(pool, true) && pool_tclear(pool, &pool->idle))
  7261. pool_resus(pool);
  7262. }
  7263. }
  7264. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  7265. cgtime(&rotate_tv);
  7266. switch_pools(NULL);
  7267. }
  7268. nmsleep(30000);
  7269. }
  7270. return NULL;
  7271. }
  7272. void mt_enable(struct thr_info *thr)
  7273. {
  7274. applog(LOG_DEBUG, "Waking up thread %d", thr->id);
  7275. notifier_wake(thr->notifier);
  7276. }
  7277. void proc_enable(struct cgpu_info *cgpu)
  7278. {
  7279. int j;
  7280. cgpu->deven = DEV_ENABLED;
  7281. for (j = cgpu->threads ?: 1; j--; )
  7282. mt_enable(cgpu->thr[j]);
  7283. }
  7284. #define device_recovered(cgpu) proc_enable(cgpu)
  7285. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  7286. * the screen at regular intervals, and restarts threads if they appear to have
  7287. * died. */
  7288. #define WATCHDOG_INTERVAL 2
  7289. #define WATCHDOG_SICK_TIME 60
  7290. #define WATCHDOG_DEAD_TIME 600
  7291. #define WATCHDOG_SICK_COUNT (WATCHDOG_SICK_TIME/WATCHDOG_INTERVAL)
  7292. #define WATCHDOG_DEAD_COUNT (WATCHDOG_DEAD_TIME/WATCHDOG_INTERVAL)
  7293. static void *watchdog_thread(void __maybe_unused *userdata)
  7294. {
  7295. const unsigned int interval = WATCHDOG_INTERVAL;
  7296. struct timeval zero_tv;
  7297. #ifndef HAVE_PTHREAD_CANCEL
  7298. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  7299. #endif
  7300. RenameThread("watchdog");
  7301. memset(&zero_tv, 0, sizeof(struct timeval));
  7302. cgtime(&rotate_tv);
  7303. while (1) {
  7304. int i;
  7305. struct timeval now;
  7306. sleep(interval);
  7307. discard_stale();
  7308. hashmeter(-1, &zero_tv, 0);
  7309. #ifdef HAVE_CURSES
  7310. if (curses_active_locked()) {
  7311. change_logwinsize();
  7312. curses_print_status();
  7313. for (i = 0; i < total_devices; i++)
  7314. curses_print_devstatus(get_devices(i));
  7315. touchwin(statuswin);
  7316. wrefresh(statuswin);
  7317. touchwin(logwin);
  7318. wrefresh(logwin);
  7319. unlock_curses();
  7320. }
  7321. #endif
  7322. cgtime(&now);
  7323. if (!sched_paused && !should_run()) {
  7324. applog(LOG_WARNING, "Pausing execution as per stop time %02d:%02d scheduled",
  7325. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  7326. if (!schedstart.enable) {
  7327. quit(0, "Terminating execution as planned");
  7328. break;
  7329. }
  7330. applog(LOG_WARNING, "Will restart execution as scheduled at %02d:%02d",
  7331. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  7332. sched_paused = true;
  7333. rd_lock(&mining_thr_lock);
  7334. for (i = 0; i < mining_threads; i++)
  7335. mining_thr[i]->pause = true;
  7336. rd_unlock(&mining_thr_lock);
  7337. } else if (sched_paused && should_run()) {
  7338. applog(LOG_WARNING, "Restarting execution as per start time %02d:%02d scheduled",
  7339. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  7340. if (schedstop.enable)
  7341. applog(LOG_WARNING, "Will pause execution as scheduled at %02d:%02d",
  7342. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  7343. sched_paused = false;
  7344. for (i = 0; i < mining_threads; i++) {
  7345. struct thr_info *thr;
  7346. thr = get_thread(i);
  7347. thr->pause = false;
  7348. }
  7349. for (i = 0; i < total_devices; ++i)
  7350. {
  7351. struct cgpu_info *cgpu = get_devices(i);
  7352. /* Don't touch disabled devices */
  7353. if (cgpu->deven == DEV_DISABLED)
  7354. continue;
  7355. proc_enable(cgpu);
  7356. }
  7357. }
  7358. for (i = 0; i < total_devices; ++i) {
  7359. struct cgpu_info *cgpu = get_devices(i);
  7360. struct thr_info *thr = cgpu->thr[0];
  7361. enum dev_enable *denable;
  7362. char *dev_str = cgpu->proc_repr;
  7363. int gpu;
  7364. if (cgpu->drv->get_stats && likely(drv_ready(cgpu)))
  7365. cgpu->drv->get_stats(cgpu);
  7366. gpu = cgpu->device_id;
  7367. denable = &cgpu->deven;
  7368. #ifdef HAVE_ADL
  7369. if (adl_active && cgpu->has_adl)
  7370. gpu_autotune(gpu, denable);
  7371. if (opt_debug && cgpu->has_adl) {
  7372. int engineclock = 0, memclock = 0, activity = 0, fanspeed = 0, fanpercent = 0, powertune = 0;
  7373. float temp = 0, vddc = 0;
  7374. if (gpu_stats(gpu, &temp, &engineclock, &memclock, &vddc, &activity, &fanspeed, &fanpercent, &powertune))
  7375. applog(LOG_DEBUG, "%.1f C F: %d%%(%dRPM) E: %dMHz M: %dMHz V: %.3fV A: %d%% P: %d%%",
  7376. temp, fanpercent, fanspeed, engineclock, memclock, vddc, activity, powertune);
  7377. }
  7378. #endif
  7379. /* Thread is disabled */
  7380. if (*denable == DEV_DISABLED)
  7381. continue;
  7382. else
  7383. if (*denable == DEV_RECOVER_ERR) {
  7384. if (opt_restart && timer_elapsed(&cgpu->tv_device_last_not_well, NULL) > cgpu->reinit_backoff) {
  7385. applog(LOG_NOTICE, "Attempting to reinitialize %s",
  7386. dev_str);
  7387. if (cgpu->reinit_backoff < 300)
  7388. cgpu->reinit_backoff *= 2;
  7389. device_recovered(cgpu);
  7390. }
  7391. continue;
  7392. }
  7393. else
  7394. if (*denable == DEV_RECOVER) {
  7395. if (opt_restart && cgpu->temp < cgpu->targettemp) {
  7396. applog(LOG_NOTICE, "%s recovered to temperature below target, re-enabling",
  7397. dev_str);
  7398. device_recovered(cgpu);
  7399. }
  7400. dev_error(cgpu, REASON_DEV_THERMAL_CUTOFF);
  7401. continue;
  7402. }
  7403. else
  7404. if (cgpu->temp > cgpu->cutofftemp)
  7405. {
  7406. applog(LOG_WARNING, "%s hit thermal cutoff limit, disabling!",
  7407. dev_str);
  7408. *denable = DEV_RECOVER;
  7409. dev_error(cgpu, REASON_DEV_THERMAL_CUTOFF);
  7410. }
  7411. if (thr->getwork) {
  7412. if (cgpu->status == LIFE_WELL && thr->getwork < now.tv_sec - opt_log_interval) {
  7413. int thrid;
  7414. bool cgpu_idle = true;
  7415. thr->rolling = 0;
  7416. for (thrid = 0; thrid < cgpu->threads; ++thrid)
  7417. if (!cgpu->thr[thrid]->getwork)
  7418. cgpu_idle = false;
  7419. if (cgpu_idle) {
  7420. cgpu->rolling = 0;
  7421. cgpu->status = LIFE_WAIT;
  7422. }
  7423. }
  7424. continue;
  7425. }
  7426. else if (cgpu->status == LIFE_WAIT)
  7427. cgpu->status = LIFE_WELL;
  7428. #ifdef WANT_CPUMINE
  7429. if (!strcmp(cgpu->drv->dname, "cpu"))
  7430. continue;
  7431. #endif
  7432. if (cgpu->status != LIFE_WELL && (now.tv_sec - thr->last.tv_sec < WATCHDOG_SICK_TIME)) {
  7433. if (likely(cgpu->status != LIFE_INIT && cgpu->status != LIFE_INIT2))
  7434. applog(LOG_ERR, "%s: Recovered, declaring WELL!", dev_str);
  7435. cgpu->status = LIFE_WELL;
  7436. cgpu->device_last_well = time(NULL);
  7437. } else if (cgpu->status == LIFE_WELL && (now.tv_sec - thr->last.tv_sec > WATCHDOG_SICK_TIME)) {
  7438. thr->rolling = cgpu->rolling = 0;
  7439. cgpu->status = LIFE_SICK;
  7440. applog(LOG_ERR, "%s: Idle for more than 60 seconds, declaring SICK!", dev_str);
  7441. cgtime(&thr->sick);
  7442. dev_error(cgpu, REASON_DEV_SICK_IDLE_60);
  7443. #ifdef HAVE_ADL
  7444. if (adl_active && cgpu->has_adl && gpu_activity(gpu) > 50) {
  7445. applog(LOG_ERR, "GPU still showing activity suggesting a hard hang.");
  7446. applog(LOG_ERR, "Will not attempt to auto-restart it.");
  7447. } else
  7448. #endif
  7449. if (opt_restart) {
  7450. applog(LOG_ERR, "%s: Attempting to restart", dev_str);
  7451. reinit_device(cgpu);
  7452. }
  7453. } else if (cgpu->status == LIFE_SICK && (now.tv_sec - thr->last.tv_sec > WATCHDOG_DEAD_TIME)) {
  7454. cgpu->status = LIFE_DEAD;
  7455. applog(LOG_ERR, "%s: Not responded for more than 10 minutes, declaring DEAD!", dev_str);
  7456. cgtime(&thr->sick);
  7457. dev_error(cgpu, REASON_DEV_DEAD_IDLE_600);
  7458. } else if (now.tv_sec - thr->sick.tv_sec > 60 &&
  7459. (cgpu->status == LIFE_SICK || cgpu->status == LIFE_DEAD)) {
  7460. /* Attempt to restart a GPU that's sick or dead once every minute */
  7461. cgtime(&thr->sick);
  7462. #ifdef HAVE_ADL
  7463. if (adl_active && cgpu->has_adl && gpu_activity(gpu) > 50) {
  7464. /* Again do not attempt to restart a device that may have hard hung */
  7465. } else
  7466. #endif
  7467. if (opt_restart)
  7468. reinit_device(cgpu);
  7469. }
  7470. }
  7471. }
  7472. return NULL;
  7473. }
  7474. static void log_print_status(struct cgpu_info *cgpu)
  7475. {
  7476. char logline[255];
  7477. get_statline(logline, cgpu);
  7478. applog(LOG_WARNING, "%s", logline);
  7479. }
  7480. void print_summary(void)
  7481. {
  7482. struct timeval diff;
  7483. int hours, mins, secs, i;
  7484. double utility, efficiency = 0.0;
  7485. char xfer[17], bw[19];
  7486. int pool_secs;
  7487. timersub(&total_tv_end, &total_tv_start, &diff);
  7488. hours = diff.tv_sec / 3600;
  7489. mins = (diff.tv_sec % 3600) / 60;
  7490. secs = diff.tv_sec % 60;
  7491. utility = total_accepted / total_secs * 60;
  7492. efficiency = total_bytes_xfer ? total_diff_accepted * 2048. / total_bytes_xfer : 0.0;
  7493. applog(LOG_WARNING, "\nSummary of runtime statistics:\n");
  7494. applog(LOG_WARNING, "Started at %s", datestamp);
  7495. if (total_pools == 1)
  7496. applog(LOG_WARNING, "Pool: %s", pools[0]->rpc_url);
  7497. #ifdef WANT_CPUMINE
  7498. if (opt_n_threads)
  7499. applog(LOG_WARNING, "CPU hasher algorithm used: %s", algo_names[opt_algo]);
  7500. #endif
  7501. applog(LOG_WARNING, "Runtime: %d hrs : %d mins : %d secs", hours, mins, secs);
  7502. applog(LOG_WARNING, "Average hashrate: %.1f Megahash/s", total_mhashes_done / total_secs);
  7503. applog(LOG_WARNING, "Solved blocks: %d", found_blocks);
  7504. applog(LOG_WARNING, "Best share difficulty: %s", best_share);
  7505. applog(LOG_WARNING, "Share submissions: %d", total_accepted + total_rejected);
  7506. applog(LOG_WARNING, "Accepted shares: %d", total_accepted);
  7507. applog(LOG_WARNING, "Rejected shares: %d + %d stale (%.2f%%)",
  7508. total_rejected, total_stale,
  7509. (float)(total_rejected + total_stale) / (float)(total_rejected + total_stale + total_accepted)
  7510. );
  7511. applog(LOG_WARNING, "Accepted difficulty shares: %1.f", total_diff_accepted);
  7512. applog(LOG_WARNING, "Rejected difficulty shares: %1.f", total_diff_rejected);
  7513. applog(LOG_WARNING, "Hardware errors: %d", hw_errors);
  7514. applog(LOG_WARNING, "Network transfer: %s (%s)",
  7515. multi_format_unit(xfer, true, "B", H2B_SPACED, " / ", 2,
  7516. (float)total_bytes_rcvd,
  7517. (float)total_bytes_sent),
  7518. multi_format_unit(bw, true, "B/s", H2B_SPACED, " / ", 2,
  7519. (float)(total_bytes_rcvd / total_secs),
  7520. (float)(total_bytes_sent / total_secs)));
  7521. applog(LOG_WARNING, "Efficiency (accepted shares * difficulty / 2 KB): %.2f", efficiency);
  7522. applog(LOG_WARNING, "Utility (accepted shares / min): %.2f/min\n", utility);
  7523. applog(LOG_WARNING, "Unable to get work from server occasions: %d", total_go);
  7524. applog(LOG_WARNING, "Work items generated locally: %d", local_work);
  7525. applog(LOG_WARNING, "Submitting work remotely delay occasions: %d", total_ro);
  7526. applog(LOG_WARNING, "New blocks detected on network: %d\n", new_blocks);
  7527. if (total_pools > 1) {
  7528. for (i = 0; i < total_pools; i++) {
  7529. struct pool *pool = pools[i];
  7530. applog(LOG_WARNING, "Pool: %s", pool->rpc_url);
  7531. if (pool->solved)
  7532. applog(LOG_WARNING, "SOLVED %d BLOCK%s!", pool->solved, pool->solved > 1 ? "S" : "");
  7533. applog(LOG_WARNING, " Share submissions: %d", pool->accepted + pool->rejected);
  7534. applog(LOG_WARNING, " Accepted shares: %d", pool->accepted);
  7535. applog(LOG_WARNING, " Rejected shares: %d + %d stale (%.2f%%)",
  7536. pool->rejected, pool->stale_shares,
  7537. (float)(pool->rejected + pool->stale_shares) / (float)(pool->rejected + pool->stale_shares + pool->accepted)
  7538. );
  7539. applog(LOG_WARNING, " Accepted difficulty shares: %1.f", pool->diff_accepted);
  7540. applog(LOG_WARNING, " Rejected difficulty shares: %1.f", pool->diff_rejected);
  7541. pool_secs = timer_elapsed(&pool->cgminer_stats.start_tv, NULL);
  7542. applog(LOG_WARNING, " Network transfer: %s (%s)",
  7543. multi_format_unit(xfer, true, "B", H2B_SPACED, " / ", 2,
  7544. (float)pool->cgminer_pool_stats.net_bytes_received,
  7545. (float)pool->cgminer_pool_stats.net_bytes_sent),
  7546. multi_format_unit(bw, true, "B/s", H2B_SPACED, " / ", 2,
  7547. (float)(pool->cgminer_pool_stats.net_bytes_received / pool_secs),
  7548. (float)(pool->cgminer_pool_stats.net_bytes_sent / pool_secs)));
  7549. uint64_t pool_bytes_xfer = pool->cgminer_pool_stats.net_bytes_received + pool->cgminer_pool_stats.net_bytes_sent;
  7550. efficiency = pool_bytes_xfer ? pool->diff_accepted * 2048. / pool_bytes_xfer : 0.0;
  7551. applog(LOG_WARNING, " Efficiency (accepted * difficulty / 2 KB): %.2f", efficiency);
  7552. applog(LOG_WARNING, " Unable to get work from server occasions: %d", pool->getfail_occasions);
  7553. applog(LOG_WARNING, " Submitting work remotely delay occasions: %d\n", pool->remotefail_occasions);
  7554. }
  7555. }
  7556. applog(LOG_WARNING, "Summary of per device statistics:\n");
  7557. for (i = 0; i < total_devices; ++i) {
  7558. struct cgpu_info *cgpu = get_devices(i);
  7559. if ((!cgpu->proc_id) && cgpu->next_proc)
  7560. {
  7561. // Device summary line
  7562. opt_show_procs = false;
  7563. log_print_status(cgpu);
  7564. opt_show_procs = true;
  7565. }
  7566. log_print_status(cgpu);
  7567. }
  7568. if (opt_shares) {
  7569. applog(LOG_WARNING, "Mined %d accepted shares of %d requested\n", total_accepted, opt_shares);
  7570. if (opt_shares > total_accepted)
  7571. applog(LOG_WARNING, "WARNING - Mined only %d shares of %d requested.", total_accepted, opt_shares);
  7572. }
  7573. applog(LOG_WARNING, " ");
  7574. fflush(stderr);
  7575. fflush(stdout);
  7576. }
  7577. void _bfg_clean_up(void)
  7578. {
  7579. #ifdef HAVE_OPENCL
  7580. clear_adl(nDevs);
  7581. #endif
  7582. #ifdef HAVE_LIBUSB
  7583. if (likely(have_libusb))
  7584. libusb_exit(NULL);
  7585. #endif
  7586. cgtime(&total_tv_end);
  7587. #ifdef HAVE_CURSES
  7588. disable_curses();
  7589. #endif
  7590. if (!opt_realquiet && successful_connect)
  7591. print_summary();
  7592. if (opt_n_threads)
  7593. free(cpus);
  7594. curl_global_cleanup();
  7595. }
  7596. void _quit(int status)
  7597. {
  7598. if (status) {
  7599. const char *ev = getenv("__BFGMINER_SEGFAULT_ERRQUIT");
  7600. if (unlikely(ev && ev[0] && ev[0] != '0')) {
  7601. int *p = NULL;
  7602. // NOTE debugger can bypass with: p = &p
  7603. *p = status; // Segfault, hopefully dumping core
  7604. }
  7605. }
  7606. #if defined(unix) || defined(__APPLE__)
  7607. if (forkpid > 0) {
  7608. kill(forkpid, SIGTERM);
  7609. forkpid = 0;
  7610. }
  7611. #endif
  7612. exit(status);
  7613. }
  7614. #ifdef HAVE_CURSES
  7615. char *curses_input(const char *query)
  7616. {
  7617. char *input;
  7618. echo();
  7619. input = malloc(255);
  7620. if (!input)
  7621. quit(1, "Failed to malloc input");
  7622. leaveok(logwin, false);
  7623. wlogprint("%s:\n", query);
  7624. wgetnstr(logwin, input, 255);
  7625. if (!strlen(input))
  7626. strcpy(input, "-1");
  7627. leaveok(logwin, true);
  7628. noecho();
  7629. return input;
  7630. }
  7631. #endif
  7632. static bool pools_active = false;
  7633. static void *test_pool_thread(void *arg)
  7634. {
  7635. struct pool *pool = (struct pool *)arg;
  7636. if (pool_active(pool, false)) {
  7637. pool_tset(pool, &pool->lagging);
  7638. pool_tclear(pool, &pool->idle);
  7639. bool first_pool = false;
  7640. cg_wlock(&control_lock);
  7641. if (!pools_active) {
  7642. currentpool = pool;
  7643. if (pool->pool_no != 0)
  7644. first_pool = true;
  7645. pools_active = true;
  7646. }
  7647. cg_wunlock(&control_lock);
  7648. if (unlikely(first_pool))
  7649. applog(LOG_NOTICE, "Switching to pool %d %s - first alive pool", pool->pool_no, pool->rpc_url);
  7650. pool_resus(pool);
  7651. } else
  7652. pool_died(pool);
  7653. return NULL;
  7654. }
  7655. /* Always returns true that the pool details were added unless we are not
  7656. * live, implying this is the only pool being added, so if no pools are
  7657. * active it returns false. */
  7658. bool add_pool_details(struct pool *pool, bool live, char *url, char *user, char *pass)
  7659. {
  7660. pool->rpc_url = url;
  7661. pool->rpc_user = user;
  7662. pool->rpc_pass = pass;
  7663. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  7664. if (!pool->rpc_userpass)
  7665. quit(1, "Failed to malloc userpass");
  7666. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  7667. pool->testing = true;
  7668. pool->idle = true;
  7669. enable_pool(pool);
  7670. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  7671. if (!live) {
  7672. pthread_join(pool->test_thread, NULL);
  7673. pool->testing = false;
  7674. return pools_active;
  7675. }
  7676. return true;
  7677. }
  7678. #ifdef HAVE_CURSES
  7679. static bool input_pool(bool live)
  7680. {
  7681. char *url = NULL, *user = NULL, *pass = NULL;
  7682. struct pool *pool;
  7683. bool ret = false;
  7684. immedok(logwin, true);
  7685. wlogprint("Input server details.\n");
  7686. url = curses_input("URL");
  7687. if (!url)
  7688. goto out;
  7689. user = curses_input("Username");
  7690. if (!user)
  7691. goto out;
  7692. pass = curses_input("Password");
  7693. if (!pass)
  7694. goto out;
  7695. pool = add_pool();
  7696. if (!detect_stratum(pool, url) && strncmp(url, "http://", 7) &&
  7697. strncmp(url, "https://", 8)) {
  7698. char *httpinput;
  7699. httpinput = malloc(256);
  7700. if (!httpinput)
  7701. quit(1, "Failed to malloc httpinput");
  7702. strcpy(httpinput, "http://");
  7703. strncat(httpinput, url, 248);
  7704. free(url);
  7705. url = httpinput;
  7706. }
  7707. ret = add_pool_details(pool, live, url, user, pass);
  7708. out:
  7709. immedok(logwin, false);
  7710. if (!ret) {
  7711. if (url)
  7712. free(url);
  7713. if (user)
  7714. free(user);
  7715. if (pass)
  7716. free(pass);
  7717. }
  7718. return ret;
  7719. }
  7720. #endif
  7721. #if defined(unix) || defined(__APPLE__)
  7722. static void fork_monitor()
  7723. {
  7724. // Make a pipe: [readFD, writeFD]
  7725. int pfd[2];
  7726. int r = pipe(pfd);
  7727. if (r < 0) {
  7728. perror("pipe - failed to create pipe for --monitor");
  7729. exit(1);
  7730. }
  7731. // Make stderr write end of pipe
  7732. fflush(stderr);
  7733. r = dup2(pfd[1], 2);
  7734. if (r < 0) {
  7735. perror("dup2 - failed to alias stderr to write end of pipe for --monitor");
  7736. exit(1);
  7737. }
  7738. r = close(pfd[1]);
  7739. if (r < 0) {
  7740. perror("close - failed to close write end of pipe for --monitor");
  7741. exit(1);
  7742. }
  7743. // Don't allow a dying monitor to kill the main process
  7744. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  7745. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  7746. if (SIG_ERR == sr0 || SIG_ERR == sr1) {
  7747. perror("signal - failed to edit signal mask for --monitor");
  7748. exit(1);
  7749. }
  7750. // Fork a child process
  7751. forkpid = fork();
  7752. if (forkpid < 0) {
  7753. perror("fork - failed to fork child process for --monitor");
  7754. exit(1);
  7755. }
  7756. // Child: launch monitor command
  7757. if (0 == forkpid) {
  7758. // Make stdin read end of pipe
  7759. r = dup2(pfd[0], 0);
  7760. if (r < 0) {
  7761. perror("dup2 - in child, failed to alias read end of pipe to stdin for --monitor");
  7762. exit(1);
  7763. }
  7764. close(pfd[0]);
  7765. if (r < 0) {
  7766. perror("close - in child, failed to close read end of pipe for --monitor");
  7767. exit(1);
  7768. }
  7769. // Launch user specified command
  7770. execl("/bin/bash", "/bin/bash", "-c", opt_stderr_cmd, (char*)NULL);
  7771. perror("execl - in child failed to exec user specified command for --monitor");
  7772. exit(1);
  7773. }
  7774. // Parent: clean up unused fds and bail
  7775. r = close(pfd[0]);
  7776. if (r < 0) {
  7777. perror("close - failed to close read end of pipe for --monitor");
  7778. exit(1);
  7779. }
  7780. }
  7781. #endif // defined(unix)
  7782. #ifdef HAVE_CURSES
  7783. void enable_curses(void) {
  7784. int x;
  7785. __maybe_unused int y;
  7786. lock_curses();
  7787. if (curses_active) {
  7788. unlock_curses();
  7789. return;
  7790. }
  7791. if (use_unicode)
  7792. setlocale(LC_CTYPE, "");
  7793. mainwin = initscr();
  7794. start_color();
  7795. if (has_colors() && ERR != init_pair(1, COLOR_WHITE, COLOR_BLUE))
  7796. menu_attr = COLOR_PAIR(1);
  7797. keypad(mainwin, true);
  7798. getmaxyx(mainwin, y, x);
  7799. statuswin = newwin(logstart, x, 0, 0);
  7800. leaveok(statuswin, true);
  7801. // For whatever reason, PDCurses crashes if the logwin is initialized to height y-logcursor
  7802. // We resize the window later anyway, so just start it off at 1 :)
  7803. logwin = newwin(1, 0, logcursor, 0);
  7804. idlok(logwin, true);
  7805. scrollok(logwin, true);
  7806. leaveok(logwin, true);
  7807. cbreak();
  7808. noecho();
  7809. nonl();
  7810. curses_active = true;
  7811. statusy = logstart;
  7812. unlock_curses();
  7813. }
  7814. #endif
  7815. /* TODO: fix need a dummy CPU device_drv even if no support for CPU mining */
  7816. #ifndef WANT_CPUMINE
  7817. struct device_drv cpu_drv;
  7818. struct device_drv cpu_drv = {
  7819. .name = "CPU",
  7820. };
  7821. #endif
  7822. #ifdef USE_BITFORCE
  7823. extern struct device_drv bitforce_drv;
  7824. #endif
  7825. #ifdef USE_ICARUS
  7826. extern struct device_drv cairnsmore_drv;
  7827. extern struct device_drv erupter_drv;
  7828. extern struct device_drv icarus_drv;
  7829. #endif
  7830. #ifdef USE_AVALON
  7831. extern struct device_drv avalon_drv;
  7832. #endif
  7833. #ifdef USE_MODMINER
  7834. extern struct device_drv modminer_drv;
  7835. #endif
  7836. #ifdef USE_X6500
  7837. extern struct device_drv x6500_api;
  7838. #endif
  7839. #ifdef USE_ZTEX
  7840. extern struct device_drv ztex_drv;
  7841. #endif
  7842. static int cgminer_id_count = 0;
  7843. static int device_line_id_count;
  7844. void register_device(struct cgpu_info *cgpu)
  7845. {
  7846. cgpu->deven = DEV_ENABLED;
  7847. wr_lock(&devices_lock);
  7848. devices[cgpu->cgminer_id = cgminer_id_count++] = cgpu;
  7849. wr_unlock(&devices_lock);
  7850. if (!cgpu->proc_id)
  7851. cgpu->device_line_id = device_line_id_count++;
  7852. mining_threads += cgpu->threads ?: 1;
  7853. #ifdef HAVE_CURSES
  7854. adj_width(mining_threads, &dev_width);
  7855. #endif
  7856. #ifdef HAVE_OPENCL
  7857. if (cgpu->drv == &opencl_api) {
  7858. gpu_threads += cgpu->threads;
  7859. }
  7860. #endif
  7861. rwlock_init(&cgpu->qlock);
  7862. cgpu->queued_work = NULL;
  7863. }
  7864. struct _cgpu_devid_counter {
  7865. char name[4];
  7866. int lastid;
  7867. UT_hash_handle hh;
  7868. };
  7869. void renumber_cgpu(struct cgpu_info *cgpu)
  7870. {
  7871. static struct _cgpu_devid_counter *devids = NULL;
  7872. struct _cgpu_devid_counter *d;
  7873. HASH_FIND_STR(devids, cgpu->drv->name, d);
  7874. if (d)
  7875. cgpu->device_id = ++d->lastid;
  7876. else {
  7877. d = malloc(sizeof(*d));
  7878. memcpy(d->name, cgpu->drv->name, sizeof(d->name));
  7879. cgpu->device_id = d->lastid = 0;
  7880. HASH_ADD_STR(devids, name, d);
  7881. }
  7882. }
  7883. static bool my_blkmaker_sha256_callback(void *digest, const void *buffer, size_t length)
  7884. {
  7885. sha2(buffer, length, digest);
  7886. return true;
  7887. }
  7888. #ifndef HAVE_PTHREAD_CANCEL
  7889. extern void setup_pthread_cancel_workaround();
  7890. extern struct sigaction pcwm_orig_term_handler;
  7891. #endif
  7892. static
  7893. void drv_detect_all()
  7894. {
  7895. #ifdef USE_X6500
  7896. if (likely(have_libusb))
  7897. ft232r_scan();
  7898. #endif
  7899. #ifdef HAVE_OPENCL
  7900. if (!opt_nogpu)
  7901. opencl_api.drv_detect();
  7902. gpu_threads = 0;
  7903. #endif
  7904. #ifdef USE_ICARUS
  7905. if (!opt_scrypt)
  7906. {
  7907. cairnsmore_drv.drv_detect();
  7908. erupter_drv.drv_detect();
  7909. icarus_drv.drv_detect();
  7910. }
  7911. #endif
  7912. #ifdef USE_BITFORCE
  7913. if (!opt_scrypt)
  7914. bitforce_drv.drv_detect();
  7915. #endif
  7916. #ifdef USE_MODMINER
  7917. if (!opt_scrypt)
  7918. modminer_drv.drv_detect();
  7919. #endif
  7920. #ifdef USE_X6500
  7921. if (likely(have_libusb) && !opt_scrypt)
  7922. x6500_api.drv_detect();
  7923. #endif
  7924. #ifdef USE_ZTEX
  7925. if (likely(have_libusb) && !opt_scrypt)
  7926. ztex_drv.drv_detect();
  7927. #endif
  7928. /* Detect avalon last since it will try to claim the device regardless
  7929. * as detection is unreliable. */
  7930. #ifdef USE_AVALON
  7931. if (!opt_scrypt)
  7932. avalon_drv.drv_detect();
  7933. #endif
  7934. #ifdef WANT_CPUMINE
  7935. cpu_drv.drv_detect();
  7936. #endif
  7937. #ifdef USE_X6500
  7938. if (likely(have_libusb))
  7939. ft232r_scan_free();
  7940. #endif
  7941. }
  7942. static
  7943. void allocate_cgpu(struct cgpu_info *cgpu, unsigned int *kp)
  7944. {
  7945. struct thr_info *thr;
  7946. int j;
  7947. struct device_drv *api = cgpu->drv;
  7948. if (!cgpu->devtype)
  7949. cgpu->devtype = "PGA";
  7950. cgpu->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  7951. int threadobj = cgpu->threads;
  7952. if (!threadobj)
  7953. // Create a fake thread object to handle hashmeter etc
  7954. threadobj = 1;
  7955. cgpu->thr = calloc(threadobj + 1, sizeof(*cgpu->thr));
  7956. cgpu->thr[threadobj] = NULL;
  7957. cgpu->status = LIFE_INIT;
  7958. cgpu->max_hashes = 0;
  7959. // Setup thread structs before starting any of the threads, in case they try to interact
  7960. for (j = 0; j < threadobj; ++j, ++*kp) {
  7961. thr = get_thread(*kp);
  7962. thr->id = *kp;
  7963. thr->cgpu = cgpu;
  7964. thr->device_thread = j;
  7965. thr->work_restart_notifier[1] = INVSOCK;
  7966. thr->mutex_request[1] = INVSOCK;
  7967. thr->_job_transition_in_progress = true;
  7968. timerclear(&thr->tv_morework);
  7969. thr->_last_sbr_state = true;
  7970. thr->scanhash_working = true;
  7971. thr->hashes_done = 0;
  7972. timerclear(&thr->tv_hashes_done);
  7973. cgtime(&thr->tv_lastupdate);
  7974. thr->tv_poll.tv_sec = -1;
  7975. thr->_max_nonce = api->can_limit_work ? api->can_limit_work(thr) : 0xffffffff;
  7976. cgpu->thr[j] = thr;
  7977. }
  7978. if (!cgpu->threads)
  7979. memcpy(&cgpu->thr[0]->notifier, &cgpu->device->thr[0]->notifier, sizeof(cgpu->thr[0]->notifier));
  7980. else
  7981. for (j = 0; j < cgpu->threads; ++j)
  7982. {
  7983. thr = cgpu->thr[j];
  7984. notifier_init(thr->notifier);
  7985. }
  7986. }
  7987. static
  7988. void start_cgpu(struct cgpu_info *cgpu)
  7989. {
  7990. struct thr_info *thr;
  7991. int j;
  7992. for (j = 0; j < cgpu->threads; ++j) {
  7993. thr = cgpu->thr[j];
  7994. /* Enable threads for devices set not to mine but disable
  7995. * their queue in case we wish to enable them later */
  7996. if (cgpu->drv->thread_prepare && !cgpu->drv->thread_prepare(thr))
  7997. continue;
  7998. thread_reportout(thr);
  7999. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  8000. quit(1, "thread %d create failed", thr->id);
  8001. }
  8002. if (cgpu->deven == DEV_ENABLED)
  8003. proc_enable(cgpu);
  8004. }
  8005. int scan_serial(const char *s)
  8006. {
  8007. static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  8008. struct string_elist *orig_scan_devices;
  8009. int devcount, i, mining_threads_new = 0;
  8010. unsigned int k;
  8011. struct string_elist *iter, *tmp;
  8012. struct cgpu_info *cgpu;
  8013. struct thr_info *thr;
  8014. void *p;
  8015. char *dummy = "\0";
  8016. mutex_lock(&mutex);
  8017. orig_scan_devices = scan_devices;
  8018. devcount = total_devices;
  8019. if (s)
  8020. {
  8021. // Make temporary scan_devices list
  8022. scan_devices = NULL;
  8023. string_elist_add("noauto", &scan_devices);
  8024. string_elist_add(s, &scan_devices);
  8025. }
  8026. drv_detect_all();
  8027. wr_lock(&devices_lock);
  8028. p = realloc(devices, sizeof(struct cgpu_info *) * (total_devices + total_devices_new + 1));
  8029. if (unlikely(!p))
  8030. {
  8031. wr_unlock(&devices_lock);
  8032. applog(LOG_ERR, "scan_serial: realloc failed trying to grow devices array");
  8033. goto out;
  8034. }
  8035. devices = p;
  8036. wr_unlock(&devices_lock);
  8037. for (i = 0; i < total_devices_new; ++i)
  8038. {
  8039. cgpu = devices_new[i];
  8040. mining_threads_new += cgpu->threads ?: 1;
  8041. }
  8042. wr_lock(&mining_thr_lock);
  8043. mining_threads_new += mining_threads;
  8044. p = realloc(mining_thr, sizeof(struct thr_info *) * mining_threads_new);
  8045. if (unlikely(!p))
  8046. {
  8047. wr_unlock(&mining_thr_lock);
  8048. applog(LOG_ERR, "scan_serial: realloc failed trying to grow mining_thr");
  8049. goto out;
  8050. }
  8051. mining_thr = p;
  8052. wr_unlock(&mining_thr_lock);
  8053. for (i = mining_threads; i < mining_threads_new; ++i) {
  8054. mining_thr[i] = calloc(1, sizeof(*thr));
  8055. if (!mining_thr[i])
  8056. {
  8057. applog(LOG_ERR, "scan_serial: Failed to calloc mining_thr[%d]", i);
  8058. for ( ; --i >= mining_threads; )
  8059. free(mining_thr[i]);
  8060. goto out;
  8061. }
  8062. }
  8063. k = mining_threads;
  8064. for (i = 0; i < total_devices_new; ++i)
  8065. {
  8066. cgpu = devices_new[i];
  8067. load_temp_config_cgpu(cgpu, &dummy, &dummy);
  8068. allocate_cgpu(cgpu, &k);
  8069. start_cgpu(cgpu);
  8070. register_device(cgpu);
  8071. ++total_devices;
  8072. }
  8073. #ifdef HAVE_CURSES
  8074. switch_logsize();
  8075. #endif
  8076. out:
  8077. if (s)
  8078. {
  8079. DL_FOREACH_SAFE(scan_devices, iter, tmp)
  8080. {
  8081. string_elist_del(&scan_devices, iter);
  8082. }
  8083. scan_devices = orig_scan_devices;
  8084. }
  8085. total_devices_new = 0;
  8086. devcount = total_devices - devcount;
  8087. mutex_unlock(&mutex);
  8088. return devcount;
  8089. }
  8090. static void probe_pools(void)
  8091. {
  8092. int i;
  8093. for (i = 0; i < total_pools; i++) {
  8094. struct pool *pool = pools[i];
  8095. pool->testing = true;
  8096. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  8097. }
  8098. }
  8099. static void raise_fd_limits(void)
  8100. {
  8101. #ifdef HAVE_SETRLIMIT
  8102. struct rlimit fdlimit;
  8103. unsigned long old_soft_limit;
  8104. if (getrlimit(RLIMIT_NOFILE, &fdlimit))
  8105. applogr(, LOG_DEBUG, "setrlimit: Failed to getrlimit(RLIMIT_NOFILE)");
  8106. if (fdlimit.rlim_cur == RLIM_INFINITY)
  8107. applogr(, LOG_DEBUG, "setrlimit: Soft fd limit already infinite");
  8108. if (fdlimit.rlim_cur == fdlimit.rlim_max)
  8109. applogr(, LOG_DEBUG, "setrlimit: Soft fd limit already identical to hard limit (%lu)", (unsigned long)fdlimit.rlim_max);
  8110. old_soft_limit = fdlimit.rlim_cur;
  8111. fdlimit.rlim_cur = fdlimit.rlim_max;
  8112. if (setrlimit(RLIMIT_NOFILE, &fdlimit))
  8113. applogr(, LOG_DEBUG, "setrlimit: Failed to increase soft fd limit from %lu to hard limit of %lu", old_soft_limit, (unsigned long)fdlimit.rlim_max);
  8114. applog(LOG_DEBUG, "setrlimit: Increased soft fd limit from %lu to hard limit of %lu", old_soft_limit, (unsigned long)fdlimit.rlim_max);
  8115. #else
  8116. applog(LOG_DEBUG, "setrlimit: Not supported by platform");
  8117. #endif
  8118. }
  8119. extern void bfg_init_threadlocal();
  8120. int main(int argc, char *argv[])
  8121. {
  8122. struct sigaction handler;
  8123. struct thr_info *thr;
  8124. struct block *block;
  8125. unsigned int k;
  8126. int i;
  8127. char *s;
  8128. #ifdef WIN32
  8129. LoadLibrary("backtrace.dll");
  8130. #endif
  8131. blkmk_sha256_impl = my_blkmaker_sha256_callback;
  8132. bfg_init_threadlocal();
  8133. #ifndef HAVE_PTHREAD_CANCEL
  8134. setup_pthread_cancel_workaround();
  8135. #endif
  8136. /* This dangerous functions tramples random dynamically allocated
  8137. * variables so do it before anything at all */
  8138. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  8139. quit(1, "Failed to curl_global_init");
  8140. initial_args = malloc(sizeof(char *) * (argc + 1));
  8141. for (i = 0; i < argc; i++)
  8142. initial_args[i] = strdup(argv[i]);
  8143. initial_args[argc] = NULL;
  8144. #ifdef HAVE_LIBUSB
  8145. int err = libusb_init(NULL);
  8146. if (err) {
  8147. applog(LOG_WARNING, "libusb_init() failed err %d", err);
  8148. have_libusb = false;
  8149. }
  8150. #endif
  8151. mutex_init(&hash_lock);
  8152. mutex_init(&console_lock);
  8153. cglock_init(&control_lock);
  8154. mutex_init(&stats_lock);
  8155. mutex_init(&sharelog_lock);
  8156. cglock_init(&ch_lock);
  8157. mutex_init(&sshare_lock);
  8158. rwlock_init(&blk_lock);
  8159. rwlock_init(&netacc_lock);
  8160. rwlock_init(&mining_thr_lock);
  8161. rwlock_init(&devices_lock);
  8162. mutex_init(&lp_lock);
  8163. if (unlikely(pthread_cond_init(&lp_cond, NULL)))
  8164. quit(1, "Failed to pthread_cond_init lp_cond");
  8165. if (unlikely(pthread_cond_init(&gws_cond, NULL)))
  8166. quit(1, "Failed to pthread_cond_init gws_cond");
  8167. notifier_init(submit_waiting_notifier);
  8168. sprintf(packagename, "%s %s", PACKAGE, VERSION);
  8169. #ifdef WANT_CPUMINE
  8170. init_max_name_len();
  8171. #endif
  8172. handler.sa_handler = &sighandler;
  8173. handler.sa_flags = 0;
  8174. sigemptyset(&handler.sa_mask);
  8175. #ifdef HAVE_PTHREAD_CANCEL
  8176. sigaction(SIGTERM, &handler, &termhandler);
  8177. #else
  8178. // Need to let pthread_cancel emulation handle SIGTERM first
  8179. termhandler = pcwm_orig_term_handler;
  8180. pcwm_orig_term_handler = handler;
  8181. #endif
  8182. sigaction(SIGINT, &handler, &inthandler);
  8183. #ifndef WIN32
  8184. signal(SIGPIPE, SIG_IGN);
  8185. #endif
  8186. opt_kernel_path = alloca(PATH_MAX);
  8187. strcpy(opt_kernel_path, CGMINER_PREFIX);
  8188. cgminer_path = alloca(PATH_MAX);
  8189. s = strdup(argv[0]);
  8190. strcpy(cgminer_path, dirname(s));
  8191. free(s);
  8192. strcat(cgminer_path, "/");
  8193. #ifdef WANT_CPUMINE
  8194. // Hack to make cgminer silent when called recursively on WIN32
  8195. int skip_to_bench = 0;
  8196. #if defined(WIN32)
  8197. char buf[32];
  8198. if (GetEnvironmentVariable("BFGMINER_BENCH_ALGO", buf, 16))
  8199. skip_to_bench = 1;
  8200. if (GetEnvironmentVariable("CGMINER_BENCH_ALGO", buf, 16))
  8201. skip_to_bench = 1;
  8202. #endif // defined(WIN32)
  8203. #endif
  8204. devcursor = 8;
  8205. logstart = devcursor;
  8206. logcursor = logstart;
  8207. block = calloc(sizeof(struct block), 1);
  8208. if (unlikely(!block))
  8209. quit (1, "main OOM");
  8210. for (i = 0; i < 36; i++)
  8211. strcat(block->hash, "0");
  8212. HASH_ADD_STR(blocks, hash, block);
  8213. strcpy(current_block, block->hash);
  8214. mutex_init(&submitting_lock);
  8215. #ifdef HAVE_OPENCL
  8216. memset(gpus, 0, sizeof(gpus));
  8217. for (i = 0; i < MAX_GPUDEVICES; i++)
  8218. gpus[i].dynamic = true;
  8219. #endif
  8220. schedstart.tm.tm_sec = 1;
  8221. schedstop .tm.tm_sec = 1;
  8222. /* parse command line */
  8223. opt_register_table(opt_config_table,
  8224. "Options for both config file and command line");
  8225. opt_register_table(opt_cmdline_table,
  8226. "Options for command line only");
  8227. opt_parse(&argc, argv, applog_and_exit);
  8228. if (argc != 1)
  8229. quit(1, "Unexpected extra commandline arguments");
  8230. if (!config_loaded)
  8231. load_default_config();
  8232. #ifndef HAVE_PTHREAD_CANCEL
  8233. // Can't do this any earlier, or config isn't loaded
  8234. applog(LOG_DEBUG, "pthread_cancel workaround in use");
  8235. #endif
  8236. raise_fd_limits();
  8237. bfg_init_time();
  8238. if (opt_benchmark) {
  8239. struct pool *pool;
  8240. want_longpoll = false;
  8241. pool = add_pool();
  8242. pool->rpc_url = malloc(255);
  8243. strcpy(pool->rpc_url, "Benchmark");
  8244. pool->rpc_user = pool->rpc_url;
  8245. pool->rpc_pass = pool->rpc_url;
  8246. enable_pool(pool);
  8247. pool->idle = false;
  8248. successful_connect = true;
  8249. }
  8250. test_intrange();
  8251. #ifdef HAVE_CURSES
  8252. if (opt_realquiet || opt_display_devs)
  8253. use_curses = false;
  8254. if (use_curses)
  8255. enable_curses();
  8256. #endif
  8257. applog(LOG_WARNING, "Started %s", packagename);
  8258. if (cnfbuf) {
  8259. applog(LOG_NOTICE, "Loaded configuration file %s", cnfbuf);
  8260. switch (fileconf_load) {
  8261. case 0:
  8262. applog(LOG_WARNING, "Fatal JSON error in configuration file.");
  8263. applog(LOG_WARNING, "Configuration file could not be used.");
  8264. break;
  8265. case -1:
  8266. applog(LOG_WARNING, "Error in configuration file, partially loaded.");
  8267. if (use_curses)
  8268. applog(LOG_WARNING, "Start BFGMiner with -T to see what failed to load.");
  8269. break;
  8270. default:
  8271. break;
  8272. }
  8273. free(cnfbuf);
  8274. cnfbuf = NULL;
  8275. }
  8276. strcat(opt_kernel_path, "/");
  8277. if (want_per_device_stats)
  8278. opt_log_output = true;
  8279. #ifdef WANT_CPUMINE
  8280. #ifdef USE_SCRYPT
  8281. if (opt_scrypt)
  8282. set_scrypt_algo(&opt_algo);
  8283. else
  8284. #endif
  8285. if (0 <= opt_bench_algo) {
  8286. double rate = bench_algo_stage3(opt_bench_algo);
  8287. if (!skip_to_bench)
  8288. printf("%.5f (%s)\n", rate, algo_names[opt_bench_algo]);
  8289. else {
  8290. // Write result to shared memory for parent
  8291. #if defined(WIN32)
  8292. char unique_name[64];
  8293. if (GetEnvironmentVariable("BFGMINER_SHARED_MEM", unique_name, 32) || GetEnvironmentVariable("CGMINER_SHARED_MEM", unique_name, 32)) {
  8294. HANDLE map_handle = CreateFileMapping(
  8295. INVALID_HANDLE_VALUE, // use paging file
  8296. NULL, // default security attributes
  8297. PAGE_READWRITE, // read/write access
  8298. 0, // size: high 32-bits
  8299. 4096, // size: low 32-bits
  8300. unique_name // name of map object
  8301. );
  8302. if (NULL != map_handle) {
  8303. void *shared_mem = MapViewOfFile(
  8304. map_handle, // object to map view of
  8305. FILE_MAP_WRITE, // read/write access
  8306. 0, // high offset: map from
  8307. 0, // low offset: beginning
  8308. 0 // default: map entire file
  8309. );
  8310. if (NULL != shared_mem)
  8311. CopyMemory(shared_mem, &rate, sizeof(rate));
  8312. (void)UnmapViewOfFile(shared_mem);
  8313. }
  8314. (void)CloseHandle(map_handle);
  8315. }
  8316. #endif
  8317. }
  8318. exit(0);
  8319. }
  8320. #endif
  8321. drv_detect_all();
  8322. total_devices = total_devices_new;
  8323. devices = devices_new;
  8324. total_devices_new = 0;
  8325. devices_new = NULL;
  8326. if (opt_display_devs) {
  8327. applog(LOG_ERR, "Devices detected:");
  8328. for (i = 0; i < total_devices; ++i) {
  8329. struct cgpu_info *cgpu = devices[i];
  8330. if (cgpu->name)
  8331. applog(LOG_ERR, " %2d. %"PRIprepr": %s (driver: %s)", i, cgpu->proc_repr, cgpu->name, cgpu->drv->dname);
  8332. else
  8333. applog(LOG_ERR, " %2d. %"PRIprepr" (driver: %s)", i, cgpu->proc_repr, cgpu->drv->dname);
  8334. }
  8335. quit(0, "%d devices listed", total_devices);
  8336. }
  8337. mining_threads = 0;
  8338. if (opt_devs_enabled) {
  8339. for (i = 0; i < MAX_DEVICES; i++) {
  8340. if (devices_enabled[i]) {
  8341. if (i >= total_devices)
  8342. quit (1, "Command line options set a device that doesn't exist");
  8343. register_device(devices[i]);
  8344. } else if (i < total_devices) {
  8345. if (opt_removedisabled) {
  8346. if (devices[i]->drv == &cpu_drv)
  8347. --opt_n_threads;
  8348. } else {
  8349. register_device(devices[i]);
  8350. }
  8351. devices[i]->deven = DEV_DISABLED;
  8352. }
  8353. }
  8354. total_devices = cgminer_id_count;
  8355. } else {
  8356. for (i = 0; i < total_devices; ++i)
  8357. register_device(devices[i]);
  8358. }
  8359. #ifdef USE_USBUTILS
  8360. if (!total_devices) {
  8361. applog(LOG_WARNING, "No devices detected!");
  8362. applog(LOG_WARNING, "Waiting for USB hotplug devices or press q to quit");
  8363. }
  8364. #else
  8365. if (!total_devices)
  8366. quit(1, "All devices disabled, cannot mine!");
  8367. #endif
  8368. load_temp_config();
  8369. #ifdef HAVE_CURSES
  8370. switch_logsize();
  8371. #endif
  8372. if (!total_pools) {
  8373. applog(LOG_WARNING, "Need to specify at least one pool server.");
  8374. #ifdef HAVE_CURSES
  8375. if (!use_curses || !input_pool(false))
  8376. #endif
  8377. quit(1, "Pool setup failed");
  8378. }
  8379. for (i = 0; i < total_pools; i++) {
  8380. struct pool *pool = pools[i];
  8381. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  8382. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  8383. if (!pool->rpc_url)
  8384. quit(1, "No URI supplied for pool %u", i);
  8385. if (!pool->rpc_userpass) {
  8386. if (!pool->rpc_user || !pool->rpc_pass)
  8387. quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  8388. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  8389. if (!pool->rpc_userpass)
  8390. quit(1, "Failed to malloc userpass");
  8391. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  8392. }
  8393. }
  8394. /* Set the currentpool to pool with priority 0 */
  8395. validate_pool_priorities();
  8396. for (i = 0; i < total_pools; i++) {
  8397. struct pool *pool = pools[i];
  8398. if (!pool->prio)
  8399. currentpool = pool;
  8400. }
  8401. #ifdef HAVE_SYSLOG_H
  8402. if (use_syslog)
  8403. openlog(PACKAGE, LOG_PID, LOG_USER);
  8404. #endif
  8405. #if defined(unix) || defined(__APPLE__)
  8406. if (opt_stderr_cmd)
  8407. fork_monitor();
  8408. #endif // defined(unix)
  8409. mining_thr = calloc(mining_threads, sizeof(thr));
  8410. if (!mining_thr)
  8411. quit(1, "Failed to calloc mining_thr");
  8412. for (i = 0; i < mining_threads; i++) {
  8413. mining_thr[i] = calloc(1, sizeof(*thr));
  8414. if (!mining_thr[i])
  8415. quit(1, "Failed to calloc mining_thr[%d]", i);
  8416. }
  8417. total_control_threads = 7;
  8418. control_thr = calloc(total_control_threads, sizeof(*thr));
  8419. if (!control_thr)
  8420. quit(1, "Failed to calloc control_thr");
  8421. gwsched_thr_id = 0;
  8422. stage_thr_id = 1;
  8423. thr = &control_thr[stage_thr_id];
  8424. thr->q = tq_new();
  8425. if (!thr->q)
  8426. quit(1, "Failed to tq_new");
  8427. /* start stage thread */
  8428. if (thr_info_create(thr, NULL, stage_thread, thr))
  8429. quit(1, "stage thread create failed");
  8430. pthread_detach(thr->pth);
  8431. /* Create a unique get work queue */
  8432. getq = tq_new();
  8433. if (!getq)
  8434. quit(1, "Failed to create getq");
  8435. /* We use the getq mutex as the staged lock */
  8436. stgd_lock = &getq->mutex;
  8437. if (opt_benchmark)
  8438. goto begin_bench;
  8439. for (i = 0; i < total_pools; i++) {
  8440. struct pool *pool = pools[i];
  8441. enable_pool(pool);
  8442. pool->idle = true;
  8443. }
  8444. applog(LOG_NOTICE, "Probing for an alive pool");
  8445. do {
  8446. int slept = 0;
  8447. /* Look for at least one active pool before starting */
  8448. probe_pools();
  8449. do {
  8450. sleep(1);
  8451. slept++;
  8452. } while (!pools_active && slept < 60);
  8453. if (!pools_active) {
  8454. applog(LOG_ERR, "No servers were found that could be used to get work from.");
  8455. applog(LOG_ERR, "Please check the details from the list below of the servers you have input");
  8456. applog(LOG_ERR, "Most likely you have input the wrong URL, forgotten to add a port, or have not set up workers");
  8457. for (i = 0; i < total_pools; i++) {
  8458. struct pool *pool;
  8459. pool = pools[i];
  8460. applog(LOG_WARNING, "Pool: %d URL: %s User: %s Password: %s",
  8461. i, pool->rpc_url, pool->rpc_user, pool->rpc_pass);
  8462. }
  8463. #ifdef HAVE_CURSES
  8464. if (use_curses) {
  8465. halfdelay(150);
  8466. applog(LOG_ERR, "Press any key to exit, or BFGMiner will try again in 15s.");
  8467. if (getch() != ERR)
  8468. quit(0, "No servers could be used! Exiting.");
  8469. cbreak();
  8470. } else
  8471. #endif
  8472. quit(0, "No servers could be used! Exiting.");
  8473. }
  8474. } while (!pools_active);
  8475. #ifdef USE_SCRYPT
  8476. if (detect_algo == 1 && !opt_scrypt) {
  8477. applog(LOG_NOTICE, "Detected scrypt algorithm");
  8478. opt_scrypt = true;
  8479. }
  8480. #endif
  8481. detect_algo = 0;
  8482. begin_bench:
  8483. total_mhashes_done = 0;
  8484. for (i = 0; i < total_devices; i++) {
  8485. struct cgpu_info *cgpu = devices[i];
  8486. cgpu->rolling = cgpu->total_mhashes = 0;
  8487. }
  8488. cgtime(&total_tv_start);
  8489. cgtime(&total_tv_end);
  8490. miner_started = total_tv_start;
  8491. time_t miner_start_ts = time(NULL);
  8492. if (schedstart.tm.tm_sec)
  8493. localtime_r(&miner_start_ts, &schedstart.tm);
  8494. if (schedstop.tm.tm_sec)
  8495. localtime_r(&miner_start_ts, &schedstop .tm);
  8496. get_datestamp(datestamp, miner_start_ts);
  8497. // Initialise processors and threads
  8498. k = 0;
  8499. for (i = 0; i < total_devices; ++i) {
  8500. struct cgpu_info *cgpu = devices[i];
  8501. allocate_cgpu(cgpu, &k);
  8502. }
  8503. // Start threads
  8504. for (i = 0; i < total_devices; ++i) {
  8505. struct cgpu_info *cgpu = devices[i];
  8506. start_cgpu(cgpu);
  8507. }
  8508. #ifdef HAVE_OPENCL
  8509. applog(LOG_INFO, "%d gpu miner threads started", gpu_threads);
  8510. for (i = 0; i < nDevs; i++)
  8511. pause_dynamic_threads(i);
  8512. #endif
  8513. #ifdef WANT_CPUMINE
  8514. applog(LOG_INFO, "%d cpu miner threads started, "
  8515. "using SHA256 '%s' algorithm.",
  8516. opt_n_threads,
  8517. algo_names[opt_algo]);
  8518. #endif
  8519. cgtime(&total_tv_start);
  8520. cgtime(&total_tv_end);
  8521. {
  8522. pthread_t submit_thread;
  8523. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, NULL)))
  8524. quit(1, "submit_work thread create failed");
  8525. }
  8526. watchpool_thr_id = 2;
  8527. thr = &control_thr[watchpool_thr_id];
  8528. /* start watchpool thread */
  8529. if (thr_info_create(thr, NULL, watchpool_thread, NULL))
  8530. quit(1, "watchpool thread create failed");
  8531. pthread_detach(thr->pth);
  8532. watchdog_thr_id = 3;
  8533. thr = &control_thr[watchdog_thr_id];
  8534. /* start watchdog thread */
  8535. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  8536. quit(1, "watchdog thread create failed");
  8537. pthread_detach(thr->pth);
  8538. #ifdef HAVE_OPENCL
  8539. /* Create reinit gpu thread */
  8540. gpur_thr_id = 4;
  8541. thr = &control_thr[gpur_thr_id];
  8542. thr->q = tq_new();
  8543. if (!thr->q)
  8544. quit(1, "tq_new failed for gpur_thr_id");
  8545. if (thr_info_create(thr, NULL, reinit_gpu, thr))
  8546. quit(1, "reinit_gpu thread create failed");
  8547. #endif
  8548. /* Create API socket thread */
  8549. api_thr_id = 5;
  8550. thr = &control_thr[api_thr_id];
  8551. if (thr_info_create(thr, NULL, api_thread, thr))
  8552. quit(1, "API thread create failed");
  8553. #ifdef HAVE_CURSES
  8554. /* Create curses input thread for keyboard input. Create this last so
  8555. * that we know all threads are created since this can call kill_work
  8556. * to try and shut down ll previous threads. */
  8557. input_thr_id = 6;
  8558. thr = &control_thr[input_thr_id];
  8559. if (thr_info_create(thr, NULL, input_thread, thr))
  8560. quit(1, "input thread create failed");
  8561. pthread_detach(thr->pth);
  8562. #endif
  8563. /* Just to be sure */
  8564. if (total_control_threads != 7)
  8565. quit(1, "incorrect total_control_threads (%d) should be 7", total_control_threads);
  8566. /* Once everything is set up, main() becomes the getwork scheduler */
  8567. while (42) {
  8568. int ts, max_staged = opt_queue;
  8569. struct pool *pool, *cp;
  8570. bool lagging = false;
  8571. struct curl_ent *ce;
  8572. struct work *work;
  8573. cp = current_pool();
  8574. /* If the primary pool is a getwork pool and cannot roll work,
  8575. * try to stage one extra work per mining thread */
  8576. if (!pool_localgen(cp) && !staged_rollable)
  8577. max_staged += mining_threads;
  8578. mutex_lock(stgd_lock);
  8579. ts = __total_staged();
  8580. if (!pool_localgen(cp) && !ts && !opt_fail_only)
  8581. lagging = true;
  8582. /* Wait until hash_pop tells us we need to create more work */
  8583. if (ts > max_staged) {
  8584. staged_full = true;
  8585. pthread_cond_wait(&gws_cond, stgd_lock);
  8586. ts = __total_staged();
  8587. }
  8588. mutex_unlock(stgd_lock);
  8589. if (ts > max_staged)
  8590. continue;
  8591. work = make_work();
  8592. if (lagging && !pool_tset(cp, &cp->lagging)) {
  8593. applog(LOG_WARNING, "Pool %d not providing work fast enough", cp->pool_no);
  8594. cp->getfail_occasions++;
  8595. total_go++;
  8596. }
  8597. pool = select_pool(lagging);
  8598. retry:
  8599. if (pool->has_stratum) {
  8600. while (!pool->stratum_active || !pool->stratum_notify) {
  8601. struct pool *altpool = select_pool(true);
  8602. if (altpool == pool && pool->has_stratum)
  8603. nmsleep(5000);
  8604. pool = altpool;
  8605. goto retry;
  8606. }
  8607. gen_stratum_work(pool, work);
  8608. applog(LOG_DEBUG, "Generated stratum work");
  8609. stage_work(work);
  8610. continue;
  8611. }
  8612. if (pool->last_work_copy) {
  8613. mutex_lock(&pool->last_work_lock);
  8614. struct work *last_work = pool->last_work_copy;
  8615. if (!last_work)
  8616. {}
  8617. else
  8618. if (can_roll(last_work) && should_roll(last_work)) {
  8619. struct timeval tv_now;
  8620. cgtime(&tv_now);
  8621. free_work(work);
  8622. work = make_clone(pool->last_work_copy);
  8623. mutex_unlock(&pool->last_work_lock);
  8624. roll_work(work);
  8625. applog(LOG_DEBUG, "Generated work from latest GBT job in get_work_thread with %d seconds left", (int)blkmk_time_left(work->tmpl, tv_now.tv_sec));
  8626. stage_work(work);
  8627. continue;
  8628. } else if (last_work->tmpl && pool->proto == PLP_GETBLOCKTEMPLATE && blkmk_work_left(last_work->tmpl) > (unsigned long)mining_threads) {
  8629. // Don't free last_work_copy, since it is used to detect upstream provides plenty of work per template
  8630. } else {
  8631. free_work(last_work);
  8632. pool->last_work_copy = NULL;
  8633. }
  8634. mutex_unlock(&pool->last_work_lock);
  8635. }
  8636. if (clone_available()) {
  8637. applog(LOG_DEBUG, "Cloned getwork work");
  8638. free_work(work);
  8639. continue;
  8640. }
  8641. if (opt_benchmark) {
  8642. get_benchmark_work(work);
  8643. applog(LOG_DEBUG, "Generated benchmark work");
  8644. stage_work(work);
  8645. continue;
  8646. }
  8647. work->pool = pool;
  8648. ce = pop_curl_entry3(pool, 2);
  8649. /* obtain new work from bitcoin via JSON-RPC */
  8650. if (!get_upstream_work(work, ce->curl)) {
  8651. struct pool *next_pool;
  8652. /* Make sure the pool just hasn't stopped serving
  8653. * requests but is up as we'll keep hammering it */
  8654. push_curl_entry(ce, pool);
  8655. ++pool->seq_getfails;
  8656. pool_died(pool);
  8657. next_pool = select_pool(!opt_fail_only);
  8658. if (pool == next_pool) {
  8659. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, retrying in 5s", pool->pool_no);
  8660. nmsleep(5000);
  8661. } else {
  8662. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, failover activated", pool->pool_no);
  8663. pool = next_pool;
  8664. }
  8665. goto retry;
  8666. }
  8667. if (ts >= max_staged)
  8668. pool_tclear(pool, &pool->lagging);
  8669. if (pool_tclear(pool, &pool->idle))
  8670. pool_resus(pool);
  8671. applog(LOG_DEBUG, "Generated getwork work");
  8672. stage_work(work);
  8673. push_curl_entry(ce, pool);
  8674. }
  8675. return 0;
  8676. }