miner.c 335 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006
  1. /*
  2. * Copyright 2011-2014 Con Kolivas
  3. * Copyright 2011-2014 Luke Dashjr
  4. * Copyright 2014 Nate Woolls
  5. * Copyright 2012-2013 Andrew Smith
  6. * Copyright 2010 Jeff Garzik
  7. *
  8. * This program is free software; you can redistribute it and/or modify it
  9. * under the terms of the GNU General Public License as published by the Free
  10. * Software Foundation; either version 3 of the License, or (at your option)
  11. * any later version. See COPYING for more details.
  12. */
  13. #include "config.h"
  14. #ifdef HAVE_CURSES
  15. #ifdef USE_UNICODE
  16. #define PDC_WIDE
  17. #endif
  18. // Must be before stdbool, since pdcurses typedefs bool :/
  19. #include <curses.h>
  20. #endif
  21. #include <ctype.h>
  22. #include <float.h>
  23. #include <limits.h>
  24. #include <locale.h>
  25. #include <stdio.h>
  26. #include <stdlib.h>
  27. #include <string.h>
  28. #include <stdbool.h>
  29. #include <stdint.h>
  30. #include <unistd.h>
  31. #include <sys/time.h>
  32. #include <time.h>
  33. #include <math.h>
  34. #include <stdarg.h>
  35. #include <assert.h>
  36. #include <signal.h>
  37. #include <wctype.h>
  38. #include <sys/stat.h>
  39. #include <sys/types.h>
  40. #include <dirent.h>
  41. #ifdef HAVE_PWD_H
  42. #include <pwd.h>
  43. #endif
  44. #ifndef WIN32
  45. #include <sys/resource.h>
  46. #include <sys/socket.h>
  47. #if defined(HAVE_LIBUDEV) && defined(HAVE_SYS_EPOLL_H)
  48. #include <libudev.h>
  49. #include <sys/epoll.h>
  50. #define HAVE_BFG_HOTPLUG
  51. #endif
  52. #else
  53. #include <winsock2.h>
  54. #include <windows.h>
  55. #include <dbt.h>
  56. #define HAVE_BFG_HOTPLUG
  57. #endif
  58. #include <ccan/opt/opt.h>
  59. #include <jansson.h>
  60. #include <curl/curl.h>
  61. #include <libgen.h>
  62. #include <sha2.h>
  63. #include <utlist.h>
  64. #include <blkmaker.h>
  65. #include <blkmaker_jansson.h>
  66. #include <blktemplate.h>
  67. #include "compat.h"
  68. #include "deviceapi.h"
  69. #include "logging.h"
  70. #include "miner.h"
  71. #include "adl.h"
  72. #include "driver-cpu.h"
  73. #include "driver-opencl.h"
  74. #include "scrypt.h"
  75. #include "util.h"
  76. #ifdef USE_AVALON
  77. #include "driver-avalon.h"
  78. #endif
  79. #ifdef HAVE_BFG_LOWLEVEL
  80. #include "lowlevel.h"
  81. #endif
  82. #if defined(unix) || defined(__APPLE__)
  83. #include <errno.h>
  84. #include <fcntl.h>
  85. #include <sys/wait.h>
  86. #endif
  87. #ifdef USE_SCRYPT
  88. #include "scrypt.h"
  89. #endif
  90. #include "version.h"
  91. #if defined(USE_AVALON) || defined(USE_BITFORCE) || defined(USE_ICARUS) || defined(USE_MODMINER) || defined(USE_NANOFURY) || defined(USE_X6500) || defined(USE_ZTEX)
  92. # define USE_FPGA
  93. #endif
  94. enum bfg_quit_summary {
  95. BQS_DEFAULT,
  96. BQS_NONE,
  97. BQS_DEVS,
  98. BQS_PROCS,
  99. BQS_DETAILED,
  100. };
  101. struct strategies strategies[] = {
  102. { "Failover" },
  103. { "Round Robin" },
  104. { "Rotate" },
  105. { "Load Balance" },
  106. { "Balance" },
  107. };
  108. static char packagename[256];
  109. bool opt_protocol;
  110. bool opt_dev_protocol;
  111. static bool opt_benchmark, opt_benchmark_intense;
  112. static bool want_longpoll = true;
  113. static bool want_gbt = true;
  114. static bool want_getwork = true;
  115. #if BLKMAKER_VERSION > 1
  116. static bool opt_load_bitcoin_conf = true;
  117. static bool have_at_least_one_getcbaddr;
  118. static bytes_t opt_coinbase_script = BYTES_INIT;
  119. static uint32_t coinbase_script_block_id;
  120. static uint32_t template_nonce;
  121. #endif
  122. #if BLKMAKER_VERSION > 0
  123. char *opt_coinbase_sig;
  124. #endif
  125. static enum bfg_quit_summary opt_quit_summary = BQS_DEFAULT;
  126. static bool include_serial_in_statline;
  127. char *request_target_str;
  128. float request_pdiff = 1.0;
  129. double request_bdiff;
  130. static bool want_stratum = true;
  131. bool have_longpoll;
  132. int opt_skip_checks;
  133. bool want_per_device_stats;
  134. bool use_syslog;
  135. bool opt_quiet_work_updates = true;
  136. bool opt_quiet;
  137. bool opt_realquiet;
  138. int loginput_size;
  139. bool opt_compact;
  140. bool opt_show_procs;
  141. const int opt_cutofftemp = 95;
  142. int opt_hysteresis = 3;
  143. static int opt_retries = -1;
  144. int opt_fail_pause = 5;
  145. int opt_log_interval = 20;
  146. int opt_queue = 1;
  147. int opt_scantime = 60;
  148. int opt_expiry = 120;
  149. int opt_expiry_lp = 3600;
  150. unsigned long long global_hashrate;
  151. static bool opt_unittest = false;
  152. unsigned long global_quota_gcd = 1;
  153. time_t last_getwork;
  154. #ifdef HAVE_OPENCL
  155. int opt_dynamic_interval = 7;
  156. int nDevs;
  157. int opt_g_threads = -1;
  158. #endif
  159. #ifdef USE_SCRYPT
  160. static char detect_algo = 1;
  161. bool opt_scrypt;
  162. #else
  163. static char detect_algo;
  164. #endif
  165. bool opt_restart = true;
  166. #ifdef USE_LIBMICROHTTPD
  167. #include "httpsrv.h"
  168. int httpsrv_port = -1;
  169. #endif
  170. #ifdef USE_LIBEVENT
  171. int stratumsrv_port = -1;
  172. #endif
  173. const
  174. int rescan_delay_ms = 1000;
  175. #ifdef HAVE_BFG_HOTPLUG
  176. bool opt_hotplug = 1;
  177. const
  178. int hotplug_delay_ms = 100;
  179. #else
  180. const bool opt_hotplug;
  181. #endif
  182. struct string_elist *scan_devices;
  183. static struct string_elist *opt_set_device_list;
  184. bool opt_force_dev_init;
  185. static struct string_elist *opt_devices_enabled_list;
  186. static bool opt_display_devs;
  187. int total_devices;
  188. struct cgpu_info **devices;
  189. int total_devices_new;
  190. struct cgpu_info **devices_new;
  191. bool have_opencl;
  192. int opt_n_threads = -1;
  193. int mining_threads;
  194. int num_processors;
  195. #ifdef HAVE_CURSES
  196. bool use_curses = true;
  197. #else
  198. bool use_curses;
  199. #endif
  200. int last_logstatusline_len;
  201. #ifdef HAVE_LIBUSB
  202. bool have_libusb;
  203. #endif
  204. static bool opt_submit_stale = true;
  205. static float opt_shares;
  206. static int opt_submit_threads = 0x40;
  207. bool opt_fail_only;
  208. int opt_fail_switch_delay = 300;
  209. bool opt_autofan;
  210. bool opt_autoengine;
  211. bool opt_noadl;
  212. char *opt_api_allow = NULL;
  213. char *opt_api_groups;
  214. char *opt_api_description = PACKAGE_STRING;
  215. int opt_api_port = 4028;
  216. bool opt_api_listen;
  217. bool opt_api_mcast;
  218. char *opt_api_mcast_addr = API_MCAST_ADDR;
  219. char *opt_api_mcast_code = API_MCAST_CODE;
  220. char *opt_api_mcast_des = "";
  221. int opt_api_mcast_port = 4028;
  222. bool opt_api_network;
  223. bool opt_delaynet;
  224. bool opt_disable_pool;
  225. bool opt_disable_client_reconnect = false;
  226. static bool no_work;
  227. bool opt_worktime;
  228. bool opt_weighed_stats;
  229. char *opt_kernel_path;
  230. char *cgminer_path;
  231. #if defined(USE_BITFORCE)
  232. bool opt_bfl_noncerange;
  233. #endif
  234. #define QUIET (opt_quiet || opt_realquiet)
  235. struct thr_info *control_thr;
  236. struct thr_info **mining_thr;
  237. static int watchpool_thr_id;
  238. static int watchdog_thr_id;
  239. #ifdef HAVE_CURSES
  240. static int input_thr_id;
  241. #endif
  242. int gpur_thr_id;
  243. static int api_thr_id;
  244. static int total_control_threads;
  245. pthread_mutex_t hash_lock;
  246. static pthread_mutex_t *stgd_lock;
  247. pthread_mutex_t console_lock;
  248. cglock_t ch_lock;
  249. static pthread_rwlock_t blk_lock;
  250. static pthread_mutex_t sshare_lock;
  251. pthread_rwlock_t netacc_lock;
  252. pthread_rwlock_t mining_thr_lock;
  253. pthread_rwlock_t devices_lock;
  254. static pthread_mutex_t lp_lock;
  255. static pthread_cond_t lp_cond;
  256. pthread_cond_t gws_cond;
  257. bool shutting_down;
  258. double total_rolling;
  259. double total_mhashes_done;
  260. static struct timeval total_tv_start, total_tv_end;
  261. static struct timeval miner_started;
  262. cglock_t control_lock;
  263. pthread_mutex_t stats_lock;
  264. static pthread_mutex_t submitting_lock;
  265. static int total_submitting;
  266. static struct work *submit_waiting;
  267. notifier_t submit_waiting_notifier;
  268. int hw_errors;
  269. int total_accepted, total_rejected;
  270. int total_getworks, total_stale, total_discarded;
  271. uint64_t total_bytes_rcvd, total_bytes_sent;
  272. double total_diff1, total_bad_diff1;
  273. double total_diff_accepted, total_diff_rejected, total_diff_stale;
  274. static int staged_rollable;
  275. unsigned int new_blocks;
  276. unsigned int found_blocks;
  277. unsigned int local_work;
  278. unsigned int total_go, total_ro;
  279. struct pool **pools;
  280. static struct pool *currentpool = NULL;
  281. int total_pools, enabled_pools;
  282. enum pool_strategy pool_strategy = POOL_FAILOVER;
  283. int opt_rotate_period;
  284. static int total_urls, total_users, total_passes;
  285. static
  286. #ifndef HAVE_CURSES
  287. const
  288. #endif
  289. bool curses_active;
  290. #ifdef HAVE_CURSES
  291. #if !(defined(PDCURSES) || defined(NCURSES_VERSION))
  292. const
  293. #endif
  294. short default_bgcolor = COLOR_BLACK;
  295. static int attr_title = A_BOLD;
  296. #endif
  297. static
  298. #if defined(HAVE_CURSES) && defined(USE_UNICODE)
  299. bool use_unicode;
  300. static
  301. bool have_unicode_degrees;
  302. static
  303. wchar_t unicode_micro = 'u';
  304. #else
  305. const bool use_unicode;
  306. static
  307. const bool have_unicode_degrees;
  308. static
  309. const char unicode_micro = 'u';
  310. #endif
  311. #ifdef HAVE_CURSES
  312. #define U8_BAD_START "\xef\x80\x81"
  313. #define U8_BAD_END "\xef\x80\x80"
  314. #define AS_BAD(x) U8_BAD_START x U8_BAD_END
  315. bool selecting_device;
  316. unsigned selected_device;
  317. #endif
  318. static int max_lpdigits;
  319. static char current_block[40];
  320. /* Protected by ch_lock */
  321. static char *current_hash;
  322. static uint32_t current_block_id;
  323. char *current_fullhash;
  324. static char datestamp[40];
  325. static char blocktime[32];
  326. time_t block_time;
  327. static char best_share[ALLOC_H2B_SHORTV] = "0";
  328. double current_diff = 0xFFFFFFFFFFFFFFFFULL;
  329. static char block_diff[ALLOC_H2B_SHORTV];
  330. static char net_hashrate[ALLOC_H2B_SHORT];
  331. double best_diff = 0;
  332. static bool known_blkheight_current;
  333. static uint32_t known_blkheight;
  334. static uint32_t known_blkheight_blkid;
  335. static uint64_t block_subsidy;
  336. struct block {
  337. char hash[40];
  338. UT_hash_handle hh;
  339. int block_no;
  340. };
  341. static struct block *blocks = NULL;
  342. int swork_id;
  343. /* For creating a hash database of stratum shares submitted that have not had
  344. * a response yet */
  345. struct stratum_share {
  346. UT_hash_handle hh;
  347. bool block;
  348. struct work *work;
  349. int id;
  350. };
  351. static struct stratum_share *stratum_shares = NULL;
  352. char *opt_socks_proxy = NULL;
  353. static const char def_conf[] = "bfgminer.conf";
  354. static bool config_loaded;
  355. static int include_count;
  356. #define JSON_INCLUDE_CONF "include"
  357. #define JSON_LOAD_ERROR "JSON decode of file '%s' failed\n %s"
  358. #define JSON_LOAD_ERROR_LEN strlen(JSON_LOAD_ERROR)
  359. #define JSON_MAX_DEPTH 10
  360. #define JSON_MAX_DEPTH_ERR "Too many levels of JSON includes (limit 10) or a loop"
  361. char *cmd_idle, *cmd_sick, *cmd_dead;
  362. #if defined(unix) || defined(__APPLE__)
  363. static char *opt_stderr_cmd = NULL;
  364. static int forkpid;
  365. #endif // defined(unix)
  366. #ifdef HAVE_CHROOT
  367. char *chroot_dir;
  368. #endif
  369. #ifdef HAVE_PWD_H
  370. char *opt_setuid;
  371. #endif
  372. struct sigaction termhandler, inthandler;
  373. struct thread_q *getq;
  374. static int total_work;
  375. static bool staged_full;
  376. struct work *staged_work = NULL;
  377. struct schedtime {
  378. bool enable;
  379. struct tm tm;
  380. };
  381. struct schedtime schedstart;
  382. struct schedtime schedstop;
  383. bool sched_paused;
  384. static bool time_before(struct tm *tm1, struct tm *tm2)
  385. {
  386. if (tm1->tm_hour < tm2->tm_hour)
  387. return true;
  388. if (tm1->tm_hour == tm2->tm_hour && tm1->tm_min < tm2->tm_min)
  389. return true;
  390. return false;
  391. }
  392. static bool should_run(void)
  393. {
  394. struct tm tm;
  395. time_t tt;
  396. bool within_range;
  397. if (!schedstart.enable && !schedstop.enable)
  398. return true;
  399. tt = time(NULL);
  400. localtime_r(&tt, &tm);
  401. // NOTE: This is delicately balanced so that should_run is always false if schedstart==schedstop
  402. if (time_before(&schedstop.tm, &schedstart.tm))
  403. within_range = (time_before(&tm, &schedstop.tm) || !time_before(&tm, &schedstart.tm));
  404. else
  405. within_range = (time_before(&tm, &schedstop.tm) && !time_before(&tm, &schedstart.tm));
  406. if (within_range && !schedstop.enable)
  407. /* This is a once off event with no stop time set */
  408. schedstart.enable = false;
  409. return within_range;
  410. }
  411. void get_datestamp(char *f, size_t fsiz, time_t tt)
  412. {
  413. struct tm _tm;
  414. struct tm *tm = &_tm;
  415. if (tt == INVALID_TIMESTAMP)
  416. tt = time(NULL);
  417. localtime_r(&tt, tm);
  418. snprintf(f, fsiz, "[%d-%02d-%02d %02d:%02d:%02d]",
  419. tm->tm_year + 1900,
  420. tm->tm_mon + 1,
  421. tm->tm_mday,
  422. tm->tm_hour,
  423. tm->tm_min,
  424. tm->tm_sec);
  425. }
  426. static
  427. void get_timestamp(char *f, size_t fsiz, time_t tt)
  428. {
  429. struct tm _tm;
  430. struct tm *tm = &_tm;
  431. localtime_r(&tt, tm);
  432. snprintf(f, fsiz, "[%02d:%02d:%02d]",
  433. tm->tm_hour,
  434. tm->tm_min,
  435. tm->tm_sec);
  436. }
  437. static void applog_and_exit(const char *fmt, ...) FORMAT_SYNTAX_CHECK(printf, 1, 2);
  438. static char exit_buf[512];
  439. static void applog_and_exit(const char *fmt, ...)
  440. {
  441. va_list ap;
  442. va_start(ap, fmt);
  443. vsnprintf(exit_buf, sizeof(exit_buf), fmt, ap);
  444. va_end(ap);
  445. _applog(LOG_ERR, exit_buf);
  446. exit(1);
  447. }
  448. char *devpath_to_devid(const char *devpath)
  449. {
  450. #ifndef WIN32
  451. if (devpath[0] != '/')
  452. return NULL;
  453. struct stat my_stat;
  454. if (stat(devpath, &my_stat))
  455. return NULL;
  456. char *devs = malloc(6 + (sizeof(dev_t) * 2) + 1);
  457. memcpy(devs, "dev_t:", 6);
  458. bin2hex(&devs[6], &my_stat.st_rdev, sizeof(dev_t));
  459. #else
  460. if (!strncmp(devpath, "\\\\.\\", 4))
  461. devpath += 4;
  462. if (strncasecmp(devpath, "COM", 3) || !devpath[3])
  463. return NULL;
  464. devpath += 3;
  465. char *p;
  466. strtol(devpath, &p, 10);
  467. if (p[0])
  468. return NULL;
  469. const int sz = (p - devpath);
  470. char *devs = malloc(4 + sz + 1);
  471. sprintf(devs, "com:%s", devpath);
  472. #endif
  473. return devs;
  474. }
  475. static
  476. bool devpaths_match(const char * const ap, const char * const bp)
  477. {
  478. char * const a = devpath_to_devid(ap);
  479. if (!a)
  480. return false;
  481. char * const b = devpath_to_devid(bp);
  482. bool rv = false;
  483. if (b)
  484. {
  485. rv = !strcmp(a, b);
  486. free(b);
  487. }
  488. free(a);
  489. return rv;
  490. }
  491. static
  492. int proc_letter_to_number(const char *s, const char ** const rem)
  493. {
  494. int n = 0, c;
  495. for ( ; s[0]; ++s)
  496. {
  497. if (unlikely(n > INT_MAX / 26))
  498. break;
  499. c = tolower(s[0]) - 'a';
  500. if (unlikely(c < 0 || c > 25))
  501. break;
  502. if (unlikely(INT_MAX - c < n))
  503. break;
  504. n = (n * 26) + c;
  505. }
  506. *rem = s;
  507. return n;
  508. }
  509. static
  510. bool cgpu_match(const char * const pattern, const struct cgpu_info * const cgpu)
  511. {
  512. // all - matches anything
  513. // d0 - matches all processors of device 0
  514. // d0-3 - matches all processors of device 0, 1, 2, or 3
  515. // d0a - matches first processor of device 0
  516. // 0 - matches processor 0
  517. // 0-4 - matches processors 0, 1, 2, 3, or 4
  518. // ___ - matches all processors on all devices using driver/name ___
  519. // ___0 - matches all processors of 0th device using driver/name ___
  520. // ___0a - matches first processor of 0th device using driver/name ___
  521. // @* - matches device with serial or path *
  522. // @*@a - matches first processor of device with serial or path *
  523. // ___@* - matches device with serial or path * using driver/name ___
  524. if (!strcasecmp(pattern, "all"))
  525. return true;
  526. const struct device_drv * const drv = cgpu->drv;
  527. const char *p = pattern, *p2;
  528. size_t L;
  529. int n, i, c = -1;
  530. int n2;
  531. int proc_first = -1, proc_last = -1;
  532. struct cgpu_info *device;
  533. if (!(strncasecmp(drv->dname, p, (L = strlen(drv->dname)))
  534. && strncasecmp(drv-> name, p, (L = strlen(drv-> name)))))
  535. // dname or name
  536. p = &pattern[L];
  537. else
  538. if (p[0] == 'd' && (isdigit(p[1]) || p[1] == '-'))
  539. // d#
  540. ++p;
  541. else
  542. if (isdigit(p[0]) || p[0] == '@' || p[0] == '-')
  543. // # or @
  544. {}
  545. else
  546. return false;
  547. L = p - pattern;
  548. while (isspace(p[0]))
  549. ++p;
  550. if (p[0] == '@')
  551. {
  552. // Serial/path
  553. const char * const ser = &p[1];
  554. for (p = ser; p[0] != '@' && p[0] != '\0'; ++p)
  555. {}
  556. p2 = (p[0] == '@') ? &p[1] : p;
  557. const size_t serlen = (p - ser);
  558. p = "";
  559. n = n2 = 0;
  560. const char * const devpath = cgpu->device_path ?: "";
  561. const char * const devser = cgpu->dev_serial ?: "";
  562. if ((!strncmp(devpath, ser, serlen)) && devpath[serlen] == '\0')
  563. {} // Match
  564. else
  565. if ((!strncmp(devser, ser, serlen)) && devser[serlen] == '\0')
  566. {} // Match
  567. else
  568. {
  569. char devpath2[serlen + 1];
  570. memcpy(devpath2, ser, serlen);
  571. devpath2[serlen] = '\0';
  572. if (!devpaths_match(devpath, ser))
  573. return false;
  574. }
  575. }
  576. else
  577. {
  578. if (isdigit(p[0]))
  579. n = strtol(p, (void*)&p2, 0);
  580. else
  581. {
  582. n = 0;
  583. p2 = p;
  584. }
  585. if (p2[0] == '-')
  586. {
  587. ++p2;
  588. if (p2[0] && isdigit(p2[0]))
  589. n2 = strtol(p2, (void*)&p2, 0);
  590. else
  591. n2 = INT_MAX;
  592. }
  593. else
  594. n2 = n;
  595. if (p == pattern)
  596. {
  597. if (!p[0])
  598. return true;
  599. if (p2 && p2[0])
  600. goto invsyntax;
  601. for (i = n; i <= n2; ++i)
  602. {
  603. if (i >= total_devices)
  604. break;
  605. if (cgpu == devices[i])
  606. return true;
  607. }
  608. return false;
  609. }
  610. }
  611. if (p2[0])
  612. {
  613. proc_first = proc_letter_to_number(&p2[0], &p2);
  614. if (p2[0] == '-')
  615. {
  616. ++p2;
  617. if (p2[0])
  618. proc_last = proc_letter_to_number(p2, &p2);
  619. else
  620. proc_last = INT_MAX;
  621. }
  622. else
  623. proc_last = proc_first;
  624. if (p2[0])
  625. goto invsyntax;
  626. }
  627. if (L > 1 || tolower(pattern[0]) != 'd' || !p[0])
  628. {
  629. if ((L == 3 && !strncasecmp(pattern, drv->name, 3)) ||
  630. (!L) ||
  631. (L == strlen(drv->dname) && !strncasecmp(pattern, drv->dname, L)))
  632. {} // Matched name or dname
  633. else
  634. return false;
  635. if (p[0] && (cgpu->device_id < n || cgpu->device_id > n2))
  636. return false;
  637. if (proc_first != -1 && (cgpu->proc_id < proc_first || cgpu->proc_id > proc_last))
  638. return false;
  639. return true;
  640. }
  641. // d#
  642. c = -1;
  643. for (i = 0; ; ++i)
  644. {
  645. if (i == total_devices)
  646. return false;
  647. if (devices[i]->device != devices[i])
  648. continue;
  649. ++c;
  650. if (c < n)
  651. continue;
  652. if (c > n2)
  653. break;
  654. for (device = devices[i]; device; device = device->next_proc)
  655. {
  656. if (proc_first != -1 && (device->proc_id < proc_first || device->proc_id > proc_last))
  657. continue;
  658. if (device == cgpu)
  659. return true;
  660. }
  661. }
  662. return false;
  663. invsyntax:
  664. applog(LOG_WARNING, "%s: Invalid syntax: %s", __func__, pattern);
  665. return false;
  666. }
  667. #define TEST_CGPU_MATCH(pattern) \
  668. if (!cgpu_match(pattern, &cgpu)) \
  669. applog(LOG_ERR, "%s: Pattern \"%s\" should have matched!", __func__, pattern); \
  670. // END TEST_CGPU_MATCH
  671. #define TEST_CGPU_NOMATCH(pattern) \
  672. if (cgpu_match(pattern, &cgpu)) \
  673. applog(LOG_ERR, "%s: Pattern \"%s\" should NOT have matched!", __func__, pattern); \
  674. // END TEST_CGPU_MATCH
  675. static __maybe_unused
  676. void test_cgpu_match()
  677. {
  678. struct device_drv drv = {
  679. .dname = "test",
  680. .name = "TST",
  681. };
  682. struct cgpu_info cgpu = {
  683. .drv = &drv,
  684. .device = &cgpu,
  685. .device_id = 1,
  686. .proc_id = 1,
  687. .proc_repr = "TST 1b",
  688. }, cgpu0a = {
  689. .drv = &drv,
  690. .device = &cgpu0a,
  691. .device_id = 0,
  692. .proc_id = 0,
  693. .proc_repr = "TST 0a",
  694. }, cgpu1a = {
  695. .drv = &drv,
  696. .device = &cgpu0a,
  697. .device_id = 1,
  698. .proc_id = 0,
  699. .proc_repr = "TST 1a",
  700. };
  701. struct cgpu_info *devices_list[3] = {&cgpu0a, &cgpu1a, &cgpu,};
  702. devices = devices_list;
  703. total_devices = 3;
  704. TEST_CGPU_MATCH("all")
  705. TEST_CGPU_MATCH("d1")
  706. TEST_CGPU_NOMATCH("d2")
  707. TEST_CGPU_MATCH("d0-5")
  708. TEST_CGPU_NOMATCH("d0-0")
  709. TEST_CGPU_NOMATCH("d2-5")
  710. TEST_CGPU_MATCH("d-1")
  711. TEST_CGPU_MATCH("d1-")
  712. TEST_CGPU_NOMATCH("d-0")
  713. TEST_CGPU_NOMATCH("d2-")
  714. TEST_CGPU_MATCH("2")
  715. TEST_CGPU_NOMATCH("3")
  716. TEST_CGPU_MATCH("1-2")
  717. TEST_CGPU_MATCH("2-3")
  718. TEST_CGPU_NOMATCH("1-1")
  719. TEST_CGPU_NOMATCH("3-4")
  720. TEST_CGPU_MATCH("TST")
  721. TEST_CGPU_MATCH("test")
  722. TEST_CGPU_MATCH("tst")
  723. TEST_CGPU_MATCH("TEST")
  724. TEST_CGPU_NOMATCH("TSF")
  725. TEST_CGPU_NOMATCH("TS")
  726. TEST_CGPU_NOMATCH("TSTF")
  727. TEST_CGPU_MATCH("TST1")
  728. TEST_CGPU_MATCH("test1")
  729. TEST_CGPU_MATCH("TST0-1")
  730. TEST_CGPU_MATCH("TST 1")
  731. TEST_CGPU_MATCH("TST 1-2")
  732. TEST_CGPU_MATCH("TEST 1-2")
  733. TEST_CGPU_NOMATCH("TST2")
  734. TEST_CGPU_NOMATCH("TST2-3")
  735. TEST_CGPU_NOMATCH("TST0-0")
  736. TEST_CGPU_MATCH("TST1b")
  737. TEST_CGPU_MATCH("tst1b")
  738. TEST_CGPU_NOMATCH("TST1c")
  739. TEST_CGPU_NOMATCH("TST1bb")
  740. TEST_CGPU_MATCH("TST0-1b")
  741. TEST_CGPU_NOMATCH("TST0-1c")
  742. TEST_CGPU_MATCH("TST1a-d")
  743. TEST_CGPU_NOMATCH("TST1a-a")
  744. TEST_CGPU_NOMATCH("TST1-a")
  745. TEST_CGPU_NOMATCH("TST1c-z")
  746. TEST_CGPU_NOMATCH("TST1c-")
  747. TEST_CGPU_MATCH("@")
  748. TEST_CGPU_NOMATCH("@abc")
  749. TEST_CGPU_MATCH("@@b")
  750. TEST_CGPU_NOMATCH("@@c")
  751. TEST_CGPU_MATCH("TST@")
  752. TEST_CGPU_NOMATCH("TST@abc")
  753. TEST_CGPU_MATCH("TST@@b")
  754. TEST_CGPU_NOMATCH("TST@@c")
  755. TEST_CGPU_MATCH("TST@@b-f")
  756. TEST_CGPU_NOMATCH("TST@@c-f")
  757. TEST_CGPU_NOMATCH("TST@@-a")
  758. cgpu.device_path = "/dev/test";
  759. cgpu.dev_serial = "testy";
  760. TEST_CGPU_MATCH("TST@/dev/test")
  761. TEST_CGPU_MATCH("TST@testy")
  762. TEST_CGPU_NOMATCH("TST@")
  763. TEST_CGPU_NOMATCH("TST@/dev/test5@b")
  764. TEST_CGPU_NOMATCH("TST@testy3@b")
  765. TEST_CGPU_MATCH("TST@/dev/test@b")
  766. TEST_CGPU_MATCH("TST@testy@b")
  767. TEST_CGPU_NOMATCH("TST@/dev/test@c")
  768. TEST_CGPU_NOMATCH("TST@testy@c")
  769. cgpu.device_path = "usb:000:999";
  770. TEST_CGPU_MATCH("TST@usb:000:999")
  771. drv.dname = "test7";
  772. TEST_CGPU_MATCH("test7")
  773. TEST_CGPU_MATCH("TEST7")
  774. TEST_CGPU_NOMATCH("test&")
  775. TEST_CGPU_MATCH("test7 1-2")
  776. TEST_CGPU_MATCH("test7@testy@b")
  777. }
  778. static
  779. int cgpu_search(const char * const pattern, const int first)
  780. {
  781. int i;
  782. struct cgpu_info *cgpu;
  783. #define CHECK_CGPU_SEARCH do{ \
  784. cgpu = get_devices(i); \
  785. if (cgpu_match(pattern, cgpu)) \
  786. return i; \
  787. }while(0)
  788. for (i = first; i < total_devices; ++i)
  789. CHECK_CGPU_SEARCH;
  790. for (i = 0; i < first; ++i)
  791. CHECK_CGPU_SEARCH;
  792. #undef CHECK_CGPU_SEARCH
  793. return -1;
  794. }
  795. static pthread_mutex_t sharelog_lock;
  796. static FILE *sharelog_file = NULL;
  797. struct thr_info *get_thread(int thr_id)
  798. {
  799. struct thr_info *thr;
  800. rd_lock(&mining_thr_lock);
  801. thr = mining_thr[thr_id];
  802. rd_unlock(&mining_thr_lock);
  803. return thr;
  804. }
  805. static struct cgpu_info *get_thr_cgpu(int thr_id)
  806. {
  807. struct thr_info *thr = get_thread(thr_id);
  808. return thr->cgpu;
  809. }
  810. struct cgpu_info *get_devices(int id)
  811. {
  812. struct cgpu_info *cgpu;
  813. rd_lock(&devices_lock);
  814. cgpu = devices[id];
  815. rd_unlock(&devices_lock);
  816. return cgpu;
  817. }
  818. static pthread_mutex_t noncelog_lock = PTHREAD_MUTEX_INITIALIZER;
  819. static FILE *noncelog_file = NULL;
  820. static
  821. void noncelog(const struct work * const work)
  822. {
  823. const int thr_id = work->thr_id;
  824. const struct cgpu_info *proc = get_thr_cgpu(thr_id);
  825. char buf[0x200], hash[65], data[161], midstate[65];
  826. int rv;
  827. size_t ret;
  828. bin2hex(hash, work->hash, 32);
  829. bin2hex(data, work->data, 80);
  830. bin2hex(midstate, work->midstate, 32);
  831. // timestamp,proc,hash,data,midstate
  832. rv = snprintf(buf, sizeof(buf), "%lu,%s,%s,%s,%s\n",
  833. (unsigned long)time(NULL), proc->proc_repr_ns,
  834. hash, data, midstate);
  835. if (unlikely(rv < 1))
  836. {
  837. applog(LOG_ERR, "noncelog printf error");
  838. return;
  839. }
  840. mutex_lock(&noncelog_lock);
  841. ret = fwrite(buf, rv, 1, noncelog_file);
  842. fflush(noncelog_file);
  843. mutex_unlock(&noncelog_lock);
  844. if (ret != 1)
  845. applog(LOG_ERR, "noncelog fwrite error");
  846. }
  847. static void sharelog(const char*disposition, const struct work*work)
  848. {
  849. char target[(sizeof(work->target) * 2) + 1];
  850. char hash[(sizeof(work->hash) * 2) + 1];
  851. char data[(sizeof(work->data) * 2) + 1];
  852. struct cgpu_info *cgpu;
  853. unsigned long int t;
  854. struct pool *pool;
  855. int thr_id, rv;
  856. char s[1024];
  857. size_t ret;
  858. if (!sharelog_file)
  859. return;
  860. thr_id = work->thr_id;
  861. cgpu = get_thr_cgpu(thr_id);
  862. pool = work->pool;
  863. t = work->ts_getwork + timer_elapsed(&work->tv_getwork, &work->tv_work_found);
  864. bin2hex(target, work->target, sizeof(work->target));
  865. bin2hex(hash, work->hash, sizeof(work->hash));
  866. bin2hex(data, work->data, sizeof(work->data));
  867. // timestamp,disposition,target,pool,dev,thr,sharehash,sharedata
  868. 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);
  869. if (rv >= (int)(sizeof(s)))
  870. s[sizeof(s) - 1] = '\0';
  871. else if (rv < 0) {
  872. applog(LOG_ERR, "sharelog printf error");
  873. return;
  874. }
  875. mutex_lock(&sharelog_lock);
  876. ret = fwrite(s, rv, 1, sharelog_file);
  877. fflush(sharelog_file);
  878. mutex_unlock(&sharelog_lock);
  879. if (ret != 1)
  880. applog(LOG_ERR, "sharelog fwrite error");
  881. }
  882. static char *getwork_req = "{\"method\": \"getwork\", \"params\": [], \"id\":0}\n";
  883. /* Adjust all the pools' quota to the greatest common denominator after a pool
  884. * has been added or the quotas changed. */
  885. void adjust_quota_gcd(void)
  886. {
  887. unsigned long gcd, lowest_quota = ~0UL, quota;
  888. struct pool *pool;
  889. int i;
  890. for (i = 0; i < total_pools; i++) {
  891. pool = pools[i];
  892. quota = pool->quota;
  893. if (!quota)
  894. continue;
  895. if (quota < lowest_quota)
  896. lowest_quota = quota;
  897. }
  898. if (likely(lowest_quota < ~0UL)) {
  899. gcd = lowest_quota;
  900. for (i = 0; i < total_pools; i++) {
  901. pool = pools[i];
  902. quota = pool->quota;
  903. if (!quota)
  904. continue;
  905. while (quota % gcd)
  906. gcd--;
  907. }
  908. } else
  909. gcd = 1;
  910. for (i = 0; i < total_pools; i++) {
  911. pool = pools[i];
  912. pool->quota_used *= global_quota_gcd;
  913. pool->quota_used /= gcd;
  914. pool->quota_gcd = pool->quota / gcd;
  915. }
  916. global_quota_gcd = gcd;
  917. applog(LOG_DEBUG, "Global quota greatest common denominator set to %lu", gcd);
  918. }
  919. /* Return value is ignored if not called from add_pool_details */
  920. struct pool *add_pool(void)
  921. {
  922. struct pool *pool;
  923. pool = calloc(sizeof(struct pool), 1);
  924. if (!pool)
  925. quit(1, "Failed to malloc pool in add_pool");
  926. pool->pool_no = pool->prio = total_pools;
  927. mutex_init(&pool->last_work_lock);
  928. mutex_init(&pool->pool_lock);
  929. mutex_init(&pool->pool_test_lock);
  930. if (unlikely(pthread_cond_init(&pool->cr_cond, bfg_condattr)))
  931. quit(1, "Failed to pthread_cond_init in add_pool");
  932. cglock_init(&pool->data_lock);
  933. mutex_init(&pool->stratum_lock);
  934. timer_unset(&pool->swork.tv_transparency);
  935. pool->swork.pool = pool;
  936. pool->idle = true;
  937. /* Make sure the pool doesn't think we've been idle since time 0 */
  938. pool->tv_idle.tv_sec = ~0UL;
  939. cgtime(&pool->cgminer_stats.start_tv);
  940. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  941. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  942. pool->rpc_proxy = NULL;
  943. pool->quota = 1;
  944. pool->sock = INVSOCK;
  945. pool->lp_socket = CURL_SOCKET_BAD;
  946. pools = realloc(pools, sizeof(struct pool *) * (total_pools + 2));
  947. pools[total_pools++] = pool;
  948. if (opt_benchmark)
  949. {
  950. // Immediately remove it
  951. remove_pool(pool);
  952. return pool;
  953. }
  954. adjust_quota_gcd();
  955. if (!currentpool)
  956. currentpool = pool;
  957. enable_pool(pool);
  958. return pool;
  959. }
  960. static
  961. void pool_set_uri(struct pool * const pool, char * const uri)
  962. {
  963. pool->rpc_url = uri;
  964. #if BLKMAKER_VERSION > 1
  965. if (uri_get_param_bool(uri, "getcbaddr", false))
  966. have_at_least_one_getcbaddr = true;
  967. #endif
  968. }
  969. /* Pool variant of test and set */
  970. static bool pool_tset(struct pool *pool, bool *var)
  971. {
  972. bool ret;
  973. mutex_lock(&pool->pool_lock);
  974. ret = *var;
  975. *var = true;
  976. mutex_unlock(&pool->pool_lock);
  977. return ret;
  978. }
  979. bool pool_tclear(struct pool *pool, bool *var)
  980. {
  981. bool ret;
  982. mutex_lock(&pool->pool_lock);
  983. ret = *var;
  984. *var = false;
  985. mutex_unlock(&pool->pool_lock);
  986. return ret;
  987. }
  988. struct pool *current_pool(void)
  989. {
  990. struct pool *pool;
  991. cg_rlock(&control_lock);
  992. pool = currentpool;
  993. cg_runlock(&control_lock);
  994. return pool;
  995. }
  996. static
  997. char *set_bool_ignore_arg(const char * const arg, bool * const b)
  998. {
  999. return opt_set_bool(b);
  1000. }
  1001. char *set_int_range(const char *arg, int *i, int min, int max)
  1002. {
  1003. char *err = opt_set_intval(arg, i);
  1004. if (err)
  1005. return err;
  1006. if (*i < min || *i > max)
  1007. return "Value out of range";
  1008. return NULL;
  1009. }
  1010. static char *set_int_0_to_9999(const char *arg, int *i)
  1011. {
  1012. return set_int_range(arg, i, 0, 9999);
  1013. }
  1014. static char *set_int_1_to_65535(const char *arg, int *i)
  1015. {
  1016. return set_int_range(arg, i, 1, 65535);
  1017. }
  1018. static char *set_int_0_to_10(const char *arg, int *i)
  1019. {
  1020. return set_int_range(arg, i, 0, 10);
  1021. }
  1022. static char *set_int_1_to_10(const char *arg, int *i)
  1023. {
  1024. return set_int_range(arg, i, 1, 10);
  1025. }
  1026. char *set_strdup(const char *arg, char **p)
  1027. {
  1028. *p = strdup((char *)arg);
  1029. return NULL;
  1030. }
  1031. #if BLKMAKER_VERSION > 1
  1032. static
  1033. char *set_b58addr(const char * const arg, bytes_t * const b)
  1034. {
  1035. size_t scriptsz = blkmk_address_to_script(NULL, 0, arg);
  1036. if (!scriptsz)
  1037. return "Invalid address";
  1038. char *script = malloc(scriptsz);
  1039. if (blkmk_address_to_script(script, scriptsz, arg) != scriptsz) {
  1040. free(script);
  1041. return "Failed to convert address to script";
  1042. }
  1043. bytes_assimilate_raw(b, script, scriptsz, scriptsz);
  1044. return NULL;
  1045. }
  1046. #endif
  1047. static
  1048. char *set_quit_summary(const char * const arg)
  1049. {
  1050. if (!(strcasecmp(arg, "none") && strcasecmp(arg, "no")))
  1051. opt_quit_summary = BQS_NONE;
  1052. else
  1053. if (!(strcasecmp(arg, "devs") && strcasecmp(arg, "devices")))
  1054. opt_quit_summary = BQS_DEVS;
  1055. else
  1056. if (!(strcasecmp(arg, "procs") && strcasecmp(arg, "processors") && strcasecmp(arg, "chips") && strcasecmp(arg, "cores")))
  1057. opt_quit_summary = BQS_PROCS;
  1058. else
  1059. if (!(strcasecmp(arg, "detailed") && strcasecmp(arg, "detail") && strcasecmp(arg, "all")))
  1060. opt_quit_summary = BQS_DETAILED;
  1061. else
  1062. return "Quit summary must be one of none/devs/procs/detailed";
  1063. return NULL;
  1064. }
  1065. static void pdiff_target_leadzero(void *, double);
  1066. char *set_request_diff(const char *arg, float *p)
  1067. {
  1068. unsigned char target[32];
  1069. char *e = opt_set_floatval(arg, p);
  1070. if (e)
  1071. return e;
  1072. request_bdiff = (double)*p * 0.9999847412109375;
  1073. pdiff_target_leadzero(target, *p);
  1074. request_target_str = malloc(65);
  1075. bin2hex(request_target_str, target, 32);
  1076. return NULL;
  1077. }
  1078. #ifdef NEED_BFG_LOWL_VCOM
  1079. extern struct lowlevel_device_info *_vcom_devinfo_findorcreate(struct lowlevel_device_info **, const char *);
  1080. #ifdef WIN32
  1081. void _vcom_devinfo_scan_querydosdevice(struct lowlevel_device_info ** const devinfo_list)
  1082. {
  1083. char dev[PATH_MAX];
  1084. char *devp = dev;
  1085. size_t bufLen = 0x100;
  1086. tryagain: ;
  1087. char buf[bufLen];
  1088. if (!QueryDosDevice(NULL, buf, bufLen)) {
  1089. if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
  1090. bufLen *= 2;
  1091. applog(LOG_DEBUG, "QueryDosDevice returned insufficent buffer error; enlarging to %lx", (unsigned long)bufLen);
  1092. goto tryagain;
  1093. }
  1094. applogr(, LOG_WARNING, "Error occurred trying to enumerate COM ports with QueryDosDevice");
  1095. }
  1096. size_t tLen;
  1097. memcpy(devp, "\\\\.\\", 4);
  1098. devp = &devp[4];
  1099. for (char *t = buf; *t; t += tLen) {
  1100. tLen = strlen(t) + 1;
  1101. if (strncmp("COM", t, 3))
  1102. continue;
  1103. memcpy(devp, t, tLen);
  1104. // NOTE: We depend on _vcom_devinfo_findorcreate to further check that there's a number (and only a number) on the end
  1105. _vcom_devinfo_findorcreate(devinfo_list, dev);
  1106. }
  1107. }
  1108. #else
  1109. void _vcom_devinfo_scan_lsdev(struct lowlevel_device_info ** const devinfo_list)
  1110. {
  1111. char dev[PATH_MAX];
  1112. char *devp = dev;
  1113. DIR *D;
  1114. struct dirent *de;
  1115. const char devdir[] = "/dev";
  1116. const size_t devdirlen = sizeof(devdir) - 1;
  1117. char *devpath = devp;
  1118. char *devfile = devpath + devdirlen + 1;
  1119. D = opendir(devdir);
  1120. if (!D)
  1121. applogr(, LOG_DEBUG, "No /dev directory to look for VCOM devices in");
  1122. memcpy(devpath, devdir, devdirlen);
  1123. devpath[devdirlen] = '/';
  1124. while ( (de = readdir(D)) ) {
  1125. if (!strncmp(de->d_name, "cu.", 3)
  1126. //don't probe Bluetooth devices - causes bus errors and segfaults
  1127. && strncmp(de->d_name, "cu.Bluetooth", 12))
  1128. goto trydev;
  1129. if (strncmp(de->d_name, "tty", 3))
  1130. continue;
  1131. if (strncmp(&de->d_name[3], "USB", 3) && strncmp(&de->d_name[3], "ACM", 3))
  1132. continue;
  1133. trydev:
  1134. strcpy(devfile, de->d_name);
  1135. _vcom_devinfo_findorcreate(devinfo_list, dev);
  1136. }
  1137. closedir(D);
  1138. }
  1139. #endif
  1140. #endif
  1141. static char *add_serial(const char *arg)
  1142. {
  1143. string_elist_add(arg, &scan_devices);
  1144. return NULL;
  1145. }
  1146. static
  1147. char *opt_string_elist_add(const char *arg, struct string_elist **elist)
  1148. {
  1149. string_elist_add(arg, elist);
  1150. return NULL;
  1151. }
  1152. bool get_intrange(const char *arg, int *val1, int *val2)
  1153. {
  1154. // NOTE: This could be done with sscanf, but its %n is broken in strange ways on Windows
  1155. char *p, *p2;
  1156. *val1 = strtol(arg, &p, 0);
  1157. if (arg == p)
  1158. // Zero-length ending number, invalid
  1159. return false;
  1160. while (true)
  1161. {
  1162. if (!p[0])
  1163. {
  1164. *val2 = *val1;
  1165. return true;
  1166. }
  1167. if (p[0] == '-')
  1168. break;
  1169. if (!isspace(p[0]))
  1170. // Garbage, invalid
  1171. return false;
  1172. ++p;
  1173. }
  1174. p2 = &p[1];
  1175. *val2 = strtol(p2, &p, 0);
  1176. if (p2 == p)
  1177. // Zero-length ending number, invalid
  1178. return false;
  1179. while (true)
  1180. {
  1181. if (!p[0])
  1182. return true;
  1183. if (!isspace(p[0]))
  1184. // Garbage, invalid
  1185. return false;
  1186. ++p;
  1187. }
  1188. }
  1189. static
  1190. void _test_intrange(const char *s, const int v[2])
  1191. {
  1192. int a[2];
  1193. if (!get_intrange(s, &a[0], &a[1]))
  1194. applog(LOG_ERR, "Test \"%s\" failed: returned false", s);
  1195. for (int i = 0; i < 2; ++i)
  1196. if (unlikely(a[i] != v[i]))
  1197. applog(LOG_ERR, "Test \"%s\" failed: value %d should be %d but got %d", s, i, v[i], a[i]);
  1198. }
  1199. #define _test_intrange(s, ...) _test_intrange(s, (int[]){ __VA_ARGS__ })
  1200. static
  1201. void _test_intrange_fail(const char *s)
  1202. {
  1203. int a[2];
  1204. if (get_intrange(s, &a[0], &a[1]))
  1205. applog(LOG_ERR, "Test !\"%s\" failed: returned true with %d and %d", s, a[0], a[1]);
  1206. }
  1207. static
  1208. void test_intrange()
  1209. {
  1210. _test_intrange("-1--2", -1, -2);
  1211. _test_intrange("-1-2", -1, 2);
  1212. _test_intrange("1--2", 1, -2);
  1213. _test_intrange("1-2", 1, 2);
  1214. _test_intrange("111-222", 111, 222);
  1215. _test_intrange(" 11 - 22 ", 11, 22);
  1216. _test_intrange("+11-+22", 11, 22);
  1217. _test_intrange("-1", -1, -1);
  1218. _test_intrange_fail("all");
  1219. _test_intrange_fail("1-");
  1220. _test_intrange_fail("");
  1221. _test_intrange_fail("1-54x");
  1222. }
  1223. static char *set_devices(char *arg)
  1224. {
  1225. if (*arg) {
  1226. if (*arg == '?') {
  1227. opt_display_devs = true;
  1228. return NULL;
  1229. }
  1230. } else
  1231. return "Invalid device parameters";
  1232. string_elist_add(arg, &opt_devices_enabled_list);
  1233. return NULL;
  1234. }
  1235. static char *set_balance(enum pool_strategy *strategy)
  1236. {
  1237. *strategy = POOL_BALANCE;
  1238. return NULL;
  1239. }
  1240. static char *set_loadbalance(enum pool_strategy *strategy)
  1241. {
  1242. *strategy = POOL_LOADBALANCE;
  1243. return NULL;
  1244. }
  1245. static char *set_rotate(const char *arg, int *i)
  1246. {
  1247. pool_strategy = POOL_ROTATE;
  1248. return set_int_range(arg, i, 0, 9999);
  1249. }
  1250. static char *set_rr(enum pool_strategy *strategy)
  1251. {
  1252. *strategy = POOL_ROUNDROBIN;
  1253. return NULL;
  1254. }
  1255. static
  1256. char *set_benchmark_intense()
  1257. {
  1258. opt_benchmark = true;
  1259. opt_benchmark_intense = true;
  1260. return NULL;
  1261. }
  1262. /* Detect that url is for a stratum protocol either via the presence of
  1263. * stratum+tcp or by detecting a stratum server response */
  1264. bool detect_stratum(struct pool *pool, char *url)
  1265. {
  1266. if (!extract_sockaddr(url, &pool->sockaddr_url, &pool->stratum_port))
  1267. return false;
  1268. if (!strncasecmp(url, "stratum+tcp://", 14)) {
  1269. pool_set_uri(pool, strdup(url));
  1270. pool->has_stratum = true;
  1271. pool->stratum_url = pool->sockaddr_url;
  1272. return true;
  1273. }
  1274. return false;
  1275. }
  1276. static struct pool *add_url(void)
  1277. {
  1278. total_urls++;
  1279. if (total_urls > total_pools)
  1280. add_pool();
  1281. return pools[total_urls - 1];
  1282. }
  1283. static void setup_url(struct pool *pool, char *arg)
  1284. {
  1285. if (detect_stratum(pool, arg))
  1286. return;
  1287. opt_set_charp(arg, &pool->rpc_url);
  1288. if (strncmp(arg, "http://", 7) &&
  1289. strncmp(arg, "https://", 8)) {
  1290. const size_t L = strlen(arg);
  1291. char *httpinput;
  1292. httpinput = malloc(8 + L);
  1293. if (!httpinput)
  1294. quit(1, "Failed to malloc httpinput");
  1295. sprintf(httpinput, "http://%s", arg);
  1296. pool_set_uri(pool, httpinput);
  1297. }
  1298. }
  1299. static char *set_url(char *arg)
  1300. {
  1301. struct pool *pool = add_url();
  1302. setup_url(pool, arg);
  1303. return NULL;
  1304. }
  1305. static char *set_quota(char *arg)
  1306. {
  1307. char *semicolon = strchr(arg, ';'), *url;
  1308. int len, qlen, quota;
  1309. struct pool *pool;
  1310. if (!semicolon)
  1311. return "No semicolon separated quota;URL pair found";
  1312. len = strlen(arg);
  1313. *semicolon = '\0';
  1314. qlen = strlen(arg);
  1315. if (!qlen)
  1316. return "No parameter for quota found";
  1317. len -= qlen + 1;
  1318. if (len < 1)
  1319. return "No parameter for URL found";
  1320. quota = atoi(arg);
  1321. if (quota < 0)
  1322. return "Invalid negative parameter for quota set";
  1323. url = arg + qlen + 1;
  1324. pool = add_url();
  1325. setup_url(pool, url);
  1326. pool->quota = quota;
  1327. applog(LOG_INFO, "Setting pool %d to quota %d", pool->pool_no, pool->quota);
  1328. adjust_quota_gcd();
  1329. return NULL;
  1330. }
  1331. static char *set_user(const char *arg)
  1332. {
  1333. struct pool *pool;
  1334. total_users++;
  1335. if (total_users > total_pools)
  1336. add_pool();
  1337. pool = pools[total_users - 1];
  1338. opt_set_charp(arg, &pool->rpc_user);
  1339. return NULL;
  1340. }
  1341. static char *set_pass(const char *arg)
  1342. {
  1343. struct pool *pool;
  1344. total_passes++;
  1345. if (total_passes > total_pools)
  1346. add_pool();
  1347. pool = pools[total_passes - 1];
  1348. opt_set_charp(arg, &pool->rpc_pass);
  1349. return NULL;
  1350. }
  1351. static char *set_userpass(const char *arg)
  1352. {
  1353. struct pool *pool;
  1354. char *updup;
  1355. if (total_users != total_passes)
  1356. return "User + pass options must be balanced before userpass";
  1357. ++total_users;
  1358. ++total_passes;
  1359. if (total_users > total_pools)
  1360. add_pool();
  1361. pool = pools[total_users - 1];
  1362. updup = strdup(arg);
  1363. opt_set_charp(arg, &pool->rpc_userpass);
  1364. pool->rpc_user = updup;
  1365. pool->rpc_pass = strchr(updup, ':');
  1366. if (pool->rpc_pass)
  1367. pool->rpc_pass++[0] = '\0';
  1368. else
  1369. pool->rpc_pass = &updup[strlen(updup)];
  1370. return NULL;
  1371. }
  1372. static char *set_pool_priority(const char *arg)
  1373. {
  1374. struct pool *pool;
  1375. if (!total_pools)
  1376. return "Usage of --pool-priority before pools are defined does not make sense";
  1377. pool = pools[total_pools - 1];
  1378. opt_set_intval(arg, &pool->prio);
  1379. return NULL;
  1380. }
  1381. static char *set_pool_proxy(const char *arg)
  1382. {
  1383. struct pool *pool;
  1384. if (!total_pools)
  1385. return "Usage of --pool-proxy before pools are defined does not make sense";
  1386. if (!our_curl_supports_proxy_uris())
  1387. return "Your installed cURL library does not support proxy URIs. At least version 7.21.7 is required.";
  1388. pool = pools[total_pools - 1];
  1389. opt_set_charp(arg, &pool->rpc_proxy);
  1390. return NULL;
  1391. }
  1392. static char *set_pool_force_rollntime(const char *arg)
  1393. {
  1394. struct pool *pool;
  1395. if (!total_pools)
  1396. return "Usage of --force-rollntime before pools are defined does not make sense";
  1397. pool = pools[total_pools - 1];
  1398. opt_set_intval(arg, &pool->force_rollntime);
  1399. return NULL;
  1400. }
  1401. static char *enable_debug(bool *flag)
  1402. {
  1403. *flag = true;
  1404. opt_debug_console = true;
  1405. /* Turn on verbose output, too. */
  1406. opt_log_output = true;
  1407. return NULL;
  1408. }
  1409. static char *set_schedtime(const char *arg, struct schedtime *st)
  1410. {
  1411. if (sscanf(arg, "%d:%d", &st->tm.tm_hour, &st->tm.tm_min) != 2)
  1412. {
  1413. if (strcasecmp(arg, "now"))
  1414. return "Invalid time set, should be HH:MM";
  1415. } else
  1416. schedstop.tm.tm_sec = 0;
  1417. if (st->tm.tm_hour > 23 || st->tm.tm_min > 59 || st->tm.tm_hour < 0 || st->tm.tm_min < 0)
  1418. return "Invalid time set.";
  1419. st->enable = true;
  1420. return NULL;
  1421. }
  1422. static
  1423. char *set_log_file(char *arg)
  1424. {
  1425. char *r = "";
  1426. long int i = strtol(arg, &r, 10);
  1427. int fd, stderr_fd = fileno(stderr);
  1428. if ((!*r) && i >= 0 && i <= INT_MAX)
  1429. fd = i;
  1430. else
  1431. if (!strcmp(arg, "-"))
  1432. {
  1433. fd = fileno(stdout);
  1434. if (unlikely(fd == -1))
  1435. return "Standard output missing for log-file";
  1436. }
  1437. else
  1438. {
  1439. fd = open(arg, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR);
  1440. if (unlikely(fd == -1))
  1441. return "Failed to open log-file";
  1442. }
  1443. close(stderr_fd);
  1444. if (unlikely(-1 == dup2(fd, stderr_fd)))
  1445. return "Failed to dup2 for log-file";
  1446. close(fd);
  1447. return NULL;
  1448. }
  1449. static
  1450. char *_bfgopt_set_file(const char *arg, FILE **F, const char *mode, const char *purpose)
  1451. {
  1452. char *r = "";
  1453. long int i = strtol(arg, &r, 10);
  1454. static char *err = NULL;
  1455. const size_t errbufsz = 0x100;
  1456. free(err);
  1457. err = NULL;
  1458. if ((!*r) && i >= 0 && i <= INT_MAX) {
  1459. *F = fdopen((int)i, mode);
  1460. if (!*F)
  1461. {
  1462. err = malloc(errbufsz);
  1463. snprintf(err, errbufsz, "Failed to open fd %d for %s",
  1464. (int)i, purpose);
  1465. return err;
  1466. }
  1467. } else if (!strcmp(arg, "-")) {
  1468. *F = (mode[0] == 'a') ? stdout : stdin;
  1469. if (!*F)
  1470. {
  1471. err = malloc(errbufsz);
  1472. snprintf(err, errbufsz, "Standard %sput missing for %s",
  1473. (mode[0] == 'a') ? "out" : "in", purpose);
  1474. return err;
  1475. }
  1476. } else {
  1477. *F = fopen(arg, mode);
  1478. if (!*F)
  1479. {
  1480. err = malloc(errbufsz);
  1481. snprintf(err, errbufsz, "Failed to open %s for %s",
  1482. arg, purpose);
  1483. return err;
  1484. }
  1485. }
  1486. return NULL;
  1487. }
  1488. static char *set_noncelog(char *arg)
  1489. {
  1490. return _bfgopt_set_file(arg, &noncelog_file, "a", "nonce log");
  1491. }
  1492. static char *set_sharelog(char *arg)
  1493. {
  1494. return _bfgopt_set_file(arg, &sharelog_file, "a", "share log");
  1495. }
  1496. static
  1497. void _add_set_device_option(const char * const func, const char * const buf)
  1498. {
  1499. applog(LOG_DEBUG, "%s: Using --set-device %s", func, buf);
  1500. string_elist_add(buf, &opt_set_device_list);
  1501. }
  1502. #define add_set_device_option(...) do{ \
  1503. char _tmp1718[0x100]; \
  1504. snprintf(_tmp1718, sizeof(_tmp1718), __VA_ARGS__); \
  1505. _add_set_device_option(__func__, _tmp1718); \
  1506. }while(0)
  1507. char *set_temp_cutoff(char *arg)
  1508. {
  1509. if (strchr(arg, ','))
  1510. return "temp-cutoff no longer supports comma-delimited syntax, use --set-device for better control";
  1511. applog(LOG_WARNING, "temp-cutoff is deprecated! Use --set-device for better control");
  1512. add_set_device_option("all:temp-cutoff=%s", arg);
  1513. return NULL;
  1514. }
  1515. char *set_temp_target(char *arg)
  1516. {
  1517. if (strchr(arg, ','))
  1518. return "temp-target no longer supports comma-delimited syntax, use --set-device for better control";
  1519. applog(LOG_WARNING, "temp-target is deprecated! Use --set-device for better control");
  1520. add_set_device_option("all:temp-target=%s", arg);
  1521. return NULL;
  1522. }
  1523. #ifdef HAVE_OPENCL
  1524. static
  1525. char *set_no_opencl_binaries(__maybe_unused void * const dummy)
  1526. {
  1527. applog(LOG_WARNING, "The --no-opencl-binaries option is deprecated! Use --set-device OCL:binary=no");
  1528. add_set_device_option("OCL:binary=no");
  1529. return NULL;
  1530. }
  1531. #endif
  1532. static
  1533. char *disable_pool_redirect(__maybe_unused void * const dummy)
  1534. {
  1535. opt_disable_client_reconnect = true;
  1536. want_stratum = false;
  1537. return NULL;
  1538. }
  1539. static char *set_api_allow(const char *arg)
  1540. {
  1541. opt_set_charp(arg, &opt_api_allow);
  1542. return NULL;
  1543. }
  1544. static char *set_api_groups(const char *arg)
  1545. {
  1546. opt_set_charp(arg, &opt_api_groups);
  1547. return NULL;
  1548. }
  1549. static char *set_api_description(const char *arg)
  1550. {
  1551. opt_set_charp(arg, &opt_api_description);
  1552. return NULL;
  1553. }
  1554. static char *set_api_mcast_des(const char *arg)
  1555. {
  1556. opt_set_charp(arg, &opt_api_mcast_des);
  1557. return NULL;
  1558. }
  1559. #ifdef USE_ICARUS
  1560. extern const struct bfg_set_device_definition icarus_set_device_funcs[];
  1561. static char *set_icarus_options(const char *arg)
  1562. {
  1563. if (strchr(arg, ','))
  1564. return "icarus-options no longer supports comma-delimited syntax, see README.FPGA for better control";
  1565. applog(LOG_WARNING, "icarus-options is deprecated! See README.FPGA for better control");
  1566. char *opts = strdup(arg), *argdup;
  1567. argdup = opts;
  1568. const struct bfg_set_device_definition *sdf = icarus_set_device_funcs;
  1569. const char *drivers[] = {"antminer", "cairnsmore", "erupter", "icarus"};
  1570. char *saveptr, *opt;
  1571. for (int i = 0; i < 4; ++i, ++sdf)
  1572. {
  1573. opt = strtok_r(opts, ":", &saveptr);
  1574. opts = NULL;
  1575. if (!opt)
  1576. break;
  1577. if (!opt[0])
  1578. continue;
  1579. for (int j = 0; j < 4; ++j)
  1580. add_set_device_option("%s:%s=%s", drivers[j], sdf->optname, opt);
  1581. }
  1582. free(argdup);
  1583. return NULL;
  1584. }
  1585. static char *set_icarus_timing(const char *arg)
  1586. {
  1587. if (strchr(arg, ','))
  1588. return "icarus-timing no longer supports comma-delimited syntax, see README.FPGA for better control";
  1589. applog(LOG_WARNING, "icarus-timing is deprecated! See README.FPGA for better control");
  1590. const char *drivers[] = {"antminer", "cairnsmore", "erupter", "icarus"};
  1591. for (int j = 0; j < 4; ++j)
  1592. add_set_device_option("%s:timing=%s", drivers[j], arg);
  1593. return NULL;
  1594. }
  1595. #endif
  1596. #ifdef USE_AVALON
  1597. extern const struct bfg_set_device_definition avalon_set_device_funcs[];
  1598. static char *set_avalon_options(const char *arg)
  1599. {
  1600. if (strchr(arg, ','))
  1601. return "avalon-options no longer supports comma-delimited syntax, see README.FPGA for better control";
  1602. applog(LOG_WARNING, "avalon-options is deprecated! See README.FPGA for better control");
  1603. char *opts = strdup(arg), *argdup;
  1604. argdup = opts;
  1605. const struct bfg_set_device_definition *sdf = avalon_set_device_funcs;
  1606. char *saveptr, *opt;
  1607. for (int i = 0; i < 5; ++i, ++sdf)
  1608. {
  1609. opt = strtok_r(opts, ":", &saveptr);
  1610. opts = NULL;
  1611. if (!opt)
  1612. break;
  1613. if (!opt[0])
  1614. continue;
  1615. add_set_device_option("avalon:%s=%s", sdf->optname, opt);
  1616. }
  1617. free(argdup);
  1618. return NULL;
  1619. }
  1620. #endif
  1621. #ifdef USE_KLONDIKE
  1622. static char *set_klondike_options(const char *arg)
  1623. {
  1624. int hashclock;
  1625. double temptarget;
  1626. switch (sscanf(arg, "%d:%lf", &hashclock, &temptarget))
  1627. {
  1628. default:
  1629. return "Unrecognised --klondike-options";
  1630. case 2:
  1631. add_set_device_option("klondike:temp-target=%lf", temptarget);
  1632. // fallthru
  1633. case 1:
  1634. add_set_device_option("klondike:clock=%d", hashclock);
  1635. }
  1636. applog(LOG_WARNING, "klondike-options is deprecated! Use --set-device for better control");
  1637. return NULL;
  1638. }
  1639. #endif
  1640. __maybe_unused
  1641. static char *set_null(const char __maybe_unused *arg)
  1642. {
  1643. return NULL;
  1644. }
  1645. /* These options are available from config file or commandline */
  1646. static struct opt_table opt_config_table[] = {
  1647. #ifdef WANT_CPUMINE
  1648. OPT_WITH_ARG("--algo",
  1649. set_algo, show_algo, &opt_algo,
  1650. "Specify sha256 implementation for CPU mining:\n"
  1651. "\tfastauto*\tQuick benchmark at startup to pick a working algorithm\n"
  1652. "\tauto\t\tBenchmark at startup and pick fastest algorithm"
  1653. "\n\tc\t\tLinux kernel sha256, implemented in C"
  1654. #ifdef WANT_SSE2_4WAY
  1655. "\n\t4way\t\ttcatm's 4-way SSE2 implementation"
  1656. #endif
  1657. #ifdef WANT_VIA_PADLOCK
  1658. "\n\tvia\t\tVIA padlock implementation"
  1659. #endif
  1660. "\n\tcryptopp\tCrypto++ C/C++ implementation"
  1661. #ifdef WANT_CRYPTOPP_ASM32
  1662. "\n\tcryptopp_asm32\tCrypto++ 32-bit assembler implementation"
  1663. #endif
  1664. #ifdef WANT_X8632_SSE2
  1665. "\n\tsse2_32\t\tSSE2 32 bit implementation for i386 machines"
  1666. #endif
  1667. #ifdef WANT_X8664_SSE2
  1668. "\n\tsse2_64\t\tSSE2 64 bit implementation for x86_64 machines"
  1669. #endif
  1670. #ifdef WANT_X8664_SSE4
  1671. "\n\tsse4_64\t\tSSE4.1 64 bit implementation for x86_64 machines"
  1672. #endif
  1673. #ifdef WANT_ALTIVEC_4WAY
  1674. "\n\taltivec_4way\tAltivec implementation for PowerPC G4 and G5 machines"
  1675. #endif
  1676. ),
  1677. OPT_WITH_ARG("-a",
  1678. set_algo, show_algo, &opt_algo,
  1679. opt_hidden),
  1680. #endif
  1681. OPT_WITH_ARG("--api-allow",
  1682. set_api_allow, NULL, NULL,
  1683. "Allow API access only to the given list of [G:]IP[/Prefix] addresses[/subnets]"),
  1684. OPT_WITH_ARG("--api-description",
  1685. set_api_description, NULL, NULL,
  1686. "Description placed in the API status header, default: BFGMiner version"),
  1687. OPT_WITH_ARG("--api-groups",
  1688. set_api_groups, NULL, NULL,
  1689. "API one letter groups G:cmd:cmd[,P:cmd:*...] defining the cmds a groups can use"),
  1690. OPT_WITHOUT_ARG("--api-listen",
  1691. opt_set_bool, &opt_api_listen,
  1692. "Enable API, default: disabled"),
  1693. OPT_WITHOUT_ARG("--api-mcast",
  1694. opt_set_bool, &opt_api_mcast,
  1695. "Enable API Multicast listener, default: disabled"),
  1696. OPT_WITH_ARG("--api-mcast-addr",
  1697. opt_set_charp, opt_show_charp, &opt_api_mcast_addr,
  1698. "API Multicast listen address"),
  1699. OPT_WITH_ARG("--api-mcast-code",
  1700. opt_set_charp, opt_show_charp, &opt_api_mcast_code,
  1701. "Code expected in the API Multicast message, don't use '-'"),
  1702. OPT_WITH_ARG("--api-mcast-des",
  1703. set_api_mcast_des, NULL, NULL,
  1704. "Description appended to the API Multicast reply, default: ''"),
  1705. OPT_WITH_ARG("--api-mcast-port",
  1706. set_int_1_to_65535, opt_show_intval, &opt_api_mcast_port,
  1707. "API Multicast listen port"),
  1708. OPT_WITHOUT_ARG("--api-network",
  1709. opt_set_bool, &opt_api_network,
  1710. "Allow API (if enabled) to listen on/for any address, default: only 127.0.0.1"),
  1711. OPT_WITH_ARG("--api-port",
  1712. set_int_1_to_65535, opt_show_intval, &opt_api_port,
  1713. "Port number of miner API"),
  1714. #ifdef HAVE_ADL
  1715. OPT_WITHOUT_ARG("--auto-fan",
  1716. opt_set_bool, &opt_autofan,
  1717. opt_hidden),
  1718. OPT_WITHOUT_ARG("--auto-gpu",
  1719. opt_set_bool, &opt_autoengine,
  1720. opt_hidden),
  1721. #endif
  1722. OPT_WITHOUT_ARG("--balance",
  1723. set_balance, &pool_strategy,
  1724. "Change multipool strategy from failover to even share balance"),
  1725. OPT_WITHOUT_ARG("--benchmark",
  1726. opt_set_bool, &opt_benchmark,
  1727. "Run BFGMiner in benchmark mode - produces no shares"),
  1728. OPT_WITHOUT_ARG("--benchmark-intense",
  1729. set_benchmark_intense, &opt_benchmark_intense,
  1730. "Run BFGMiner in intensive benchmark mode - produces no shares"),
  1731. #if defined(USE_BITFORCE)
  1732. OPT_WITHOUT_ARG("--bfl-range",
  1733. opt_set_bool, &opt_bfl_noncerange,
  1734. "Use nonce range on bitforce devices if supported"),
  1735. #endif
  1736. #ifdef HAVE_CHROOT
  1737. OPT_WITH_ARG("--chroot-dir",
  1738. opt_set_charp, NULL, &chroot_dir,
  1739. "Chroot to a directory right after startup"),
  1740. #endif
  1741. OPT_WITH_ARG("--cmd-idle",
  1742. opt_set_charp, NULL, &cmd_idle,
  1743. "Execute a command when a device is allowed to be idle (rest or wait)"),
  1744. OPT_WITH_ARG("--cmd-sick",
  1745. opt_set_charp, NULL, &cmd_sick,
  1746. "Execute a command when a device is declared sick"),
  1747. OPT_WITH_ARG("--cmd-dead",
  1748. opt_set_charp, NULL, &cmd_dead,
  1749. "Execute a command when a device is declared dead"),
  1750. #if BLKMAKER_VERSION > 1
  1751. OPT_WITH_ARG("--coinbase-addr",
  1752. set_b58addr, NULL, &opt_coinbase_script,
  1753. "Set coinbase payout address for solo mining"),
  1754. OPT_WITH_ARG("--coinbase-address|--coinbase-payout|--cbaddress|--cbaddr|--cb-address|--cb-addr|--payout",
  1755. set_b58addr, NULL, &opt_coinbase_script,
  1756. opt_hidden),
  1757. #endif
  1758. #if BLKMAKER_VERSION > 0
  1759. OPT_WITH_ARG("--coinbase-sig",
  1760. set_strdup, NULL, &opt_coinbase_sig,
  1761. "Set coinbase signature when possible"),
  1762. OPT_WITH_ARG("--coinbase|--cbsig|--cb-sig|--cb|--prayer",
  1763. set_strdup, NULL, &opt_coinbase_sig,
  1764. opt_hidden),
  1765. #endif
  1766. #ifdef HAVE_CURSES
  1767. OPT_WITHOUT_ARG("--compact",
  1768. opt_set_bool, &opt_compact,
  1769. "Use compact display without per device statistics"),
  1770. #endif
  1771. #ifdef WANT_CPUMINE
  1772. OPT_WITH_ARG("--cpu-threads",
  1773. force_nthreads_int, opt_show_intval, &opt_n_threads,
  1774. "Number of miner CPU threads"),
  1775. OPT_WITH_ARG("-t",
  1776. force_nthreads_int, opt_show_intval, &opt_n_threads,
  1777. opt_hidden),
  1778. #endif
  1779. OPT_WITHOUT_ARG("--debug|-D",
  1780. enable_debug, &opt_debug,
  1781. "Enable debug output"),
  1782. OPT_WITHOUT_ARG("--debuglog",
  1783. opt_set_bool, &opt_debug,
  1784. "Enable debug logging"),
  1785. OPT_WITHOUT_ARG("--device-protocol-dump",
  1786. opt_set_bool, &opt_dev_protocol,
  1787. "Verbose dump of device protocol-level activities"),
  1788. OPT_WITH_ARG("--device|-d",
  1789. set_devices, NULL, NULL,
  1790. "Enable only devices matching pattern (default: all)"),
  1791. OPT_WITHOUT_ARG("--disable-rejecting",
  1792. opt_set_bool, &opt_disable_pool,
  1793. "Automatically disable pools that continually reject shares"),
  1794. #ifdef USE_LIBMICROHTTPD
  1795. OPT_WITH_ARG("--http-port",
  1796. opt_set_intval, opt_show_intval, &httpsrv_port,
  1797. "Port number to listen on for HTTP getwork miners (-1 means disabled)"),
  1798. #endif
  1799. OPT_WITH_ARG("--expiry",
  1800. set_int_0_to_9999, opt_show_intval, &opt_expiry,
  1801. "Upper bound on how many seconds after getting work we consider a share from it stale (w/o longpoll active)"),
  1802. OPT_WITH_ARG("-E",
  1803. set_int_0_to_9999, opt_show_intval, &opt_expiry,
  1804. opt_hidden),
  1805. OPT_WITH_ARG("--expiry-lp",
  1806. set_int_0_to_9999, opt_show_intval, &opt_expiry_lp,
  1807. "Upper bound on how many seconds after getting work we consider a share from it stale (with longpoll active)"),
  1808. OPT_WITHOUT_ARG("--failover-only",
  1809. opt_set_bool, &opt_fail_only,
  1810. "Don't leak work to backup pools when primary pool is lagging"),
  1811. OPT_WITH_ARG("--failover-switch-delay",
  1812. set_int_1_to_65535, opt_show_intval, &opt_fail_switch_delay,
  1813. "Delay in seconds before switching back to a failed pool"),
  1814. #ifdef USE_FPGA
  1815. OPT_WITHOUT_ARG("--force-dev-init",
  1816. opt_set_bool, &opt_force_dev_init,
  1817. "Always initialize devices when possible (such as bitstream uploads to some FPGAs)"),
  1818. #endif
  1819. #ifdef HAVE_OPENCL
  1820. OPT_WITH_ARG("--gpu-dyninterval",
  1821. set_int_1_to_65535, opt_show_intval, &opt_dynamic_interval,
  1822. opt_hidden),
  1823. OPT_WITH_ARG("--gpu-platform",
  1824. set_int_0_to_9999, opt_show_intval, &opt_platform_id,
  1825. "Select OpenCL platform ID to use for GPU mining"),
  1826. OPT_WITH_ARG("--gpu-threads|-g",
  1827. set_gpu_threads, opt_show_intval, &opt_g_threads,
  1828. opt_hidden),
  1829. #ifdef HAVE_ADL
  1830. OPT_WITH_ARG("--gpu-engine",
  1831. set_gpu_engine, NULL, NULL,
  1832. opt_hidden),
  1833. OPT_WITH_ARG("--gpu-fan",
  1834. set_gpu_fan, NULL, NULL,
  1835. opt_hidden),
  1836. OPT_WITH_ARG("--gpu-map",
  1837. set_gpu_map, NULL, NULL,
  1838. "Map OpenCL to ADL device order manually, paired CSV (e.g. 1:0,2:1 maps OpenCL 1 to ADL 0, 2 to 1)"),
  1839. OPT_WITH_ARG("--gpu-memclock",
  1840. set_gpu_memclock, NULL, NULL,
  1841. opt_hidden),
  1842. OPT_WITH_ARG("--gpu-memdiff",
  1843. set_gpu_memdiff, NULL, NULL,
  1844. opt_hidden),
  1845. OPT_WITH_ARG("--gpu-powertune",
  1846. set_gpu_powertune, NULL, NULL,
  1847. opt_hidden),
  1848. OPT_WITHOUT_ARG("--gpu-reorder",
  1849. opt_set_bool, &opt_reorder,
  1850. "Attempt to reorder GPU devices according to PCI Bus ID"),
  1851. OPT_WITH_ARG("--gpu-vddc",
  1852. set_gpu_vddc, NULL, NULL,
  1853. opt_hidden),
  1854. #endif
  1855. #ifdef USE_SCRYPT
  1856. OPT_WITH_ARG("--lookup-gap",
  1857. set_lookup_gap, NULL, NULL,
  1858. opt_hidden),
  1859. #endif
  1860. OPT_WITH_ARG("--intensity|-I",
  1861. set_intensity, NULL, NULL,
  1862. opt_hidden),
  1863. #endif
  1864. #if defined(HAVE_OPENCL) || defined(USE_MODMINER) || defined(USE_X6500) || defined(USE_ZTEX)
  1865. OPT_WITH_ARG("--kernel-path",
  1866. opt_set_charp, opt_show_charp, &opt_kernel_path,
  1867. "Specify a path to where bitstream and kernel files are"),
  1868. OPT_WITH_ARG("-K",
  1869. opt_set_charp, opt_show_charp, &opt_kernel_path,
  1870. opt_hidden),
  1871. #endif
  1872. #ifdef HAVE_OPENCL
  1873. OPT_WITH_ARG("--kernel|-k",
  1874. set_kernel, NULL, NULL,
  1875. opt_hidden),
  1876. #endif
  1877. #ifdef USE_ICARUS
  1878. OPT_WITH_ARG("--icarus-options",
  1879. set_icarus_options, NULL, NULL,
  1880. opt_hidden),
  1881. OPT_WITH_ARG("--icarus-timing",
  1882. set_icarus_timing, NULL, NULL,
  1883. opt_hidden),
  1884. #endif
  1885. #ifdef USE_AVALON
  1886. OPT_WITH_ARG("--avalon-options",
  1887. set_avalon_options, NULL, NULL,
  1888. opt_hidden),
  1889. #endif
  1890. #ifdef USE_KLONDIKE
  1891. OPT_WITH_ARG("--klondike-options",
  1892. set_klondike_options, NULL, NULL,
  1893. "Set klondike options clock:temptarget"),
  1894. #endif
  1895. OPT_WITHOUT_ARG("--load-balance",
  1896. set_loadbalance, &pool_strategy,
  1897. "Change multipool strategy from failover to quota based balance"),
  1898. OPT_WITH_ARG("--log|-l",
  1899. set_int_0_to_9999, opt_show_intval, &opt_log_interval,
  1900. "Interval in seconds between log output"),
  1901. OPT_WITH_ARG("--log-file|-L",
  1902. set_log_file, NULL, NULL,
  1903. "Append log file for output messages"),
  1904. OPT_WITH_ARG("--logfile",
  1905. set_log_file, NULL, NULL,
  1906. opt_hidden),
  1907. OPT_WITHOUT_ARG("--log-microseconds",
  1908. opt_set_bool, &opt_log_microseconds,
  1909. "Include microseconds in log output"),
  1910. #if defined(unix) || defined(__APPLE__)
  1911. OPT_WITH_ARG("--monitor|-m",
  1912. opt_set_charp, NULL, &opt_stderr_cmd,
  1913. "Use custom pipe cmd for output messages"),
  1914. #endif // defined(unix)
  1915. OPT_WITHOUT_ARG("--net-delay",
  1916. opt_set_bool, &opt_delaynet,
  1917. "Impose small delays in networking to avoid overloading slow routers"),
  1918. OPT_WITHOUT_ARG("--no-adl",
  1919. opt_set_bool, &opt_noadl,
  1920. #ifdef HAVE_ADL
  1921. "Disable the ATI display library used for monitoring and setting GPU parameters"
  1922. #else
  1923. opt_hidden
  1924. #endif
  1925. ),
  1926. OPT_WITHOUT_ARG("--no-gbt",
  1927. opt_set_invbool, &want_gbt,
  1928. "Disable getblocktemplate support"),
  1929. OPT_WITHOUT_ARG("--no-getwork",
  1930. opt_set_invbool, &want_getwork,
  1931. "Disable getwork support"),
  1932. OPT_WITHOUT_ARG("--no-hotplug",
  1933. #ifdef HAVE_BFG_HOTPLUG
  1934. opt_set_invbool, &opt_hotplug,
  1935. "Disable hotplug detection"
  1936. #else
  1937. set_null, &opt_hotplug,
  1938. opt_hidden
  1939. #endif
  1940. ),
  1941. OPT_WITHOUT_ARG("--no-local-bitcoin",
  1942. #if BLKMAKER_VERSION > 1
  1943. opt_set_invbool, &opt_load_bitcoin_conf,
  1944. "Disable adding pools for local bitcoin RPC servers"),
  1945. #else
  1946. set_null, NULL, opt_hidden),
  1947. #endif
  1948. OPT_WITHOUT_ARG("--no-longpoll",
  1949. opt_set_invbool, &want_longpoll,
  1950. "Disable X-Long-Polling support"),
  1951. OPT_WITHOUT_ARG("--no-pool-disable",
  1952. opt_set_invbool, &opt_disable_pool,
  1953. opt_hidden),
  1954. OPT_WITHOUT_ARG("--no-client-reconnect",
  1955. opt_set_invbool, &opt_disable_client_reconnect,
  1956. opt_hidden),
  1957. OPT_WITHOUT_ARG("--no-pool-redirect",
  1958. disable_pool_redirect, NULL,
  1959. "Ignore pool requests to redirect to another server"),
  1960. OPT_WITHOUT_ARG("--no-restart",
  1961. opt_set_invbool, &opt_restart,
  1962. "Do not attempt to restart devices that hang"
  1963. ),
  1964. OPT_WITHOUT_ARG("--no-show-processors",
  1965. opt_set_invbool, &opt_show_procs,
  1966. opt_hidden),
  1967. OPT_WITHOUT_ARG("--no-show-procs",
  1968. opt_set_invbool, &opt_show_procs,
  1969. opt_hidden),
  1970. OPT_WITHOUT_ARG("--no-stratum",
  1971. opt_set_invbool, &want_stratum,
  1972. "Disable Stratum detection"),
  1973. OPT_WITHOUT_ARG("--no-submit-stale",
  1974. opt_set_invbool, &opt_submit_stale,
  1975. "Don't submit shares if they are detected as stale"),
  1976. #ifdef HAVE_OPENCL
  1977. OPT_WITHOUT_ARG("--no-opencl-binaries",
  1978. set_no_opencl_binaries, NULL,
  1979. opt_hidden),
  1980. #endif
  1981. OPT_WITHOUT_ARG("--no-unicode",
  1982. #ifdef USE_UNICODE
  1983. opt_set_invbool, &use_unicode,
  1984. "Don't use Unicode characters in TUI"
  1985. #else
  1986. set_null, &use_unicode,
  1987. opt_hidden
  1988. #endif
  1989. ),
  1990. OPT_WITH_ARG("--noncelog",
  1991. set_noncelog, NULL, NULL,
  1992. "Create log of all nonces found"),
  1993. OPT_WITH_ARG("--pass|-p",
  1994. set_pass, NULL, NULL,
  1995. "Password for bitcoin JSON-RPC server"),
  1996. OPT_WITHOUT_ARG("--per-device-stats",
  1997. opt_set_bool, &want_per_device_stats,
  1998. "Force verbose mode and output per-device statistics"),
  1999. OPT_WITH_ARG("--userpass|-O", // duplicate to ensure config loads it before pool-priority
  2000. set_userpass, NULL, NULL,
  2001. opt_hidden),
  2002. OPT_WITH_ARG("--pool-priority",
  2003. set_pool_priority, NULL, NULL,
  2004. "Priority for just the previous-defined pool"),
  2005. OPT_WITH_ARG("--pool-proxy|-x",
  2006. set_pool_proxy, NULL, NULL,
  2007. "Proxy URI to use for connecting to just the previous-defined pool"),
  2008. OPT_WITH_ARG("--force-rollntime", // NOTE: must be after --pass for config file ordering
  2009. set_pool_force_rollntime, NULL, NULL,
  2010. opt_hidden),
  2011. OPT_WITHOUT_ARG("--protocol-dump|-P",
  2012. opt_set_bool, &opt_protocol,
  2013. "Verbose dump of protocol-level activities"),
  2014. OPT_WITH_ARG("--queue|-Q",
  2015. set_int_0_to_9999, opt_show_intval, &opt_queue,
  2016. "Minimum number of work items to have queued (0+)"),
  2017. OPT_WITHOUT_ARG("--quiet|-q",
  2018. opt_set_bool, &opt_quiet,
  2019. "Disable logging output, display status and errors"),
  2020. OPT_WITHOUT_ARG("--quiet-work-updates|--quiet-work-update",
  2021. opt_set_bool, &opt_quiet_work_updates,
  2022. opt_hidden),
  2023. OPT_WITH_ARG("--quit-summary",
  2024. set_quit_summary, NULL, NULL,
  2025. "Summary printed when you quit: none/devs/procs/detailed"),
  2026. OPT_WITH_ARG("--quota|-U",
  2027. set_quota, NULL, NULL,
  2028. "quota;URL combination for server with load-balance strategy quotas"),
  2029. OPT_WITHOUT_ARG("--real-quiet",
  2030. opt_set_bool, &opt_realquiet,
  2031. "Disable all output"),
  2032. OPT_WITH_ARG("--request-diff",
  2033. set_request_diff, opt_show_floatval, &request_pdiff,
  2034. "Request a specific difficulty from pools"),
  2035. OPT_WITH_ARG("--retries",
  2036. opt_set_intval, opt_show_intval, &opt_retries,
  2037. "Number of times to retry failed submissions before giving up (-1 means never)"),
  2038. OPT_WITH_ARG("--retry-pause",
  2039. set_null, NULL, NULL,
  2040. opt_hidden),
  2041. OPT_WITH_ARG("--rotate",
  2042. set_rotate, opt_show_intval, &opt_rotate_period,
  2043. "Change multipool strategy from failover to regularly rotate at N minutes"),
  2044. OPT_WITHOUT_ARG("--round-robin",
  2045. set_rr, &pool_strategy,
  2046. "Change multipool strategy from failover to round robin on failure"),
  2047. OPT_WITH_ARG("--scan|-S",
  2048. add_serial, NULL, NULL,
  2049. "Configure how to scan for mining devices"),
  2050. OPT_WITH_ARG("--scan-device|--scan-serial|--devscan",
  2051. add_serial, NULL, NULL,
  2052. opt_hidden),
  2053. OPT_WITH_ARG("--scan-time",
  2054. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  2055. "Upper bound on time spent scanning current work, in seconds"),
  2056. OPT_WITH_ARG("-s",
  2057. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  2058. opt_hidden),
  2059. OPT_WITH_ARG("--scantime",
  2060. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  2061. opt_hidden),
  2062. OPT_WITH_ARG("--sched-start",
  2063. set_schedtime, NULL, &schedstart,
  2064. "Set a time of day in HH:MM to start mining (a once off without a stop time)"),
  2065. OPT_WITH_ARG("--sched-stop",
  2066. set_schedtime, NULL, &schedstop,
  2067. "Set a time of day in HH:MM to stop mining (will quit without a start time)"),
  2068. #ifdef USE_SCRYPT
  2069. OPT_WITHOUT_ARG("--scrypt",
  2070. opt_set_bool, &opt_scrypt,
  2071. "Use the scrypt algorithm for mining (non-bitcoin)"),
  2072. #endif
  2073. OPT_WITH_ARG("--set-device|--set",
  2074. opt_string_elist_add, NULL, &opt_set_device_list,
  2075. "Set default parameters on devices; eg, NFY:osc6_bits=50"),
  2076. #if defined(USE_SCRYPT) && defined(HAVE_OPENCL)
  2077. OPT_WITH_ARG("--shaders",
  2078. set_shaders, NULL, NULL,
  2079. opt_hidden),
  2080. #endif
  2081. #ifdef HAVE_PWD_H
  2082. OPT_WITH_ARG("--setuid",
  2083. opt_set_charp, NULL, &opt_setuid,
  2084. "Username of an unprivileged user to run as"),
  2085. #endif
  2086. OPT_WITH_ARG("--sharelog",
  2087. set_sharelog, NULL, NULL,
  2088. "Append share log to file"),
  2089. OPT_WITH_ARG("--shares",
  2090. opt_set_floatval, NULL, &opt_shares,
  2091. "Quit after mining 2^32 * N hashes worth of shares (default: unlimited)"),
  2092. OPT_WITHOUT_ARG("--show-processors",
  2093. opt_set_bool, &opt_show_procs,
  2094. "Show per processor statistics in summary"),
  2095. OPT_WITHOUT_ARG("--show-procs",
  2096. opt_set_bool, &opt_show_procs,
  2097. opt_hidden),
  2098. OPT_WITH_ARG("--skip-security-checks",
  2099. set_int_0_to_9999, NULL, &opt_skip_checks,
  2100. "Skip security checks sometimes to save bandwidth; only check 1/<arg>th of the time (default: never skip)"),
  2101. OPT_WITH_ARG("--socks-proxy",
  2102. opt_set_charp, NULL, &opt_socks_proxy,
  2103. "Set socks proxy (host:port)"),
  2104. #ifdef USE_LIBEVENT
  2105. OPT_WITH_ARG("--stratum-port",
  2106. opt_set_intval, opt_show_intval, &stratumsrv_port,
  2107. "Port number to listen on for stratum miners (-1 means disabled)"),
  2108. #endif
  2109. OPT_WITHOUT_ARG("--submit-stale",
  2110. opt_set_bool, &opt_submit_stale,
  2111. opt_hidden),
  2112. OPT_WITH_ARG("--submit-threads",
  2113. opt_set_intval, opt_show_intval, &opt_submit_threads,
  2114. "Minimum number of concurrent share submissions (default: 64)"),
  2115. #ifdef HAVE_SYSLOG_H
  2116. OPT_WITHOUT_ARG("--syslog",
  2117. opt_set_bool, &use_syslog,
  2118. "Use system log for output messages (default: standard error)"),
  2119. #endif
  2120. OPT_WITH_ARG("--temp-cutoff",
  2121. set_temp_cutoff, NULL, &opt_cutofftemp,
  2122. opt_hidden),
  2123. OPT_WITH_ARG("--temp-hysteresis",
  2124. set_int_1_to_10, opt_show_intval, &opt_hysteresis,
  2125. "Set how much the temperature can fluctuate outside limits when automanaging speeds"),
  2126. #ifdef HAVE_ADL
  2127. OPT_WITH_ARG("--temp-overheat",
  2128. set_temp_overheat, opt_show_intval, &opt_overheattemp,
  2129. opt_hidden),
  2130. #endif
  2131. OPT_WITH_ARG("--temp-target",
  2132. set_temp_target, NULL, NULL,
  2133. opt_hidden),
  2134. OPT_WITHOUT_ARG("--text-only|-T",
  2135. opt_set_invbool, &use_curses,
  2136. #ifdef HAVE_CURSES
  2137. "Disable ncurses formatted screen output"
  2138. #else
  2139. opt_hidden
  2140. #endif
  2141. ),
  2142. #if defined(USE_SCRYPT) && defined(HAVE_OPENCL)
  2143. OPT_WITH_ARG("--thread-concurrency",
  2144. set_thread_concurrency, NULL, NULL,
  2145. opt_hidden),
  2146. #endif
  2147. #ifdef USE_UNICODE
  2148. OPT_WITHOUT_ARG("--unicode",
  2149. opt_set_bool, &use_unicode,
  2150. "Use Unicode characters in TUI"),
  2151. #endif
  2152. OPT_WITH_ARG("--url|-o",
  2153. set_url, NULL, NULL,
  2154. "URL for bitcoin JSON-RPC server"),
  2155. OPT_WITH_ARG("--user|-u",
  2156. set_user, NULL, NULL,
  2157. "Username for bitcoin JSON-RPC server"),
  2158. #ifdef HAVE_OPENCL
  2159. OPT_WITH_ARG("--vectors|-v",
  2160. set_vector, NULL, NULL,
  2161. opt_hidden),
  2162. #endif
  2163. OPT_WITHOUT_ARG("--verbose",
  2164. opt_set_bool, &opt_log_output,
  2165. "Log verbose output to stderr as well as status output"),
  2166. OPT_WITHOUT_ARG("--verbose-work-updates|--verbose-work-update",
  2167. opt_set_invbool, &opt_quiet_work_updates,
  2168. opt_hidden),
  2169. OPT_WITHOUT_ARG("--weighed-stats",
  2170. opt_set_bool, &opt_weighed_stats,
  2171. "Display statistics weighed to difficulty 1"),
  2172. #ifdef HAVE_OPENCL
  2173. OPT_WITH_ARG("--worksize|-w",
  2174. set_worksize, NULL, NULL,
  2175. opt_hidden),
  2176. #endif
  2177. OPT_WITHOUT_ARG("--unittest",
  2178. opt_set_bool, &opt_unittest, opt_hidden),
  2179. OPT_WITH_ARG("--userpass|-O",
  2180. set_userpass, NULL, NULL,
  2181. "Username:Password pair for bitcoin JSON-RPC server"),
  2182. OPT_WITHOUT_ARG("--worktime",
  2183. opt_set_bool, &opt_worktime,
  2184. "Display extra work time debug information"),
  2185. OPT_WITH_ARG("--pools",
  2186. opt_set_bool, NULL, NULL, opt_hidden),
  2187. OPT_ENDTABLE
  2188. };
  2189. static char *load_config(const char *arg, void __maybe_unused *unused);
  2190. static char *parse_config(json_t *config, bool fileconf, int * const fileconf_load_p)
  2191. {
  2192. static char err_buf[200];
  2193. struct opt_table *opt;
  2194. json_t *val;
  2195. if (fileconf && !*fileconf_load_p)
  2196. *fileconf_load_p = 1;
  2197. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  2198. char *p, *name, *sp;
  2199. /* We don't handle subtables. */
  2200. assert(!(opt->type & OPT_SUBTABLE));
  2201. if (!opt->names)
  2202. continue;
  2203. /* Pull apart the option name(s). */
  2204. name = strdup(opt->names);
  2205. for (p = strtok_r(name, "|", &sp); p; p = strtok_r(NULL, "|", &sp)) {
  2206. char *err = "Invalid value";
  2207. /* Ignore short options. */
  2208. if (p[1] != '-')
  2209. continue;
  2210. val = json_object_get(config, p+2);
  2211. if (!val)
  2212. continue;
  2213. if (opt->type & OPT_HASARG) {
  2214. if (json_is_string(val)) {
  2215. err = opt->cb_arg(json_string_value(val),
  2216. opt->u.arg);
  2217. } else if (json_is_number(val)) {
  2218. char buf[256], *p, *q;
  2219. snprintf(buf, 256, "%f", json_number_value(val));
  2220. if ( (p = strchr(buf, '.')) ) {
  2221. // Trim /\.0*$/ to work properly with integer-only arguments
  2222. q = p;
  2223. while (*(++q) == '0') {}
  2224. if (*q == '\0')
  2225. *p = '\0';
  2226. }
  2227. err = opt->cb_arg(buf, opt->u.arg);
  2228. } else if (json_is_array(val)) {
  2229. int n, size = json_array_size(val);
  2230. err = NULL;
  2231. for (n = 0; n < size && !err; n++) {
  2232. if (json_is_string(json_array_get(val, n)))
  2233. err = opt->cb_arg(json_string_value(json_array_get(val, n)), opt->u.arg);
  2234. else if (json_is_object(json_array_get(val, n)))
  2235. err = parse_config(json_array_get(val, n), false, fileconf_load_p);
  2236. }
  2237. }
  2238. } else if (opt->type & OPT_NOARG) {
  2239. if (json_is_true(val))
  2240. err = opt->cb(opt->u.arg);
  2241. else if (json_is_boolean(val)) {
  2242. if (opt->cb == (void*)opt_set_bool)
  2243. err = opt_set_invbool(opt->u.arg);
  2244. else if (opt->cb == (void*)opt_set_invbool)
  2245. err = opt_set_bool(opt->u.arg);
  2246. }
  2247. }
  2248. if (err) {
  2249. /* Allow invalid values to be in configuration
  2250. * file, just skipping over them provided the
  2251. * JSON is still valid after that. */
  2252. if (fileconf) {
  2253. applog(LOG_ERR, "Invalid config option %s: %s", p, err);
  2254. *fileconf_load_p = -1;
  2255. } else {
  2256. snprintf(err_buf, sizeof(err_buf), "Parsing JSON option %s: %s",
  2257. p, err);
  2258. return err_buf;
  2259. }
  2260. }
  2261. }
  2262. free(name);
  2263. }
  2264. val = json_object_get(config, JSON_INCLUDE_CONF);
  2265. if (val && json_is_string(val))
  2266. return load_config(json_string_value(val), NULL);
  2267. return NULL;
  2268. }
  2269. struct bfg_loaded_configfile *bfg_loaded_configfiles;
  2270. static char *load_config(const char *arg, void __maybe_unused *unused)
  2271. {
  2272. json_error_t err;
  2273. json_t *config;
  2274. char *json_error;
  2275. size_t siz;
  2276. struct bfg_loaded_configfile *cfginfo;
  2277. cfginfo = malloc(sizeof(*cfginfo));
  2278. *cfginfo = (struct bfg_loaded_configfile){
  2279. .filename = strdup(arg),
  2280. };
  2281. LL_APPEND(bfg_loaded_configfiles, cfginfo);
  2282. if (++include_count > JSON_MAX_DEPTH)
  2283. return JSON_MAX_DEPTH_ERR;
  2284. #if JANSSON_MAJOR_VERSION > 1
  2285. config = json_load_file(arg, 0, &err);
  2286. #else
  2287. config = json_load_file(arg, &err);
  2288. #endif
  2289. if (!json_is_object(config)) {
  2290. siz = JSON_LOAD_ERROR_LEN + strlen(arg) + strlen(err.text);
  2291. json_error = malloc(siz);
  2292. if (!json_error)
  2293. quit(1, "Malloc failure in json error");
  2294. snprintf(json_error, siz, JSON_LOAD_ERROR, arg, err.text);
  2295. return json_error;
  2296. }
  2297. config_loaded = true;
  2298. /* Parse the config now, so we can override it. That can keep pointers
  2299. * so don't free config object. */
  2300. return parse_config(config, true, &cfginfo->fileconf_load);
  2301. }
  2302. static
  2303. bool _load_default_configs(const char * const filepath, void * __maybe_unused userp)
  2304. {
  2305. bool * const found_defcfg_p = userp;
  2306. *found_defcfg_p = true;
  2307. load_config(filepath, NULL);
  2308. // Regardless of status of loading the config file, we should continue loading other defaults
  2309. return false;
  2310. }
  2311. static void load_default_config(void)
  2312. {
  2313. bool found_defcfg = false;
  2314. appdata_file_call("BFGMiner", def_conf, _load_default_configs, &found_defcfg);
  2315. if (!found_defcfg)
  2316. {
  2317. // No BFGMiner config, try Cgminer's...
  2318. appdata_file_call("cgminer", "cgminer.conf", _load_default_configs, &found_defcfg);
  2319. }
  2320. }
  2321. extern const char *opt_argv0;
  2322. static char *opt_verusage_and_exit(const char *extra)
  2323. {
  2324. puts(packagename);
  2325. printf(" Lowlevel:%s\n", BFG_LOWLLIST);
  2326. printf(" Drivers:%s\n", BFG_DRIVERLIST);
  2327. printf(" Algorithms:%s\n", BFG_ALGOLIST);
  2328. printf(" Options:%s\n", BFG_OPTLIST);
  2329. printf("%s", opt_usage(opt_argv0, extra));
  2330. fflush(stdout);
  2331. exit(0);
  2332. }
  2333. /* These options are parsed before anything else */
  2334. static struct opt_table opt_early_table[] = {
  2335. // Default config is loaded in command line order, like a regular config
  2336. OPT_EARLY_WITH_ARG("--config|-c|--default-config",
  2337. set_bool_ignore_arg, NULL, &config_loaded,
  2338. opt_hidden),
  2339. OPT_EARLY_WITHOUT_ARG("--no-config|--no-default-config",
  2340. opt_set_bool, &config_loaded,
  2341. "Inhibit loading default config file"),
  2342. OPT_ENDTABLE
  2343. };
  2344. /* These options are available from commandline only */
  2345. static struct opt_table opt_cmdline_table[] = {
  2346. OPT_WITH_ARG("--config|-c",
  2347. load_config, NULL, NULL,
  2348. "Load a JSON-format configuration file\n"
  2349. "See example.conf for an example configuration."),
  2350. OPT_EARLY_WITHOUT_ARG("--no-config",
  2351. opt_set_bool, &config_loaded,
  2352. opt_hidden),
  2353. OPT_EARLY_WITHOUT_ARG("--no-default-config",
  2354. opt_set_bool, &config_loaded,
  2355. "Inhibit loading default config file"),
  2356. OPT_WITHOUT_ARG("--default-config",
  2357. load_default_config, NULL,
  2358. "Always load the default config file"),
  2359. OPT_WITHOUT_ARG("--help|-h",
  2360. opt_verusage_and_exit, NULL,
  2361. "Print this message"),
  2362. #ifdef HAVE_OPENCL
  2363. OPT_WITHOUT_ARG("--ndevs|-n",
  2364. print_ndevs_and_exit, &nDevs,
  2365. opt_hidden),
  2366. #endif
  2367. OPT_WITHOUT_ARG("--version|-V",
  2368. opt_version_and_exit, packagename,
  2369. "Display version and exit"),
  2370. OPT_ENDTABLE
  2371. };
  2372. static bool jobj_binary(const json_t *obj, const char *key,
  2373. void *buf, size_t buflen, bool required)
  2374. {
  2375. const char *hexstr;
  2376. json_t *tmp;
  2377. tmp = json_object_get(obj, key);
  2378. if (unlikely(!tmp)) {
  2379. if (unlikely(required))
  2380. applog(LOG_ERR, "JSON key '%s' not found", key);
  2381. return false;
  2382. }
  2383. hexstr = json_string_value(tmp);
  2384. if (unlikely(!hexstr)) {
  2385. applog(LOG_ERR, "JSON key '%s' is not a string", key);
  2386. return false;
  2387. }
  2388. if (!hex2bin(buf, hexstr, buflen))
  2389. return false;
  2390. return true;
  2391. }
  2392. static void calc_midstate(struct work *work)
  2393. {
  2394. union {
  2395. unsigned char c[64];
  2396. uint32_t i[16];
  2397. } data;
  2398. swap32yes(&data.i[0], work->data, 16);
  2399. sha256_ctx ctx;
  2400. sha256_init(&ctx);
  2401. sha256_update(&ctx, data.c, 64);
  2402. memcpy(work->midstate, ctx.h, sizeof(work->midstate));
  2403. swap32tole(work->midstate, work->midstate, 8);
  2404. }
  2405. static
  2406. struct bfg_tmpl_ref *tmpl_makeref(blktemplate_t * const tmpl)
  2407. {
  2408. struct bfg_tmpl_ref * const tr = malloc(sizeof(*tr));
  2409. *tr = (struct bfg_tmpl_ref){
  2410. .tmpl = tmpl,
  2411. .refcount = 1,
  2412. };
  2413. mutex_init(&tr->mutex);
  2414. return tr;
  2415. }
  2416. static
  2417. void tmpl_incref(struct bfg_tmpl_ref * const tr)
  2418. {
  2419. mutex_lock(&tr->mutex);
  2420. ++tr->refcount;
  2421. mutex_unlock(&tr->mutex);
  2422. }
  2423. void tmpl_decref(struct bfg_tmpl_ref * const tr)
  2424. {
  2425. mutex_lock(&tr->mutex);
  2426. bool free_tmpl = !--tr->refcount;
  2427. mutex_unlock(&tr->mutex);
  2428. if (free_tmpl)
  2429. {
  2430. blktmpl_free(tr->tmpl);
  2431. mutex_destroy(&tr->mutex);
  2432. free(tr);
  2433. }
  2434. }
  2435. static struct work *make_work(void)
  2436. {
  2437. struct work *work = calloc(1, sizeof(struct work));
  2438. if (unlikely(!work))
  2439. quit(1, "Failed to calloc work in make_work");
  2440. cg_wlock(&control_lock);
  2441. work->id = total_work++;
  2442. cg_wunlock(&control_lock);
  2443. return work;
  2444. }
  2445. /* This is the central place all work that is about to be retired should be
  2446. * cleaned to remove any dynamically allocated arrays within the struct */
  2447. void clean_work(struct work *work)
  2448. {
  2449. free(work->job_id);
  2450. bytes_free(&work->nonce2);
  2451. free(work->nonce1);
  2452. if (work->device_data_free_func)
  2453. work->device_data_free_func(work);
  2454. if (work->tr)
  2455. tmpl_decref(work->tr);
  2456. memset(work, 0, sizeof(struct work));
  2457. }
  2458. /* All dynamically allocated work structs should be freed here to not leak any
  2459. * ram from arrays allocated within the work struct */
  2460. void free_work(struct work *work)
  2461. {
  2462. clean_work(work);
  2463. free(work);
  2464. }
  2465. const char *bfg_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";
  2466. #define workpadding_bin bfg_workpadding_bin
  2467. // Must only be called with ch_lock held!
  2468. static
  2469. void __update_block_title(const unsigned char *hash_swap)
  2470. {
  2471. if (hash_swap) {
  2472. char tmp[17];
  2473. // Only provided when the block has actually changed
  2474. free(current_hash);
  2475. current_hash = malloc(3 /* ... */ + 16 /* block hash segment */ + 1);
  2476. bin2hex(tmp, &hash_swap[24], 8);
  2477. memset(current_hash, '.', 3);
  2478. memcpy(&current_hash[3], tmp, 17);
  2479. known_blkheight_current = false;
  2480. } else if (likely(known_blkheight_current)) {
  2481. return;
  2482. }
  2483. if (current_block_id == known_blkheight_blkid) {
  2484. // FIXME: The block number will overflow this sometime around AD 2025-2027
  2485. if (known_blkheight < 1000000) {
  2486. memmove(&current_hash[3], &current_hash[11], 8);
  2487. snprintf(&current_hash[11], 20-11, " #%6u", known_blkheight);
  2488. }
  2489. known_blkheight_current = true;
  2490. }
  2491. }
  2492. static
  2493. void have_block_height(uint32_t block_id, uint32_t blkheight)
  2494. {
  2495. if (known_blkheight == blkheight)
  2496. return;
  2497. applog(LOG_DEBUG, "Learned that block id %08" PRIx32 " is height %" PRIu32, (uint32_t)be32toh(block_id), blkheight);
  2498. cg_wlock(&ch_lock);
  2499. known_blkheight = blkheight;
  2500. known_blkheight_blkid = block_id;
  2501. block_subsidy = 5000000000LL >> (blkheight / 210000);
  2502. if (block_id == current_block_id)
  2503. __update_block_title(NULL);
  2504. cg_wunlock(&ch_lock);
  2505. }
  2506. static
  2507. void pool_set_opaque(struct pool *pool, bool opaque)
  2508. {
  2509. if (pool->swork.opaque == opaque)
  2510. return;
  2511. pool->swork.opaque = opaque;
  2512. if (opaque)
  2513. applog(LOG_WARNING, "Pool %u is hiding block contents from us",
  2514. pool->pool_no);
  2515. else
  2516. applog(LOG_NOTICE, "Pool %u now providing block contents to us",
  2517. pool->pool_no);
  2518. }
  2519. bool pool_may_redirect_to(struct pool * const pool, const char * const uri)
  2520. {
  2521. if (uri_get_param_bool(pool->rpc_url, "redirect", false))
  2522. return true;
  2523. return match_domains(pool->rpc_url, strlen(pool->rpc_url), uri, strlen(uri));
  2524. }
  2525. void set_simple_ntime_roll_limit(struct ntime_roll_limits * const nrl, const uint32_t ntime_base, const int ntime_roll, const struct timeval * const tvp_ref)
  2526. {
  2527. const int offsets = max(ntime_roll, 60);
  2528. *nrl = (struct ntime_roll_limits){
  2529. .min = ntime_base,
  2530. .max = ntime_base + ntime_roll,
  2531. .tv_ref = *tvp_ref,
  2532. .minoff = -offsets,
  2533. .maxoff = offsets,
  2534. };
  2535. }
  2536. void work_set_simple_ntime_roll_limit(struct work * const work, const int ntime_roll, const struct timeval * const tvp_ref)
  2537. {
  2538. set_simple_ntime_roll_limit(&work->ntime_roll_limits, upk_u32be(work->data, 0x44), ntime_roll, tvp_ref);
  2539. }
  2540. int work_ntime_range(struct work * const work, const struct timeval * const tvp_earliest, const struct timeval * const tvp_latest, const int desired_roll)
  2541. {
  2542. const struct ntime_roll_limits * const nrl = &work->ntime_roll_limits;
  2543. const uint32_t ref_ntime = work_get_ntime(work);
  2544. const int earliest_elapsed = timer_elapsed(&nrl->tv_ref, tvp_earliest);
  2545. const int latest_elapsed = timer_elapsed(&nrl->tv_ref, tvp_latest);
  2546. // minimum ntime is the latest possible result (add a second to spare) adjusted for minimum offset (or fixed minimum ntime)
  2547. uint32_t min_ntime = max(nrl->min, ref_ntime + latest_elapsed+1 + nrl->minoff);
  2548. // maximum ntime is the earliest possible result adjusted for maximum offset (or fixed maximum ntime)
  2549. uint32_t max_ntime = min(nrl->max, ref_ntime + earliest_elapsed + nrl->maxoff);
  2550. if (max_ntime < min_ntime)
  2551. return -1;
  2552. if (max_ntime - min_ntime > desired_roll)
  2553. {
  2554. // Adjust min_ntime upward for accuracy, when possible
  2555. const int mid_elapsed = ((latest_elapsed - earliest_elapsed) / 2) + earliest_elapsed;
  2556. uint32_t ideal_ntime = ref_ntime + mid_elapsed;
  2557. if (ideal_ntime > min_ntime)
  2558. min_ntime = min(ideal_ntime, max_ntime - desired_roll);
  2559. }
  2560. work_set_ntime(work, min_ntime);
  2561. return max_ntime - min_ntime;
  2562. }
  2563. #if BLKMAKER_VERSION > 1
  2564. static
  2565. void refresh_bitcoind_address(const bool fresh)
  2566. {
  2567. if (!have_at_least_one_getcbaddr)
  2568. return;
  2569. char getcbaddr_req[60];
  2570. CURL *curl = NULL;
  2571. json_t *json, *j2;
  2572. const char *s, *s2;
  2573. bytes_t newscript = BYTES_INIT;
  2574. snprintf(getcbaddr_req, sizeof(getcbaddr_req), "{\"method\":\"get%saddress\",\"id\":0,\"params\":[\"BFGMiner\"]}", fresh ? "new" : "account");
  2575. for (int i = 0; i < total_pools; ++i)
  2576. {
  2577. struct pool * const pool = pools[i];
  2578. if (!uri_get_param_bool(pool->rpc_url, "getcbaddr", false))
  2579. continue;
  2580. applog(LOG_DEBUG, "Refreshing coinbase address from pool %d", pool->pool_no);
  2581. if (!curl)
  2582. {
  2583. curl = curl_easy_init();
  2584. if (unlikely(!curl))
  2585. {
  2586. applogfail(LOG_ERR, "curl_easy_init");
  2587. break;
  2588. }
  2589. }
  2590. json = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, getcbaddr_req, false, false, NULL, pool, true);
  2591. if (unlikely((!json) || !json_is_null( (j2 = json_object_get(json, "error")) )))
  2592. {
  2593. const char *estrc;
  2594. char *estr = NULL;
  2595. if (!(json && j2))
  2596. estrc = NULL;
  2597. else
  2598. {
  2599. estrc = json_string_value(j2);
  2600. if (!estrc)
  2601. estrc = estr = json_dumps_ANY(j2, JSON_ENSURE_ASCII | JSON_SORT_KEYS);
  2602. }
  2603. applog(LOG_WARNING, "Error %cetting coinbase address from pool %d: %s", 'g', pool->pool_no, estrc);
  2604. free(estr);
  2605. continue;
  2606. }
  2607. s = bfg_json_obj_string(json, "result", NULL);
  2608. if (unlikely(!s))
  2609. {
  2610. applog(LOG_WARNING, "Error %cetting coinbase address from pool %d: %s", 'g', pool->pool_no, "(return value was not a String)");
  2611. continue;
  2612. }
  2613. s2 = set_b58addr(s, &newscript);
  2614. if (unlikely(s2))
  2615. {
  2616. applog(LOG_WARNING, "Error %cetting coinbase address from pool %d: %s", 's', pool->pool_no, s2);
  2617. continue;
  2618. }
  2619. if (bytes_eq(&newscript, &opt_coinbase_script))
  2620. {
  2621. applog(LOG_DEBUG, "Pool %d returned coinbase address already in use (%s)", pool->pool_no, s2);
  2622. break;
  2623. }
  2624. bytes_assimilate(&opt_coinbase_script, &newscript);
  2625. coinbase_script_block_id = current_block_id;
  2626. applog(LOG_NOTICE, "Now using coinbase address %s, provided by pool %d", s, pool->pool_no);
  2627. break;
  2628. }
  2629. bytes_free(&newscript);
  2630. if (curl)
  2631. curl_easy_cleanup(curl);
  2632. }
  2633. #endif
  2634. #define GBT_XNONCESZ (sizeof(uint32_t))
  2635. #if BLKMAKER_VERSION > 4
  2636. #define blkmk_append_coinbase_safe(tmpl, append, appendsz) \
  2637. blkmk_append_coinbase_safe2(tmpl, append, appendsz, GBT_XNONCESZ, false)
  2638. #endif
  2639. static bool work_decode(struct pool *pool, struct work *work, json_t *val)
  2640. {
  2641. json_t *res_val = json_object_get(val, "result");
  2642. json_t *tmp_val;
  2643. bool ret = false;
  2644. struct timeval tv_now;
  2645. if (unlikely(detect_algo == 1)) {
  2646. json_t *tmp = json_object_get(res_val, "algorithm");
  2647. const char *v = tmp ? json_string_value(tmp) : "";
  2648. if (strncasecmp(v, "scrypt", 6))
  2649. detect_algo = 2;
  2650. }
  2651. timer_set_now(&tv_now);
  2652. if (work->tr)
  2653. {
  2654. blktemplate_t * const tmpl = work->tr->tmpl;
  2655. const char *err = blktmpl_add_jansson(tmpl, res_val, tv_now.tv_sec);
  2656. if (err) {
  2657. applog(LOG_ERR, "blktmpl error: %s", err);
  2658. return false;
  2659. }
  2660. work->rolltime = blkmk_time_left(tmpl, tv_now.tv_sec);
  2661. #if BLKMAKER_VERSION > 1
  2662. const uint32_t tmpl_block_id = ((uint32_t*)tmpl->prevblk)[0];
  2663. if ((!tmpl->cbtxn) && coinbase_script_block_id != tmpl_block_id)
  2664. refresh_bitcoind_address(false);
  2665. if (bytes_len(&opt_coinbase_script))
  2666. {
  2667. bool newcb;
  2668. #if BLKMAKER_VERSION > 2
  2669. blkmk_init_generation2(tmpl, bytes_buf(&opt_coinbase_script), bytes_len(&opt_coinbase_script), &newcb);
  2670. #else
  2671. newcb = !tmpl->cbtxn;
  2672. blkmk_init_generation(tmpl, bytes_buf(&opt_coinbase_script), bytes_len(&opt_coinbase_script));
  2673. #endif
  2674. if (newcb)
  2675. {
  2676. ssize_t ae = blkmk_append_coinbase_safe(tmpl, &template_nonce, sizeof(template_nonce));
  2677. if (ae < (ssize_t)sizeof(template_nonce))
  2678. 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);
  2679. ++template_nonce;
  2680. }
  2681. }
  2682. #endif
  2683. #if BLKMAKER_VERSION > 0
  2684. {
  2685. ssize_t ae = blkmk_append_coinbase_safe(tmpl, opt_coinbase_sig, 101);
  2686. static bool appenderr = false;
  2687. if (ae <= 0) {
  2688. if (opt_coinbase_sig) {
  2689. applog((appenderr ? LOG_DEBUG : LOG_WARNING), "Cannot append coinbase signature at all on pool %u (%"PRId64")", pool->pool_no, (int64_t)ae);
  2690. appenderr = true;
  2691. }
  2692. } else if (ae >= 3 || opt_coinbase_sig) {
  2693. const char *cbappend = opt_coinbase_sig;
  2694. const char full[] = PACKAGE " " VERSION;
  2695. char *need_free = NULL;
  2696. if (!cbappend) {
  2697. if ((size_t)ae >= sizeof(full) - 1)
  2698. cbappend = full;
  2699. else if ((size_t)ae >= sizeof(PACKAGE) - 1)
  2700. {
  2701. const char *pos = strchr(full, '-');
  2702. size_t sz = (pos - full);
  2703. if (pos && ae > sz)
  2704. {
  2705. cbappend = need_free = malloc(sz + 1);
  2706. memcpy(need_free, full, sz);
  2707. need_free[sz] = '\0';
  2708. }
  2709. else
  2710. cbappend = PACKAGE;
  2711. }
  2712. else
  2713. cbappend = "BFG";
  2714. }
  2715. size_t cbappendsz = strlen(cbappend);
  2716. static bool truncatewarning = false;
  2717. if (cbappendsz <= (size_t)ae) {
  2718. if (cbappendsz < (size_t)ae)
  2719. // If we have space, include the trailing \0
  2720. ++cbappendsz;
  2721. ae = cbappendsz;
  2722. truncatewarning = false;
  2723. } else {
  2724. char *tmp = malloc(ae + 1);
  2725. memcpy(tmp, opt_coinbase_sig, ae);
  2726. tmp[ae] = '\0';
  2727. applog((truncatewarning ? LOG_DEBUG : LOG_WARNING),
  2728. "Pool %u truncating appended coinbase signature at %"PRId64" bytes: %s(%s)",
  2729. pool->pool_no, (int64_t)ae, tmp, &opt_coinbase_sig[ae]);
  2730. free(tmp);
  2731. truncatewarning = true;
  2732. }
  2733. ae = blkmk_append_coinbase_safe(tmpl, cbappend, ae);
  2734. free(need_free);
  2735. if (ae <= 0) {
  2736. applog((appenderr ? LOG_DEBUG : LOG_WARNING), "Error appending coinbase signature (%"PRId64")", (int64_t)ae);
  2737. appenderr = true;
  2738. } else
  2739. appenderr = false;
  2740. }
  2741. }
  2742. #endif
  2743. if (blkmk_get_data(tmpl, work->data, 80, tv_now.tv_sec, NULL, &work->dataid) < 76)
  2744. return false;
  2745. swap32yes(work->data, work->data, 80 / 4);
  2746. memcpy(&work->data[80], workpadding_bin, 48);
  2747. work->ntime_roll_limits = (struct ntime_roll_limits){
  2748. .min = tmpl->mintime,
  2749. .max = tmpl->maxtime,
  2750. .tv_ref = tv_now,
  2751. .minoff = tmpl->mintimeoff,
  2752. .maxoff = tmpl->maxtimeoff,
  2753. };
  2754. const struct blktmpl_longpoll_req *lp;
  2755. if ((lp = blktmpl_get_longpoll(tmpl)) && ((!pool->lp_id) || strcmp(lp->id, pool->lp_id))) {
  2756. free(pool->lp_id);
  2757. pool->lp_id = strdup(lp->id);
  2758. #if 0 /* This just doesn't work :( */
  2759. curl_socket_t sock = pool->lp_socket;
  2760. if (sock != CURL_SOCKET_BAD) {
  2761. pool->lp_socket = CURL_SOCKET_BAD;
  2762. applog(LOG_WARNING, "Pool %u long poll request hanging, reconnecting", pool->pool_no);
  2763. shutdown(sock, SHUT_RDWR);
  2764. }
  2765. #endif
  2766. }
  2767. }
  2768. else
  2769. if (unlikely(!jobj_binary(res_val, "data", work->data, sizeof(work->data), true))) {
  2770. applog(LOG_ERR, "JSON inval data");
  2771. return false;
  2772. }
  2773. else
  2774. work_set_simple_ntime_roll_limit(work, 0, &tv_now);
  2775. if (!jobj_binary(res_val, "midstate", work->midstate, sizeof(work->midstate), false)) {
  2776. // Calculate it ourselves
  2777. applog(LOG_DEBUG, "Calculating midstate locally");
  2778. calc_midstate(work);
  2779. }
  2780. if (unlikely(!jobj_binary(res_val, "target", work->target, sizeof(work->target), true))) {
  2781. applog(LOG_ERR, "JSON inval target");
  2782. return false;
  2783. }
  2784. if (work->tr)
  2785. {
  2786. for (size_t i = 0; i < sizeof(work->target) / 2; ++i)
  2787. {
  2788. int p = (sizeof(work->target) - 1) - i;
  2789. unsigned char c = work->target[i];
  2790. work->target[i] = work->target[p];
  2791. work->target[p] = c;
  2792. }
  2793. }
  2794. if ( (tmp_val = json_object_get(res_val, "height")) ) {
  2795. uint32_t blkheight = json_number_value(tmp_val);
  2796. uint32_t block_id = ((uint32_t*)work->data)[1];
  2797. have_block_height(block_id, blkheight);
  2798. }
  2799. memset(work->hash, 0, sizeof(work->hash));
  2800. work->tv_staged = tv_now;
  2801. #if BLKMAKER_VERSION > 4
  2802. if (work->tr)
  2803. {
  2804. blktemplate_t * const tmpl = work->tr->tmpl;
  2805. uint8_t buf[80];
  2806. int16_t expire;
  2807. uint8_t *cbtxn;
  2808. size_t cbtxnsz;
  2809. size_t cbextranonceoffset;
  2810. int branchcount;
  2811. libblkmaker_hash_t *branches;
  2812. if (blkmk_get_mdata(tmpl, buf, sizeof(buf), tv_now.tv_sec, &expire, &cbtxn, &cbtxnsz, &cbextranonceoffset, &branchcount, &branches, GBT_XNONCESZ, false))
  2813. {
  2814. struct stratum_work * const swork = &pool->swork;
  2815. const size_t branchdatasz = branchcount * 0x20;
  2816. cg_wlock(&pool->data_lock);
  2817. swork->tr = work->tr;
  2818. bytes_assimilate_raw(&swork->coinbase, cbtxn, cbtxnsz, cbtxnsz);
  2819. swork->nonce2_offset = cbextranonceoffset;
  2820. bytes_assimilate_raw(&swork->merkle_bin, branches, branchdatasz, branchdatasz);
  2821. swork->merkles = branchcount;
  2822. memcpy(swork->header1, &buf[0], 36);
  2823. swork->ntime = le32toh(*(uint32_t *)(&buf[68]));
  2824. swork->tv_received = tv_now;
  2825. memcpy(swork->diffbits, &buf[72], 4);
  2826. memcpy(swork->target, work->target, sizeof(swork->target));
  2827. free(swork->job_id);
  2828. swork->job_id = NULL;
  2829. swork->clean = true;
  2830. swork->work_restart_id = pool->work_restart_id;
  2831. // FIXME: Do something with expire
  2832. pool->nonce2sz = swork->n2size = GBT_XNONCESZ;
  2833. pool->nonce2 = 0;
  2834. cg_wunlock(&pool->data_lock);
  2835. }
  2836. else
  2837. applog(LOG_DEBUG, "blkmk_get_mdata failed for pool %u", pool->pool_no);
  2838. }
  2839. #endif // BLKMAKER_VERSION > 4
  2840. pool_set_opaque(pool, !work->tr);
  2841. ret = true;
  2842. return ret;
  2843. }
  2844. /* Returns whether the pool supports local work generation or not. */
  2845. static bool pool_localgen(struct pool *pool)
  2846. {
  2847. return (pool->last_work_copy || pool->has_stratum);
  2848. }
  2849. int dev_from_id(int thr_id)
  2850. {
  2851. struct cgpu_info *cgpu = get_thr_cgpu(thr_id);
  2852. return cgpu->device_id;
  2853. }
  2854. /* Create an exponentially decaying average over the opt_log_interval */
  2855. void decay_time(double *f, double fadd, double fsecs)
  2856. {
  2857. double ftotal, fprop;
  2858. fprop = 1.0 - 1 / (exp(fsecs / (double)opt_log_interval));
  2859. ftotal = 1.0 + fprop;
  2860. *f += (fadd * fprop);
  2861. *f /= ftotal;
  2862. }
  2863. static int __total_staged(void)
  2864. {
  2865. return HASH_COUNT(staged_work);
  2866. }
  2867. static int total_staged(void)
  2868. {
  2869. int ret;
  2870. mutex_lock(stgd_lock);
  2871. ret = __total_staged();
  2872. mutex_unlock(stgd_lock);
  2873. return ret;
  2874. }
  2875. #ifdef HAVE_CURSES
  2876. WINDOW *mainwin, *statuswin, *logwin;
  2877. #endif
  2878. double total_secs = 1.0;
  2879. static char statusline[256];
  2880. /* logstart is where the log window should start */
  2881. static int devcursor, logstart, logcursor;
  2882. #ifdef HAVE_CURSES
  2883. /* statusy is where the status window goes up to in cases where it won't fit at startup */
  2884. static int statusy;
  2885. static int devsummaryYOffset;
  2886. static int total_lines;
  2887. #endif
  2888. #ifdef HAVE_OPENCL
  2889. struct cgpu_info gpus[MAX_GPUDEVICES]; /* Maximum number apparently possible */
  2890. #endif
  2891. struct cgpu_info *cpus;
  2892. bool _bfg_console_cancel_disabled;
  2893. int _bfg_console_prev_cancelstate;
  2894. #ifdef HAVE_CURSES
  2895. #define lock_curses() bfg_console_lock()
  2896. #define unlock_curses() bfg_console_unlock()
  2897. static bool curses_active_locked(void)
  2898. {
  2899. bool ret;
  2900. lock_curses();
  2901. ret = curses_active;
  2902. if (!ret)
  2903. unlock_curses();
  2904. return ret;
  2905. }
  2906. // Cancellable getch
  2907. int my_cancellable_getch(void)
  2908. {
  2909. // This only works because the macro only hits direct getch() calls
  2910. typedef int (*real_getch_t)(void);
  2911. const real_getch_t real_getch = __real_getch;
  2912. int type, rv;
  2913. bool sct;
  2914. sct = !pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &type);
  2915. rv = real_getch();
  2916. if (sct)
  2917. pthread_setcanceltype(type, &type);
  2918. return rv;
  2919. }
  2920. #ifdef PDCURSES
  2921. static
  2922. int bfg_wresize(WINDOW *win, int lines, int columns)
  2923. {
  2924. int rv = wresize(win, lines, columns);
  2925. int x, y;
  2926. getyx(win, y, x);
  2927. if (unlikely(y >= lines || x >= columns))
  2928. {
  2929. if (y >= lines)
  2930. y = lines - 1;
  2931. if (x >= columns)
  2932. x = columns - 1;
  2933. wmove(win, y, x);
  2934. }
  2935. return rv;
  2936. }
  2937. #else
  2938. # define bfg_wresize wresize
  2939. #endif
  2940. #endif
  2941. void tailsprintf(char *buf, size_t bufsz, const char *fmt, ...)
  2942. {
  2943. va_list ap;
  2944. size_t presz = strlen(buf);
  2945. va_start(ap, fmt);
  2946. vsnprintf(&buf[presz], bufsz - presz, fmt, ap);
  2947. va_end(ap);
  2948. }
  2949. double stats_elapsed(struct cgminer_stats *stats)
  2950. {
  2951. struct timeval now;
  2952. double elapsed;
  2953. if (stats->start_tv.tv_sec == 0)
  2954. elapsed = total_secs;
  2955. else {
  2956. cgtime(&now);
  2957. elapsed = tdiff(&now, &stats->start_tv);
  2958. }
  2959. if (elapsed < 1.0)
  2960. elapsed = 1.0;
  2961. return elapsed;
  2962. }
  2963. bool drv_ready(struct cgpu_info *cgpu)
  2964. {
  2965. switch (cgpu->status) {
  2966. case LIFE_INIT:
  2967. case LIFE_DEAD2:
  2968. return false;
  2969. default:
  2970. return true;
  2971. }
  2972. }
  2973. double cgpu_utility(struct cgpu_info *cgpu)
  2974. {
  2975. double dev_runtime = cgpu_runtime(cgpu);
  2976. return cgpu->utility = cgpu->accepted / dev_runtime * 60;
  2977. }
  2978. #define suffix_string(val, buf, bufsiz, sigdigits) do{ \
  2979. _Static_assert(sigdigits == 0, "suffix_string only supported with sigdigits==0"); \
  2980. format_unit3(buf, bufsiz, FUP_DIFF, "", H2B_SHORTV, val, -1); \
  2981. }while(0)
  2982. static float
  2983. utility_to_hashrate(double utility)
  2984. {
  2985. return utility * 0x4444444;
  2986. }
  2987. static const char*_unitchar = "pn\xb5m kMGTPEZY?";
  2988. static const int _unitbase = 4;
  2989. static
  2990. void pick_unit(float hashrate, unsigned char *unit)
  2991. {
  2992. unsigned char i;
  2993. if (hashrate == 0 || !isfinite(hashrate))
  2994. {
  2995. if (*unit < _unitbase)
  2996. *unit = _unitbase;
  2997. return;
  2998. }
  2999. hashrate *= 1e12;
  3000. for (i = 0; i < *unit; ++i)
  3001. hashrate /= 1e3;
  3002. // 1000 but with tolerance for floating-point rounding, avoid showing "1000.0"
  3003. while (hashrate >= 999.95)
  3004. {
  3005. hashrate /= 1e3;
  3006. if (likely(_unitchar[*unit] != '?'))
  3007. ++*unit;
  3008. }
  3009. }
  3010. #define hashrate_pick_unit(hashrate, unit) pick_unit(hashrate, unit)
  3011. enum h2bs_fmt {
  3012. H2B_NOUNIT, // "xxx.x"
  3013. H2B_SHORT, // "xxx.xMH/s"
  3014. H2B_SPACED, // "xxx.x MH/s"
  3015. H2B_SHORTV, // Like H2B_SHORT, but omit space for base unit
  3016. };
  3017. enum bfu_floatprec {
  3018. FUP_INTEGER,
  3019. FUP_HASHES,
  3020. FUP_BTC,
  3021. FUP_DIFF,
  3022. };
  3023. static
  3024. int format_unit3(char *buf, size_t sz, enum bfu_floatprec fprec, const char *measurement, enum h2bs_fmt fmt, float hashrate, signed char unitin)
  3025. {
  3026. char *s = buf;
  3027. unsigned char prec, i, unit;
  3028. int rv = 0;
  3029. if (unitin == -1)
  3030. {
  3031. unit = 0;
  3032. hashrate_pick_unit(hashrate, &unit);
  3033. }
  3034. else
  3035. unit = unitin;
  3036. hashrate *= 1e12;
  3037. for (i = 0; i < unit; ++i)
  3038. hashrate /= 1000;
  3039. switch (fprec)
  3040. {
  3041. case FUP_HASHES:
  3042. // 100 but with tolerance for floating-point rounding, max "99.99" then "100.0"
  3043. if (hashrate >= 99.995 || unit < 6)
  3044. prec = 1;
  3045. else
  3046. prec = 2;
  3047. _SNP("%5.*f", prec, hashrate);
  3048. break;
  3049. case FUP_INTEGER:
  3050. _SNP("%3d", (int)hashrate);
  3051. break;
  3052. case FUP_BTC:
  3053. if (hashrate >= 99.995)
  3054. prec = 0;
  3055. else
  3056. prec = 2;
  3057. _SNP("%5.*f", prec, hashrate);
  3058. break;
  3059. case FUP_DIFF:
  3060. if (unit > _unitbase)
  3061. _SNP("%.3g", hashrate);
  3062. else
  3063. _SNP("%u", (unsigned int)hashrate);
  3064. }
  3065. if (fmt != H2B_NOUNIT)
  3066. {
  3067. char uc[3] = {_unitchar[unit], '\0'};
  3068. switch (fmt) {
  3069. case H2B_SPACED:
  3070. _SNP(" ");
  3071. default:
  3072. break;
  3073. case H2B_SHORTV:
  3074. if (isspace(uc[0]))
  3075. uc[0] = '\0';
  3076. }
  3077. if (uc[0] == '\xb5')
  3078. // Convert to UTF-8
  3079. snprintf(uc, sizeof(uc), "%s", U8_MICRO);
  3080. _SNP("%s%s", uc, measurement);
  3081. }
  3082. return rv;
  3083. }
  3084. #define format_unit2(buf, sz, floatprec, measurement, fmt, n, unit) \
  3085. format_unit3(buf, sz, floatprec ? FUP_HASHES : FUP_INTEGER, measurement, fmt, n, unit)
  3086. static
  3087. char *_multi_format_unit(char **buflist, size_t *bufszlist, bool floatprec, const char *measurement, enum h2bs_fmt fmt, const char *delim, int count, const float *numbers, bool isarray)
  3088. {
  3089. unsigned char unit = 0;
  3090. bool allzero = true;
  3091. int i;
  3092. size_t delimsz = 0;
  3093. char *buf = buflist[0];
  3094. size_t bufsz = bufszlist[0];
  3095. size_t itemwidth = (floatprec ? 5 : 3);
  3096. if (!isarray)
  3097. delimsz = strlen(delim);
  3098. for (i = 0; i < count; ++i)
  3099. if (numbers[i] != 0)
  3100. {
  3101. pick_unit(numbers[i], &unit);
  3102. allzero = false;
  3103. }
  3104. if (allzero)
  3105. unit = _unitbase;
  3106. --count;
  3107. for (i = 0; i < count; ++i)
  3108. {
  3109. format_unit2(buf, bufsz, floatprec, NULL, H2B_NOUNIT, numbers[i], unit);
  3110. if (isarray)
  3111. {
  3112. buf = buflist[i + 1];
  3113. bufsz = bufszlist[i + 1];
  3114. }
  3115. else
  3116. {
  3117. buf += itemwidth;
  3118. bufsz -= itemwidth;
  3119. if (delimsz > bufsz)
  3120. delimsz = bufsz;
  3121. memcpy(buf, delim, delimsz);
  3122. buf += delimsz;
  3123. bufsz -= delimsz;
  3124. }
  3125. }
  3126. // Last entry has the unit
  3127. format_unit2(buf, bufsz, floatprec, measurement, fmt, numbers[count], unit);
  3128. return buflist[0];
  3129. }
  3130. #define multi_format_unit2(buf, bufsz, floatprec, measurement, fmt, delim, count, ...) _multi_format_unit((char *[]){buf}, (size_t[]){bufsz}, floatprec, measurement, fmt, delim, count, (float[]){ __VA_ARGS__ }, false)
  3131. #define multi_format_unit_array2(buflist, bufszlist, floatprec, measurement, fmt, count, ...) (void)_multi_format_unit(buflist, bufszlist, floatprec, measurement, fmt, NULL, count, (float[]){ __VA_ARGS__ }, true)
  3132. static
  3133. int percentf3(char * const buf, size_t sz, double p, const double t)
  3134. {
  3135. char *s = buf;
  3136. int rv = 0;
  3137. if (!p)
  3138. _SNP("none");
  3139. else
  3140. if (t <= p)
  3141. _SNP("100%%");
  3142. else
  3143. {
  3144. p /= t;
  3145. if (p < 0.00995) // 0.01 but with tolerance for floating-point rounding, max ".99%"
  3146. _SNP(".%02.0f%%", p * 10000); // ".01%"
  3147. else
  3148. if (p < 0.0995) // 0.1 but with tolerance for floating-point rounding, max "9.9%"
  3149. _SNP("%.1f%%", p * 100); // "9.1%"
  3150. else
  3151. _SNP("%3.0f%%", p * 100); // " 99%"
  3152. }
  3153. return rv;
  3154. }
  3155. #define percentf4(buf, bufsz, p, t) percentf3(buf, bufsz, p, p + t)
  3156. static
  3157. void test_decimal_width()
  3158. {
  3159. // The pipe character at end of each line should perfectly line up
  3160. char printbuf[512];
  3161. char testbuf1[64];
  3162. char testbuf2[64];
  3163. char testbuf3[64];
  3164. char testbuf4[64];
  3165. double testn;
  3166. int width;
  3167. int saved;
  3168. // Hotspots around 0.1 and 0.01
  3169. saved = -1;
  3170. for (testn = 0.09; testn <= 0.11; testn += 0.000001) {
  3171. percentf3(testbuf1, sizeof(testbuf1), testn, 1.0);
  3172. percentf3(testbuf2, sizeof(testbuf2), testn, 10.0);
  3173. width = snprintf(printbuf, sizeof(printbuf), "%10g %s %s |", testn, testbuf1, testbuf2);
  3174. if (unlikely((saved != -1) && (width != saved))) {
  3175. applog(LOG_ERR, "Test width mismatch in percentf3! %d not %d at %10g", width, saved, testn);
  3176. applog(LOG_ERR, "%s", printbuf);
  3177. }
  3178. saved = width;
  3179. }
  3180. // Hotspot around 100 (but test this in several units because format_unit2 also has unit<2 check)
  3181. saved = -1;
  3182. for (testn = 99.0; testn <= 101.0; testn += 0.0001) {
  3183. format_unit2(testbuf1, sizeof(testbuf1), true, "x", H2B_SHORT, testn , -1);
  3184. format_unit2(testbuf2, sizeof(testbuf2), true, "x", H2B_SHORT, testn * 1e3, -1);
  3185. format_unit2(testbuf3, sizeof(testbuf3), true, "x", H2B_SHORT, testn * 1e6, -1);
  3186. snprintf(printbuf, sizeof(printbuf), "%10g %s %s %s |", testn, testbuf1, testbuf2, testbuf3);
  3187. width = utf8_strlen(printbuf);
  3188. if (unlikely((saved != -1) && (width != saved))) {
  3189. applog(LOG_ERR, "Test width mismatch in format_unit2! %d not %d at %10g", width, saved, testn);
  3190. applog(LOG_ERR, "%s", printbuf);
  3191. }
  3192. saved = width;
  3193. }
  3194. // Hotspot around unit transition boundary in pick_unit
  3195. saved = -1;
  3196. for (testn = 999.0; testn <= 1001.0; testn += 0.0001) {
  3197. format_unit2(testbuf1, sizeof(testbuf1), true, "x", H2B_SHORT, testn , -1);
  3198. format_unit2(testbuf2, sizeof(testbuf2), true, "x", H2B_SHORT, testn * 1e3, -1);
  3199. format_unit2(testbuf3, sizeof(testbuf3), true, "x", H2B_SHORT, testn * 1e6, -1);
  3200. format_unit2(testbuf4, sizeof(testbuf4), true, "x", H2B_SHORT, testn * 1e9, -1);
  3201. snprintf(printbuf, sizeof(printbuf), "%10g %s %s %s %s |", testn, testbuf1, testbuf2, testbuf3, testbuf4);
  3202. width = utf8_strlen(printbuf);
  3203. if (unlikely((saved != -1) && (width != saved))) {
  3204. applog(LOG_ERR, "Test width mismatch in pick_unit! %d not %d at %10g", width, saved, testn);
  3205. applog(LOG_ERR, "%s", printbuf);
  3206. }
  3207. saved = width;
  3208. }
  3209. }
  3210. #ifdef HAVE_CURSES
  3211. static void adj_width(int var, int *length);
  3212. #endif
  3213. #ifdef HAVE_CURSES
  3214. static int awidth = 1, rwidth = 1, swidth = 1, hwwidth = 1;
  3215. static
  3216. void format_statline(char *buf, size_t bufsz, const char *cHr, const char *aHr, const char *uHr, int accepted, int rejected, int stale, double wnotaccepted, double waccepted, int hwerrs, double bad_diff1, double allnonces)
  3217. {
  3218. char rejpcbuf[6];
  3219. char bnbuf[6];
  3220. adj_width(accepted, &awidth);
  3221. adj_width(rejected, &rwidth);
  3222. adj_width(stale, &swidth);
  3223. adj_width(hwerrs, &hwwidth);
  3224. percentf4(rejpcbuf, sizeof(rejpcbuf), wnotaccepted, waccepted);
  3225. percentf3(bnbuf, sizeof(bnbuf), bad_diff1, allnonces);
  3226. tailsprintf(buf, bufsz, "%s/%s/%s | A:%*d R:%*d+%*d(%s) HW:%*d/%s",
  3227. cHr, aHr, uHr,
  3228. awidth, accepted,
  3229. rwidth, rejected,
  3230. swidth, stale,
  3231. rejpcbuf,
  3232. hwwidth, hwerrs,
  3233. bnbuf
  3234. );
  3235. }
  3236. static
  3237. const char *pool_proto_str(const struct pool * const pool)
  3238. {
  3239. if (pool->idle)
  3240. return "Dead ";
  3241. if (pool->has_stratum)
  3242. return "Strtm";
  3243. if (pool->lp_url && pool->proto != pool->lp_proto)
  3244. return "Mixed";
  3245. switch (pool->proto)
  3246. {
  3247. case PLP_GETBLOCKTEMPLATE:
  3248. return " GBT ";
  3249. case PLP_GETWORK:
  3250. return "GWork";
  3251. default:
  3252. return "Alive";
  3253. }
  3254. }
  3255. #endif
  3256. static inline
  3257. void temperature_column(char *buf, size_t bufsz, bool maybe_unicode, const float * const temp)
  3258. {
  3259. if (!(use_unicode && have_unicode_degrees))
  3260. maybe_unicode = false;
  3261. if (temp && *temp > 0.)
  3262. if (maybe_unicode)
  3263. snprintf(buf, bufsz, "%4.1f"U8_DEGREE"C", *temp);
  3264. else
  3265. snprintf(buf, bufsz, "%4.1fC", *temp);
  3266. else
  3267. {
  3268. if (temp)
  3269. snprintf(buf, bufsz, " ");
  3270. if (maybe_unicode)
  3271. tailsprintf(buf, bufsz, " ");
  3272. }
  3273. tailsprintf(buf, bufsz, " | ");
  3274. }
  3275. void get_statline3(char *buf, size_t bufsz, struct cgpu_info *cgpu, bool for_curses, bool opt_show_procs)
  3276. {
  3277. #ifndef HAVE_CURSES
  3278. assert(for_curses == false);
  3279. #endif
  3280. struct device_drv *drv = cgpu->drv;
  3281. enum h2bs_fmt hashrate_style = for_curses ? H2B_SHORT : H2B_SPACED;
  3282. char cHr[ALLOC_H2B_NOUNIT+1], aHr[ALLOC_H2B_NOUNIT+1], uHr[max(ALLOC_H2B_SHORT, ALLOC_H2B_SPACED)+3+1];
  3283. char rejpcbuf[6];
  3284. char bnbuf[6];
  3285. double dev_runtime;
  3286. if (!opt_show_procs)
  3287. cgpu = cgpu->device;
  3288. dev_runtime = cgpu_runtime(cgpu);
  3289. double rolling, mhashes;
  3290. int accepted, rejected, stale;
  3291. double waccepted;
  3292. double wnotaccepted;
  3293. int hwerrs;
  3294. double bad_diff1, good_diff1;
  3295. rolling = mhashes = waccepted = wnotaccepted = 0;
  3296. accepted = rejected = stale = hwerrs = bad_diff1 = good_diff1 = 0;
  3297. {
  3298. struct cgpu_info *slave = cgpu;
  3299. for (int i = 0; i < cgpu->procs; ++i, (slave = slave->next_proc))
  3300. {
  3301. slave->utility = slave->accepted / dev_runtime * 60;
  3302. slave->utility_diff1 = slave->diff_accepted / dev_runtime * 60;
  3303. rolling += slave->rolling;
  3304. mhashes += slave->total_mhashes;
  3305. if (opt_weighed_stats)
  3306. {
  3307. accepted += slave->diff_accepted;
  3308. rejected += slave->diff_rejected;
  3309. stale += slave->diff_stale;
  3310. }
  3311. else
  3312. {
  3313. accepted += slave->accepted;
  3314. rejected += slave->rejected;
  3315. stale += slave->stale;
  3316. }
  3317. waccepted += slave->diff_accepted;
  3318. wnotaccepted += slave->diff_rejected + slave->diff_stale;
  3319. hwerrs += slave->hw_errors;
  3320. bad_diff1 += slave->bad_diff1;
  3321. good_diff1 += slave->diff1;
  3322. if (opt_show_procs)
  3323. break;
  3324. }
  3325. }
  3326. double wtotal = (waccepted + wnotaccepted);
  3327. multi_format_unit_array2(
  3328. ((char*[]){cHr, aHr, uHr}),
  3329. ((size_t[]){sizeof(cHr), sizeof(aHr), sizeof(uHr)}),
  3330. true, "h/s", hashrate_style,
  3331. 3,
  3332. 1e6*rolling,
  3333. 1e6*mhashes / dev_runtime,
  3334. utility_to_hashrate(good_diff1 * (wtotal ? (waccepted / wtotal) : 1) * 60 / dev_runtime));
  3335. // Processor representation
  3336. #ifdef HAVE_CURSES
  3337. if (for_curses)
  3338. {
  3339. if (opt_show_procs)
  3340. snprintf(buf, bufsz, " %*s: ", -(5 + max_lpdigits), cgpu->proc_repr);
  3341. else
  3342. snprintf(buf, bufsz, " %s: ", cgpu->dev_repr);
  3343. }
  3344. else
  3345. #endif
  3346. snprintf(buf, bufsz, "%s ", opt_show_procs ? cgpu->proc_repr_ns : cgpu->dev_repr_ns);
  3347. if (include_serial_in_statline && cgpu->dev_serial)
  3348. tailsprintf(buf, bufsz, "[serial=%s] ", cgpu->dev_serial);
  3349. if (unlikely(cgpu->status == LIFE_INIT))
  3350. {
  3351. tailsprintf(buf, bufsz, "Initializing...");
  3352. return;
  3353. }
  3354. {
  3355. const size_t bufln = strlen(buf);
  3356. const size_t abufsz = (bufln >= bufsz) ? 0 : (bufsz - bufln);
  3357. if (likely(cgpu->status != LIFE_DEAD2) && drv->override_statline_temp2 && drv->override_statline_temp2(buf, bufsz, cgpu, opt_show_procs))
  3358. temperature_column(&buf[bufln], abufsz, for_curses, NULL);
  3359. else
  3360. {
  3361. float temp = cgpu->temp;
  3362. if (!opt_show_procs)
  3363. {
  3364. // Find the highest temperature of all processors
  3365. struct cgpu_info *proc = cgpu;
  3366. for (int i = 0; i < cgpu->procs; ++i, (proc = proc->next_proc))
  3367. if (proc->temp > temp)
  3368. temp = proc->temp;
  3369. }
  3370. temperature_column(&buf[bufln], abufsz, for_curses, &temp);
  3371. }
  3372. }
  3373. #ifdef HAVE_CURSES
  3374. if (for_curses)
  3375. {
  3376. const char *cHrStatsOpt[] = {AS_BAD("DEAD "), AS_BAD("SICK "), "OFF ", AS_BAD("REST "), AS_BAD(" ERR "), AS_BAD("WAIT "), cHr};
  3377. const char *cHrStats;
  3378. int cHrStatsI = (sizeof(cHrStatsOpt) / sizeof(*cHrStatsOpt)) - 1;
  3379. bool all_dead = true, all_off = true, all_rdrv = true;
  3380. struct cgpu_info *proc = cgpu;
  3381. for (int i = 0; i < cgpu->procs; ++i, (proc = proc->next_proc))
  3382. {
  3383. switch (cHrStatsI) {
  3384. default:
  3385. if (proc->status == LIFE_WAIT)
  3386. cHrStatsI = 5;
  3387. case 5:
  3388. if (proc->deven == DEV_RECOVER_ERR)
  3389. cHrStatsI = 4;
  3390. case 4:
  3391. if (proc->deven == DEV_RECOVER)
  3392. cHrStatsI = 3;
  3393. case 3:
  3394. if (proc->status == LIFE_SICK || proc->status == LIFE_DEAD || proc->status == LIFE_DEAD2)
  3395. {
  3396. cHrStatsI = 1;
  3397. all_off = false;
  3398. }
  3399. else
  3400. {
  3401. if (likely(proc->deven == DEV_ENABLED))
  3402. all_off = false;
  3403. if (proc->deven != DEV_RECOVER_DRV)
  3404. all_rdrv = false;
  3405. }
  3406. case 1:
  3407. break;
  3408. }
  3409. if (likely(proc->status != LIFE_DEAD && proc->status != LIFE_DEAD2))
  3410. all_dead = false;
  3411. if (opt_show_procs)
  3412. break;
  3413. }
  3414. if (unlikely(all_dead))
  3415. cHrStatsI = 0;
  3416. else
  3417. if (unlikely(all_off))
  3418. cHrStatsI = 2;
  3419. cHrStats = cHrStatsOpt[cHrStatsI];
  3420. if (cHrStatsI == 2 && all_rdrv)
  3421. cHrStats = " RST ";
  3422. format_statline(buf, bufsz,
  3423. cHrStats,
  3424. aHr, uHr,
  3425. accepted, rejected, stale,
  3426. wnotaccepted, waccepted,
  3427. hwerrs,
  3428. bad_diff1, bad_diff1 + good_diff1);
  3429. }
  3430. else
  3431. #endif
  3432. {
  3433. percentf4(rejpcbuf, sizeof(rejpcbuf), wnotaccepted, waccepted);
  3434. percentf4(bnbuf, sizeof(bnbuf), bad_diff1, good_diff1);
  3435. tailsprintf(buf, bufsz, "%ds:%s avg:%s u:%s | A:%d R:%d+%d(%s) HW:%d/%s",
  3436. opt_log_interval,
  3437. cHr, aHr, uHr,
  3438. accepted,
  3439. rejected,
  3440. stale,
  3441. rejpcbuf,
  3442. hwerrs,
  3443. bnbuf
  3444. );
  3445. }
  3446. }
  3447. #define get_statline(buf, bufsz, cgpu) get_statline3(buf, bufsz, cgpu, false, opt_show_procs)
  3448. #define get_statline2(buf, bufsz, cgpu, for_curses) get_statline3(buf, bufsz, cgpu, for_curses, opt_show_procs)
  3449. static void text_print_status(int thr_id)
  3450. {
  3451. struct cgpu_info *cgpu;
  3452. char logline[256];
  3453. cgpu = get_thr_cgpu(thr_id);
  3454. if (cgpu) {
  3455. get_statline(logline, sizeof(logline), cgpu);
  3456. printf("\n%s\r", logline);
  3457. fflush(stdout);
  3458. }
  3459. }
  3460. #ifdef HAVE_CURSES
  3461. static int attr_bad = A_BOLD;
  3462. #ifdef WIN32
  3463. #define swprintf snwprintf
  3464. #endif
  3465. static
  3466. void bfg_waddstr(WINDOW *win, const char *s)
  3467. {
  3468. const char *p = s;
  3469. int32_t w;
  3470. int wlen;
  3471. unsigned char stop_ascii = (use_unicode ? '|' : 0x80);
  3472. while (true)
  3473. {
  3474. while (likely(p[0] == '\n' || (p[0] >= 0x20 && p[0] < stop_ascii)))
  3475. {
  3476. // Printable ASCII
  3477. ++p;
  3478. }
  3479. if (p != s)
  3480. waddnstr(win, s, p - s);
  3481. w = utf8_decode(p, &wlen);
  3482. s = p += wlen;
  3483. switch(w)
  3484. {
  3485. // NOTE: U+F000-U+F7FF are reserved for font hacks
  3486. case '\0':
  3487. return;
  3488. case 0xb5: // micro symbol
  3489. w = unicode_micro;
  3490. goto default_addch;
  3491. case 0xf000: // "bad" off
  3492. wattroff(win, attr_bad);
  3493. break;
  3494. case 0xf001: // "bad" on
  3495. wattron(win, attr_bad);
  3496. break;
  3497. #ifdef USE_UNICODE
  3498. case '|':
  3499. wadd_wch(win, WACS_VLINE);
  3500. break;
  3501. #endif
  3502. case 0x2500: // BOX DRAWINGS LIGHT HORIZONTAL
  3503. case 0x2534: // BOX DRAWINGS LIGHT UP AND HORIZONTAL
  3504. if (!use_unicode)
  3505. {
  3506. waddch(win, '-');
  3507. break;
  3508. }
  3509. #ifdef USE_UNICODE
  3510. wadd_wch(win, (w == 0x2500) ? WACS_HLINE : WACS_BTEE);
  3511. break;
  3512. #endif
  3513. case 0x2022:
  3514. if (w > WCHAR_MAX || !iswprint(w))
  3515. w = '*';
  3516. default:
  3517. default_addch:
  3518. if (w > WCHAR_MAX || !(iswprint(w) || w == '\n'))
  3519. {
  3520. #if REPLACEMENT_CHAR <= WCHAR_MAX
  3521. if (iswprint(REPLACEMENT_CHAR))
  3522. w = REPLACEMENT_CHAR;
  3523. else
  3524. #endif
  3525. w = '?';
  3526. }
  3527. {
  3528. #ifdef USE_UNICODE
  3529. wchar_t wbuf[0x10];
  3530. int wbuflen = sizeof(wbuf) / sizeof(*wbuf);
  3531. wbuflen = swprintf(wbuf, wbuflen, L"%lc", (wint_t)w);
  3532. waddnwstr(win, wbuf, wbuflen);
  3533. #else
  3534. wprintw(win, "%lc", (wint_t)w);
  3535. #endif
  3536. }
  3537. }
  3538. }
  3539. }
  3540. static inline
  3541. void bfg_hline(WINDOW *win, int y)
  3542. {
  3543. int maxx, __maybe_unused maxy;
  3544. getmaxyx(win, maxy, maxx);
  3545. #ifdef USE_UNICODE
  3546. if (use_unicode)
  3547. mvwhline_set(win, y, 0, WACS_HLINE, maxx);
  3548. else
  3549. #endif
  3550. mvwhline(win, y, 0, '-', maxx);
  3551. }
  3552. static
  3553. int bfg_win_linelen(WINDOW * const win)
  3554. {
  3555. int maxx;
  3556. int __maybe_unused y;
  3557. getmaxyx(win, y, maxx);
  3558. return maxx;
  3559. }
  3560. // Spaces until end of line, using current attributes (ie, not completely clear)
  3561. static
  3562. void bfg_wspctoeol(WINDOW * const win, const int offset)
  3563. {
  3564. int x, maxx;
  3565. int __maybe_unused y;
  3566. getmaxyx(win, y, maxx);
  3567. getyx(win, y, x);
  3568. const int space_count = (maxx - x) - offset;
  3569. // Check for negative - terminal too narrow
  3570. if (space_count <= 0)
  3571. return;
  3572. char buf[space_count];
  3573. memset(buf, ' ', space_count);
  3574. waddnstr(win, buf, space_count);
  3575. }
  3576. static int menu_attr = A_REVERSE;
  3577. #define CURBUFSIZ 256
  3578. #define cg_mvwprintw(win, y, x, fmt, ...) do { \
  3579. char tmp42[CURBUFSIZ]; \
  3580. snprintf(tmp42, sizeof(tmp42), fmt, ##__VA_ARGS__); \
  3581. wmove(win, y, x); \
  3582. bfg_waddstr(win, tmp42); \
  3583. } while (0)
  3584. #define cg_wprintw(win, fmt, ...) do { \
  3585. char tmp42[CURBUFSIZ]; \
  3586. snprintf(tmp42, sizeof(tmp42), fmt, ##__VA_ARGS__); \
  3587. bfg_waddstr(win, tmp42); \
  3588. } while (0)
  3589. static bool pool_unworkable(const struct pool *);
  3590. /* Must be called with curses mutex lock held and curses_active */
  3591. static void curses_print_status(const int ts)
  3592. {
  3593. struct pool *pool = currentpool;
  3594. struct timeval now, tv;
  3595. float efficiency;
  3596. double income;
  3597. int logdiv;
  3598. efficiency = total_bytes_xfer ? total_diff_accepted * 2048. / total_bytes_xfer : 0.0;
  3599. wattron(statuswin, attr_title);
  3600. const int linelen = bfg_win_linelen(statuswin);
  3601. int titlelen = 1 + strlen(PACKAGE) + 1 + strlen(VERSION) + 3 + 21 + 3 + 19;
  3602. cg_mvwprintw(statuswin, 0, 0, " " PACKAGE " ");
  3603. if (titlelen + 17 < linelen)
  3604. cg_wprintw(statuswin, "version ");
  3605. cg_wprintw(statuswin, VERSION " - ");
  3606. if (titlelen + 9 < linelen)
  3607. cg_wprintw(statuswin, "Started: ");
  3608. else
  3609. if (titlelen + 7 <= linelen)
  3610. cg_wprintw(statuswin, "Start: ");
  3611. cg_wprintw(statuswin, "%s", datestamp);
  3612. timer_set_now(&now);
  3613. {
  3614. unsigned int days, hours;
  3615. div_t d;
  3616. timersub(&now, &miner_started, &tv);
  3617. d = div(tv.tv_sec, 86400);
  3618. days = d.quot;
  3619. d = div(d.rem, 3600);
  3620. hours = d.quot;
  3621. d = div(d.rem, 60);
  3622. cg_wprintw(statuswin, " - [%3u day%c %02d:%02d:%02d]"
  3623. , days
  3624. , (days == 1) ? ' ' : 's'
  3625. , hours
  3626. , d.quot
  3627. , d.rem
  3628. );
  3629. }
  3630. bfg_wspctoeol(statuswin, 0);
  3631. wattroff(statuswin, attr_title);
  3632. wattron(statuswin, menu_attr);
  3633. wmove(statuswin, 1, 0);
  3634. bfg_waddstr(statuswin, " [M]anage devices [P]ool management [S]ettings [D]isplay options ");
  3635. bfg_wspctoeol(statuswin, 14);
  3636. bfg_waddstr(statuswin, "[H]elp [Q]uit ");
  3637. wattroff(statuswin, menu_attr);
  3638. if ((pool_strategy == POOL_LOADBALANCE || pool_strategy == POOL_BALANCE) && enabled_pools > 1) {
  3639. char poolinfo[20], poolinfo2[20];
  3640. int poolinfooff = 0, poolinfo2off, workable_pools = 0;
  3641. double lowdiff = DBL_MAX, highdiff = -1;
  3642. struct pool *lowdiff_pool = pools[0], *highdiff_pool = pools[0];
  3643. time_t oldest_work_restart = time(NULL) + 1;
  3644. struct pool *oldest_work_restart_pool = pools[0];
  3645. for (int i = 0; i < total_pools; ++i)
  3646. {
  3647. if (pool_unworkable(pools[i]))
  3648. continue;
  3649. // NOTE: Only set pool var when it's workable; if only one is, it gets used by single-pool code
  3650. pool = pools[i];
  3651. ++workable_pools;
  3652. if (poolinfooff < sizeof(poolinfo))
  3653. poolinfooff += snprintf(&poolinfo[poolinfooff], sizeof(poolinfo) - poolinfooff, "%u,", pool->pool_no);
  3654. struct cgminer_pool_stats * const pool_stats = &pool->cgminer_pool_stats;
  3655. if (pool_stats->last_diff < lowdiff)
  3656. {
  3657. lowdiff = pool_stats->last_diff;
  3658. lowdiff_pool = pool;
  3659. }
  3660. if (pool_stats->last_diff > highdiff)
  3661. {
  3662. highdiff = pool_stats->last_diff;
  3663. highdiff_pool = pool;
  3664. }
  3665. if (oldest_work_restart >= pool->work_restart_time)
  3666. {
  3667. oldest_work_restart = pool->work_restart_time;
  3668. oldest_work_restart_pool = pool;
  3669. }
  3670. }
  3671. if (unlikely(!workable_pools))
  3672. goto no_workable_pools;
  3673. if (workable_pools == 1)
  3674. goto one_workable_pool;
  3675. poolinfo2off = snprintf(poolinfo2, sizeof(poolinfo2), "%u (", workable_pools);
  3676. if (poolinfooff > sizeof(poolinfo2) - poolinfo2off - 1)
  3677. snprintf(&poolinfo2[poolinfo2off], sizeof(poolinfo2) - poolinfo2off, "%.*s...)", (int)(sizeof(poolinfo2) - poolinfo2off - 5), poolinfo);
  3678. else
  3679. snprintf(&poolinfo2[poolinfo2off], sizeof(poolinfo2) - poolinfo2off, "%.*s)%*s", (int)(poolinfooff - 1), poolinfo, (int)(sizeof(poolinfo2)), "");
  3680. cg_mvwprintw(statuswin, 2, 0, " Pools: %s Diff:%s%s%s %c LU:%s",
  3681. poolinfo2,
  3682. lowdiff_pool->diff,
  3683. (lowdiff == highdiff) ? "" : "-",
  3684. (lowdiff == highdiff) ? "" : highdiff_pool->diff,
  3685. have_longpoll ? '+' : '-',
  3686. oldest_work_restart_pool->work_restart_timestamp);
  3687. }
  3688. else
  3689. if (pool_unworkable(pool))
  3690. {
  3691. no_workable_pools: ;
  3692. wattron(statuswin, attr_bad);
  3693. cg_mvwprintw(statuswin, 2, 0, " (all pools are dead) ");
  3694. wattroff(statuswin, attr_bad);
  3695. }
  3696. else
  3697. {
  3698. one_workable_pool: ;
  3699. char pooladdr[19];
  3700. {
  3701. const char *rawaddr = pool->sockaddr_url;
  3702. BFGINIT(rawaddr, pool->rpc_url);
  3703. size_t pooladdrlen = strlen(rawaddr);
  3704. if (pooladdrlen > 20)
  3705. snprintf(pooladdr, sizeof(pooladdr), "...%s", &rawaddr[pooladdrlen - (sizeof(pooladdr) - 4)]);
  3706. else
  3707. snprintf(pooladdr, sizeof(pooladdr), "%*s", -(int)(sizeof(pooladdr) - 1), rawaddr);
  3708. }
  3709. cg_mvwprintw(statuswin, 2, 0, " Pool%2u: %s Diff:%s %c%s LU:%s User:%s",
  3710. pool->pool_no, pooladdr, pool->diff,
  3711. have_longpoll ? '+' : '-', pool_proto_str(pool),
  3712. pool->work_restart_timestamp,
  3713. pool->rpc_user);
  3714. }
  3715. wclrtoeol(statuswin);
  3716. cg_mvwprintw(statuswin, 3, 0, " Block: %s Diff:%s (%s) Started: %s",
  3717. current_hash, block_diff, net_hashrate, blocktime);
  3718. income = total_diff_accepted * 3600 * block_subsidy / total_secs / current_diff;
  3719. char bwstr[(ALLOC_H2B_SHORT*2)+3+1], incomestr[ALLOC_H2B_SHORT+6+1];
  3720. format_unit3(incomestr, sizeof(incomestr), FUP_BTC, "BTC/hr", H2B_SHORT, income/1e8, -1);
  3721. cg_mvwprintw(statuswin, 4, 0, " ST:%d F:%d NB:%d AS:%d BW:[%s] E:%.2f I:%s BS:%s",
  3722. ts,
  3723. total_go + total_ro,
  3724. new_blocks,
  3725. total_submitting,
  3726. multi_format_unit2(bwstr, sizeof(bwstr),
  3727. false, "B/s", H2B_SHORT, "/", 2,
  3728. (float)(total_bytes_rcvd / total_secs),
  3729. (float)(total_bytes_sent / total_secs)),
  3730. efficiency,
  3731. incomestr,
  3732. best_share);
  3733. wclrtoeol(statuswin);
  3734. mvwaddstr(statuswin, 5, 0, " ");
  3735. bfg_waddstr(statuswin, statusline);
  3736. wclrtoeol(statuswin);
  3737. logdiv = statusy - 1;
  3738. bfg_hline(statuswin, 6);
  3739. bfg_hline(statuswin, logdiv);
  3740. #ifdef USE_UNICODE
  3741. if (use_unicode)
  3742. {
  3743. int offset = 8 /* device */ + 5 /* temperature */ + 1 /* padding space */;
  3744. if (opt_show_procs && !opt_compact)
  3745. offset += max_lpdigits; // proc letter(s)
  3746. if (have_unicode_degrees)
  3747. ++offset; // degrees symbol
  3748. mvwadd_wch(statuswin, 6, offset, WACS_PLUS);
  3749. mvwadd_wch(statuswin, logdiv, offset, WACS_BTEE);
  3750. offset += 24; // hashrates etc
  3751. mvwadd_wch(statuswin, 6, offset, WACS_PLUS);
  3752. mvwadd_wch(statuswin, logdiv, offset, WACS_BTEE);
  3753. }
  3754. #endif
  3755. }
  3756. static void adj_width(int var, int *length)
  3757. {
  3758. if ((int)(log10(var) + 1) > *length)
  3759. (*length)++;
  3760. }
  3761. static int dev_width;
  3762. static void curses_print_devstatus(struct cgpu_info *cgpu)
  3763. {
  3764. char logline[256];
  3765. int ypos;
  3766. if (opt_compact)
  3767. return;
  3768. /* Check this isn't out of the window size */
  3769. if (opt_show_procs)
  3770. ypos = cgpu->cgminer_id;
  3771. else
  3772. {
  3773. if (cgpu->proc_id)
  3774. return;
  3775. ypos = cgpu->device_line_id;
  3776. }
  3777. ypos += devsummaryYOffset;
  3778. if (ypos < 0)
  3779. return;
  3780. ypos += devcursor - 1;
  3781. if (ypos >= statusy - 1)
  3782. return;
  3783. if (wmove(statuswin, ypos, 0) == ERR)
  3784. return;
  3785. get_statline2(logline, sizeof(logline), cgpu, true);
  3786. if (selecting_device && (opt_show_procs ? (selected_device == cgpu->cgminer_id) : (devices[selected_device]->device == cgpu)))
  3787. wattron(statuswin, A_REVERSE);
  3788. bfg_waddstr(statuswin, logline);
  3789. wattroff(statuswin, A_REVERSE);
  3790. wclrtoeol(statuswin);
  3791. }
  3792. static
  3793. void _refresh_devstatus(const bool already_have_lock) {
  3794. if ((!opt_compact) && (already_have_lock || curses_active_locked())) {
  3795. int i;
  3796. if (unlikely(!total_devices))
  3797. {
  3798. const int ypos = devcursor - 1;
  3799. if (ypos < statusy - 1 && wmove(statuswin, ypos, 0) != ERR)
  3800. {
  3801. wattron(statuswin, attr_bad);
  3802. bfg_waddstr(statuswin, "NO DEVICES FOUND: Press 'M' and '+' to add");
  3803. wclrtoeol(statuswin);
  3804. wattroff(statuswin, attr_bad);
  3805. }
  3806. }
  3807. for (i = 0; i < total_devices; i++)
  3808. curses_print_devstatus(get_devices(i));
  3809. touchwin(statuswin);
  3810. wrefresh(statuswin);
  3811. if (!already_have_lock)
  3812. unlock_curses();
  3813. }
  3814. }
  3815. #define refresh_devstatus() _refresh_devstatus(false)
  3816. #endif
  3817. static void print_status(int thr_id)
  3818. {
  3819. if (!curses_active)
  3820. text_print_status(thr_id);
  3821. }
  3822. #ifdef HAVE_CURSES
  3823. static
  3824. bool set_statusy(int maxy)
  3825. {
  3826. if (loginput_size)
  3827. {
  3828. maxy -= loginput_size;
  3829. if (maxy < 0)
  3830. maxy = 0;
  3831. }
  3832. if (logstart < maxy)
  3833. maxy = logstart;
  3834. if (statusy == maxy)
  3835. return false;
  3836. statusy = maxy;
  3837. logcursor = statusy;
  3838. return true;
  3839. }
  3840. /* Check for window resize. Called with curses mutex locked */
  3841. static inline void change_logwinsize(void)
  3842. {
  3843. int x, y, logx, logy;
  3844. getmaxyx(mainwin, y, x);
  3845. if (x < 80 || y < 25)
  3846. return;
  3847. if (y > statusy + 2 && statusy < logstart) {
  3848. set_statusy(y - 2);
  3849. mvwin(logwin, logcursor, 0);
  3850. bfg_wresize(statuswin, statusy, x);
  3851. }
  3852. y -= logcursor;
  3853. getmaxyx(logwin, logy, logx);
  3854. /* Detect screen size change */
  3855. if (x != logx || y != logy)
  3856. bfg_wresize(logwin, y, x);
  3857. }
  3858. static void check_winsizes(void)
  3859. {
  3860. if (!use_curses)
  3861. return;
  3862. if (curses_active_locked()) {
  3863. int y, x;
  3864. x = getmaxx(statuswin);
  3865. if (set_statusy(LINES - 2))
  3866. {
  3867. erase();
  3868. bfg_wresize(statuswin, statusy, x);
  3869. getmaxyx(mainwin, y, x);
  3870. y -= logcursor;
  3871. bfg_wresize(logwin, y, x);
  3872. mvwin(logwin, logcursor, 0);
  3873. }
  3874. unlock_curses();
  3875. }
  3876. }
  3877. static int device_line_id_count;
  3878. static void switch_logsize(void)
  3879. {
  3880. if (curses_active_locked()) {
  3881. if (opt_compact) {
  3882. logstart = devcursor - 1;
  3883. logcursor = logstart + 1;
  3884. } else {
  3885. total_lines = (opt_show_procs ? total_devices : device_line_id_count) ?: 1;
  3886. logstart = devcursor + total_lines;
  3887. logcursor = logstart;
  3888. }
  3889. unlock_curses();
  3890. }
  3891. check_winsizes();
  3892. }
  3893. /* For mandatory printing when mutex is already locked */
  3894. void _wlog(const char *str)
  3895. {
  3896. static bool newline;
  3897. size_t end = strlen(str) - 1;
  3898. if (newline)
  3899. bfg_waddstr(logwin, "\n");
  3900. if (str[end] == '\n')
  3901. {
  3902. char *s;
  3903. newline = true;
  3904. s = alloca(end + 1);
  3905. memcpy(s, str, end);
  3906. s[end] = '\0';
  3907. str = s;
  3908. }
  3909. else
  3910. newline = false;
  3911. bfg_waddstr(logwin, str);
  3912. }
  3913. /* Mandatory printing */
  3914. void _wlogprint(const char *str)
  3915. {
  3916. if (curses_active_locked()) {
  3917. _wlog(str);
  3918. unlock_curses();
  3919. }
  3920. }
  3921. #endif
  3922. #ifdef HAVE_CURSES
  3923. bool _log_curses_only(int prio, const char *datetime, const char *str)
  3924. {
  3925. bool high_prio;
  3926. high_prio = (prio == LOG_WARNING || prio == LOG_ERR);
  3927. if (curses_active)
  3928. {
  3929. if (!loginput_size || high_prio) {
  3930. wlog(" %s %s\n", datetime, str);
  3931. if (high_prio) {
  3932. touchwin(logwin);
  3933. wrefresh(logwin);
  3934. }
  3935. }
  3936. return true;
  3937. }
  3938. return false;
  3939. }
  3940. void clear_logwin(void)
  3941. {
  3942. if (curses_active_locked()) {
  3943. wclear(logwin);
  3944. unlock_curses();
  3945. }
  3946. }
  3947. void logwin_update(void)
  3948. {
  3949. if (curses_active_locked()) {
  3950. touchwin(logwin);
  3951. wrefresh(logwin);
  3952. unlock_curses();
  3953. }
  3954. }
  3955. #endif
  3956. void enable_pool(struct pool * const pool)
  3957. {
  3958. if (pool->enabled != POOL_ENABLED) {
  3959. mutex_lock(&lp_lock);
  3960. enabled_pools++;
  3961. pool->enabled = POOL_ENABLED;
  3962. pthread_cond_broadcast(&lp_cond);
  3963. mutex_unlock(&lp_lock);
  3964. if (pool->prio < current_pool()->prio)
  3965. switch_pools(pool);
  3966. }
  3967. }
  3968. void disable_pool(struct pool * const pool, const enum pool_enable enable_status)
  3969. {
  3970. if (pool->enabled == POOL_DISABLED)
  3971. /* had been manually disabled before */
  3972. return;
  3973. if (pool->enabled != POOL_ENABLED)
  3974. {
  3975. /* has been programmatically disabled already, just change to the new status directly */
  3976. pool->enabled = enable_status;
  3977. return;
  3978. }
  3979. /* Fall into the lock area */
  3980. mutex_lock(&lp_lock);
  3981. --enabled_pools;
  3982. pool->enabled = enable_status;
  3983. mutex_unlock(&lp_lock);
  3984. if (pool == current_pool())
  3985. switch_pools(NULL);
  3986. }
  3987. static
  3988. void share_result_msg(const struct work *work, const char *disp, const char *reason, bool resubmit, const char *worktime) {
  3989. struct cgpu_info *cgpu;
  3990. const unsigned char *hashpart = &work->hash[opt_scrypt ? 26 : 24];
  3991. char shrdiffdisp[ALLOC_H2B_SHORTV];
  3992. const double tgtdiff = work->work_difficulty;
  3993. char tgtdiffdisp[ALLOC_H2B_SHORTV];
  3994. char where[20];
  3995. cgpu = get_thr_cgpu(work->thr_id);
  3996. suffix_string(work->share_diff, shrdiffdisp, sizeof(shrdiffdisp), 0);
  3997. suffix_string(tgtdiff, tgtdiffdisp, sizeof(tgtdiffdisp), 0);
  3998. if (total_pools > 1)
  3999. snprintf(where, sizeof(where), " pool %d", work->pool->pool_no);
  4000. else
  4001. where[0] = '\0';
  4002. applog(LOG_NOTICE, "%s %02x%02x%02x%02x %"PRIprepr"%s Diff %s/%s%s %s%s",
  4003. disp,
  4004. (unsigned)hashpart[3], (unsigned)hashpart[2], (unsigned)hashpart[1], (unsigned)hashpart[0],
  4005. cgpu->proc_repr,
  4006. where,
  4007. shrdiffdisp, tgtdiffdisp,
  4008. reason,
  4009. resubmit ? "(resubmit)" : "",
  4010. worktime
  4011. );
  4012. }
  4013. static bool test_work_current(struct work *);
  4014. static void _submit_work_async(struct work *);
  4015. static
  4016. void maybe_local_submit(const struct work *work)
  4017. {
  4018. #if BLKMAKER_VERSION > 3
  4019. if (unlikely(work->block && work->tr))
  4020. {
  4021. // This is a block with a full template (GBT)
  4022. // Regardless of the result, submit to local bitcoind(s) as well
  4023. struct work *work_cp;
  4024. for (int i = 0; i < total_pools; ++i)
  4025. {
  4026. if (!uri_get_param_bool(pools[i]->rpc_url, "allblocks", false))
  4027. continue;
  4028. applog(LOG_DEBUG, "Attempting submission of full block to pool %d", pools[i]->pool_no);
  4029. work_cp = copy_work(work);
  4030. work_cp->pool = pools[i];
  4031. work_cp->do_foreign_submit = true;
  4032. _submit_work_async(work_cp);
  4033. }
  4034. }
  4035. #endif
  4036. }
  4037. /* Theoretically threads could race when modifying accepted and
  4038. * rejected values but the chance of two submits completing at the
  4039. * same time is zero so there is no point adding extra locking */
  4040. static void
  4041. share_result(json_t *val, json_t *res, json_t *err, const struct work *work,
  4042. /*char *hashshow,*/ bool resubmit, char *worktime)
  4043. {
  4044. struct pool *pool = work->pool;
  4045. struct cgpu_info *cgpu;
  4046. cgpu = get_thr_cgpu(work->thr_id);
  4047. if ((json_is_null(err) || !err) && (json_is_null(res) || json_is_true(res))) {
  4048. mutex_lock(&stats_lock);
  4049. cgpu->accepted++;
  4050. total_accepted++;
  4051. pool->accepted++;
  4052. cgpu->diff_accepted += work->work_difficulty;
  4053. total_diff_accepted += work->work_difficulty;
  4054. pool->diff_accepted += work->work_difficulty;
  4055. mutex_unlock(&stats_lock);
  4056. pool->seq_rejects = 0;
  4057. cgpu->last_share_pool = pool->pool_no;
  4058. cgpu->last_share_pool_time = time(NULL);
  4059. cgpu->last_share_diff = work->work_difficulty;
  4060. pool->last_share_time = cgpu->last_share_pool_time;
  4061. pool->last_share_diff = work->work_difficulty;
  4062. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  4063. if (!QUIET) {
  4064. share_result_msg(work, "Accepted", "", resubmit, worktime);
  4065. }
  4066. sharelog("accept", work);
  4067. if (opt_shares && total_diff_accepted >= opt_shares) {
  4068. applog(LOG_WARNING, "Successfully mined %g accepted shares as requested and exiting.", opt_shares);
  4069. kill_work();
  4070. return;
  4071. }
  4072. /* Detect if a pool that has been temporarily disabled for
  4073. * continually rejecting shares has started accepting shares.
  4074. * This will only happen with the work returned from a
  4075. * longpoll */
  4076. if (unlikely(pool->enabled == POOL_REJECTING)) {
  4077. applog(LOG_WARNING, "Rejecting pool %d now accepting shares, re-enabling!", pool->pool_no);
  4078. enable_pool(pool);
  4079. }
  4080. if (unlikely(work->block)) {
  4081. // Force moving on to this new block :)
  4082. struct work fakework;
  4083. memset(&fakework, 0, sizeof(fakework));
  4084. fakework.pool = work->pool;
  4085. // Copy block version, bits, and time from share
  4086. memcpy(&fakework.data[ 0], &work->data[ 0], 4);
  4087. memcpy(&fakework.data[68], &work->data[68], 8);
  4088. // Set prevblock to winning hash (swap32'd)
  4089. swap32yes(&fakework.data[4], &work->hash[0], 32 / 4);
  4090. test_work_current(&fakework);
  4091. }
  4092. } else {
  4093. mutex_lock(&stats_lock);
  4094. cgpu->rejected++;
  4095. total_rejected++;
  4096. pool->rejected++;
  4097. cgpu->diff_rejected += work->work_difficulty;
  4098. total_diff_rejected += work->work_difficulty;
  4099. pool->diff_rejected += work->work_difficulty;
  4100. pool->seq_rejects++;
  4101. mutex_unlock(&stats_lock);
  4102. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  4103. if (!QUIET) {
  4104. char where[20];
  4105. char disposition[36] = "reject";
  4106. char reason[32];
  4107. strcpy(reason, "");
  4108. if (total_pools > 1)
  4109. snprintf(where, sizeof(where), "pool %d", work->pool->pool_no);
  4110. else
  4111. strcpy(where, "");
  4112. if (!json_is_string(res))
  4113. res = json_object_get(val, "reject-reason");
  4114. if (res) {
  4115. const char *reasontmp = json_string_value(res);
  4116. size_t reasonLen = strlen(reasontmp);
  4117. if (reasonLen > 28)
  4118. reasonLen = 28;
  4119. reason[0] = ' '; reason[1] = '(';
  4120. memcpy(2 + reason, reasontmp, reasonLen);
  4121. reason[reasonLen + 2] = ')'; reason[reasonLen + 3] = '\0';
  4122. memcpy(disposition + 7, reasontmp, reasonLen);
  4123. disposition[6] = ':'; disposition[reasonLen + 7] = '\0';
  4124. } else if (work->stratum && err && json_is_array(err)) {
  4125. json_t *reason_val = json_array_get(err, 1);
  4126. char *reason_str;
  4127. if (reason_val && json_is_string(reason_val)) {
  4128. reason_str = (char *)json_string_value(reason_val);
  4129. snprintf(reason, 31, " (%s)", reason_str);
  4130. }
  4131. }
  4132. share_result_msg(work, "Rejected", reason, resubmit, worktime);
  4133. sharelog(disposition, work);
  4134. }
  4135. /* Once we have more than a nominal amount of sequential rejects,
  4136. * at least 10 and more than 3 mins at the current utility,
  4137. * disable the pool because some pool error is likely to have
  4138. * ensued. Do not do this if we know the share just happened to
  4139. * be stale due to networking delays.
  4140. */
  4141. if (pool->seq_rejects > 10 && !work->stale && opt_disable_pool && enabled_pools > 1) {
  4142. double utility = total_accepted / total_secs * 60;
  4143. if (pool->seq_rejects > utility * 3) {
  4144. applog(LOG_WARNING, "Pool %d rejected %d sequential shares, disabling!",
  4145. pool->pool_no, pool->seq_rejects);
  4146. disable_pool(pool, POOL_REJECTING);
  4147. pool->seq_rejects = 0;
  4148. }
  4149. }
  4150. }
  4151. maybe_local_submit(work);
  4152. }
  4153. static char *submit_upstream_work_request(struct work *work)
  4154. {
  4155. char *hexstr = NULL;
  4156. char *s, *sd;
  4157. struct pool *pool = work->pool;
  4158. if (work->tr)
  4159. {
  4160. blktemplate_t * const tmpl = work->tr->tmpl;
  4161. json_t *req;
  4162. unsigned char data[80];
  4163. swap32yes(data, work->data, 80 / 4);
  4164. #if BLKMAKER_VERSION > 3
  4165. if (work->do_foreign_submit)
  4166. req = blkmk_submit_foreign_jansson(tmpl, data, work->dataid, le32toh(*((uint32_t*)&work->data[76])));
  4167. else
  4168. #endif
  4169. req = blkmk_submit_jansson(tmpl, data, work->dataid, le32toh(*((uint32_t*)&work->data[76])));
  4170. s = json_dumps(req, 0);
  4171. json_decref(req);
  4172. sd = malloc(161);
  4173. bin2hex(sd, data, 80);
  4174. } else {
  4175. /* build hex string */
  4176. hexstr = malloc((sizeof(work->data) * 2) + 1);
  4177. bin2hex(hexstr, work->data, sizeof(work->data));
  4178. /* build JSON-RPC request */
  4179. s = strdup("{\"method\": \"getwork\", \"params\": [ \"");
  4180. s = realloc_strcat(s, hexstr);
  4181. s = realloc_strcat(s, "\" ], \"id\":1}");
  4182. free(hexstr);
  4183. sd = s;
  4184. }
  4185. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->rpc_url, sd);
  4186. if (work->tr)
  4187. free(sd);
  4188. else
  4189. s = realloc_strcat(s, "\n");
  4190. return s;
  4191. }
  4192. static bool submit_upstream_work_completed(struct work *work, bool resubmit, struct timeval *ptv_submit, json_t *val) {
  4193. json_t *res, *err;
  4194. bool rc = false;
  4195. int thr_id = work->thr_id;
  4196. struct pool *pool = work->pool;
  4197. struct timeval tv_submit_reply;
  4198. time_t ts_submit_reply;
  4199. char worktime[200] = "";
  4200. cgtime(&tv_submit_reply);
  4201. ts_submit_reply = time(NULL);
  4202. if (unlikely(!val)) {
  4203. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  4204. if (!pool_tset(pool, &pool->submit_fail)) {
  4205. total_ro++;
  4206. pool->remotefail_occasions++;
  4207. applog(LOG_WARNING, "Pool %d communication failure, caching submissions", pool->pool_no);
  4208. }
  4209. goto out;
  4210. } else if (pool_tclear(pool, &pool->submit_fail))
  4211. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  4212. res = json_object_get(val, "result");
  4213. err = json_object_get(val, "error");
  4214. if (!QUIET) {
  4215. if (opt_worktime) {
  4216. char workclone[20];
  4217. struct tm _tm;
  4218. struct tm *tm, tm_getwork, tm_submit_reply;
  4219. tm = &_tm;
  4220. double getwork_time = tdiff((struct timeval *)&(work->tv_getwork_reply),
  4221. (struct timeval *)&(work->tv_getwork));
  4222. double getwork_to_work = tdiff((struct timeval *)&(work->tv_work_start),
  4223. (struct timeval *)&(work->tv_getwork_reply));
  4224. double work_time = tdiff((struct timeval *)&(work->tv_work_found),
  4225. (struct timeval *)&(work->tv_work_start));
  4226. double work_to_submit = tdiff(ptv_submit,
  4227. (struct timeval *)&(work->tv_work_found));
  4228. double submit_time = tdiff(&tv_submit_reply, ptv_submit);
  4229. int diffplaces = 3;
  4230. localtime_r(&work->ts_getwork, tm);
  4231. memcpy(&tm_getwork, tm, sizeof(struct tm));
  4232. localtime_r(&ts_submit_reply, tm);
  4233. memcpy(&tm_submit_reply, tm, sizeof(struct tm));
  4234. if (work->clone) {
  4235. snprintf(workclone, sizeof(workclone), "C:%1.3f",
  4236. tdiff((struct timeval *)&(work->tv_cloned),
  4237. (struct timeval *)&(work->tv_getwork_reply)));
  4238. }
  4239. else
  4240. strcpy(workclone, "O");
  4241. if (work->work_difficulty < 1)
  4242. diffplaces = 6;
  4243. snprintf(worktime, sizeof(worktime),
  4244. " <-%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",
  4245. (unsigned long)be32toh(*(uint32_t *)&(work->data[opt_scrypt ? 32 : 28])),
  4246. (unsigned long)be32toh(*(uint32_t *)&(work->data[opt_scrypt ? 28 : 24])),
  4247. work->getwork_mode, diffplaces, work->work_difficulty,
  4248. tm_getwork.tm_hour, tm_getwork.tm_min,
  4249. tm_getwork.tm_sec, getwork_time, workclone,
  4250. getwork_to_work, work_time, work_to_submit, submit_time,
  4251. tm_submit_reply.tm_hour, tm_submit_reply.tm_min,
  4252. tm_submit_reply.tm_sec);
  4253. }
  4254. }
  4255. share_result(val, res, err, work, resubmit, worktime);
  4256. if (!opt_realquiet)
  4257. print_status(thr_id);
  4258. if (!want_per_device_stats) {
  4259. char logline[256];
  4260. struct cgpu_info *cgpu;
  4261. cgpu = get_thr_cgpu(thr_id);
  4262. get_statline(logline, sizeof(logline), cgpu);
  4263. applog(LOG_INFO, "%s", logline);
  4264. }
  4265. json_decref(val);
  4266. rc = true;
  4267. out:
  4268. return rc;
  4269. }
  4270. /* Specifies whether we can use this pool for work or not. */
  4271. static bool pool_unworkable(const struct pool * const pool)
  4272. {
  4273. if (pool->idle)
  4274. return true;
  4275. if (pool->enabled != POOL_ENABLED)
  4276. return true;
  4277. if (pool->has_stratum && !pool->stratum_active)
  4278. return true;
  4279. return false;
  4280. }
  4281. static
  4282. bool pool_actively_desired(const struct pool * const pool, const struct pool *cp)
  4283. {
  4284. if (pool->enabled != POOL_ENABLED)
  4285. return false;
  4286. if (pool_strategy == POOL_LOADBALANCE || pool_strategy == POOL_BALANCE)
  4287. return true;
  4288. if (!cp)
  4289. cp = current_pool();
  4290. return (pool == cp);
  4291. }
  4292. static
  4293. bool pool_actively_in_use(const struct pool * const pool, const struct pool *cp)
  4294. {
  4295. return (!pool_unworkable(pool)) && pool_actively_desired(pool, cp);
  4296. }
  4297. static
  4298. bool pool_supports_block_change_notification(struct pool * const pool)
  4299. {
  4300. return pool->has_stratum || pool->lp_url;
  4301. }
  4302. static
  4303. bool pool_has_active_block_change_notification(struct pool * const pool)
  4304. {
  4305. return pool->stratum_active || pool->lp_active;
  4306. }
  4307. static struct pool *_select_longpoll_pool(struct pool *, bool(*)(struct pool *));
  4308. #define select_longpoll_pool(pool) _select_longpoll_pool(pool, pool_supports_block_change_notification)
  4309. #define pool_active_lp_pool(pool) _select_longpoll_pool(pool, pool_has_active_block_change_notification)
  4310. /* In balanced mode, the amount of diff1 solutions per pool is monitored as a
  4311. * rolling average per 10 minutes and if pools start getting more, it biases
  4312. * away from them to distribute work evenly. The share count is reset to the
  4313. * rolling average every 10 minutes to not send all work to one pool after it
  4314. * has been disabled/out for an extended period. */
  4315. static struct pool *select_balanced(struct pool *cp)
  4316. {
  4317. int i, lowest = cp->shares;
  4318. struct pool *ret = cp, *failover_pool = NULL;
  4319. for (i = 0; i < total_pools; i++) {
  4320. struct pool *pool = pools[i];
  4321. if (pool_unworkable(pool))
  4322. continue;
  4323. if (pool->failover_only)
  4324. {
  4325. BFGINIT(failover_pool, pool);
  4326. continue;
  4327. }
  4328. if (pool->shares < lowest) {
  4329. lowest = pool->shares;
  4330. ret = pool;
  4331. }
  4332. }
  4333. if (pool_unworkable(ret) && failover_pool)
  4334. ret = failover_pool;
  4335. ret->shares++;
  4336. return ret;
  4337. }
  4338. static bool pool_active(struct pool *, bool pinging);
  4339. static void pool_died(struct pool *);
  4340. static struct pool *priority_pool(int choice);
  4341. static bool pool_unusable(struct pool *pool);
  4342. /* Select any active pool in a rotating fashion when loadbalance is chosen if
  4343. * it has any quota left. */
  4344. static inline struct pool *select_pool(bool lagging)
  4345. {
  4346. static int rotating_pool = 0;
  4347. struct pool *pool, *cp;
  4348. bool avail = false;
  4349. int tested, i;
  4350. retry:
  4351. cp = current_pool();
  4352. if (pool_strategy == POOL_BALANCE) {
  4353. pool = select_balanced(cp);
  4354. if (pool_unworkable(pool))
  4355. goto simple_failover;
  4356. goto out;
  4357. }
  4358. if (pool_strategy != POOL_LOADBALANCE && (!lagging || opt_fail_only)) {
  4359. pool = cp;
  4360. goto out;
  4361. } else
  4362. pool = NULL;
  4363. for (i = 0; i < total_pools; i++) {
  4364. struct pool *tp = pools[i];
  4365. if (tp->quota_used < tp->quota_gcd) {
  4366. avail = true;
  4367. break;
  4368. }
  4369. }
  4370. /* There are no pools with quota, so reset them. */
  4371. if (!avail) {
  4372. for (i = 0; i < total_pools; i++)
  4373. pools[i]->quota_used = 0;
  4374. if (++rotating_pool >= total_pools)
  4375. rotating_pool = 0;
  4376. }
  4377. /* Try to find the first pool in the rotation that is usable */
  4378. tested = 0;
  4379. while (!pool && tested++ < total_pools) {
  4380. pool = pools[rotating_pool];
  4381. if (pool->quota_used++ < pool->quota_gcd) {
  4382. if (!pool_unworkable(pool))
  4383. break;
  4384. /* Failover-only flag for load-balance means distribute
  4385. * unused quota to priority pool 0. */
  4386. if (opt_fail_only)
  4387. priority_pool(0)->quota_used--;
  4388. }
  4389. pool = NULL;
  4390. if (++rotating_pool >= total_pools)
  4391. rotating_pool = 0;
  4392. }
  4393. simple_failover:
  4394. /* If there are no alive pools with quota, choose according to
  4395. * priority. */
  4396. if (!pool) {
  4397. for (i = 0; i < total_pools; i++) {
  4398. struct pool *tp = priority_pool(i);
  4399. if (!pool_unusable(tp)) {
  4400. pool = tp;
  4401. break;
  4402. }
  4403. }
  4404. }
  4405. /* If still nothing is usable, use the current pool */
  4406. if (!pool)
  4407. pool = cp;
  4408. out:
  4409. if (!pool_actively_in_use(pool, cp))
  4410. {
  4411. if (!pool_active(pool, false))
  4412. {
  4413. pool_died(pool);
  4414. goto retry;
  4415. }
  4416. pool_tclear(pool, &pool->idle);
  4417. }
  4418. applog(LOG_DEBUG, "Selecting pool %d for work", pool->pool_no);
  4419. return pool;
  4420. }
  4421. static double DIFFEXACTONE = 26959946667150639794667015087019630673637144422540572481103610249215.0;
  4422. double target_diff(const unsigned char *target)
  4423. {
  4424. double targ = 0;
  4425. signed int i;
  4426. for (i = 31; i >= 0; --i)
  4427. targ = (targ * 0x100) + target[i];
  4428. return DIFFEXACTONE / (targ ?: 1);
  4429. }
  4430. /*
  4431. * Calculate the work share difficulty
  4432. */
  4433. static void calc_diff(struct work *work, int known)
  4434. {
  4435. struct cgminer_pool_stats *pool_stats = &(work->pool->cgminer_pool_stats);
  4436. double difficulty;
  4437. if (!known) {
  4438. work->work_difficulty = target_diff(work->target);
  4439. } else
  4440. work->work_difficulty = known;
  4441. difficulty = work->work_difficulty;
  4442. pool_stats->last_diff = difficulty;
  4443. suffix_string(difficulty, work->pool->diff, sizeof(work->pool->diff), 0);
  4444. if (difficulty == pool_stats->min_diff)
  4445. pool_stats->min_diff_count++;
  4446. else if (difficulty < pool_stats->min_diff || pool_stats->min_diff == 0) {
  4447. pool_stats->min_diff = difficulty;
  4448. pool_stats->min_diff_count = 1;
  4449. }
  4450. if (difficulty == pool_stats->max_diff)
  4451. pool_stats->max_diff_count++;
  4452. else if (difficulty > pool_stats->max_diff) {
  4453. pool_stats->max_diff = difficulty;
  4454. pool_stats->max_diff_count = 1;
  4455. }
  4456. }
  4457. static void gen_stratum_work(struct pool *, struct work *);
  4458. static void pool_update_work_restart_time(struct pool *);
  4459. static void restart_threads(void);
  4460. static uint32_t benchmark_blkhdr[20];
  4461. static const int benchmark_update_interval = 1;
  4462. static
  4463. void *benchmark_intense_work_update_thread(void *userp)
  4464. {
  4465. pthread_detach(pthread_self());
  4466. RenameThread("benchmark-intense");
  4467. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  4468. struct pool * const pool = userp;
  4469. struct stratum_work * const swork = &pool->swork;
  4470. uint8_t * const blkhdr = swork->header1;
  4471. while (true)
  4472. {
  4473. sleep(benchmark_update_interval);
  4474. cg_wlock(&pool->data_lock);
  4475. for (int i = 36; --i >= 0; )
  4476. if (++blkhdr[i])
  4477. break;
  4478. cg_wunlock(&pool->data_lock);
  4479. struct work *work = make_work();
  4480. gen_stratum_work(pool, work);
  4481. pool->swork.work_restart_id = ++pool->work_restart_id;
  4482. pool_update_work_restart_time(pool);
  4483. test_work_current(work);
  4484. free_work(work);
  4485. restart_threads();
  4486. }
  4487. return NULL;
  4488. }
  4489. static
  4490. void setup_benchmark_pool()
  4491. {
  4492. struct pool *pool;
  4493. want_longpoll = false;
  4494. // Temporarily disable opt_benchmark to avoid auto-removal
  4495. opt_benchmark = false;
  4496. pool = add_pool();
  4497. opt_benchmark = true;
  4498. pool->rpc_url = malloc(255);
  4499. strcpy(pool->rpc_url, "Benchmark");
  4500. pool_set_uri(pool, pool->rpc_url);
  4501. pool->rpc_user = pool->rpc_url;
  4502. pool->rpc_pass = pool->rpc_url;
  4503. enable_pool(pool);
  4504. pool->idle = false;
  4505. successful_connect = true;
  4506. {
  4507. uint32_t * const blkhdr = benchmark_blkhdr;
  4508. blkhdr[2] = htobe32(1);
  4509. blkhdr[17] = htobe32(0x7fffffff); // timestamp
  4510. blkhdr[18] = htobe32(0x1700ffff); // "bits"
  4511. }
  4512. {
  4513. struct stratum_work * const swork = &pool->swork;
  4514. const int branchcount = 15; // 1 MB block
  4515. const size_t branchdatasz = branchcount * 0x20;
  4516. const size_t coinbase_sz = (opt_benchmark_intense ? 250 : 6) * 1024;
  4517. bytes_resize(&swork->coinbase, coinbase_sz);
  4518. memset(bytes_buf(&swork->coinbase), '\xff', coinbase_sz);
  4519. swork->nonce2_offset = 0;
  4520. bytes_resize(&swork->merkle_bin, branchdatasz);
  4521. memset(bytes_buf(&swork->merkle_bin), '\xff', branchdatasz);
  4522. swork->merkles = branchcount;
  4523. swork->header1[0] = '\xff';
  4524. memset(&swork->header1[1], '\0', 34);
  4525. swork->header1[35] = '\x01';
  4526. swork->ntime = 0x7fffffff;
  4527. timer_unset(&swork->tv_received);
  4528. memcpy(swork->diffbits, "\x17\0\xff\xff", 4);
  4529. set_target_to_pdiff(swork->target, opt_scrypt ? (1./0x10000) : 1.);
  4530. pool->nonce2sz = swork->n2size = GBT_XNONCESZ;
  4531. pool->nonce2 = 0;
  4532. }
  4533. if (opt_benchmark_intense)
  4534. {
  4535. pthread_t pth;
  4536. if (unlikely(pthread_create(&pth, NULL, benchmark_intense_work_update_thread, pool)))
  4537. applog(LOG_WARNING, "Failed to start benchmark intense work update thread");
  4538. }
  4539. }
  4540. void get_benchmark_work(struct work *work, bool use_swork)
  4541. {
  4542. if (use_swork)
  4543. {
  4544. struct timeval tv_now;
  4545. timer_set_now(&tv_now);
  4546. gen_stratum_work(pools[0], work);
  4547. work->getwork_mode = GETWORK_MODE_BENCHMARK;
  4548. work_set_simple_ntime_roll_limit(work, 0, &tv_now);
  4549. return;
  4550. }
  4551. struct pool * const pool = pools[0];
  4552. uint32_t * const blkhdr = benchmark_blkhdr;
  4553. for (int i = 16; i >= 0; --i)
  4554. if (++blkhdr[i])
  4555. break;
  4556. memcpy(&work->data[ 0], blkhdr, 80);
  4557. memcpy(&work->data[80], workpadding_bin, 48);
  4558. char hex[161];
  4559. bin2hex(hex, work->data, 80);
  4560. applog(LOG_DEBUG, "Generated benchmark header %s", hex);
  4561. calc_midstate(work);
  4562. memcpy(work->target, pool->swork.target, sizeof(work->target));
  4563. work->mandatory = true;
  4564. work->pool = pools[0];
  4565. cgtime(&work->tv_getwork);
  4566. copy_time(&work->tv_getwork_reply, &work->tv_getwork);
  4567. copy_time(&work->tv_staged, &work->tv_getwork);
  4568. work->getwork_mode = GETWORK_MODE_BENCHMARK;
  4569. calc_diff(work, 0);
  4570. work_set_simple_ntime_roll_limit(work, 60, &work->tv_getwork);
  4571. }
  4572. static void wake_gws(void);
  4573. static void update_last_work(struct work *work)
  4574. {
  4575. if (!work->tr)
  4576. // Only save GBT jobs, since rollntime isn't coordinated well yet
  4577. return;
  4578. struct pool *pool = work->pool;
  4579. mutex_lock(&pool->last_work_lock);
  4580. if (pool->last_work_copy)
  4581. free_work(pool->last_work_copy);
  4582. pool->last_work_copy = copy_work(work);
  4583. pool->last_work_copy->work_restart_id = pool->work_restart_id;
  4584. mutex_unlock(&pool->last_work_lock);
  4585. }
  4586. static
  4587. void gbt_req_target(json_t *req)
  4588. {
  4589. json_t *j;
  4590. json_t *n;
  4591. if (!request_target_str)
  4592. return;
  4593. j = json_object_get(req, "params");
  4594. if (!j)
  4595. {
  4596. n = json_array();
  4597. if (!n)
  4598. return;
  4599. if (json_object_set_new(req, "params", n))
  4600. goto erradd;
  4601. j = n;
  4602. }
  4603. n = json_array_get(j, 0);
  4604. if (!n)
  4605. {
  4606. n = json_object();
  4607. if (!n)
  4608. return;
  4609. if (json_array_append_new(j, n))
  4610. goto erradd;
  4611. }
  4612. j = n;
  4613. n = json_string(request_target_str);
  4614. if (!n)
  4615. return;
  4616. if (json_object_set_new(j, "target", n))
  4617. goto erradd;
  4618. return;
  4619. erradd:
  4620. json_decref(n);
  4621. }
  4622. static char *prepare_rpc_req2(struct work *work, enum pool_protocol proto, const char *lpid, bool probe)
  4623. {
  4624. char *rpc_req;
  4625. clean_work(work);
  4626. switch (proto) {
  4627. case PLP_GETWORK:
  4628. work->getwork_mode = GETWORK_MODE_POOL;
  4629. return strdup(getwork_req);
  4630. case PLP_GETBLOCKTEMPLATE:
  4631. work->getwork_mode = GETWORK_MODE_GBT;
  4632. blktemplate_t * const tmpl = blktmpl_create();
  4633. if (!tmpl)
  4634. goto gbtfail2;
  4635. work->tr = tmpl_makeref(tmpl);
  4636. gbt_capabilities_t caps = blktmpl_addcaps(tmpl);
  4637. if (!caps)
  4638. goto gbtfail;
  4639. caps |= GBT_LONGPOLL;
  4640. #if BLKMAKER_VERSION > 1
  4641. if (bytes_len(&opt_coinbase_script) || have_at_least_one_getcbaddr)
  4642. caps |= GBT_CBVALUE;
  4643. #endif
  4644. json_t *req = blktmpl_request_jansson(caps, lpid);
  4645. if (!req)
  4646. goto gbtfail;
  4647. if (probe)
  4648. gbt_req_target(req);
  4649. rpc_req = json_dumps(req, 0);
  4650. if (!rpc_req)
  4651. goto gbtfail;
  4652. json_decref(req);
  4653. return rpc_req;
  4654. default:
  4655. return NULL;
  4656. }
  4657. return NULL;
  4658. gbtfail:
  4659. tmpl_decref(work->tr);
  4660. work->tr = NULL;
  4661. gbtfail2:
  4662. return NULL;
  4663. }
  4664. #define prepare_rpc_req(work, proto, lpid) prepare_rpc_req2(work, proto, lpid, false)
  4665. #define prepare_rpc_req_probe(work, proto, lpid) prepare_rpc_req2(work, proto, lpid, true)
  4666. static const char *pool_protocol_name(enum pool_protocol proto)
  4667. {
  4668. switch (proto) {
  4669. case PLP_GETBLOCKTEMPLATE:
  4670. return "getblocktemplate";
  4671. case PLP_GETWORK:
  4672. return "getwork";
  4673. default:
  4674. return "UNKNOWN";
  4675. }
  4676. }
  4677. static enum pool_protocol pool_protocol_fallback(enum pool_protocol proto)
  4678. {
  4679. switch (proto) {
  4680. case PLP_GETBLOCKTEMPLATE:
  4681. if (want_getwork)
  4682. return PLP_GETWORK;
  4683. default:
  4684. return PLP_NONE;
  4685. }
  4686. }
  4687. static bool get_upstream_work(struct work *work, CURL *curl)
  4688. {
  4689. struct pool *pool = work->pool;
  4690. struct cgminer_pool_stats *pool_stats = &(pool->cgminer_pool_stats);
  4691. struct timeval tv_elapsed;
  4692. json_t *val = NULL;
  4693. bool rc = false;
  4694. char *url;
  4695. enum pool_protocol proto;
  4696. char *rpc_req;
  4697. if (pool->proto == PLP_NONE)
  4698. pool->proto = PLP_GETBLOCKTEMPLATE;
  4699. tryagain:
  4700. rpc_req = prepare_rpc_req(work, pool->proto, NULL);
  4701. work->pool = pool;
  4702. if (!rpc_req)
  4703. return false;
  4704. applog(LOG_DEBUG, "DBG: sending %s get RPC call: %s", pool->rpc_url, rpc_req);
  4705. url = pool->rpc_url;
  4706. cgtime(&work->tv_getwork);
  4707. val = json_rpc_call(curl, url, pool->rpc_userpass, rpc_req, false,
  4708. false, &work->rolltime, pool, false);
  4709. pool_stats->getwork_attempts++;
  4710. free(rpc_req);
  4711. if (likely(val)) {
  4712. rc = work_decode(pool, work, val);
  4713. if (unlikely(!rc))
  4714. applog(LOG_DEBUG, "Failed to decode work in get_upstream_work");
  4715. } else if (PLP_NONE != (proto = pool_protocol_fallback(pool->proto))) {
  4716. applog(LOG_WARNING, "Pool %u failed getblocktemplate request; falling back to getwork protocol", pool->pool_no);
  4717. pool->proto = proto;
  4718. goto tryagain;
  4719. } else
  4720. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  4721. cgtime(&work->tv_getwork_reply);
  4722. timersub(&(work->tv_getwork_reply), &(work->tv_getwork), &tv_elapsed);
  4723. pool_stats->getwork_wait_rolling += ((double)tv_elapsed.tv_sec + ((double)tv_elapsed.tv_usec / 1000000)) * 0.63;
  4724. pool_stats->getwork_wait_rolling /= 1.63;
  4725. timeradd(&tv_elapsed, &(pool_stats->getwork_wait), &(pool_stats->getwork_wait));
  4726. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_max), >)) {
  4727. pool_stats->getwork_wait_max.tv_sec = tv_elapsed.tv_sec;
  4728. pool_stats->getwork_wait_max.tv_usec = tv_elapsed.tv_usec;
  4729. }
  4730. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_min), <)) {
  4731. pool_stats->getwork_wait_min.tv_sec = tv_elapsed.tv_sec;
  4732. pool_stats->getwork_wait_min.tv_usec = tv_elapsed.tv_usec;
  4733. }
  4734. pool_stats->getwork_calls++;
  4735. work->pool = pool;
  4736. work->longpoll = false;
  4737. calc_diff(work, 0);
  4738. total_getworks++;
  4739. pool->getwork_requested++;
  4740. if (rc)
  4741. update_last_work(work);
  4742. if (likely(val))
  4743. json_decref(val);
  4744. return rc;
  4745. }
  4746. #ifdef HAVE_CURSES
  4747. static void disable_curses(void)
  4748. {
  4749. if (curses_active_locked()) {
  4750. use_curses = false;
  4751. curses_active = false;
  4752. leaveok(logwin, false);
  4753. leaveok(statuswin, false);
  4754. leaveok(mainwin, false);
  4755. nocbreak();
  4756. echo();
  4757. delwin(logwin);
  4758. delwin(statuswin);
  4759. delwin(mainwin);
  4760. endwin();
  4761. #ifdef WIN32
  4762. // Move the cursor to after curses output.
  4763. HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
  4764. CONSOLE_SCREEN_BUFFER_INFO csbi;
  4765. COORD coord;
  4766. if (GetConsoleScreenBufferInfo(hout, &csbi)) {
  4767. coord.X = 0;
  4768. coord.Y = csbi.dwSize.Y - 1;
  4769. SetConsoleCursorPosition(hout, coord);
  4770. }
  4771. #endif
  4772. unlock_curses();
  4773. }
  4774. }
  4775. #endif
  4776. static void __kill_work(void)
  4777. {
  4778. struct cgpu_info *cgpu;
  4779. struct thr_info *thr;
  4780. int i;
  4781. if (!successful_connect)
  4782. return;
  4783. applog(LOG_INFO, "Received kill message");
  4784. shutting_down = true;
  4785. applog(LOG_DEBUG, "Prompting submit_work thread to finish");
  4786. notifier_wake(submit_waiting_notifier);
  4787. #ifdef USE_LIBMICROHTTPD
  4788. httpsrv_stop();
  4789. #endif
  4790. applog(LOG_DEBUG, "Killing off watchpool thread");
  4791. /* Kill the watchpool thread */
  4792. thr = &control_thr[watchpool_thr_id];
  4793. thr_info_cancel(thr);
  4794. applog(LOG_DEBUG, "Killing off watchdog thread");
  4795. /* Kill the watchdog thread */
  4796. thr = &control_thr[watchdog_thr_id];
  4797. thr_info_cancel(thr);
  4798. applog(LOG_DEBUG, "Shutting down mining threads");
  4799. for (i = 0; i < mining_threads; i++) {
  4800. thr = get_thread(i);
  4801. if (!thr)
  4802. continue;
  4803. cgpu = thr->cgpu;
  4804. if (!cgpu)
  4805. continue;
  4806. if (!cgpu->threads)
  4807. continue;
  4808. cgpu->shutdown = true;
  4809. thr->work_restart = true;
  4810. notifier_wake(thr->notifier);
  4811. notifier_wake(thr->work_restart_notifier);
  4812. }
  4813. sleep(1);
  4814. applog(LOG_DEBUG, "Killing off mining threads");
  4815. /* Kill the mining threads*/
  4816. for (i = 0; i < mining_threads; i++) {
  4817. thr = get_thread(i);
  4818. if (!thr)
  4819. continue;
  4820. cgpu = thr->cgpu;
  4821. if (cgpu->threads)
  4822. {
  4823. applog(LOG_WARNING, "Killing %"PRIpreprv, thr->cgpu->proc_repr);
  4824. thr_info_cancel(thr);
  4825. }
  4826. cgpu->status = LIFE_DEAD2;
  4827. }
  4828. /* Stop the others */
  4829. applog(LOG_DEBUG, "Killing off API thread");
  4830. thr = &control_thr[api_thr_id];
  4831. thr_info_cancel(thr);
  4832. }
  4833. /* This should be the common exit path */
  4834. void kill_work(void)
  4835. {
  4836. __kill_work();
  4837. quit(0, "Shutdown signal received.");
  4838. }
  4839. static
  4840. #ifdef WIN32
  4841. #ifndef _WIN64
  4842. const
  4843. #endif
  4844. #endif
  4845. char **initial_args;
  4846. void _bfg_clean_up(bool);
  4847. void app_restart(void)
  4848. {
  4849. applog(LOG_WARNING, "Attempting to restart %s", packagename);
  4850. __kill_work();
  4851. _bfg_clean_up(true);
  4852. #if defined(unix) || defined(__APPLE__)
  4853. if (forkpid > 0) {
  4854. kill(forkpid, SIGTERM);
  4855. forkpid = 0;
  4856. }
  4857. #endif
  4858. execv(initial_args[0], initial_args);
  4859. applog(LOG_WARNING, "Failed to restart application");
  4860. }
  4861. static void sighandler(int __maybe_unused sig)
  4862. {
  4863. /* Restore signal handlers so we can still quit if kill_work fails */
  4864. sigaction(SIGTERM, &termhandler, NULL);
  4865. sigaction(SIGINT, &inthandler, NULL);
  4866. kill_work();
  4867. }
  4868. static void start_longpoll(void);
  4869. static void stop_longpoll(void);
  4870. /* Called with pool_lock held. Recruit an extra curl if none are available for
  4871. * this pool. */
  4872. static void recruit_curl(struct pool *pool)
  4873. {
  4874. struct curl_ent *ce = calloc(sizeof(struct curl_ent), 1);
  4875. if (unlikely(!ce))
  4876. quit(1, "Failed to calloc in recruit_curl");
  4877. ce->curl = curl_easy_init();
  4878. if (unlikely(!ce->curl))
  4879. quit(1, "Failed to init in recruit_curl");
  4880. LL_PREPEND(pool->curllist, ce);
  4881. pool->curls++;
  4882. }
  4883. /* Grab an available curl if there is one. If not, then recruit extra curls
  4884. * unless we are in a submit_fail situation, or we have opt_delaynet enabled
  4885. * and there are already 5 curls in circulation. Limit total number to the
  4886. * number of mining threads per pool as well to prevent blasting a pool during
  4887. * network delays/outages. */
  4888. static struct curl_ent *pop_curl_entry3(struct pool *pool, int blocking)
  4889. {
  4890. int curl_limit = opt_delaynet ? 5 : (mining_threads + opt_queue) * 2;
  4891. bool recruited = false;
  4892. struct curl_ent *ce;
  4893. mutex_lock(&pool->pool_lock);
  4894. retry:
  4895. if (!pool->curls) {
  4896. recruit_curl(pool);
  4897. recruited = true;
  4898. } else if (!pool->curllist) {
  4899. if (blocking < 2 && pool->curls >= curl_limit && (blocking || pool->curls >= opt_submit_threads)) {
  4900. if (!blocking) {
  4901. mutex_unlock(&pool->pool_lock);
  4902. return NULL;
  4903. }
  4904. pthread_cond_wait(&pool->cr_cond, &pool->pool_lock);
  4905. goto retry;
  4906. } else {
  4907. recruit_curl(pool);
  4908. recruited = true;
  4909. }
  4910. }
  4911. ce = pool->curllist;
  4912. LL_DELETE(pool->curllist, ce);
  4913. mutex_unlock(&pool->pool_lock);
  4914. if (recruited)
  4915. applog(LOG_DEBUG, "Recruited curl for pool %d", pool->pool_no);
  4916. return ce;
  4917. }
  4918. static struct curl_ent *pop_curl_entry2(struct pool *pool, bool blocking)
  4919. {
  4920. return pop_curl_entry3(pool, blocking ? 1 : 0);
  4921. }
  4922. __maybe_unused
  4923. static struct curl_ent *pop_curl_entry(struct pool *pool)
  4924. {
  4925. return pop_curl_entry3(pool, 1);
  4926. }
  4927. static void push_curl_entry(struct curl_ent *ce, struct pool *pool)
  4928. {
  4929. mutex_lock(&pool->pool_lock);
  4930. if (!ce || !ce->curl)
  4931. quithere(1, "Attempted to add NULL");
  4932. LL_PREPEND(pool->curllist, ce);
  4933. cgtime(&ce->tv);
  4934. pthread_cond_broadcast(&pool->cr_cond);
  4935. mutex_unlock(&pool->pool_lock);
  4936. }
  4937. bool stale_work(struct work *work, bool share);
  4938. static inline bool should_roll(struct work *work)
  4939. {
  4940. struct timeval now;
  4941. time_t expiry;
  4942. if (!pool_actively_in_use(work->pool, NULL))
  4943. return false;
  4944. if (stale_work(work, false))
  4945. return false;
  4946. if (work->rolltime > opt_scantime)
  4947. expiry = work->rolltime;
  4948. else
  4949. expiry = opt_scantime;
  4950. expiry = expiry * 2 / 3;
  4951. /* We shouldn't roll if we're unlikely to get one shares' duration
  4952. * work out of doing so */
  4953. cgtime(&now);
  4954. if (now.tv_sec - work->tv_staged.tv_sec > expiry)
  4955. return false;
  4956. return true;
  4957. }
  4958. /* Limit rolls to 7000 to not beyond 2 hours in the future where bitcoind will
  4959. * reject blocks as invalid. */
  4960. static inline bool can_roll(struct work *work)
  4961. {
  4962. if (work->stratum)
  4963. return false;
  4964. if (!(work->pool && !work->clone))
  4965. return false;
  4966. if (work->tr)
  4967. {
  4968. if (stale_work(work, false))
  4969. return false;
  4970. return blkmk_work_left(work->tr->tmpl);
  4971. }
  4972. return (work->rolltime &&
  4973. work->rolls < 7000 && !stale_work(work, false));
  4974. }
  4975. static void roll_work(struct work *work)
  4976. {
  4977. if (work->tr)
  4978. {
  4979. struct timeval tv_now;
  4980. cgtime(&tv_now);
  4981. if (blkmk_get_data(work->tr->tmpl, work->data, 80, tv_now.tv_sec, NULL, &work->dataid) < 76)
  4982. applog(LOG_ERR, "Failed to get next data from template; spinning wheels!");
  4983. swap32yes(work->data, work->data, 80 / 4);
  4984. calc_midstate(work);
  4985. applog(LOG_DEBUG, "Successfully rolled extranonce to dataid %u", work->dataid);
  4986. } else {
  4987. uint32_t *work_ntime;
  4988. uint32_t ntime;
  4989. work_ntime = (uint32_t *)(work->data + 68);
  4990. ntime = be32toh(*work_ntime);
  4991. ntime++;
  4992. *work_ntime = htobe32(ntime);
  4993. work_set_simple_ntime_roll_limit(work, 0, &work->ntime_roll_limits.tv_ref);
  4994. applog(LOG_DEBUG, "Successfully rolled time header in work");
  4995. }
  4996. local_work++;
  4997. work->rolls++;
  4998. work->blk.nonce = 0;
  4999. /* This is now a different work item so it needs a different ID for the
  5000. * hashtable */
  5001. work->id = total_work++;
  5002. }
  5003. /* Duplicates any dynamically allocated arrays within the work struct to
  5004. * prevent a copied work struct from freeing ram belonging to another struct */
  5005. static void _copy_work(struct work *work, const struct work *base_work, int noffset)
  5006. {
  5007. int id = work->id;
  5008. clean_work(work);
  5009. memcpy(work, base_work, sizeof(struct work));
  5010. /* Keep the unique new id assigned during make_work to prevent copied
  5011. * work from having the same id. */
  5012. work->id = id;
  5013. if (base_work->job_id)
  5014. work->job_id = strdup(base_work->job_id);
  5015. if (base_work->nonce1)
  5016. work->nonce1 = strdup(base_work->nonce1);
  5017. bytes_cpy(&work->nonce2, &base_work->nonce2);
  5018. if (base_work->tr)
  5019. tmpl_incref(base_work->tr);
  5020. if (noffset)
  5021. {
  5022. uint32_t *work_ntime = (uint32_t *)(work->data + 68);
  5023. uint32_t ntime = be32toh(*work_ntime);
  5024. ntime += noffset;
  5025. *work_ntime = htobe32(ntime);
  5026. }
  5027. if (work->device_data_dup_func)
  5028. work->device_data = work->device_data_dup_func(work);
  5029. }
  5030. /* Generates a copy of an existing work struct, creating fresh heap allocations
  5031. * for all dynamically allocated arrays within the struct. noffset is used for
  5032. * when a driver has internally rolled the ntime, noffset is a relative value.
  5033. * The macro copy_work() calls this function with an noffset of 0. */
  5034. struct work *copy_work_noffset(const struct work *base_work, int noffset)
  5035. {
  5036. struct work *work = make_work();
  5037. _copy_work(work, base_work, noffset);
  5038. return work;
  5039. }
  5040. void __copy_work(struct work *work, const struct work *base_work)
  5041. {
  5042. _copy_work(work, base_work, 0);
  5043. }
  5044. static struct work *make_clone(struct work *work)
  5045. {
  5046. struct work *work_clone = copy_work(work);
  5047. work_clone->clone = true;
  5048. cgtime((struct timeval *)&(work_clone->tv_cloned));
  5049. work_clone->longpoll = false;
  5050. work_clone->mandatory = false;
  5051. /* Make cloned work appear slightly older to bias towards keeping the
  5052. * master work item which can be further rolled */
  5053. work_clone->tv_staged.tv_sec -= 1;
  5054. return work_clone;
  5055. }
  5056. static void stage_work(struct work *work);
  5057. static bool clone_available(void)
  5058. {
  5059. struct work *work_clone = NULL, *work, *tmp;
  5060. bool cloned = false;
  5061. mutex_lock(stgd_lock);
  5062. if (!staged_rollable)
  5063. goto out_unlock;
  5064. HASH_ITER(hh, staged_work, work, tmp) {
  5065. if (can_roll(work) && should_roll(work)) {
  5066. roll_work(work);
  5067. work_clone = make_clone(work);
  5068. applog(LOG_DEBUG, "%s: Rolling work %d to %d", __func__, work->id, work_clone->id);
  5069. roll_work(work);
  5070. cloned = true;
  5071. break;
  5072. }
  5073. }
  5074. out_unlock:
  5075. mutex_unlock(stgd_lock);
  5076. if (cloned) {
  5077. applog(LOG_DEBUG, "Pushing cloned available work to stage thread");
  5078. stage_work(work_clone);
  5079. }
  5080. return cloned;
  5081. }
  5082. static void pool_died(struct pool *pool)
  5083. {
  5084. mutex_lock(&lp_lock);
  5085. if (!pool_tset(pool, &pool->idle)) {
  5086. cgtime(&pool->tv_idle);
  5087. pthread_cond_broadcast(&lp_cond);
  5088. mutex_unlock(&lp_lock);
  5089. if (pool == current_pool()) {
  5090. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  5091. switch_pools(NULL);
  5092. } else
  5093. applog(LOG_INFO, "Pool %d %s failed to return work", pool->pool_no, pool->rpc_url);
  5094. }
  5095. else
  5096. mutex_unlock(&lp_lock);
  5097. }
  5098. bool stale_work(struct work *work, bool share)
  5099. {
  5100. unsigned work_expiry;
  5101. struct pool *pool;
  5102. uint32_t block_id;
  5103. unsigned getwork_delay;
  5104. block_id = ((uint32_t*)work->data)[1];
  5105. pool = work->pool;
  5106. /* Technically the rolltime should be correct but some pools
  5107. * advertise a broken expire= that is lower than a meaningful
  5108. * scantime */
  5109. if (work->rolltime >= opt_scantime || work->tr)
  5110. work_expiry = work->rolltime;
  5111. else
  5112. work_expiry = opt_expiry;
  5113. unsigned max_expiry = (have_longpoll ? opt_expiry_lp : opt_expiry);
  5114. if (work_expiry > max_expiry)
  5115. work_expiry = max_expiry;
  5116. if (share) {
  5117. /* If the share isn't on this pool's latest block, it's stale */
  5118. if (pool->block_id && pool->block_id != block_id)
  5119. {
  5120. applog(LOG_DEBUG, "Share stale due to block mismatch (%08lx != %08lx)", (long)block_id, (long)pool->block_id);
  5121. return true;
  5122. }
  5123. /* If the pool doesn't want old shares, then any found in work before
  5124. * the most recent longpoll is stale */
  5125. if ((!pool->submit_old) && work->work_restart_id != pool->work_restart_id)
  5126. {
  5127. applog(LOG_DEBUG, "Share stale due to mandatory work update (%02x != %02x)", work->work_restart_id, pool->work_restart_id);
  5128. return true;
  5129. }
  5130. } else {
  5131. /* If this work isn't for the latest Bitcoin block, it's stale */
  5132. /* But only care about the current pool if failover-only */
  5133. if (enabled_pools <= 1 || opt_fail_only) {
  5134. if (pool->block_id && block_id != pool->block_id)
  5135. {
  5136. applog(LOG_DEBUG, "Work stale due to block mismatch (%08lx != 1 ? %08lx : %08lx)", (long)block_id, (long)pool->block_id, (long)current_block_id);
  5137. return true;
  5138. }
  5139. } else {
  5140. if (block_id != current_block_id)
  5141. {
  5142. applog(LOG_DEBUG, "Work stale due to block mismatch (%08lx != 0 ? %08lx : %08lx)", (long)block_id, (long)pool->block_id, (long)current_block_id);
  5143. return true;
  5144. }
  5145. }
  5146. /* If the pool has asked us to restart since this work, it's stale */
  5147. if (work->work_restart_id != pool->work_restart_id)
  5148. {
  5149. applog(LOG_DEBUG, "Work stale due to work update (%02x != %02x)", work->work_restart_id, pool->work_restart_id);
  5150. return true;
  5151. }
  5152. if (pool->has_stratum && work->job_id) {
  5153. bool same_job;
  5154. if (!pool->stratum_active || !pool->stratum_notify) {
  5155. applog(LOG_DEBUG, "Work stale due to stratum inactive");
  5156. return true;
  5157. }
  5158. same_job = true;
  5159. cg_rlock(&pool->data_lock);
  5160. if (strcmp(work->job_id, pool->swork.job_id))
  5161. same_job = false;
  5162. cg_runlock(&pool->data_lock);
  5163. if (!same_job) {
  5164. applog(LOG_DEBUG, "Work stale due to stratum job_id mismatch");
  5165. return true;
  5166. }
  5167. }
  5168. /* Factor in the average getwork delay of this pool, rounding it up to
  5169. * the nearest second */
  5170. getwork_delay = pool->cgminer_pool_stats.getwork_wait_rolling * 5 + 1;
  5171. if (unlikely(work_expiry <= getwork_delay + 5))
  5172. work_expiry = 5;
  5173. else
  5174. work_expiry -= getwork_delay;
  5175. }
  5176. int elapsed_since_staged = timer_elapsed(&work->tv_staged, NULL);
  5177. if (elapsed_since_staged > work_expiry) {
  5178. applog(LOG_DEBUG, "%s stale due to expiry (%d >= %u)", share?"Share":"Work", elapsed_since_staged, work_expiry);
  5179. return true;
  5180. }
  5181. /* If the user only wants strict failover, any work from a pool other than
  5182. * the current one is always considered stale */
  5183. if (opt_fail_only && !share && !work->mandatory && !pool_actively_in_use(pool, NULL))
  5184. {
  5185. applog(LOG_DEBUG, "Work stale due to fail only pool mismatch (pool %u vs %u)", pool->pool_no, current_pool()->pool_no);
  5186. return true;
  5187. }
  5188. return false;
  5189. }
  5190. double share_diff(const struct work *work)
  5191. {
  5192. double ret;
  5193. bool new_best = false;
  5194. ret = target_diff(work->hash);
  5195. cg_wlock(&control_lock);
  5196. if (unlikely(ret > best_diff)) {
  5197. new_best = true;
  5198. best_diff = ret;
  5199. suffix_string(best_diff, best_share, sizeof(best_share), 0);
  5200. }
  5201. if (unlikely(ret > work->pool->best_diff))
  5202. work->pool->best_diff = ret;
  5203. cg_wunlock(&control_lock);
  5204. if (unlikely(new_best))
  5205. applog(LOG_INFO, "New best share: %s", best_share);
  5206. return ret;
  5207. }
  5208. static
  5209. void work_check_for_block(struct work * const work)
  5210. {
  5211. work->share_diff = share_diff(work);
  5212. if (unlikely(work->share_diff >= current_diff)) {
  5213. work->block = true;
  5214. work->pool->solved++;
  5215. found_blocks++;
  5216. work->mandatory = true;
  5217. applog(LOG_NOTICE, "Found block for pool %d!", work->pool->pool_no);
  5218. }
  5219. }
  5220. static void submit_discard_share2(const char *reason, struct work *work)
  5221. {
  5222. struct cgpu_info *cgpu = get_thr_cgpu(work->thr_id);
  5223. sharelog(reason, work);
  5224. mutex_lock(&stats_lock);
  5225. ++total_stale;
  5226. ++cgpu->stale;
  5227. ++(work->pool->stale_shares);
  5228. total_diff_stale += work->work_difficulty;
  5229. cgpu->diff_stale += work->work_difficulty;
  5230. work->pool->diff_stale += work->work_difficulty;
  5231. mutex_unlock(&stats_lock);
  5232. }
  5233. static void submit_discard_share(struct work *work)
  5234. {
  5235. submit_discard_share2("discard", work);
  5236. }
  5237. struct submit_work_state {
  5238. struct work *work;
  5239. bool resubmit;
  5240. struct curl_ent *ce;
  5241. int failures;
  5242. struct timeval tv_staleexpire;
  5243. char *s;
  5244. struct timeval tv_submit;
  5245. struct submit_work_state *next;
  5246. };
  5247. static int my_curl_timer_set(__maybe_unused CURLM *curlm, long timeout_ms, void *userp)
  5248. {
  5249. long *p_timeout_us = userp;
  5250. const long max_ms = LONG_MAX / 1000;
  5251. if (max_ms < timeout_ms)
  5252. timeout_ms = max_ms;
  5253. *p_timeout_us = timeout_ms * 1000;
  5254. return 0;
  5255. }
  5256. static void sws_has_ce(struct submit_work_state *sws)
  5257. {
  5258. struct pool *pool = sws->work->pool;
  5259. sws->s = submit_upstream_work_request(sws->work);
  5260. cgtime(&sws->tv_submit);
  5261. json_rpc_call_async(sws->ce->curl, pool->rpc_url, pool->rpc_userpass, sws->s, false, pool, true, sws);
  5262. }
  5263. static struct submit_work_state *begin_submission(struct work *work)
  5264. {
  5265. struct pool *pool;
  5266. struct submit_work_state *sws = NULL;
  5267. pool = work->pool;
  5268. sws = malloc(sizeof(*sws));
  5269. *sws = (struct submit_work_state){
  5270. .work = work,
  5271. };
  5272. work_check_for_block(work);
  5273. if (stale_work(work, true)) {
  5274. work->stale = true;
  5275. if (opt_submit_stale)
  5276. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as user requested", pool->pool_no);
  5277. else if (pool->submit_old)
  5278. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as pool requested", pool->pool_no);
  5279. else {
  5280. applog(LOG_NOTICE, "Pool %d stale share detected, discarding", pool->pool_no);
  5281. submit_discard_share(work);
  5282. goto out;
  5283. }
  5284. timer_set_delay_from_now(&sws->tv_staleexpire, 300000000);
  5285. }
  5286. if (work->stratum) {
  5287. char *s;
  5288. s = malloc(1024);
  5289. sws->s = s;
  5290. } else {
  5291. /* submit solution to bitcoin via JSON-RPC */
  5292. sws->ce = pop_curl_entry2(pool, false);
  5293. if (sws->ce) {
  5294. sws_has_ce(sws);
  5295. } else {
  5296. sws->next = pool->sws_waiting_on_curl;
  5297. pool->sws_waiting_on_curl = sws;
  5298. if (sws->next)
  5299. applog(LOG_DEBUG, "submit_thread queuing submission");
  5300. else
  5301. applog(LOG_WARNING, "submit_thread queuing submissions (see --submit-threads)");
  5302. }
  5303. }
  5304. return sws;
  5305. out:
  5306. free(sws);
  5307. return NULL;
  5308. }
  5309. static bool retry_submission(struct submit_work_state *sws)
  5310. {
  5311. struct work *work = sws->work;
  5312. struct pool *pool = work->pool;
  5313. sws->resubmit = true;
  5314. if ((!work->stale) && stale_work(work, true)) {
  5315. work->stale = true;
  5316. if (opt_submit_stale)
  5317. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, will retry as user requested", pool->pool_no);
  5318. else if (pool->submit_old)
  5319. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, will retry as pool requested", pool->pool_no);
  5320. else {
  5321. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, discarding", pool->pool_no);
  5322. submit_discard_share(work);
  5323. return false;
  5324. }
  5325. timer_set_delay_from_now(&sws->tv_staleexpire, 300000000);
  5326. }
  5327. if (unlikely((opt_retries >= 0) && (++sws->failures > opt_retries))) {
  5328. applog(LOG_ERR, "Pool %d failed %d submission retries, discarding", pool->pool_no, opt_retries);
  5329. submit_discard_share(work);
  5330. return false;
  5331. }
  5332. else if (work->stale) {
  5333. if (unlikely(opt_retries < 0 && timer_passed(&sws->tv_staleexpire, NULL)))
  5334. {
  5335. applog(LOG_NOTICE, "Pool %d stale share failed to submit for 5 minutes, discarding", pool->pool_no);
  5336. submit_discard_share(work);
  5337. return false;
  5338. }
  5339. }
  5340. /* pause, then restart work-request loop */
  5341. applog(LOG_INFO, "json_rpc_call failed on submit_work, retrying");
  5342. cgtime(&sws->tv_submit);
  5343. json_rpc_call_async(sws->ce->curl, pool->rpc_url, pool->rpc_userpass, sws->s, false, pool, true, sws);
  5344. return true;
  5345. }
  5346. static void free_sws(struct submit_work_state *sws)
  5347. {
  5348. free(sws->s);
  5349. free_work(sws->work);
  5350. free(sws);
  5351. }
  5352. static void *submit_work_thread(__maybe_unused void *userdata)
  5353. {
  5354. int wip = 0;
  5355. CURLM *curlm;
  5356. long curlm_timeout_us = -1;
  5357. struct timeval curlm_timer;
  5358. struct submit_work_state *sws, **swsp;
  5359. struct submit_work_state *write_sws = NULL;
  5360. unsigned tsreduce = 0;
  5361. pthread_detach(pthread_self());
  5362. RenameThread("submit_work");
  5363. applog(LOG_DEBUG, "Creating extra submit work thread");
  5364. curlm = curl_multi_init();
  5365. curlm_timeout_us = -1;
  5366. curl_multi_setopt(curlm, CURLMOPT_TIMERDATA, &curlm_timeout_us);
  5367. curl_multi_setopt(curlm, CURLMOPT_TIMERFUNCTION, my_curl_timer_set);
  5368. fd_set rfds, wfds, efds;
  5369. int maxfd;
  5370. struct timeval tv_timeout, tv_now;
  5371. int n;
  5372. CURLMsg *cm;
  5373. FD_ZERO(&rfds);
  5374. while (1) {
  5375. mutex_lock(&submitting_lock);
  5376. total_submitting -= tsreduce;
  5377. tsreduce = 0;
  5378. if (FD_ISSET(submit_waiting_notifier[0], &rfds)) {
  5379. notifier_read(submit_waiting_notifier);
  5380. }
  5381. // Receive any new submissions
  5382. while (submit_waiting) {
  5383. struct work *work = submit_waiting;
  5384. DL_DELETE(submit_waiting, work);
  5385. if ( (sws = begin_submission(work)) ) {
  5386. if (sws->ce)
  5387. curl_multi_add_handle(curlm, sws->ce->curl);
  5388. else if (sws->s) {
  5389. sws->next = write_sws;
  5390. write_sws = sws;
  5391. }
  5392. ++wip;
  5393. }
  5394. else {
  5395. --total_submitting;
  5396. free_work(work);
  5397. }
  5398. }
  5399. if (unlikely(shutting_down && !wip))
  5400. break;
  5401. mutex_unlock(&submitting_lock);
  5402. FD_ZERO(&rfds);
  5403. FD_ZERO(&wfds);
  5404. FD_ZERO(&efds);
  5405. tv_timeout.tv_sec = -1;
  5406. // Setup cURL with select
  5407. // Need to call perform to ensure the timeout gets updated
  5408. curl_multi_perform(curlm, &n);
  5409. curl_multi_fdset(curlm, &rfds, &wfds, &efds, &maxfd);
  5410. if (curlm_timeout_us >= 0)
  5411. {
  5412. timer_set_delay_from_now(&curlm_timer, curlm_timeout_us);
  5413. reduce_timeout_to(&tv_timeout, &curlm_timer);
  5414. }
  5415. // Setup waiting stratum submissions with select
  5416. for (sws = write_sws; sws; sws = sws->next)
  5417. {
  5418. struct pool *pool = sws->work->pool;
  5419. int fd = pool->sock;
  5420. if (fd == INVSOCK || (!pool->stratum_init) || !pool->stratum_notify)
  5421. continue;
  5422. FD_SET(fd, &wfds);
  5423. set_maxfd(&maxfd, fd);
  5424. }
  5425. // Setup "submit waiting" notifier with select
  5426. FD_SET(submit_waiting_notifier[0], &rfds);
  5427. set_maxfd(&maxfd, submit_waiting_notifier[0]);
  5428. // Wait for something interesting to happen :)
  5429. cgtime(&tv_now);
  5430. if (select(maxfd+1, &rfds, &wfds, &efds, select_timeout(&tv_timeout, &tv_now)) < 0) {
  5431. FD_ZERO(&rfds);
  5432. continue;
  5433. }
  5434. // Handle any stratum ready-to-write results
  5435. for (swsp = &write_sws; (sws = *swsp); ) {
  5436. struct work *work = sws->work;
  5437. struct pool *pool = work->pool;
  5438. int fd = pool->sock;
  5439. bool sessionid_match;
  5440. if (fd == INVSOCK || (!pool->stratum_init) || (!pool->stratum_notify) || !FD_ISSET(fd, &wfds)) {
  5441. next_write_sws:
  5442. // TODO: Check if stale, possibly discard etc
  5443. swsp = &sws->next;
  5444. continue;
  5445. }
  5446. cg_rlock(&pool->data_lock);
  5447. // 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
  5448. // NOTE: Worst case scenario for a false positive: the pool rejects it as H-not-zero
  5449. sessionid_match = (!pool->swork.nonce1) || !strcmp(work->nonce1, pool->swork.nonce1);
  5450. cg_runlock(&pool->data_lock);
  5451. if (!sessionid_match)
  5452. {
  5453. applog(LOG_DEBUG, "No matching session id for resubmitting stratum share");
  5454. submit_discard_share2("disconnect", work);
  5455. ++tsreduce;
  5456. next_write_sws_del:
  5457. // Clear the fd from wfds, to avoid potentially blocking on other submissions to the same socket
  5458. FD_CLR(fd, &wfds);
  5459. // Delete sws for this submission, since we're done with it
  5460. *swsp = sws->next;
  5461. free_sws(sws);
  5462. --wip;
  5463. continue;
  5464. }
  5465. char *s = sws->s;
  5466. struct stratum_share *sshare = calloc(sizeof(struct stratum_share), 1);
  5467. int sshare_id;
  5468. uint32_t nonce;
  5469. char nonce2hex[(bytes_len(&work->nonce2) * 2) + 1];
  5470. char noncehex[9];
  5471. char ntimehex[9];
  5472. sshare->work = copy_work(work);
  5473. bin2hex(nonce2hex, bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  5474. nonce = *((uint32_t *)(work->data + 76));
  5475. bin2hex(noncehex, (const unsigned char *)&nonce, 4);
  5476. bin2hex(ntimehex, (void *)&work->data[68], 4);
  5477. mutex_lock(&sshare_lock);
  5478. /* Give the stratum share a unique id */
  5479. sshare_id =
  5480. sshare->id = swork_id++;
  5481. HASH_ADD_INT(stratum_shares, id, sshare);
  5482. snprintf(s, 1024, "{\"params\": [\"%s\", \"%s\", \"%s\", \"%s\", \"%s\"], \"id\": %d, \"method\": \"mining.submit\"}",
  5483. pool->rpc_user, work->job_id, nonce2hex, ntimehex, noncehex, sshare->id);
  5484. mutex_unlock(&sshare_lock);
  5485. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->stratum_url, s);
  5486. if (likely(stratum_send(pool, s, strlen(s)))) {
  5487. if (pool_tclear(pool, &pool->submit_fail))
  5488. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  5489. applog(LOG_DEBUG, "Successfully submitted, adding to stratum_shares db");
  5490. goto next_write_sws_del;
  5491. } else if (!pool_tset(pool, &pool->submit_fail)) {
  5492. // Undo stuff
  5493. mutex_lock(&sshare_lock);
  5494. // NOTE: Need to find it again in case something else has consumed it already (like the stratum-disconnect resubmitter...)
  5495. HASH_FIND_INT(stratum_shares, &sshare_id, sshare);
  5496. if (sshare)
  5497. HASH_DEL(stratum_shares, sshare);
  5498. mutex_unlock(&sshare_lock);
  5499. if (sshare)
  5500. {
  5501. free_work(sshare->work);
  5502. free(sshare);
  5503. }
  5504. applog(LOG_WARNING, "Pool %d stratum share submission failure", pool->pool_no);
  5505. total_ro++;
  5506. pool->remotefail_occasions++;
  5507. if (!sshare)
  5508. goto next_write_sws_del;
  5509. goto next_write_sws;
  5510. }
  5511. }
  5512. // Handle any cURL activities
  5513. curl_multi_perform(curlm, &n);
  5514. while( (cm = curl_multi_info_read(curlm, &n)) ) {
  5515. if (cm->msg == CURLMSG_DONE)
  5516. {
  5517. bool finished;
  5518. json_t *val = json_rpc_call_completed(cm->easy_handle, cm->data.result, false, NULL, &sws);
  5519. curl_multi_remove_handle(curlm, cm->easy_handle);
  5520. finished = submit_upstream_work_completed(sws->work, sws->resubmit, &sws->tv_submit, val);
  5521. if (!finished) {
  5522. if (retry_submission(sws))
  5523. curl_multi_add_handle(curlm, sws->ce->curl);
  5524. else
  5525. finished = true;
  5526. }
  5527. if (finished) {
  5528. --wip;
  5529. ++tsreduce;
  5530. struct pool *pool = sws->work->pool;
  5531. if (pool->sws_waiting_on_curl) {
  5532. pool->sws_waiting_on_curl->ce = sws->ce;
  5533. sws_has_ce(pool->sws_waiting_on_curl);
  5534. pool->sws_waiting_on_curl = pool->sws_waiting_on_curl->next;
  5535. curl_multi_add_handle(curlm, sws->ce->curl);
  5536. } else {
  5537. push_curl_entry(sws->ce, sws->work->pool);
  5538. }
  5539. free_sws(sws);
  5540. }
  5541. }
  5542. }
  5543. }
  5544. assert(!write_sws);
  5545. mutex_unlock(&submitting_lock);
  5546. curl_multi_cleanup(curlm);
  5547. applog(LOG_DEBUG, "submit_work thread exiting");
  5548. return NULL;
  5549. }
  5550. /* Find the pool that currently has the highest priority */
  5551. static struct pool *priority_pool(int choice)
  5552. {
  5553. struct pool *ret = NULL;
  5554. int i;
  5555. for (i = 0; i < total_pools; i++) {
  5556. struct pool *pool = pools[i];
  5557. if (pool->prio == choice) {
  5558. ret = pool;
  5559. break;
  5560. }
  5561. }
  5562. if (unlikely(!ret)) {
  5563. applog(LOG_ERR, "WTF No pool %d found!", choice);
  5564. return pools[choice];
  5565. }
  5566. return ret;
  5567. }
  5568. int prioritize_pools(char *param, int *pid)
  5569. {
  5570. char *ptr, *next;
  5571. int i, pr, prio = 0;
  5572. if (total_pools == 0) {
  5573. return MSG_NOPOOL;
  5574. }
  5575. if (param == NULL || *param == '\0') {
  5576. return MSG_MISPID;
  5577. }
  5578. bool pools_changed[total_pools];
  5579. int new_prio[total_pools];
  5580. for (i = 0; i < total_pools; ++i)
  5581. pools_changed[i] = false;
  5582. next = param;
  5583. while (next && *next) {
  5584. ptr = next;
  5585. next = strchr(ptr, ',');
  5586. if (next)
  5587. *(next++) = '\0';
  5588. i = atoi(ptr);
  5589. if (i < 0 || i >= total_pools) {
  5590. *pid = i;
  5591. return MSG_INVPID;
  5592. }
  5593. if (pools_changed[i]) {
  5594. *pid = i;
  5595. return MSG_DUPPID;
  5596. }
  5597. pools_changed[i] = true;
  5598. new_prio[i] = prio++;
  5599. }
  5600. // Only change them if no errors
  5601. for (i = 0; i < total_pools; i++) {
  5602. if (pools_changed[i])
  5603. pools[i]->prio = new_prio[i];
  5604. }
  5605. // In priority order, cycle through the unchanged pools and append them
  5606. for (pr = 0; pr < total_pools; pr++)
  5607. for (i = 0; i < total_pools; i++) {
  5608. if (!pools_changed[i] && pools[i]->prio == pr) {
  5609. pools[i]->prio = prio++;
  5610. pools_changed[i] = true;
  5611. break;
  5612. }
  5613. }
  5614. if (current_pool()->prio)
  5615. switch_pools(NULL);
  5616. return MSG_POOLPRIO;
  5617. }
  5618. void validate_pool_priorities(void)
  5619. {
  5620. // TODO: this should probably do some sort of logging
  5621. int i, j;
  5622. bool used[total_pools];
  5623. bool valid[total_pools];
  5624. for (i = 0; i < total_pools; i++)
  5625. used[i] = valid[i] = false;
  5626. for (i = 0; i < total_pools; i++) {
  5627. if (pools[i]->prio >=0 && pools[i]->prio < total_pools) {
  5628. if (!used[pools[i]->prio]) {
  5629. valid[i] = true;
  5630. used[pools[i]->prio] = true;
  5631. }
  5632. }
  5633. }
  5634. for (i = 0; i < total_pools; i++) {
  5635. if (!valid[i]) {
  5636. for (j = 0; j < total_pools; j++) {
  5637. if (!used[j]) {
  5638. applog(LOG_WARNING, "Pool %d priority changed from %d to %d", i, pools[i]->prio, j);
  5639. pools[i]->prio = j;
  5640. used[j] = true;
  5641. break;
  5642. }
  5643. }
  5644. }
  5645. }
  5646. }
  5647. static void clear_pool_work(struct pool *pool);
  5648. /* Specifies whether we can switch to this pool or not. */
  5649. static bool pool_unusable(struct pool *pool)
  5650. {
  5651. if (pool->idle)
  5652. return true;
  5653. if (pool->enabled != POOL_ENABLED)
  5654. return true;
  5655. return false;
  5656. }
  5657. void switch_pools(struct pool *selected)
  5658. {
  5659. struct pool *pool, *last_pool, *failover_pool = NULL;
  5660. int i, pool_no, next_pool;
  5661. if (selected)
  5662. enable_pool(selected);
  5663. cg_wlock(&control_lock);
  5664. last_pool = currentpool;
  5665. pool_no = currentpool->pool_no;
  5666. /* Switch selected to pool number 0 and move the rest down */
  5667. if (selected) {
  5668. if (selected->prio != 0) {
  5669. for (i = 0; i < total_pools; i++) {
  5670. pool = pools[i];
  5671. if (pool->prio < selected->prio)
  5672. pool->prio++;
  5673. }
  5674. selected->prio = 0;
  5675. }
  5676. }
  5677. switch (pool_strategy) {
  5678. /* All of these set to the master pool */
  5679. case POOL_BALANCE:
  5680. case POOL_FAILOVER:
  5681. case POOL_LOADBALANCE:
  5682. for (i = 0; i < total_pools; i++) {
  5683. pool = priority_pool(i);
  5684. if (pool_unusable(pool))
  5685. continue;
  5686. pool_no = pool->pool_no;
  5687. break;
  5688. }
  5689. break;
  5690. /* Both of these simply increment and cycle */
  5691. case POOL_ROUNDROBIN:
  5692. case POOL_ROTATE:
  5693. if (selected && !selected->idle) {
  5694. pool_no = selected->pool_no;
  5695. break;
  5696. }
  5697. next_pool = pool_no;
  5698. /* Select the next alive pool */
  5699. for (i = 1; i < total_pools; i++) {
  5700. next_pool++;
  5701. if (next_pool >= total_pools)
  5702. next_pool = 0;
  5703. pool = pools[next_pool];
  5704. if (pool_unusable(pool))
  5705. continue;
  5706. if (pool->failover_only)
  5707. {
  5708. BFGINIT(failover_pool, pool);
  5709. continue;
  5710. }
  5711. pool_no = next_pool;
  5712. break;
  5713. }
  5714. break;
  5715. default:
  5716. break;
  5717. }
  5718. pool = pools[pool_no];
  5719. if (pool_unusable(pool) && failover_pool)
  5720. pool = failover_pool;
  5721. currentpool = pool;
  5722. cg_wunlock(&control_lock);
  5723. mutex_lock(&lp_lock);
  5724. pthread_cond_broadcast(&lp_cond);
  5725. mutex_unlock(&lp_lock);
  5726. /* Set the lagging flag to avoid pool not providing work fast enough
  5727. * messages in failover only mode since we have to get all fresh work
  5728. * as in restart_threads */
  5729. if (opt_fail_only)
  5730. pool_tset(pool, &pool->lagging);
  5731. if (pool != last_pool)
  5732. {
  5733. pool->block_id = 0;
  5734. if (pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  5735. applog(LOG_WARNING, "Switching to pool %d %s", pool->pool_no, pool->rpc_url);
  5736. if (pool_localgen(pool) || opt_fail_only)
  5737. clear_pool_work(last_pool);
  5738. }
  5739. }
  5740. mutex_lock(&lp_lock);
  5741. pthread_cond_broadcast(&lp_cond);
  5742. mutex_unlock(&lp_lock);
  5743. }
  5744. static void discard_work(struct work *work)
  5745. {
  5746. if (!work->clone && !work->rolls && !work->mined) {
  5747. if (work->pool) {
  5748. work->pool->discarded_work++;
  5749. work->pool->quota_used--;
  5750. work->pool->works--;
  5751. }
  5752. total_discarded++;
  5753. applog(LOG_DEBUG, "Discarded work");
  5754. } else
  5755. applog(LOG_DEBUG, "Discarded cloned or rolled work");
  5756. free_work(work);
  5757. }
  5758. static void wake_gws(void)
  5759. {
  5760. mutex_lock(stgd_lock);
  5761. pthread_cond_signal(&gws_cond);
  5762. mutex_unlock(stgd_lock);
  5763. }
  5764. static void discard_stale(void)
  5765. {
  5766. struct work *work, *tmp;
  5767. int stale = 0;
  5768. mutex_lock(stgd_lock);
  5769. HASH_ITER(hh, staged_work, work, tmp) {
  5770. if (stale_work(work, false)) {
  5771. HASH_DEL(staged_work, work);
  5772. discard_work(work);
  5773. stale++;
  5774. staged_full = false;
  5775. }
  5776. }
  5777. pthread_cond_signal(&gws_cond);
  5778. mutex_unlock(stgd_lock);
  5779. if (stale)
  5780. applog(LOG_DEBUG, "Discarded %d stales that didn't match current hash", stale);
  5781. }
  5782. bool stale_work_future(struct work *work, bool share, unsigned long ustime)
  5783. {
  5784. bool rv;
  5785. struct timeval tv, orig;
  5786. ldiv_t d;
  5787. d = ldiv(ustime, 1000000);
  5788. tv = (struct timeval){
  5789. .tv_sec = d.quot,
  5790. .tv_usec = d.rem,
  5791. };
  5792. orig = work->tv_staged;
  5793. timersub(&orig, &tv, &work->tv_staged);
  5794. rv = stale_work(work, share);
  5795. work->tv_staged = orig;
  5796. return rv;
  5797. }
  5798. static
  5799. void pool_update_work_restart_time(struct pool * const pool)
  5800. {
  5801. pool->work_restart_time = time(NULL);
  5802. get_timestamp(pool->work_restart_timestamp, sizeof(pool->work_restart_timestamp), pool->work_restart_time);
  5803. }
  5804. static void restart_threads(void)
  5805. {
  5806. struct pool *cp = current_pool();
  5807. int i;
  5808. struct thr_info *thr;
  5809. /* Artificially set the lagging flag to avoid pool not providing work
  5810. * fast enough messages after every long poll */
  5811. pool_tset(cp, &cp->lagging);
  5812. /* Discard staged work that is now stale */
  5813. discard_stale();
  5814. rd_lock(&mining_thr_lock);
  5815. for (i = 0; i < mining_threads; i++)
  5816. {
  5817. thr = mining_thr[i];
  5818. thr->work_restart = true;
  5819. }
  5820. for (i = 0; i < mining_threads; i++)
  5821. {
  5822. thr = mining_thr[i];
  5823. notifier_wake(thr->work_restart_notifier);
  5824. }
  5825. rd_unlock(&mining_thr_lock);
  5826. }
  5827. static
  5828. void blkhashstr(char *rv, const unsigned char *hash)
  5829. {
  5830. unsigned char hash_swap[32];
  5831. swap256(hash_swap, hash);
  5832. swap32tole(hash_swap, hash_swap, 32 / 4);
  5833. bin2hex(rv, hash_swap, 32);
  5834. }
  5835. static void set_curblock(char *hexstr, unsigned char *hash)
  5836. {
  5837. unsigned char hash_swap[32];
  5838. current_block_id = ((uint32_t*)hash)[0];
  5839. strcpy(current_block, hexstr);
  5840. swap256(hash_swap, hash);
  5841. swap32tole(hash_swap, hash_swap, 32 / 4);
  5842. cg_wlock(&ch_lock);
  5843. block_time = time(NULL);
  5844. __update_block_title(hash_swap);
  5845. free(current_fullhash);
  5846. current_fullhash = malloc(65);
  5847. bin2hex(current_fullhash, hash_swap, 32);
  5848. get_timestamp(blocktime, sizeof(blocktime), block_time);
  5849. cg_wunlock(&ch_lock);
  5850. applog(LOG_INFO, "New block: %s diff %s (%s)", current_hash, block_diff, net_hashrate);
  5851. }
  5852. /* Search to see if this string is from a block that has been seen before */
  5853. static bool block_exists(char *hexstr)
  5854. {
  5855. struct block *s;
  5856. rd_lock(&blk_lock);
  5857. HASH_FIND_STR(blocks, hexstr, s);
  5858. rd_unlock(&blk_lock);
  5859. if (s)
  5860. return true;
  5861. return false;
  5862. }
  5863. #if 0
  5864. /* Tests if this work is from a block that has been seen before */
  5865. static inline bool from_existing_block(struct work *work)
  5866. {
  5867. char hexstr[37];
  5868. bool ret;
  5869. bin2hex(hexstr, work->data + 8, 18);
  5870. ret = block_exists(hexstr);
  5871. return ret;
  5872. }
  5873. #endif
  5874. static int block_sort(struct block *blocka, struct block *blockb)
  5875. {
  5876. return blocka->block_no - blockb->block_no;
  5877. }
  5878. static void set_blockdiff(const struct work *work)
  5879. {
  5880. unsigned char target[32];
  5881. double diff;
  5882. uint64_t diff64;
  5883. real_block_target(target, work->data);
  5884. diff = target_diff(target);
  5885. diff64 = diff;
  5886. suffix_string(diff64, block_diff, sizeof(block_diff), 0);
  5887. format_unit2(net_hashrate, sizeof(net_hashrate),
  5888. true, "h/s", H2B_SHORT, diff * 7158278, -1);
  5889. if (unlikely(current_diff != diff))
  5890. applog(LOG_NOTICE, "Network difficulty changed to %s (%s)", block_diff, net_hashrate);
  5891. current_diff = diff;
  5892. }
  5893. static bool test_work_current(struct work *work)
  5894. {
  5895. bool ret = true;
  5896. char hexstr[65];
  5897. if (work->mandatory)
  5898. return ret;
  5899. uint32_t block_id = ((uint32_t*)(work->data))[1];
  5900. /* Hack to work around dud work sneaking into test */
  5901. bin2hex(hexstr, work->data + 8, 18);
  5902. if (!strncmp(hexstr, "000000000000000000000000000000000000", 36))
  5903. goto out_free;
  5904. struct pool * const pool = work->pool;
  5905. /* Search to see if this block exists yet and if not, consider it a
  5906. * new block and set the current block details to this one */
  5907. if (!block_exists(hexstr))
  5908. {
  5909. struct block *s = calloc(sizeof(struct block), 1);
  5910. int deleted_block = 0;
  5911. ret = false;
  5912. if (unlikely(!s))
  5913. quit (1, "test_work_current OOM");
  5914. strcpy(s->hash, hexstr);
  5915. s->block_no = new_blocks++;
  5916. wr_lock(&blk_lock);
  5917. /* Only keep the last hour's worth of blocks in memory since
  5918. * work from blocks before this is virtually impossible and we
  5919. * want to prevent memory usage from continually rising */
  5920. if (HASH_COUNT(blocks) > 6)
  5921. {
  5922. struct block *oldblock;
  5923. HASH_SORT(blocks, block_sort);
  5924. oldblock = blocks;
  5925. deleted_block = oldblock->block_no;
  5926. HASH_DEL(blocks, oldblock);
  5927. free(oldblock);
  5928. }
  5929. HASH_ADD_STR(blocks, hash, s);
  5930. set_blockdiff(work);
  5931. wr_unlock(&blk_lock);
  5932. pool->block_id = block_id;
  5933. pool_update_work_restart_time(pool);
  5934. if (deleted_block)
  5935. applog(LOG_DEBUG, "Deleted block %d from database", deleted_block);
  5936. #if BLKMAKER_VERSION > 1
  5937. template_nonce = 0;
  5938. #endif
  5939. set_curblock(hexstr, &work->data[4]);
  5940. if (unlikely(new_blocks == 1))
  5941. goto out_free;
  5942. if (!work->stratum)
  5943. {
  5944. if (work->longpoll)
  5945. {
  5946. applog(LOG_NOTICE, "Longpoll from pool %d detected new block",
  5947. pool->pool_no);
  5948. }
  5949. else
  5950. if (have_longpoll)
  5951. applog(LOG_NOTICE, "New block detected on network before longpoll");
  5952. else
  5953. applog(LOG_NOTICE, "New block detected on network");
  5954. }
  5955. restart_threads();
  5956. }
  5957. else
  5958. {
  5959. bool restart = false;
  5960. if (unlikely(pool->block_id != block_id))
  5961. {
  5962. bool was_active = pool->block_id != 0;
  5963. pool->block_id = block_id;
  5964. pool_update_work_restart_time(pool);
  5965. if (!work->longpoll)
  5966. update_last_work(work);
  5967. if (was_active)
  5968. {
  5969. // Pool actively changed block
  5970. if (pool == current_pool())
  5971. restart = true;
  5972. if (block_id == current_block_id)
  5973. {
  5974. // Caught up, only announce if this pool is the one in use
  5975. if (restart)
  5976. applog(LOG_NOTICE, "%s %d caught up to new block",
  5977. work->longpoll ? "Longpoll from pool" : "Pool",
  5978. pool->pool_no);
  5979. }
  5980. else
  5981. {
  5982. // Switched to a block we know, but not the latest... why?
  5983. // This might detect pools trying to double-spend or 51%,
  5984. // but let's not make any accusations until it's had time
  5985. // in the real world.
  5986. blkhashstr(hexstr, &work->data[4]);
  5987. applog(LOG_WARNING, "%s %d is issuing work for an old block: %s",
  5988. work->longpoll ? "Longpoll from pool" : "Pool",
  5989. pool->pool_no,
  5990. hexstr);
  5991. }
  5992. }
  5993. }
  5994. if (work->longpoll)
  5995. {
  5996. struct pool * const cp = current_pool();
  5997. ++pool->work_restart_id;
  5998. if (work->tr && work->tr == pool->swork.tr)
  5999. pool->swork.work_restart_id = pool->work_restart_id;
  6000. update_last_work(work);
  6001. pool_update_work_restart_time(pool);
  6002. applog(
  6003. ((!opt_quiet_work_updates) && pool_actively_in_use(pool, cp) ? LOG_NOTICE : LOG_DEBUG),
  6004. "Longpoll from pool %d requested work update",
  6005. pool->pool_no);
  6006. if ((!restart) && pool == cp)
  6007. restart = true;
  6008. }
  6009. if (restart)
  6010. restart_threads();
  6011. }
  6012. work->longpoll = false;
  6013. out_free:
  6014. return ret;
  6015. }
  6016. static int tv_sort(struct work *worka, struct work *workb)
  6017. {
  6018. return worka->tv_staged.tv_sec - workb->tv_staged.tv_sec;
  6019. }
  6020. static bool work_rollable(struct work *work)
  6021. {
  6022. return (!work->clone && work->rolltime);
  6023. }
  6024. static bool hash_push(struct work *work)
  6025. {
  6026. bool rc = true;
  6027. mutex_lock(stgd_lock);
  6028. if (work_rollable(work))
  6029. staged_rollable++;
  6030. if (likely(!getq->frozen)) {
  6031. HASH_ADD_INT(staged_work, id, work);
  6032. HASH_SORT(staged_work, tv_sort);
  6033. } else
  6034. rc = false;
  6035. pthread_cond_broadcast(&getq->cond);
  6036. mutex_unlock(stgd_lock);
  6037. return rc;
  6038. }
  6039. static void stage_work(struct work *work)
  6040. {
  6041. applog(LOG_DEBUG, "Pushing work %d from pool %d to hash queue",
  6042. work->id, work->pool->pool_no);
  6043. work->work_restart_id = work->pool->work_restart_id;
  6044. work->pool->last_work_time = time(NULL);
  6045. cgtime(&work->pool->tv_last_work_time);
  6046. test_work_current(work);
  6047. work->pool->works++;
  6048. hash_push(work);
  6049. }
  6050. #ifdef HAVE_CURSES
  6051. int curses_int(const char *query)
  6052. {
  6053. int ret;
  6054. char *cvar;
  6055. cvar = curses_input(query);
  6056. if (unlikely(!cvar))
  6057. return -1;
  6058. ret = atoi(cvar);
  6059. free(cvar);
  6060. return ret;
  6061. }
  6062. #endif
  6063. #ifdef HAVE_CURSES
  6064. static bool input_pool(bool live);
  6065. #endif
  6066. #ifdef HAVE_CURSES
  6067. static void display_pool_summary(struct pool *pool)
  6068. {
  6069. double efficiency = 0.0;
  6070. char xfer[ALLOC_H2B_NOUNIT+ALLOC_H2B_SPACED+4+1], bw[ALLOC_H2B_NOUNIT+ALLOC_H2B_SPACED+6+1];
  6071. int pool_secs;
  6072. if (curses_active_locked()) {
  6073. wlog("Pool: %s\n", pool->rpc_url);
  6074. if (pool->solved)
  6075. wlog("SOLVED %d BLOCK%s!\n", pool->solved, pool->solved > 1 ? "S" : "");
  6076. if (!pool->has_stratum)
  6077. wlog("%s own long-poll support\n", pool->lp_url ? "Has" : "Does not have");
  6078. wlog(" Queued work requests: %d\n", pool->getwork_requested);
  6079. wlog(" Share submissions: %d\n", pool->accepted + pool->rejected);
  6080. wlog(" Accepted shares: %d\n", pool->accepted);
  6081. wlog(" Rejected shares: %d + %d stale (%.2f%%)\n",
  6082. pool->rejected, pool->stale_shares,
  6083. (float)(pool->rejected + pool->stale_shares) / (float)(pool->rejected + pool->stale_shares + pool->accepted)
  6084. );
  6085. wlog(" Accepted difficulty shares: %1.f\n", pool->diff_accepted);
  6086. wlog(" Rejected difficulty shares: %1.f\n", pool->diff_rejected);
  6087. pool_secs = timer_elapsed(&pool->cgminer_stats.start_tv, NULL);
  6088. wlog(" Network transfer: %s (%s)\n",
  6089. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  6090. (float)pool->cgminer_pool_stats.net_bytes_received,
  6091. (float)pool->cgminer_pool_stats.net_bytes_sent),
  6092. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  6093. (float)(pool->cgminer_pool_stats.net_bytes_received / pool_secs),
  6094. (float)(pool->cgminer_pool_stats.net_bytes_sent / pool_secs)));
  6095. uint64_t pool_bytes_xfer = pool->cgminer_pool_stats.net_bytes_received + pool->cgminer_pool_stats.net_bytes_sent;
  6096. efficiency = pool_bytes_xfer ? pool->diff_accepted * 2048. / pool_bytes_xfer : 0.0;
  6097. wlog(" Efficiency (accepted * difficulty / 2 KB): %.2f\n", efficiency);
  6098. wlog(" Items worked on: %d\n", pool->works);
  6099. wlog(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  6100. wlog(" Unable to get work from server occasions: %d\n", pool->getfail_occasions);
  6101. wlog(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  6102. unlock_curses();
  6103. }
  6104. }
  6105. #endif
  6106. /* We can't remove the memory used for this struct pool because there may
  6107. * still be work referencing it. We just remove it from the pools list */
  6108. void remove_pool(struct pool *pool)
  6109. {
  6110. int i, last_pool = total_pools - 1;
  6111. struct pool *other;
  6112. disable_pool(pool, POOL_DISABLED);
  6113. /* Boost priority of any lower prio than this one */
  6114. for (i = 0; i < total_pools; i++) {
  6115. other = pools[i];
  6116. if (other->prio > pool->prio)
  6117. other->prio--;
  6118. }
  6119. if (pool->pool_no < last_pool) {
  6120. /* Swap the last pool for this one */
  6121. (pools[last_pool])->pool_no = pool->pool_no;
  6122. pools[pool->pool_no] = pools[last_pool];
  6123. }
  6124. /* Give it an invalid number */
  6125. pool->pool_no = total_pools;
  6126. pool->removed = true;
  6127. pool->has_stratum = false;
  6128. total_pools--;
  6129. }
  6130. /* add a mutex if this needs to be thread safe in the future */
  6131. static struct JE {
  6132. char *buf;
  6133. struct JE *next;
  6134. } *jedata = NULL;
  6135. static void json_escape_free()
  6136. {
  6137. struct JE *jeptr = jedata;
  6138. struct JE *jenext;
  6139. jedata = NULL;
  6140. while (jeptr) {
  6141. jenext = jeptr->next;
  6142. free(jeptr->buf);
  6143. free(jeptr);
  6144. jeptr = jenext;
  6145. }
  6146. }
  6147. static
  6148. char *json_escape(const char *str)
  6149. {
  6150. struct JE *jeptr;
  6151. char *buf, *ptr;
  6152. /* 2x is the max, may as well just allocate that */
  6153. ptr = buf = malloc(strlen(str) * 2 + 1);
  6154. jeptr = malloc(sizeof(*jeptr));
  6155. jeptr->buf = buf;
  6156. jeptr->next = jedata;
  6157. jedata = jeptr;
  6158. while (*str) {
  6159. if (*str == '\\' || *str == '"')
  6160. *(ptr++) = '\\';
  6161. *(ptr++) = *(str++);
  6162. }
  6163. *ptr = '\0';
  6164. return buf;
  6165. }
  6166. static
  6167. void _write_config_string_elist(FILE *fcfg, const char *configname, struct string_elist * const elist)
  6168. {
  6169. if (!elist)
  6170. return;
  6171. static struct string_elist *entry;
  6172. fprintf(fcfg, ",\n\"%s\" : [", configname);
  6173. bool first = true;
  6174. DL_FOREACH(elist, entry)
  6175. {
  6176. const char * const s = entry->string;
  6177. fprintf(fcfg, "%s\n\t\"%s\"", first ? "" : ",", json_escape(s));
  6178. first = false;
  6179. }
  6180. fprintf(fcfg, "\n]");
  6181. }
  6182. void write_config(FILE *fcfg)
  6183. {
  6184. int i;
  6185. /* Write pool values */
  6186. fputs("{\n\"pools\" : [", fcfg);
  6187. for(i = 0; i < total_pools; i++) {
  6188. struct pool *pool = pools[i];
  6189. if (pool->failover_only)
  6190. // Don't write failover-only (automatically added) pools to the config file for now
  6191. continue;
  6192. if (pool->quota != 1) {
  6193. fprintf(fcfg, "%s\n\t{\n\t\t\"quota\" : \"%d;%s\",", i > 0 ? "," : "",
  6194. pool->quota,
  6195. json_escape(pool->rpc_url));
  6196. } else {
  6197. fprintf(fcfg, "%s\n\t{\n\t\t\"url\" : \"%s\",", i > 0 ? "," : "",
  6198. json_escape(pool->rpc_url));
  6199. }
  6200. if (pool->rpc_proxy)
  6201. fprintf(fcfg, "\n\t\t\"pool-proxy\" : \"%s\",", json_escape(pool->rpc_proxy));
  6202. fprintf(fcfg, "\n\t\t\"user\" : \"%s\",", json_escape(pool->rpc_user));
  6203. fprintf(fcfg, "\n\t\t\"pass\" : \"%s\",", json_escape(pool->rpc_pass));
  6204. fprintf(fcfg, "\n\t\t\"pool-priority\" : \"%d\"", pool->prio);
  6205. if (pool->force_rollntime)
  6206. fprintf(fcfg, ",\n\t\t\"force-rollntime\" : %d", pool->force_rollntime);
  6207. fprintf(fcfg, "\n\t}");
  6208. }
  6209. fputs("\n]\n", fcfg);
  6210. #ifdef HAVE_OPENCL
  6211. write_config_opencl(fcfg);
  6212. #endif
  6213. #ifdef WANT_CPUMINE
  6214. fprintf(fcfg, ",\n\"algo\" : \"%s\"", algo_names[opt_algo]);
  6215. #endif
  6216. /* Simple bool and int options */
  6217. struct opt_table *opt;
  6218. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  6219. char *p, *name = strdup(opt->names);
  6220. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  6221. if (p[1] != '-')
  6222. continue;
  6223. if (opt->type & OPT_NOARG &&
  6224. ((void *)opt->cb == (void *)opt_set_bool || (void *)opt->cb == (void *)opt_set_invbool) &&
  6225. (*(bool *)opt->u.arg == ((void *)opt->cb == (void *)opt_set_bool)))
  6226. fprintf(fcfg, ",\n\"%s\" : true", p+2);
  6227. if (opt->type & OPT_HASARG &&
  6228. ((void *)opt->cb_arg == (void *)set_int_0_to_9999 ||
  6229. (void *)opt->cb_arg == (void *)set_int_1_to_65535 ||
  6230. (void *)opt->cb_arg == (void *)set_int_0_to_10 ||
  6231. (void *)opt->cb_arg == (void *)set_int_1_to_10) &&
  6232. opt->desc != opt_hidden &&
  6233. 0 <= *(int *)opt->u.arg)
  6234. fprintf(fcfg, ",\n\"%s\" : \"%d\"", p+2, *(int *)opt->u.arg);
  6235. }
  6236. }
  6237. /* Special case options */
  6238. if (request_target_str)
  6239. {
  6240. if (request_pdiff == (long)request_pdiff)
  6241. fprintf(fcfg, ",\n\"request-diff\" : %ld", (long)request_pdiff);
  6242. else
  6243. fprintf(fcfg, ",\n\"request-diff\" : %f", request_pdiff);
  6244. }
  6245. fprintf(fcfg, ",\n\"shares\" : %g", opt_shares);
  6246. if (pool_strategy == POOL_BALANCE)
  6247. fputs(",\n\"balance\" : true", fcfg);
  6248. if (pool_strategy == POOL_LOADBALANCE)
  6249. fputs(",\n\"load-balance\" : true", fcfg);
  6250. if (pool_strategy == POOL_ROUNDROBIN)
  6251. fputs(",\n\"round-robin\" : true", fcfg);
  6252. if (pool_strategy == POOL_ROTATE)
  6253. fprintf(fcfg, ",\n\"rotate\" : \"%d\"", opt_rotate_period);
  6254. #if defined(unix) || defined(__APPLE__)
  6255. if (opt_stderr_cmd && *opt_stderr_cmd)
  6256. fprintf(fcfg, ",\n\"monitor\" : \"%s\"", json_escape(opt_stderr_cmd));
  6257. #endif // defined(unix)
  6258. if (opt_kernel_path && *opt_kernel_path) {
  6259. char *kpath = strdup(opt_kernel_path);
  6260. if (kpath[strlen(kpath)-1] == '/')
  6261. kpath[strlen(kpath)-1] = 0;
  6262. fprintf(fcfg, ",\n\"kernel-path\" : \"%s\"", json_escape(kpath));
  6263. free(kpath);
  6264. }
  6265. if (schedstart.enable)
  6266. fprintf(fcfg, ",\n\"sched-time\" : \"%d:%d\"", schedstart.tm.tm_hour, schedstart.tm.tm_min);
  6267. if (schedstop.enable)
  6268. fprintf(fcfg, ",\n\"stop-time\" : \"%d:%d\"", schedstop.tm.tm_hour, schedstop.tm.tm_min);
  6269. if (opt_socks_proxy && *opt_socks_proxy)
  6270. fprintf(fcfg, ",\n\"socks-proxy\" : \"%s\"", json_escape(opt_socks_proxy));
  6271. _write_config_string_elist(fcfg, "scan", scan_devices);
  6272. #ifdef USE_LIBMICROHTTPD
  6273. if (httpsrv_port != -1)
  6274. fprintf(fcfg, ",\n\"http-port\" : %d", httpsrv_port);
  6275. #endif
  6276. #ifdef USE_LIBEVENT
  6277. if (stratumsrv_port != -1)
  6278. fprintf(fcfg, ",\n\"stratum-port\" : %d", stratumsrv_port);
  6279. #endif
  6280. _write_config_string_elist(fcfg, "device", opt_devices_enabled_list);
  6281. _write_config_string_elist(fcfg, "set-device", opt_set_device_list);
  6282. if (opt_api_allow)
  6283. fprintf(fcfg, ",\n\"api-allow\" : \"%s\"", json_escape(opt_api_allow));
  6284. if (strcmp(opt_api_mcast_addr, API_MCAST_ADDR) != 0)
  6285. fprintf(fcfg, ",\n\"api-mcast-addr\" : \"%s\"", json_escape(opt_api_mcast_addr));
  6286. if (strcmp(opt_api_mcast_code, API_MCAST_CODE) != 0)
  6287. fprintf(fcfg, ",\n\"api-mcast-code\" : \"%s\"", json_escape(opt_api_mcast_code));
  6288. if (*opt_api_mcast_des)
  6289. fprintf(fcfg, ",\n\"api-mcast-des\" : \"%s\"", json_escape(opt_api_mcast_des));
  6290. if (strcmp(opt_api_description, PACKAGE_STRING) != 0)
  6291. fprintf(fcfg, ",\n\"api-description\" : \"%s\"", json_escape(opt_api_description));
  6292. if (opt_api_groups)
  6293. fprintf(fcfg, ",\n\"api-groups\" : \"%s\"", json_escape(opt_api_groups));
  6294. fputs("\n}\n", fcfg);
  6295. json_escape_free();
  6296. }
  6297. void zero_bestshare(void)
  6298. {
  6299. int i;
  6300. best_diff = 0;
  6301. suffix_string(best_diff, best_share, sizeof(best_share), 0);
  6302. for (i = 0; i < total_pools; i++) {
  6303. struct pool *pool = pools[i];
  6304. pool->best_diff = 0;
  6305. }
  6306. }
  6307. void zero_stats(void)
  6308. {
  6309. int i;
  6310. applog(LOG_DEBUG, "Zeroing stats");
  6311. cgtime(&total_tv_start);
  6312. miner_started = total_tv_start;
  6313. total_rolling = 0;
  6314. total_mhashes_done = 0;
  6315. total_getworks = 0;
  6316. total_accepted = 0;
  6317. total_rejected = 0;
  6318. hw_errors = 0;
  6319. total_stale = 0;
  6320. total_discarded = 0;
  6321. total_bytes_rcvd = total_bytes_sent = 0;
  6322. new_blocks = 0;
  6323. local_work = 0;
  6324. total_go = 0;
  6325. total_ro = 0;
  6326. total_secs = 1.0;
  6327. total_diff1 = 0;
  6328. total_bad_diff1 = 0;
  6329. found_blocks = 0;
  6330. total_diff_accepted = 0;
  6331. total_diff_rejected = 0;
  6332. total_diff_stale = 0;
  6333. #ifdef HAVE_CURSES
  6334. awidth = rwidth = swidth = hwwidth = 1;
  6335. #endif
  6336. for (i = 0; i < total_pools; i++) {
  6337. struct pool *pool = pools[i];
  6338. pool->getwork_requested = 0;
  6339. pool->accepted = 0;
  6340. pool->rejected = 0;
  6341. pool->solved = 0;
  6342. pool->getwork_requested = 0;
  6343. pool->stale_shares = 0;
  6344. pool->discarded_work = 0;
  6345. pool->getfail_occasions = 0;
  6346. pool->remotefail_occasions = 0;
  6347. pool->last_share_time = 0;
  6348. pool->works = 0;
  6349. pool->diff1 = 0;
  6350. pool->diff_accepted = 0;
  6351. pool->diff_rejected = 0;
  6352. pool->diff_stale = 0;
  6353. pool->last_share_diff = 0;
  6354. pool->cgminer_stats.start_tv = total_tv_start;
  6355. pool->cgminer_stats.getwork_calls = 0;
  6356. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6357. pool->cgminer_stats.getwork_wait_max.tv_sec = 0;
  6358. pool->cgminer_stats.getwork_wait_max.tv_usec = 0;
  6359. pool->cgminer_pool_stats.getwork_calls = 0;
  6360. pool->cgminer_pool_stats.getwork_attempts = 0;
  6361. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6362. pool->cgminer_pool_stats.getwork_wait_max.tv_sec = 0;
  6363. pool->cgminer_pool_stats.getwork_wait_max.tv_usec = 0;
  6364. pool->cgminer_pool_stats.min_diff = 0;
  6365. pool->cgminer_pool_stats.max_diff = 0;
  6366. pool->cgminer_pool_stats.min_diff_count = 0;
  6367. pool->cgminer_pool_stats.max_diff_count = 0;
  6368. pool->cgminer_pool_stats.times_sent = 0;
  6369. pool->cgminer_pool_stats.bytes_sent = 0;
  6370. pool->cgminer_pool_stats.net_bytes_sent = 0;
  6371. pool->cgminer_pool_stats.times_received = 0;
  6372. pool->cgminer_pool_stats.bytes_received = 0;
  6373. pool->cgminer_pool_stats.net_bytes_received = 0;
  6374. }
  6375. zero_bestshare();
  6376. for (i = 0; i < total_devices; ++i) {
  6377. struct cgpu_info *cgpu = get_devices(i);
  6378. mutex_lock(&hash_lock);
  6379. cgpu->total_mhashes = 0;
  6380. cgpu->accepted = 0;
  6381. cgpu->rejected = 0;
  6382. cgpu->stale = 0;
  6383. cgpu->hw_errors = 0;
  6384. cgpu->utility = 0.0;
  6385. cgpu->utility_diff1 = 0;
  6386. cgpu->last_share_pool_time = 0;
  6387. cgpu->bad_diff1 = 0;
  6388. cgpu->diff1 = 0;
  6389. cgpu->diff_accepted = 0;
  6390. cgpu->diff_rejected = 0;
  6391. cgpu->diff_stale = 0;
  6392. cgpu->last_share_diff = 0;
  6393. cgpu->thread_fail_init_count = 0;
  6394. cgpu->thread_zero_hash_count = 0;
  6395. cgpu->thread_fail_queue_count = 0;
  6396. cgpu->dev_sick_idle_60_count = 0;
  6397. cgpu->dev_dead_idle_600_count = 0;
  6398. cgpu->dev_nostart_count = 0;
  6399. cgpu->dev_over_heat_count = 0;
  6400. cgpu->dev_thermal_cutoff_count = 0;
  6401. cgpu->dev_comms_error_count = 0;
  6402. cgpu->dev_throttle_count = 0;
  6403. cgpu->cgminer_stats.start_tv = total_tv_start;
  6404. cgpu->cgminer_stats.getwork_calls = 0;
  6405. cgpu->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6406. cgpu->cgminer_stats.getwork_wait_max.tv_sec = 0;
  6407. cgpu->cgminer_stats.getwork_wait_max.tv_usec = 0;
  6408. mutex_unlock(&hash_lock);
  6409. if (cgpu->drv->zero_stats)
  6410. cgpu->drv->zero_stats(cgpu);
  6411. }
  6412. }
  6413. #ifdef HAVE_CURSES
  6414. static
  6415. void loginput_mode(const int size)
  6416. {
  6417. clear_logwin();
  6418. loginput_size = size;
  6419. check_winsizes();
  6420. }
  6421. static void display_pools(void)
  6422. {
  6423. struct pool *pool;
  6424. int selected, i, j;
  6425. char input;
  6426. loginput_mode(7 + total_pools);
  6427. immedok(logwin, true);
  6428. updated:
  6429. for (j = 0; j < total_pools; j++) {
  6430. for (i = 0; i < total_pools; i++) {
  6431. pool = pools[i];
  6432. if (pool->prio != j)
  6433. continue;
  6434. if (pool == current_pool())
  6435. wattron(logwin, A_BOLD);
  6436. if (pool->enabled != POOL_ENABLED || pool->failover_only)
  6437. wattron(logwin, A_DIM);
  6438. wlogprint("%d: ", pool->prio);
  6439. switch (pool->enabled) {
  6440. case POOL_ENABLED:
  6441. if (pool->failover_only)
  6442. wlogprint("Failover ");
  6443. else
  6444. wlogprint("Enabled ");
  6445. break;
  6446. case POOL_DISABLED:
  6447. wlogprint("Disabled ");
  6448. break;
  6449. case POOL_REJECTING:
  6450. wlogprint("Rejectin ");
  6451. break;
  6452. }
  6453. _wlogprint(pool_proto_str(pool));
  6454. wlogprint(" Quota %d Pool %d: %s User:%s\n",
  6455. pool->quota,
  6456. pool->pool_no,
  6457. pool->rpc_url, pool->rpc_user);
  6458. wattroff(logwin, A_BOLD | A_DIM);
  6459. break; //for (i = 0; i < total_pools; i++)
  6460. }
  6461. }
  6462. retry:
  6463. wlogprint("\nCurrent pool management strategy: %s\n",
  6464. strategies[pool_strategy].s);
  6465. if (pool_strategy == POOL_ROTATE)
  6466. wlogprint("Set to rotate every %d minutes\n", opt_rotate_period);
  6467. wlogprint("[F]ailover only %s\n", opt_fail_only ? "enabled" : "disabled");
  6468. wlogprint("Pool [A]dd [R]emove [D]isable [E]nable [P]rioritize [Q]uota change\n");
  6469. wlogprint("[C]hange management strategy [S]witch pool [I]nformation\n");
  6470. wlogprint("Or press any other key to continue\n");
  6471. logwin_update();
  6472. input = getch();
  6473. if (!strncasecmp(&input, "a", 1)) {
  6474. if (opt_benchmark)
  6475. {
  6476. wlogprint("Cannot add pools in benchmark mode");
  6477. goto retry;
  6478. }
  6479. input_pool(true);
  6480. goto updated;
  6481. } else if (!strncasecmp(&input, "r", 1)) {
  6482. if (total_pools <= 1) {
  6483. wlogprint("Cannot remove last pool");
  6484. goto retry;
  6485. }
  6486. selected = curses_int("Select pool number");
  6487. if (selected < 0 || selected >= total_pools) {
  6488. wlogprint("Invalid selection\n");
  6489. goto retry;
  6490. }
  6491. pool = pools[selected];
  6492. if (pool == current_pool())
  6493. switch_pools(NULL);
  6494. if (pool == current_pool()) {
  6495. wlogprint("Unable to remove pool due to activity\n");
  6496. goto retry;
  6497. }
  6498. remove_pool(pool);
  6499. goto updated;
  6500. } else if (!strncasecmp(&input, "s", 1)) {
  6501. selected = curses_int("Select pool number");
  6502. if (selected < 0 || selected >= total_pools) {
  6503. wlogprint("Invalid selection\n");
  6504. goto retry;
  6505. }
  6506. pool = pools[selected];
  6507. pool->failover_only = false;
  6508. switch_pools(pool);
  6509. goto updated;
  6510. } else if (!strncasecmp(&input, "d", 1)) {
  6511. if (enabled_pools <= 1) {
  6512. wlogprint("Cannot disable last pool");
  6513. goto retry;
  6514. }
  6515. selected = curses_int("Select pool number");
  6516. if (selected < 0 || selected >= total_pools) {
  6517. wlogprint("Invalid selection\n");
  6518. goto retry;
  6519. }
  6520. pool = pools[selected];
  6521. disable_pool(pool, POOL_DISABLED);
  6522. goto updated;
  6523. } else if (!strncasecmp(&input, "e", 1)) {
  6524. selected = curses_int("Select pool number");
  6525. if (selected < 0 || selected >= total_pools) {
  6526. wlogprint("Invalid selection\n");
  6527. goto retry;
  6528. }
  6529. pool = pools[selected];
  6530. pool->failover_only = false;
  6531. enable_pool(pool);
  6532. goto updated;
  6533. } else if (!strncasecmp(&input, "c", 1)) {
  6534. for (i = 0; i <= TOP_STRATEGY; i++)
  6535. wlogprint("%d: %s\n", i, strategies[i].s);
  6536. selected = curses_int("Select strategy number type");
  6537. if (selected < 0 || selected > TOP_STRATEGY) {
  6538. wlogprint("Invalid selection\n");
  6539. goto retry;
  6540. }
  6541. if (selected == POOL_ROTATE) {
  6542. opt_rotate_period = curses_int("Select interval in minutes");
  6543. if (opt_rotate_period < 0 || opt_rotate_period > 9999) {
  6544. opt_rotate_period = 0;
  6545. wlogprint("Invalid selection\n");
  6546. goto retry;
  6547. }
  6548. }
  6549. mutex_lock(&lp_lock);
  6550. pool_strategy = selected;
  6551. pthread_cond_broadcast(&lp_cond);
  6552. mutex_unlock(&lp_lock);
  6553. switch_pools(NULL);
  6554. goto updated;
  6555. } else if (!strncasecmp(&input, "i", 1)) {
  6556. selected = curses_int("Select pool number");
  6557. if (selected < 0 || selected >= total_pools) {
  6558. wlogprint("Invalid selection\n");
  6559. goto retry;
  6560. }
  6561. pool = pools[selected];
  6562. display_pool_summary(pool);
  6563. goto retry;
  6564. } else if (!strncasecmp(&input, "q", 1)) {
  6565. selected = curses_int("Select pool number");
  6566. if (selected < 0 || selected >= total_pools) {
  6567. wlogprint("Invalid selection\n");
  6568. goto retry;
  6569. }
  6570. pool = pools[selected];
  6571. selected = curses_int("Set quota");
  6572. if (selected < 0) {
  6573. wlogprint("Invalid negative quota\n");
  6574. goto retry;
  6575. }
  6576. pool->quota = selected;
  6577. adjust_quota_gcd();
  6578. goto updated;
  6579. } else if (!strncasecmp(&input, "f", 1)) {
  6580. opt_fail_only ^= true;
  6581. goto updated;
  6582. } else if (!strncasecmp(&input, "p", 1)) {
  6583. char *prilist = curses_input("Enter new pool priority (comma separated list)");
  6584. if (!prilist)
  6585. {
  6586. wlogprint("Not changing priorities\n");
  6587. goto retry;
  6588. }
  6589. int res = prioritize_pools(prilist, &i);
  6590. free(prilist);
  6591. switch (res) {
  6592. case MSG_NOPOOL:
  6593. wlogprint("No pools\n");
  6594. goto retry;
  6595. case MSG_MISPID:
  6596. wlogprint("Missing pool id parameter\n");
  6597. goto retry;
  6598. case MSG_INVPID:
  6599. wlogprint("Invalid pool id %d - range is 0 - %d\n", i, total_pools - 1);
  6600. goto retry;
  6601. case MSG_DUPPID:
  6602. wlogprint("Duplicate pool specified %d\n", i);
  6603. goto retry;
  6604. case MSG_POOLPRIO:
  6605. default:
  6606. goto updated;
  6607. }
  6608. }
  6609. immedok(logwin, false);
  6610. loginput_mode(0);
  6611. }
  6612. static const char *summary_detail_level_str(void)
  6613. {
  6614. if (opt_compact)
  6615. return "compact";
  6616. if (opt_show_procs)
  6617. return "processors";
  6618. return "devices";
  6619. }
  6620. static void display_options(void)
  6621. {
  6622. int selected;
  6623. char input;
  6624. immedok(logwin, true);
  6625. loginput_mode(12);
  6626. retry:
  6627. clear_logwin();
  6628. wlogprint("[N]ormal [C]lear [S]ilent mode (disable all output)\n");
  6629. wlogprint("[D]ebug:%s\n[P]er-device:%s\n[Q]uiet:%s\n[V]erbose:%s\n"
  6630. "[R]PC debug:%s\n[W]orkTime details:%s\nsu[M]mary detail level:%s\n"
  6631. "[L]og interval:%d\nS[T]atistical counts: %s\n[Z]ero statistics\n",
  6632. opt_debug_console ? "on" : "off",
  6633. want_per_device_stats? "on" : "off",
  6634. opt_quiet ? "on" : "off",
  6635. opt_log_output ? "on" : "off",
  6636. opt_protocol ? "on" : "off",
  6637. opt_worktime ? "on" : "off",
  6638. summary_detail_level_str(),
  6639. opt_log_interval,
  6640. opt_weighed_stats ? "weighed" : "absolute");
  6641. wlogprint("Select an option or any other key to return\n");
  6642. logwin_update();
  6643. input = getch();
  6644. if (!strncasecmp(&input, "q", 1)) {
  6645. opt_quiet ^= true;
  6646. wlogprint("Quiet mode %s\n", opt_quiet ? "enabled" : "disabled");
  6647. goto retry;
  6648. } else if (!strncasecmp(&input, "v", 1)) {
  6649. opt_log_output ^= true;
  6650. if (opt_log_output)
  6651. opt_quiet = false;
  6652. wlogprint("Verbose mode %s\n", opt_log_output ? "enabled" : "disabled");
  6653. goto retry;
  6654. } else if (!strncasecmp(&input, "n", 1)) {
  6655. opt_log_output = false;
  6656. opt_debug_console = false;
  6657. opt_quiet = false;
  6658. opt_protocol = false;
  6659. opt_compact = false;
  6660. opt_show_procs = false;
  6661. devsummaryYOffset = 0;
  6662. want_per_device_stats = false;
  6663. wlogprint("Output mode reset to normal\n");
  6664. switch_logsize();
  6665. goto retry;
  6666. } else if (!strncasecmp(&input, "d", 1)) {
  6667. opt_debug = true;
  6668. opt_debug_console ^= true;
  6669. opt_log_output = opt_debug_console;
  6670. if (opt_debug_console)
  6671. opt_quiet = false;
  6672. wlogprint("Debug mode %s\n", opt_debug_console ? "enabled" : "disabled");
  6673. goto retry;
  6674. } else if (!strncasecmp(&input, "m", 1)) {
  6675. if (opt_compact)
  6676. opt_compact = false;
  6677. else
  6678. if (!opt_show_procs)
  6679. opt_show_procs = true;
  6680. else
  6681. {
  6682. opt_compact = true;
  6683. opt_show_procs = false;
  6684. devsummaryYOffset = 0;
  6685. }
  6686. wlogprint("su[M]mary detail level changed to: %s\n", summary_detail_level_str());
  6687. switch_logsize();
  6688. goto retry;
  6689. } else if (!strncasecmp(&input, "p", 1)) {
  6690. want_per_device_stats ^= true;
  6691. opt_log_output = want_per_device_stats;
  6692. wlogprint("Per-device stats %s\n", want_per_device_stats ? "enabled" : "disabled");
  6693. goto retry;
  6694. } else if (!strncasecmp(&input, "r", 1)) {
  6695. opt_protocol ^= true;
  6696. if (opt_protocol)
  6697. opt_quiet = false;
  6698. wlogprint("RPC protocol debugging %s\n", opt_protocol ? "enabled" : "disabled");
  6699. goto retry;
  6700. } else if (!strncasecmp(&input, "c", 1))
  6701. clear_logwin();
  6702. else if (!strncasecmp(&input, "l", 1)) {
  6703. selected = curses_int("Interval in seconds");
  6704. if (selected < 0 || selected > 9999) {
  6705. wlogprint("Invalid selection\n");
  6706. goto retry;
  6707. }
  6708. opt_log_interval = selected;
  6709. wlogprint("Log interval set to %d seconds\n", opt_log_interval);
  6710. goto retry;
  6711. } else if (!strncasecmp(&input, "s", 1)) {
  6712. opt_realquiet = true;
  6713. } else if (!strncasecmp(&input, "w", 1)) {
  6714. opt_worktime ^= true;
  6715. wlogprint("WorkTime details %s\n", opt_worktime ? "enabled" : "disabled");
  6716. goto retry;
  6717. } else if (!strncasecmp(&input, "t", 1)) {
  6718. opt_weighed_stats ^= true;
  6719. wlogprint("Now displaying %s statistics\n", opt_weighed_stats ? "weighed" : "absolute");
  6720. goto retry;
  6721. } else if (!strncasecmp(&input, "z", 1)) {
  6722. zero_stats();
  6723. goto retry;
  6724. }
  6725. immedok(logwin, false);
  6726. loginput_mode(0);
  6727. }
  6728. #endif
  6729. void default_save_file(char *filename)
  6730. {
  6731. #if defined(unix) || defined(__APPLE__)
  6732. if (getenv("HOME") && *getenv("HOME")) {
  6733. strcpy(filename, getenv("HOME"));
  6734. strcat(filename, "/");
  6735. }
  6736. else
  6737. strcpy(filename, "");
  6738. strcat(filename, ".bfgminer/");
  6739. mkdir(filename, 0777);
  6740. #else
  6741. strcpy(filename, "");
  6742. #endif
  6743. strcat(filename, def_conf);
  6744. }
  6745. #ifdef HAVE_CURSES
  6746. static void set_options(void)
  6747. {
  6748. int selected;
  6749. char input;
  6750. immedok(logwin, true);
  6751. loginput_mode(8);
  6752. retry:
  6753. wlogprint("\n[L]ongpoll: %s\n", want_longpoll ? "On" : "Off");
  6754. wlogprint("[Q]ueue: %d\n[S]cantime: %d\n[E]xpiry: %d\n[R]etries: %d\n"
  6755. "[W]rite config file\n[B]FGMiner restart\n",
  6756. opt_queue, opt_scantime, opt_expiry, opt_retries);
  6757. wlogprint("Select an option or any other key to return\n");
  6758. logwin_update();
  6759. input = getch();
  6760. if (!strncasecmp(&input, "q", 1)) {
  6761. selected = curses_int("Extra work items to queue");
  6762. if (selected < 0 || selected > 9999) {
  6763. wlogprint("Invalid selection\n");
  6764. goto retry;
  6765. }
  6766. opt_queue = selected;
  6767. goto retry;
  6768. } else if (!strncasecmp(&input, "l", 1)) {
  6769. if (want_longpoll)
  6770. stop_longpoll();
  6771. else
  6772. start_longpoll();
  6773. applog(LOG_WARNING, "Longpoll %s", want_longpoll ? "enabled" : "disabled");
  6774. goto retry;
  6775. } else if (!strncasecmp(&input, "s", 1)) {
  6776. selected = curses_int("Set scantime in seconds");
  6777. if (selected < 0 || selected > 9999) {
  6778. wlogprint("Invalid selection\n");
  6779. goto retry;
  6780. }
  6781. opt_scantime = selected;
  6782. goto retry;
  6783. } else if (!strncasecmp(&input, "e", 1)) {
  6784. selected = curses_int("Set expiry time in seconds");
  6785. if (selected < 0 || selected > 9999) {
  6786. wlogprint("Invalid selection\n");
  6787. goto retry;
  6788. }
  6789. opt_expiry = selected;
  6790. goto retry;
  6791. } else if (!strncasecmp(&input, "r", 1)) {
  6792. selected = curses_int("Retries before failing (-1 infinite)");
  6793. if (selected < -1 || selected > 9999) {
  6794. wlogprint("Invalid selection\n");
  6795. goto retry;
  6796. }
  6797. opt_retries = selected;
  6798. goto retry;
  6799. } else if (!strncasecmp(&input, "w", 1)) {
  6800. FILE *fcfg;
  6801. char *str, filename[PATH_MAX], prompt[PATH_MAX + 50];
  6802. default_save_file(filename);
  6803. snprintf(prompt, sizeof(prompt), "Config filename to write (Enter for default) [%s]", filename);
  6804. str = curses_input(prompt);
  6805. if (str) {
  6806. struct stat statbuf;
  6807. strcpy(filename, str);
  6808. free(str);
  6809. if (!stat(filename, &statbuf)) {
  6810. wlogprint("File exists, overwrite?\n");
  6811. input = getch();
  6812. if (strncasecmp(&input, "y", 1))
  6813. goto retry;
  6814. }
  6815. }
  6816. fcfg = fopen(filename, "w");
  6817. if (!fcfg) {
  6818. wlogprint("Cannot open or create file\n");
  6819. goto retry;
  6820. }
  6821. write_config(fcfg);
  6822. fclose(fcfg);
  6823. goto retry;
  6824. } else if (!strncasecmp(&input, "b", 1)) {
  6825. wlogprint("Are you sure?\n");
  6826. input = getch();
  6827. if (!strncasecmp(&input, "y", 1))
  6828. app_restart();
  6829. else
  6830. clear_logwin();
  6831. } else
  6832. clear_logwin();
  6833. loginput_mode(0);
  6834. immedok(logwin, false);
  6835. }
  6836. int scan_serial(const char *);
  6837. static
  6838. void _managetui_msg(const char *repr, const char **msg)
  6839. {
  6840. if (*msg)
  6841. {
  6842. applog(LOG_DEBUG, "ManageTUI: %"PRIpreprv": %s", repr, *msg);
  6843. wattron(logwin, A_BOLD);
  6844. wlogprint("%s", *msg);
  6845. wattroff(logwin, A_BOLD);
  6846. *msg = NULL;
  6847. }
  6848. logwin_update();
  6849. }
  6850. void manage_device(void)
  6851. {
  6852. char logline[256];
  6853. const char *msg = NULL;
  6854. struct cgpu_info *cgpu;
  6855. const struct device_drv *drv;
  6856. selecting_device = true;
  6857. immedok(logwin, true);
  6858. loginput_mode(12);
  6859. devchange:
  6860. if (unlikely(!total_devices))
  6861. {
  6862. clear_logwin();
  6863. wlogprint("(no devices)\n");
  6864. wlogprint("[Plus] Add device(s) [Enter] Close device manager\n");
  6865. _managetui_msg("(none)", &msg);
  6866. int input = getch();
  6867. switch (input)
  6868. {
  6869. case '+': case '=': // add new device
  6870. goto addnew;
  6871. default:
  6872. goto out;
  6873. }
  6874. }
  6875. cgpu = devices[selected_device];
  6876. drv = cgpu->drv;
  6877. refresh_devstatus();
  6878. refresh:
  6879. clear_logwin();
  6880. wlogprint("Select processor to manage using up/down arrow keys\n");
  6881. get_statline3(logline, sizeof(logline), cgpu, true, true);
  6882. wattron(logwin, A_BOLD);
  6883. wlogprint("%s", logline);
  6884. wattroff(logwin, A_BOLD);
  6885. wlogprint("\n");
  6886. if (cgpu->dev_manufacturer)
  6887. wlogprint(" %s from %s\n", (cgpu->dev_product ?: "Device"), cgpu->dev_manufacturer);
  6888. else
  6889. if (cgpu->dev_product)
  6890. wlogprint(" %s\n", cgpu->dev_product);
  6891. if (cgpu->dev_serial)
  6892. wlogprint("Serial: %s\n", cgpu->dev_serial);
  6893. if (cgpu->kname)
  6894. wlogprint("Kernel: %s\n", cgpu->kname);
  6895. if (drv->proc_wlogprint_status && likely(cgpu->status != LIFE_INIT))
  6896. drv->proc_wlogprint_status(cgpu);
  6897. wlogprint("\n");
  6898. // TODO: Last share at TIMESTAMP on pool N
  6899. // TODO: Custom device info/commands
  6900. if (cgpu->deven != DEV_ENABLED)
  6901. wlogprint("[E]nable ");
  6902. if (cgpu->deven != DEV_DISABLED)
  6903. wlogprint("[D]isable ");
  6904. if (drv->identify_device)
  6905. wlogprint("[I]dentify ");
  6906. if (drv->proc_tui_wlogprint_choices && likely(cgpu->status != LIFE_INIT))
  6907. drv->proc_tui_wlogprint_choices(cgpu);
  6908. wlogprint("\n");
  6909. wlogprint("[Slash] Find processor [Plus] Add device(s) [Enter] Close device manager\n");
  6910. _managetui_msg(cgpu->proc_repr, &msg);
  6911. while (true)
  6912. {
  6913. int input = getch();
  6914. applog(LOG_DEBUG, "ManageTUI: %"PRIpreprv": (choice %d)", cgpu->proc_repr, input);
  6915. switch (input) {
  6916. case 'd': case 'D':
  6917. if (cgpu->deven == DEV_DISABLED)
  6918. msg = "Processor already disabled\n";
  6919. else
  6920. {
  6921. cgpu->deven = DEV_DISABLED;
  6922. msg = "Processor being disabled\n";
  6923. }
  6924. goto refresh;
  6925. case 'e': case 'E':
  6926. if (cgpu->deven == DEV_ENABLED)
  6927. msg = "Processor already enabled\n";
  6928. else
  6929. {
  6930. proc_enable(cgpu);
  6931. msg = "Processor being enabled\n";
  6932. }
  6933. goto refresh;
  6934. case 'i': case 'I':
  6935. if (drv->identify_device && drv->identify_device(cgpu))
  6936. msg = "Identify command sent\n";
  6937. else
  6938. goto key_default;
  6939. goto refresh;
  6940. case KEY_DOWN:
  6941. if (selected_device >= total_devices - 1)
  6942. break;
  6943. ++selected_device;
  6944. goto devchange;
  6945. case KEY_UP:
  6946. if (selected_device <= 0)
  6947. break;
  6948. --selected_device;
  6949. goto devchange;
  6950. case KEY_NPAGE:
  6951. {
  6952. if (selected_device >= total_devices - 1)
  6953. break;
  6954. struct cgpu_info *mdev = devices[selected_device]->device;
  6955. do {
  6956. ++selected_device;
  6957. } while (devices[selected_device]->device == mdev && selected_device < total_devices - 1);
  6958. goto devchange;
  6959. }
  6960. case KEY_PPAGE:
  6961. {
  6962. if (selected_device <= 0)
  6963. break;
  6964. struct cgpu_info *mdev = devices[selected_device]->device;
  6965. do {
  6966. --selected_device;
  6967. } while (devices[selected_device]->device == mdev && selected_device > 0);
  6968. goto devchange;
  6969. }
  6970. case '/': case '?': // find device
  6971. {
  6972. static char *pattern = NULL;
  6973. char *newpattern = curses_input("Enter pattern");
  6974. if (newpattern)
  6975. {
  6976. free(pattern);
  6977. pattern = newpattern;
  6978. }
  6979. else
  6980. if (!pattern)
  6981. pattern = calloc(1, 1);
  6982. int match = cgpu_search(pattern, selected_device + 1);
  6983. if (match == -1)
  6984. {
  6985. msg = "Couldn't find device\n";
  6986. goto refresh;
  6987. }
  6988. selected_device = match;
  6989. goto devchange;
  6990. }
  6991. case '+': case '=': // add new device
  6992. {
  6993. addnew:
  6994. clear_logwin();
  6995. _wlogprint(
  6996. "Enter \"auto\", \"all\", or a serial port to probe for mining devices.\n"
  6997. "Prefix by a driver name and colon to only probe a specific driver.\n"
  6998. "For example: erupter:"
  6999. #ifdef WIN32
  7000. "\\\\.\\COM40"
  7001. #elif defined(__APPLE__)
  7002. "/dev/cu.SLAB_USBtoUART"
  7003. #else
  7004. "/dev/ttyUSB39"
  7005. #endif
  7006. "\n"
  7007. );
  7008. char *scanser = curses_input("Enter target");
  7009. if (scan_serial(scanser))
  7010. {
  7011. selected_device = total_devices - 1;
  7012. msg = "Device scan succeeded\n";
  7013. }
  7014. else
  7015. msg = "No new devices found\n";
  7016. goto devchange;
  7017. }
  7018. case 'Q': case 'q':
  7019. case KEY_BREAK: case KEY_BACKSPACE: case KEY_CANCEL: case KEY_CLOSE: case KEY_EXIT:
  7020. case '\x1b': // ESC
  7021. case KEY_ENTER:
  7022. case '\r': // Ctrl-M on Windows, with nonl
  7023. #ifdef PADENTER
  7024. case PADENTER: // pdcurses, used by Enter key on Windows with nonl
  7025. #endif
  7026. case '\n':
  7027. goto out;
  7028. default:
  7029. ;
  7030. key_default:
  7031. if (drv->proc_tui_handle_choice && likely(drv_ready(cgpu)))
  7032. {
  7033. msg = drv->proc_tui_handle_choice(cgpu, input);
  7034. if (msg)
  7035. goto refresh;
  7036. }
  7037. }
  7038. }
  7039. out:
  7040. selecting_device = false;
  7041. loginput_mode(0);
  7042. immedok(logwin, false);
  7043. }
  7044. void show_help(void)
  7045. {
  7046. loginput_mode(11);
  7047. // NOTE: wlogprint is a macro with a buffer limit
  7048. _wlogprint(
  7049. "LU: oldest explicit work update currently being used for new work\n"
  7050. "ST: work in queue | F: network fails | NB: new blocks detected\n"
  7051. "AS: shares being submitted | BW: bandwidth (up/down)\n"
  7052. "E: # shares * diff per 2kB bw | I: expected income | BS: best share ever found\n"
  7053. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7054. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7055. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7056. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_BTEE
  7057. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7058. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7059. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_BTEE U8_HLINE U8_HLINE U8_HLINE
  7060. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7061. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7062. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7063. "\n"
  7064. "devices/processors hashing (only for totals line), hottest temperature\n"
  7065. );
  7066. wlogprint(
  7067. "hashrates: %ds decaying / all-time average / all-time average (effective)\n"
  7068. , opt_log_interval);
  7069. _wlogprint(
  7070. "A: accepted shares | R: rejected+discarded(% of total)\n"
  7071. "HW: hardware errors / % nonces invalid\n"
  7072. "\n"
  7073. "Press any key to clear"
  7074. );
  7075. logwin_update();
  7076. getch();
  7077. loginput_mode(0);
  7078. }
  7079. static void *input_thread(void __maybe_unused *userdata)
  7080. {
  7081. RenameThread("input");
  7082. if (!curses_active)
  7083. return NULL;
  7084. while (1) {
  7085. int input;
  7086. input = getch();
  7087. switch (input) {
  7088. case 'h': case 'H': case '?':
  7089. case KEY_F(1):
  7090. show_help();
  7091. break;
  7092. case 'q': case 'Q':
  7093. kill_work();
  7094. return NULL;
  7095. case 'd': case 'D':
  7096. display_options();
  7097. break;
  7098. case 'm': case 'M':
  7099. manage_device();
  7100. break;
  7101. case 'p': case 'P':
  7102. display_pools();
  7103. break;
  7104. case 's': case 'S':
  7105. set_options();
  7106. break;
  7107. #ifdef HAVE_CURSES
  7108. case KEY_DOWN:
  7109. {
  7110. const int visible_lines = logcursor - devcursor;
  7111. const int invisible_lines = total_lines - visible_lines;
  7112. if (devsummaryYOffset <= -invisible_lines)
  7113. break;
  7114. devsummaryYOffset -= 2;
  7115. }
  7116. case KEY_UP:
  7117. if (devsummaryYOffset == 0)
  7118. break;
  7119. ++devsummaryYOffset;
  7120. refresh_devstatus();
  7121. break;
  7122. case KEY_NPAGE:
  7123. {
  7124. const int visible_lines = logcursor - devcursor;
  7125. const int invisible_lines = total_lines - visible_lines;
  7126. if (devsummaryYOffset - visible_lines <= -invisible_lines)
  7127. devsummaryYOffset = -invisible_lines;
  7128. else
  7129. devsummaryYOffset -= visible_lines;
  7130. refresh_devstatus();
  7131. break;
  7132. }
  7133. case KEY_PPAGE:
  7134. {
  7135. const int visible_lines = logcursor - devcursor;
  7136. if (devsummaryYOffset + visible_lines >= 0)
  7137. devsummaryYOffset = 0;
  7138. else
  7139. devsummaryYOffset += visible_lines;
  7140. refresh_devstatus();
  7141. break;
  7142. }
  7143. #endif
  7144. }
  7145. if (opt_realquiet) {
  7146. disable_curses();
  7147. break;
  7148. }
  7149. }
  7150. return NULL;
  7151. }
  7152. #endif
  7153. static void *api_thread(void *userdata)
  7154. {
  7155. struct thr_info *mythr = userdata;
  7156. pthread_detach(pthread_self());
  7157. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  7158. RenameThread("rpc");
  7159. api(api_thr_id);
  7160. mythr->has_pth = false;
  7161. return NULL;
  7162. }
  7163. void thread_reportin(struct thr_info *thr)
  7164. {
  7165. cgtime(&thr->last);
  7166. thr->cgpu->status = LIFE_WELL;
  7167. thr->getwork = 0;
  7168. thr->cgpu->device_last_well = time(NULL);
  7169. }
  7170. void thread_reportout(struct thr_info *thr)
  7171. {
  7172. thr->getwork = time(NULL);
  7173. }
  7174. static void hashmeter(int thr_id, struct timeval *diff,
  7175. uint64_t hashes_done)
  7176. {
  7177. char logstatusline[256];
  7178. struct timeval temp_tv_end, total_diff;
  7179. double secs;
  7180. double local_secs;
  7181. static double local_mhashes_done = 0;
  7182. double local_mhashes = (double)hashes_done / 1000000.0;
  7183. bool showlog = false;
  7184. char cHr[ALLOC_H2B_NOUNIT+1], aHr[ALLOC_H2B_NOUNIT+1], uHr[ALLOC_H2B_SPACED+3+1];
  7185. char rejpcbuf[6];
  7186. char bnbuf[6];
  7187. struct thr_info *thr;
  7188. /* Update the last time this thread reported in */
  7189. if (thr_id >= 0) {
  7190. thr = get_thread(thr_id);
  7191. cgtime(&(thr->last));
  7192. thr->cgpu->device_last_well = time(NULL);
  7193. }
  7194. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  7195. /* So we can call hashmeter from a non worker thread */
  7196. if (thr_id >= 0) {
  7197. struct cgpu_info *cgpu = thr->cgpu;
  7198. int threadobj = cgpu->threads ?: 1;
  7199. double thread_rolling = 0.0;
  7200. int i;
  7201. applog(LOG_DEBUG, "[thread %d: %"PRIu64" hashes, %.1f khash/sec]",
  7202. thr_id, hashes_done, hashes_done / 1000 / secs);
  7203. /* Rolling average for each thread and each device */
  7204. decay_time(&thr->rolling, local_mhashes / secs, secs);
  7205. for (i = 0; i < threadobj; i++)
  7206. thread_rolling += cgpu->thr[i]->rolling;
  7207. mutex_lock(&hash_lock);
  7208. decay_time(&cgpu->rolling, thread_rolling, secs);
  7209. cgpu->total_mhashes += local_mhashes;
  7210. mutex_unlock(&hash_lock);
  7211. // If needed, output detailed, per-device stats
  7212. if (want_per_device_stats) {
  7213. struct timeval now;
  7214. struct timeval elapsed;
  7215. struct timeval *last_msg_tv = opt_show_procs ? &thr->cgpu->last_message_tv : &thr->cgpu->device->last_message_tv;
  7216. cgtime(&now);
  7217. timersub(&now, last_msg_tv, &elapsed);
  7218. if (opt_log_interval <= elapsed.tv_sec) {
  7219. struct cgpu_info *cgpu = thr->cgpu;
  7220. char logline[255];
  7221. *last_msg_tv = now;
  7222. get_statline(logline, sizeof(logline), cgpu);
  7223. if (!curses_active) {
  7224. printf("\n%s\r", logline);
  7225. fflush(stdout);
  7226. } else
  7227. applog(LOG_INFO, "%s", logline);
  7228. }
  7229. }
  7230. }
  7231. /* Totals are updated by all threads so can race without locking */
  7232. mutex_lock(&hash_lock);
  7233. cgtime(&temp_tv_end);
  7234. timersub(&temp_tv_end, &total_tv_end, &total_diff);
  7235. total_mhashes_done += local_mhashes;
  7236. local_mhashes_done += local_mhashes;
  7237. /* Only update with opt_log_interval */
  7238. if (total_diff.tv_sec < opt_log_interval)
  7239. goto out_unlock;
  7240. showlog = true;
  7241. cgtime(&total_tv_end);
  7242. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  7243. decay_time(&total_rolling, local_mhashes_done / local_secs, local_secs);
  7244. global_hashrate = ((unsigned long long)lround(total_rolling)) * 1000000;
  7245. timersub(&total_tv_end, &total_tv_start, &total_diff);
  7246. total_secs = (double)total_diff.tv_sec +
  7247. ((double)total_diff.tv_usec / 1000000.0);
  7248. double wtotal = (total_diff_accepted + total_diff_rejected + total_diff_stale);
  7249. multi_format_unit_array2(
  7250. ((char*[]){cHr, aHr, uHr}),
  7251. ((size_t[]){sizeof(cHr), sizeof(aHr), sizeof(uHr)}),
  7252. true, "h/s", H2B_SHORT,
  7253. 3,
  7254. 1e6*total_rolling,
  7255. 1e6*total_mhashes_done / total_secs,
  7256. utility_to_hashrate(total_diff1 * (wtotal ? (total_diff_accepted / wtotal) : 1) * 60 / total_secs));
  7257. int ui_accepted, ui_rejected, ui_stale;
  7258. if (opt_weighed_stats)
  7259. {
  7260. ui_accepted = total_diff_accepted;
  7261. ui_rejected = total_diff_rejected;
  7262. ui_stale = total_diff_stale;
  7263. }
  7264. else
  7265. {
  7266. ui_accepted = total_accepted;
  7267. ui_rejected = total_rejected;
  7268. ui_stale = total_stale;
  7269. }
  7270. #ifdef HAVE_CURSES
  7271. if (curses_active_locked()) {
  7272. float temp = 0;
  7273. struct cgpu_info *proc, *last_working_dev = NULL;
  7274. int i, working_devs = 0, working_procs = 0;
  7275. int divx;
  7276. bool bad = false;
  7277. // Find the highest temperature of all processors
  7278. for (i = 0; i < total_devices; ++i)
  7279. {
  7280. proc = get_devices(i);
  7281. if (proc->temp > temp)
  7282. temp = proc->temp;
  7283. if (unlikely(proc->deven == DEV_DISABLED))
  7284. ; // Just need to block it off from both conditions
  7285. else
  7286. if (likely(proc->status == LIFE_WELL && proc->deven == DEV_ENABLED))
  7287. {
  7288. if (proc->rolling > .1)
  7289. {
  7290. ++working_procs;
  7291. if (proc->device != last_working_dev)
  7292. {
  7293. ++working_devs;
  7294. last_working_dev = proc->device;
  7295. }
  7296. }
  7297. }
  7298. else
  7299. bad = true;
  7300. }
  7301. if (working_devs == working_procs)
  7302. snprintf(statusline, sizeof(statusline), "%s%d ", bad ? U8_BAD_START : "", working_devs);
  7303. else
  7304. snprintf(statusline, sizeof(statusline), "%s%d/%d ", bad ? U8_BAD_START : "", working_devs, working_procs);
  7305. divx = 7;
  7306. if (opt_show_procs && !opt_compact)
  7307. divx += max_lpdigits;
  7308. if (bad)
  7309. {
  7310. divx += sizeof(U8_BAD_START)-1;
  7311. strcpy(&statusline[divx], U8_BAD_END);
  7312. divx += sizeof(U8_BAD_END)-1;
  7313. }
  7314. temperature_column(&statusline[divx], sizeof(statusline)-divx, true, &temp);
  7315. format_statline(statusline, sizeof(statusline),
  7316. cHr, aHr,
  7317. uHr,
  7318. ui_accepted,
  7319. ui_rejected,
  7320. ui_stale,
  7321. total_diff_rejected + total_diff_stale, total_diff_accepted,
  7322. hw_errors,
  7323. total_bad_diff1, total_bad_diff1 + total_diff1);
  7324. unlock_curses();
  7325. }
  7326. #endif
  7327. // Add a space
  7328. memmove(&uHr[6], &uHr[5], strlen(&uHr[5]) + 1);
  7329. uHr[5] = ' ';
  7330. percentf4(rejpcbuf, sizeof(rejpcbuf), total_diff_rejected + total_diff_stale, total_diff_accepted);
  7331. percentf4(bnbuf, sizeof(bnbuf), total_bad_diff1, total_diff1);
  7332. snprintf(logstatusline, sizeof(logstatusline),
  7333. "%s%ds:%s avg:%s u:%s | A:%d R:%d+%d(%s) HW:%d/%s",
  7334. want_per_device_stats ? "ALL " : "",
  7335. opt_log_interval,
  7336. cHr, aHr,
  7337. uHr,
  7338. ui_accepted,
  7339. ui_rejected,
  7340. ui_stale,
  7341. rejpcbuf,
  7342. hw_errors,
  7343. bnbuf
  7344. );
  7345. local_mhashes_done = 0;
  7346. out_unlock:
  7347. mutex_unlock(&hash_lock);
  7348. if (showlog) {
  7349. if (!curses_active) {
  7350. if (want_per_device_stats)
  7351. printf("\n%s\r", logstatusline);
  7352. else
  7353. {
  7354. const int logstatusline_len = strlen(logstatusline);
  7355. int padding;
  7356. if (last_logstatusline_len > logstatusline_len)
  7357. padding = (last_logstatusline_len - logstatusline_len);
  7358. else
  7359. {
  7360. padding = 0;
  7361. if (last_logstatusline_len == -1)
  7362. puts("");
  7363. }
  7364. printf("%s%*s\r", logstatusline, padding, "");
  7365. last_logstatusline_len = logstatusline_len;
  7366. }
  7367. fflush(stdout);
  7368. } else
  7369. applog(LOG_INFO, "%s", logstatusline);
  7370. }
  7371. }
  7372. void hashmeter2(struct thr_info *thr)
  7373. {
  7374. struct timeval tv_now, tv_elapsed;
  7375. timerclear(&thr->tv_hashes_done);
  7376. cgtime(&tv_now);
  7377. timersub(&tv_now, &thr->tv_lastupdate, &tv_elapsed);
  7378. /* Update the hashmeter at most 5 times per second */
  7379. if ((thr->hashes_done && (tv_elapsed.tv_sec > 0 || tv_elapsed.tv_usec > 200000)) ||
  7380. tv_elapsed.tv_sec >= opt_log_interval) {
  7381. hashmeter(thr->id, &tv_elapsed, thr->hashes_done);
  7382. thr->hashes_done = 0;
  7383. thr->tv_lastupdate = tv_now;
  7384. }
  7385. }
  7386. static void stratum_share_result(json_t *val, json_t *res_val, json_t *err_val,
  7387. struct stratum_share *sshare)
  7388. {
  7389. struct work *work = sshare->work;
  7390. share_result(val, res_val, err_val, work, false, "");
  7391. }
  7392. /* Parses stratum json responses and tries to find the id that the request
  7393. * matched to and treat it accordingly. */
  7394. bool parse_stratum_response(struct pool *pool, char *s)
  7395. {
  7396. json_t *val = NULL, *err_val, *res_val, *id_val;
  7397. struct stratum_share *sshare;
  7398. json_error_t err;
  7399. bool ret = false;
  7400. int id;
  7401. val = JSON_LOADS(s, &err);
  7402. if (!val) {
  7403. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  7404. goto out;
  7405. }
  7406. res_val = json_object_get(val, "result");
  7407. err_val = json_object_get(val, "error");
  7408. id_val = json_object_get(val, "id");
  7409. if (json_is_null(id_val) || !id_val) {
  7410. char *ss;
  7411. if (err_val)
  7412. ss = json_dumps(err_val, JSON_INDENT(3));
  7413. else
  7414. ss = strdup("(unknown reason)");
  7415. applog(LOG_INFO, "JSON-RPC non method decode failed: %s", ss);
  7416. free(ss);
  7417. goto out;
  7418. }
  7419. if (!json_is_integer(id_val)) {
  7420. if (json_is_string(id_val)
  7421. && !strncmp(json_string_value(id_val), "txlist", 6))
  7422. {
  7423. const bool is_array = json_is_array(res_val);
  7424. applog(LOG_DEBUG, "Received %s for pool %u job %s",
  7425. is_array ? "transaction list" : "no-transaction-list response",
  7426. pool->pool_no, &json_string_value(id_val)[6]);
  7427. if (!is_array)
  7428. {
  7429. // No need to wait for a timeout
  7430. timer_unset(&pool->swork.tv_transparency);
  7431. pool_set_opaque(pool, true);
  7432. goto fishy;
  7433. }
  7434. if (strcmp(json_string_value(id_val) + 6, pool->swork.job_id))
  7435. // We only care about a transaction list for the current job id
  7436. goto fishy;
  7437. // Check that the transactions actually hash to the merkle links
  7438. {
  7439. unsigned maxtx = 1 << pool->swork.merkles;
  7440. unsigned mintx = maxtx >> 1;
  7441. --maxtx;
  7442. unsigned acttx = (unsigned)json_array_size(res_val);
  7443. if (acttx < mintx || acttx > maxtx) {
  7444. applog(LOG_WARNING, "Pool %u is sending mismatched block contents to us (%u is not %u-%u)",
  7445. pool->pool_no, acttx, mintx, maxtx);
  7446. goto fishy;
  7447. }
  7448. // TODO: Check hashes match actual merkle links
  7449. }
  7450. pool_set_opaque(pool, false);
  7451. timer_unset(&pool->swork.tv_transparency);
  7452. fishy:
  7453. ret = true;
  7454. }
  7455. goto out;
  7456. }
  7457. id = json_integer_value(id_val);
  7458. mutex_lock(&sshare_lock);
  7459. HASH_FIND_INT(stratum_shares, &id, sshare);
  7460. if (sshare)
  7461. HASH_DEL(stratum_shares, sshare);
  7462. mutex_unlock(&sshare_lock);
  7463. if (!sshare) {
  7464. double pool_diff;
  7465. /* Since the share is untracked, we can only guess at what the
  7466. * work difficulty is based on the current pool diff. */
  7467. cg_rlock(&pool->data_lock);
  7468. pool_diff = target_diff(pool->swork.target);
  7469. cg_runlock(&pool->data_lock);
  7470. if (json_is_true(res_val)) {
  7471. applog(LOG_NOTICE, "Accepted untracked stratum share from pool %d", pool->pool_no);
  7472. /* We don't know what device this came from so we can't
  7473. * attribute the work to the relevant cgpu */
  7474. mutex_lock(&stats_lock);
  7475. total_accepted++;
  7476. pool->accepted++;
  7477. total_diff_accepted += pool_diff;
  7478. pool->diff_accepted += pool_diff;
  7479. mutex_unlock(&stats_lock);
  7480. } else {
  7481. applog(LOG_NOTICE, "Rejected untracked stratum share from pool %d", pool->pool_no);
  7482. mutex_lock(&stats_lock);
  7483. total_rejected++;
  7484. pool->rejected++;
  7485. total_diff_rejected += pool_diff;
  7486. pool->diff_rejected += pool_diff;
  7487. mutex_unlock(&stats_lock);
  7488. }
  7489. goto out;
  7490. }
  7491. else {
  7492. mutex_lock(&submitting_lock);
  7493. --total_submitting;
  7494. mutex_unlock(&submitting_lock);
  7495. }
  7496. stratum_share_result(val, res_val, err_val, sshare);
  7497. free_work(sshare->work);
  7498. free(sshare);
  7499. ret = true;
  7500. out:
  7501. if (val)
  7502. json_decref(val);
  7503. return ret;
  7504. }
  7505. static void shutdown_stratum(struct pool *pool)
  7506. {
  7507. // Shut down Stratum as if we never had it
  7508. pool->stratum_active = false;
  7509. pool->stratum_init = false;
  7510. pool->has_stratum = false;
  7511. shutdown(pool->sock, SHUT_RDWR);
  7512. free(pool->stratum_url);
  7513. if (pool->sockaddr_url == pool->stratum_url)
  7514. pool->sockaddr_url = NULL;
  7515. pool->stratum_url = NULL;
  7516. }
  7517. void clear_stratum_shares(struct pool *pool)
  7518. {
  7519. int my_mining_threads = mining_threads; // Cached outside of locking
  7520. struct stratum_share *sshare, *tmpshare;
  7521. struct work *work;
  7522. struct cgpu_info *cgpu;
  7523. double diff_cleared = 0;
  7524. double thr_diff_cleared[my_mining_threads];
  7525. int cleared = 0;
  7526. int thr_cleared[my_mining_threads];
  7527. // NOTE: This is per-thread rather than per-device to avoid getting devices lock in stratum_shares loop
  7528. for (int i = 0; i < my_mining_threads; ++i)
  7529. {
  7530. thr_diff_cleared[i] = 0;
  7531. thr_cleared[i] = 0;
  7532. }
  7533. mutex_lock(&sshare_lock);
  7534. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  7535. work = sshare->work;
  7536. if (sshare->work->pool == pool && work->thr_id < my_mining_threads) {
  7537. HASH_DEL(stratum_shares, sshare);
  7538. sharelog("disconnect", work);
  7539. diff_cleared += sshare->work->work_difficulty;
  7540. thr_diff_cleared[work->thr_id] += work->work_difficulty;
  7541. ++thr_cleared[work->thr_id];
  7542. free_work(sshare->work);
  7543. free(sshare);
  7544. cleared++;
  7545. }
  7546. }
  7547. mutex_unlock(&sshare_lock);
  7548. if (cleared) {
  7549. applog(LOG_WARNING, "Lost %d shares due to stratum disconnect on pool %d", cleared, pool->pool_no);
  7550. mutex_lock(&stats_lock);
  7551. pool->stale_shares += cleared;
  7552. total_stale += cleared;
  7553. pool->diff_stale += diff_cleared;
  7554. total_diff_stale += diff_cleared;
  7555. for (int i = 0; i < my_mining_threads; ++i)
  7556. if (thr_cleared[i])
  7557. {
  7558. cgpu = get_thr_cgpu(i);
  7559. cgpu->diff_stale += thr_diff_cleared[i];
  7560. cgpu->stale += thr_cleared[i];
  7561. }
  7562. mutex_unlock(&stats_lock);
  7563. mutex_lock(&submitting_lock);
  7564. total_submitting -= cleared;
  7565. mutex_unlock(&submitting_lock);
  7566. }
  7567. }
  7568. static void resubmit_stratum_shares(struct pool *pool)
  7569. {
  7570. struct stratum_share *sshare, *tmpshare;
  7571. struct work *work;
  7572. unsigned resubmitted = 0;
  7573. mutex_lock(&sshare_lock);
  7574. mutex_lock(&submitting_lock);
  7575. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  7576. if (sshare->work->pool != pool)
  7577. continue;
  7578. HASH_DEL(stratum_shares, sshare);
  7579. work = sshare->work;
  7580. DL_APPEND(submit_waiting, work);
  7581. free(sshare);
  7582. ++resubmitted;
  7583. }
  7584. mutex_unlock(&submitting_lock);
  7585. mutex_unlock(&sshare_lock);
  7586. if (resubmitted) {
  7587. notifier_wake(submit_waiting_notifier);
  7588. applog(LOG_DEBUG, "Resubmitting %u shares due to stratum disconnect on pool %u", resubmitted, pool->pool_no);
  7589. }
  7590. }
  7591. static void clear_pool_work(struct pool *pool)
  7592. {
  7593. struct work *work, *tmp;
  7594. int cleared = 0;
  7595. mutex_lock(stgd_lock);
  7596. HASH_ITER(hh, staged_work, work, tmp) {
  7597. if (work->pool == pool) {
  7598. HASH_DEL(staged_work, work);
  7599. free_work(work);
  7600. cleared++;
  7601. staged_full = false;
  7602. }
  7603. }
  7604. mutex_unlock(stgd_lock);
  7605. }
  7606. static int cp_prio(void)
  7607. {
  7608. int prio;
  7609. cg_rlock(&control_lock);
  7610. prio = currentpool->prio;
  7611. cg_runlock(&control_lock);
  7612. return prio;
  7613. }
  7614. /* We only need to maintain a secondary pool connection when we need the
  7615. * capacity to get work from the backup pools while still on the primary */
  7616. static bool cnx_needed(struct pool *pool)
  7617. {
  7618. struct pool *cp;
  7619. if (pool->enabled != POOL_ENABLED)
  7620. return false;
  7621. /* Idle stratum pool needs something to kick it alive again */
  7622. if (pool->has_stratum && pool->idle)
  7623. return true;
  7624. /* Getwork pools without opt_fail_only need backup pools up to be able
  7625. * to leak shares */
  7626. cp = current_pool();
  7627. if (pool_actively_desired(pool, cp))
  7628. return true;
  7629. if (!pool_localgen(cp) && (!opt_fail_only || !cp->hdr_path))
  7630. return true;
  7631. /* Keep the connection open to allow any stray shares to be submitted
  7632. * on switching pools for 2 minutes. */
  7633. if (timer_elapsed(&pool->tv_last_work_time, NULL) < 120)
  7634. return true;
  7635. /* If the pool has only just come to life and is higher priority than
  7636. * the current pool keep the connection open so we can fail back to
  7637. * it. */
  7638. if (pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  7639. return true;
  7640. if (pool_unworkable(cp))
  7641. return true;
  7642. /* We've run out of work, bring anything back to life. */
  7643. if (no_work)
  7644. return true;
  7645. // If the current pool lacks its own block change detection, see if we are needed for that
  7646. if (pool_active_lp_pool(cp) == pool)
  7647. return true;
  7648. return false;
  7649. }
  7650. static void wait_lpcurrent(struct pool *pool);
  7651. static void pool_resus(struct pool *pool);
  7652. static void stratum_resumed(struct pool *pool)
  7653. {
  7654. if (!pool->stratum_notify)
  7655. return;
  7656. if (pool_tclear(pool, &pool->idle)) {
  7657. applog(LOG_INFO, "Stratum connection to pool %d resumed", pool->pool_no);
  7658. pool_resus(pool);
  7659. }
  7660. }
  7661. static bool supports_resume(struct pool *pool)
  7662. {
  7663. bool ret;
  7664. cg_rlock(&pool->data_lock);
  7665. ret = (pool->sessionid != NULL);
  7666. cg_runlock(&pool->data_lock);
  7667. return ret;
  7668. }
  7669. static bool pools_active;
  7670. /* One stratum thread per pool that has stratum waits on the socket checking
  7671. * for new messages and for the integrity of the socket connection. We reset
  7672. * the connection based on the integrity of the receive side only as the send
  7673. * side will eventually expire data it fails to send. */
  7674. static void *stratum_thread(void *userdata)
  7675. {
  7676. struct pool *pool = (struct pool *)userdata;
  7677. pthread_detach(pthread_self());
  7678. char threadname[20];
  7679. snprintf(threadname, 20, "stratum%u", pool->pool_no);
  7680. RenameThread(threadname);
  7681. srand(time(NULL) + (intptr_t)userdata);
  7682. while (42) {
  7683. struct timeval timeout;
  7684. int sel_ret;
  7685. fd_set rd;
  7686. char *s;
  7687. int sock;
  7688. if (unlikely(!pool->has_stratum))
  7689. break;
  7690. /* Check to see whether we need to maintain this connection
  7691. * indefinitely or just bring it up when we switch to this
  7692. * pool */
  7693. while (true)
  7694. {
  7695. sock = pool->sock;
  7696. if (sock == INVSOCK)
  7697. applog(LOG_DEBUG, "Pool %u: Invalid socket, suspending",
  7698. pool->pool_no);
  7699. else
  7700. if (!sock_full(pool) && !cnx_needed(pool) && pools_active)
  7701. applog(LOG_DEBUG, "Pool %u: Connection not needed, suspending",
  7702. pool->pool_no);
  7703. else
  7704. break;
  7705. suspend_stratum(pool);
  7706. clear_stratum_shares(pool);
  7707. clear_pool_work(pool);
  7708. wait_lpcurrent(pool);
  7709. if (!restart_stratum(pool)) {
  7710. pool_died(pool);
  7711. while (!restart_stratum(pool)) {
  7712. if (pool->removed)
  7713. goto out;
  7714. cgsleep_ms(30000);
  7715. }
  7716. }
  7717. }
  7718. FD_ZERO(&rd);
  7719. FD_SET(sock, &rd);
  7720. timeout.tv_sec = 120;
  7721. timeout.tv_usec = 0;
  7722. /* If we fail to receive any notify messages for 2 minutes we
  7723. * assume the connection has been dropped and treat this pool
  7724. * as dead */
  7725. if (!sock_full(pool) && (sel_ret = select(sock + 1, &rd, NULL, NULL, &timeout)) < 1) {
  7726. applog(LOG_DEBUG, "Stratum select failed on pool %d with value %d", pool->pool_no, sel_ret);
  7727. s = NULL;
  7728. } else
  7729. s = recv_line(pool);
  7730. if (!s) {
  7731. if (!pool->has_stratum)
  7732. break;
  7733. applog(LOG_NOTICE, "Stratum connection to pool %d interrupted", pool->pool_no);
  7734. pool->getfail_occasions++;
  7735. total_go++;
  7736. mutex_lock(&pool->stratum_lock);
  7737. pool->stratum_active = pool->stratum_notify = false;
  7738. pool->sock = INVSOCK;
  7739. mutex_unlock(&pool->stratum_lock);
  7740. /* If the socket to our stratum pool disconnects, all
  7741. * submissions need to be discarded or resent. */
  7742. if (!supports_resume(pool))
  7743. clear_stratum_shares(pool);
  7744. else
  7745. resubmit_stratum_shares(pool);
  7746. clear_pool_work(pool);
  7747. if (pool == current_pool())
  7748. restart_threads();
  7749. if (restart_stratum(pool))
  7750. continue;
  7751. shutdown_stratum(pool);
  7752. pool_died(pool);
  7753. break;
  7754. }
  7755. /* Check this pool hasn't died while being a backup pool and
  7756. * has not had its idle flag cleared */
  7757. stratum_resumed(pool);
  7758. if (!parse_method(pool, s) && !parse_stratum_response(pool, s))
  7759. applog(LOG_INFO, "Unknown stratum msg: %s", s);
  7760. free(s);
  7761. if (pool->swork.clean) {
  7762. struct work *work = make_work();
  7763. /* Generate a single work item to update the current
  7764. * block database */
  7765. pool->swork.clean = false;
  7766. gen_stratum_work(pool, work);
  7767. /* Try to extract block height from coinbase scriptSig */
  7768. uint8_t *bin_height = &bytes_buf(&pool->swork.coinbase)[4 /*version*/ + 1 /*txin count*/ + 36 /*prevout*/ + 1 /*scriptSig len*/ + 1 /*push opcode*/];
  7769. unsigned char cb_height_sz;
  7770. cb_height_sz = bin_height[-1];
  7771. if (cb_height_sz == 3) {
  7772. // FIXME: The block number will overflow this by AD 2173
  7773. uint32_t block_id = ((uint32_t*)work->data)[1];
  7774. uint32_t height = 0;
  7775. memcpy(&height, bin_height, 3);
  7776. height = le32toh(height);
  7777. have_block_height(block_id, height);
  7778. }
  7779. pool->swork.work_restart_id =
  7780. ++pool->work_restart_id;
  7781. pool_update_work_restart_time(pool);
  7782. if (test_work_current(work)) {
  7783. /* Only accept a work update if this stratum
  7784. * connection is from the current pool */
  7785. struct pool * const cp = current_pool();
  7786. if (pool == cp)
  7787. restart_threads();
  7788. applog(
  7789. ((!opt_quiet_work_updates) && pool_actively_in_use(pool, cp) ? LOG_NOTICE : LOG_DEBUG),
  7790. "Stratum from pool %d requested work update", pool->pool_no);
  7791. } else
  7792. applog(LOG_NOTICE, "Stratum from pool %d detected new block", pool->pool_no);
  7793. free_work(work);
  7794. }
  7795. if (timer_passed(&pool->swork.tv_transparency, NULL)) {
  7796. // More than 4 timmills past since requested transactions
  7797. timer_unset(&pool->swork.tv_transparency);
  7798. pool_set_opaque(pool, true);
  7799. }
  7800. }
  7801. out:
  7802. return NULL;
  7803. }
  7804. static void init_stratum_thread(struct pool *pool)
  7805. {
  7806. have_longpoll = true;
  7807. if (unlikely(pthread_create(&pool->stratum_thread, NULL, stratum_thread, (void *)pool)))
  7808. quit(1, "Failed to create stratum thread");
  7809. }
  7810. static void *longpoll_thread(void *userdata);
  7811. static bool stratum_works(struct pool *pool)
  7812. {
  7813. applog(LOG_INFO, "Testing pool %d stratum %s", pool->pool_no, pool->stratum_url);
  7814. if (!extract_sockaddr(pool->stratum_url, &pool->sockaddr_url, &pool->stratum_port))
  7815. return false;
  7816. if (pool->stratum_active)
  7817. return true;
  7818. if (!initiate_stratum(pool))
  7819. return false;
  7820. return true;
  7821. }
  7822. static
  7823. bool pool_recently_got_work(struct pool * const pool, const struct timeval * const tvp_now)
  7824. {
  7825. return (timer_isset(&pool->tv_last_work_time) && timer_elapsed(&pool->tv_last_work_time, tvp_now) < 60);
  7826. }
  7827. static bool pool_active(struct pool *pool, bool pinging)
  7828. {
  7829. struct timeval tv_now, tv_getwork, tv_getwork_reply;
  7830. bool ret = false;
  7831. json_t *val;
  7832. CURL *curl = NULL;
  7833. int rolltime;
  7834. char *rpc_req;
  7835. struct work *work;
  7836. enum pool_protocol proto;
  7837. if (pool->stratum_init)
  7838. {
  7839. if (pool->stratum_active)
  7840. return true;
  7841. }
  7842. else
  7843. if (!pool->idle)
  7844. {
  7845. timer_set_now(&tv_now);
  7846. if (pool_recently_got_work(pool, &tv_now))
  7847. return true;
  7848. }
  7849. mutex_lock(&pool->pool_test_lock);
  7850. if (pool->stratum_init)
  7851. {
  7852. ret = pool->stratum_active;
  7853. goto out;
  7854. }
  7855. timer_set_now(&tv_now);
  7856. if (pool->idle)
  7857. {
  7858. if (timer_elapsed(&pool->tv_idle, &tv_now) < 30)
  7859. goto out;
  7860. }
  7861. else
  7862. if (pool_recently_got_work(pool, &tv_now))
  7863. {
  7864. ret = true;
  7865. goto out;
  7866. }
  7867. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  7868. /* This is the central point we activate stratum when we can */
  7869. curl = curl_easy_init();
  7870. if (unlikely(!curl)) {
  7871. applog(LOG_ERR, "CURL initialisation failed");
  7872. goto out;
  7873. }
  7874. if (!(want_gbt || want_getwork))
  7875. goto nohttp;
  7876. work = make_work();
  7877. /* Probe for GBT support on first pass */
  7878. proto = want_gbt ? PLP_GETBLOCKTEMPLATE : PLP_GETWORK;
  7879. tryagain:
  7880. rpc_req = prepare_rpc_req_probe(work, proto, NULL);
  7881. work->pool = pool;
  7882. if (!rpc_req)
  7883. goto out;
  7884. pool->probed = false;
  7885. cgtime(&tv_getwork);
  7886. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  7887. true, false, &rolltime, pool, false);
  7888. cgtime(&tv_getwork_reply);
  7889. free(rpc_req);
  7890. /* Detect if a http getwork pool has an X-Stratum header at startup,
  7891. * and if so, switch to that in preference to getwork if it works */
  7892. if (pool->stratum_url && want_stratum && pool_may_redirect_to(pool, pool->stratum_url) && (pool->has_stratum || stratum_works(pool))) {
  7893. if (!pool->has_stratum) {
  7894. applog(LOG_NOTICE, "Switching pool %d %s to %s", pool->pool_no, pool->rpc_url, pool->stratum_url);
  7895. if (!pool->rpc_url)
  7896. pool_set_uri(pool, strdup(pool->stratum_url));
  7897. pool->has_stratum = true;
  7898. }
  7899. free_work(work);
  7900. if (val)
  7901. json_decref(val);
  7902. retry_stratum:
  7903. ;
  7904. /* We create the stratum thread for each pool just after
  7905. * successful authorisation. Once the init flag has been set
  7906. * we never unset it and the stratum thread is responsible for
  7907. * setting/unsetting the active flag */
  7908. bool init = pool_tset(pool, &pool->stratum_init);
  7909. if (!init) {
  7910. ret = initiate_stratum(pool) && auth_stratum(pool);
  7911. if (ret)
  7912. {
  7913. detect_algo = 2;
  7914. init_stratum_thread(pool);
  7915. }
  7916. else
  7917. {
  7918. pool_tclear(pool, &pool->stratum_init);
  7919. pool->tv_idle = tv_getwork_reply;
  7920. }
  7921. goto out;
  7922. }
  7923. ret = pool->stratum_active;
  7924. goto out;
  7925. }
  7926. else if (pool->has_stratum)
  7927. shutdown_stratum(pool);
  7928. if (val) {
  7929. bool rc;
  7930. json_t *res;
  7931. res = json_object_get(val, "result");
  7932. if ((!json_is_object(res)) || (proto == PLP_GETBLOCKTEMPLATE && !json_object_get(res, "bits")))
  7933. goto badwork;
  7934. work->rolltime = rolltime;
  7935. rc = work_decode(pool, work, val);
  7936. if (rc) {
  7937. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  7938. pool->pool_no, pool->rpc_url);
  7939. work->pool = pool;
  7940. copy_time(&work->tv_getwork, &tv_getwork);
  7941. copy_time(&work->tv_getwork_reply, &tv_getwork_reply);
  7942. work->getwork_mode = GETWORK_MODE_TESTPOOL;
  7943. calc_diff(work, 0);
  7944. update_last_work(work);
  7945. applog(LOG_DEBUG, "Pushing pooltest work to base pool");
  7946. stage_work(work);
  7947. total_getworks++;
  7948. pool->getwork_requested++;
  7949. ret = true;
  7950. pool->tv_idle = tv_getwork_reply;
  7951. } else {
  7952. badwork:
  7953. json_decref(val);
  7954. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher work from pool %u %s",
  7955. pool->pool_no, pool->rpc_url);
  7956. pool->proto = proto = pool_protocol_fallback(proto);
  7957. if (PLP_NONE != proto)
  7958. goto tryagain;
  7959. pool->tv_idle = tv_getwork_reply;
  7960. free_work(work);
  7961. goto out;
  7962. }
  7963. json_decref(val);
  7964. if (proto != pool->proto) {
  7965. pool->proto = proto;
  7966. applog(LOG_INFO, "Selected %s protocol for pool %u", pool_protocol_name(proto), pool->pool_no);
  7967. }
  7968. if (pool->lp_url)
  7969. goto out;
  7970. /* Decipher the longpoll URL, if any, and store it in ->lp_url */
  7971. const struct blktmpl_longpoll_req *lp;
  7972. if (work->tr && (lp = blktmpl_get_longpoll(work->tr->tmpl))) {
  7973. // NOTE: work_decode takes care of lp id
  7974. pool->lp_url = lp->uri ? absolute_uri(lp->uri, pool->rpc_url) : pool->rpc_url;
  7975. if (!pool->lp_url)
  7976. {
  7977. ret = false;
  7978. goto out;
  7979. }
  7980. pool->lp_proto = PLP_GETBLOCKTEMPLATE;
  7981. }
  7982. else
  7983. if (pool->hdr_path && want_getwork) {
  7984. pool->lp_url = absolute_uri(pool->hdr_path, pool->rpc_url);
  7985. if (!pool->lp_url)
  7986. {
  7987. ret = false;
  7988. goto out;
  7989. }
  7990. pool->lp_proto = PLP_GETWORK;
  7991. } else
  7992. pool->lp_url = NULL;
  7993. if (want_longpoll && !pool->lp_started) {
  7994. pool->lp_started = true;
  7995. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  7996. quit(1, "Failed to create pool longpoll thread");
  7997. }
  7998. } else if (PLP_NONE != (proto = pool_protocol_fallback(proto))) {
  7999. pool->proto = proto;
  8000. goto tryagain;
  8001. } else {
  8002. pool->tv_idle = tv_getwork_reply;
  8003. free_work(work);
  8004. nohttp:
  8005. /* If we failed to parse a getwork, this could be a stratum
  8006. * url without the prefix stratum+tcp:// so let's check it */
  8007. if (extract_sockaddr(pool->rpc_url, &pool->sockaddr_url, &pool->stratum_port) && initiate_stratum(pool)) {
  8008. pool->has_stratum = true;
  8009. goto retry_stratum;
  8010. }
  8011. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  8012. pool->pool_no, pool->rpc_url);
  8013. if (!pinging)
  8014. applog(LOG_WARNING, "Pool %u slow/down or URL or credentials invalid", pool->pool_no);
  8015. }
  8016. out:
  8017. if (curl)
  8018. curl_easy_cleanup(curl);
  8019. mutex_unlock(&pool->pool_test_lock);
  8020. return ret;
  8021. }
  8022. static void pool_resus(struct pool *pool)
  8023. {
  8024. if (pool->enabled == POOL_ENABLED && pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  8025. applog(LOG_WARNING, "Pool %d %s alive, testing stability", pool->pool_no, pool->rpc_url);
  8026. else
  8027. applog(LOG_INFO, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  8028. }
  8029. static struct work *hash_pop(void)
  8030. {
  8031. struct work *work = NULL, *tmp;
  8032. int hc;
  8033. retry:
  8034. mutex_lock(stgd_lock);
  8035. while (!HASH_COUNT(staged_work))
  8036. {
  8037. if (unlikely(staged_full))
  8038. {
  8039. if (likely(opt_queue < 10 + mining_threads))
  8040. {
  8041. ++opt_queue;
  8042. applog(LOG_WARNING, "Staged work underrun; increasing queue minimum to %d", opt_queue);
  8043. }
  8044. else
  8045. applog(LOG_WARNING, "Staged work underrun; not automatically increasing above %d", opt_queue);
  8046. staged_full = false; // Let it fill up before triggering an underrun again
  8047. no_work = true;
  8048. }
  8049. pthread_cond_signal(&gws_cond);
  8050. const struct timeval tv = { .tv_sec = opt_log_interval, };
  8051. if (ETIMEDOUT == bfg_cond_timedwait(&getq->cond, stgd_lock, &tv))
  8052. {
  8053. run_cmd(cmd_idle);
  8054. pthread_cond_signal(&gws_cond);
  8055. pthread_cond_wait(&getq->cond, stgd_lock);
  8056. }
  8057. }
  8058. no_work = false;
  8059. hc = HASH_COUNT(staged_work);
  8060. /* Find clone work if possible, to allow masters to be reused */
  8061. if (hc > staged_rollable) {
  8062. HASH_ITER(hh, staged_work, work, tmp) {
  8063. if (!work_rollable(work))
  8064. break;
  8065. }
  8066. } else
  8067. work = staged_work;
  8068. if (can_roll(work) && should_roll(work))
  8069. {
  8070. // Instead of consuming it, force it to be cloned and grab the clone
  8071. mutex_unlock(stgd_lock);
  8072. clone_available();
  8073. goto retry;
  8074. }
  8075. HASH_DEL(staged_work, work);
  8076. if (work_rollable(work))
  8077. staged_rollable--;
  8078. /* Signal the getwork scheduler to look for more work */
  8079. pthread_cond_signal(&gws_cond);
  8080. /* Signal hash_pop again in case there are mutliple hash_pop waiters */
  8081. pthread_cond_signal(&getq->cond);
  8082. mutex_unlock(stgd_lock);
  8083. work->pool->last_work_time = time(NULL);
  8084. cgtime(&work->pool->tv_last_work_time);
  8085. return work;
  8086. }
  8087. /* Clones work by rolling it if possible, and returning a clone instead of the
  8088. * original work item which gets staged again to possibly be rolled again in
  8089. * the future */
  8090. static struct work *clone_work(struct work *work)
  8091. {
  8092. int mrs = mining_threads + opt_queue - total_staged();
  8093. struct work *work_clone;
  8094. bool cloned;
  8095. if (mrs < 1)
  8096. return work;
  8097. cloned = false;
  8098. work_clone = make_clone(work);
  8099. while (mrs-- > 0 && can_roll(work) && should_roll(work)) {
  8100. applog(LOG_DEBUG, "Pushing rolled converted work to stage thread");
  8101. stage_work(work_clone);
  8102. roll_work(work);
  8103. work_clone = make_clone(work);
  8104. /* Roll it again to prevent duplicates should this be used
  8105. * directly later on */
  8106. roll_work(work);
  8107. cloned = true;
  8108. }
  8109. if (cloned) {
  8110. stage_work(work);
  8111. return work_clone;
  8112. }
  8113. free_work(work_clone);
  8114. return work;
  8115. }
  8116. void gen_hash(unsigned char *data, unsigned char *hash, int len)
  8117. {
  8118. unsigned char hash1[32];
  8119. sha256(data, len, hash1);
  8120. sha256(hash1, 32, hash);
  8121. }
  8122. /* PDiff 1 is a 256 bit unsigned integer of
  8123. * 0x00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff
  8124. * so we use a big endian 32 bit unsigned integer positioned at the Nth byte to
  8125. * cover a huge range of difficulty targets, though not all 256 bits' worth */
  8126. static void pdiff_target_leadzero(void * const target_p, double diff)
  8127. {
  8128. uint8_t *target = target_p;
  8129. diff *= 0x100000000;
  8130. int skip = log2(diff) / 8;
  8131. if (skip)
  8132. {
  8133. if (skip > 0x1c)
  8134. skip = 0x1c;
  8135. diff /= pow(0x100, skip);
  8136. memset(target, 0, skip);
  8137. }
  8138. uint32_t n = 0xffffffff;
  8139. n = (double)n / diff;
  8140. n = htobe32(n);
  8141. memcpy(&target[skip], &n, sizeof(n));
  8142. memset(&target[skip + sizeof(n)], 0xff, 32 - (skip + sizeof(n)));
  8143. }
  8144. void set_target_to_pdiff(void * const dest_target, const double pdiff)
  8145. {
  8146. unsigned char rtarget[32];
  8147. pdiff_target_leadzero(rtarget, pdiff);
  8148. swab256(dest_target, rtarget);
  8149. if (opt_debug) {
  8150. char htarget[65];
  8151. bin2hex(htarget, rtarget, 32);
  8152. applog(LOG_DEBUG, "Generated target %s", htarget);
  8153. }
  8154. }
  8155. void set_target_to_bdiff(void * const dest_target, const double bdiff)
  8156. {
  8157. set_target_to_pdiff(dest_target, bdiff_to_pdiff(bdiff));
  8158. }
  8159. void _test_target(void * const funcp, const char * const funcname, const bool little_endian, const void * const expectp, const double diff)
  8160. {
  8161. uint8_t bufr[32], buf[32], expectr[32], expect[32];
  8162. int off;
  8163. void (*func)(void *, double) = funcp;
  8164. func(little_endian ? bufr : buf, diff);
  8165. if (little_endian)
  8166. swab256(buf, bufr);
  8167. swap32tobe(expect, expectp, 256/32);
  8168. // Fuzzy comparison: the first 32 bits set must match, and the actual target must be >= the expected
  8169. for (off = 0; off < 28 && !buf[off]; ++off)
  8170. {}
  8171. if (memcmp(&buf[off], &expect[off], 4))
  8172. {
  8173. testfail: ;
  8174. char hexbuf[65], expectbuf[65];
  8175. bin2hex(hexbuf, buf, 32);
  8176. bin2hex(expectbuf, expect, 32);
  8177. applogr(, LOG_WARNING, "%s test failed: diff %g got %s (expected %s)",
  8178. funcname, diff, hexbuf, expectbuf);
  8179. }
  8180. if (!little_endian)
  8181. swab256(bufr, buf);
  8182. swab256(expectr, expect);
  8183. if (!hash_target_check(expectr, bufr))
  8184. goto testfail;
  8185. }
  8186. #define TEST_TARGET(func, le, expect, diff) \
  8187. _test_target(func, #func, le, expect, diff)
  8188. void test_target()
  8189. {
  8190. uint32_t expect[8] = {0};
  8191. // bdiff 1 should be exactly 00000000ffff0000000006f29cfd29510a6caee84634e86a57257cf03152537f due to floating-point imprecision (pdiff1 / 1.0000152590218966)
  8192. expect[0] = 0x0000ffff;
  8193. TEST_TARGET(set_target_to_bdiff, true, expect, 1./0x10000);
  8194. expect[0] = 0;
  8195. expect[1] = 0xffff0000;
  8196. TEST_TARGET(set_target_to_bdiff, true, expect, 1);
  8197. expect[1] >>= 1;
  8198. TEST_TARGET(set_target_to_bdiff, true, expect, 2);
  8199. expect[1] >>= 3;
  8200. TEST_TARGET(set_target_to_bdiff, true, expect, 0x10);
  8201. expect[1] >>= 4;
  8202. TEST_TARGET(set_target_to_bdiff, true, expect, 0x100);
  8203. memset(&expect[1], '\xff', 28);
  8204. expect[0] = 0x0000ffff;
  8205. TEST_TARGET(set_target_to_pdiff, true, expect, 1./0x10000);
  8206. expect[0] = 0;
  8207. TEST_TARGET(set_target_to_pdiff, true, expect, 1);
  8208. expect[1] >>= 1;
  8209. TEST_TARGET(set_target_to_pdiff, true, expect, 2);
  8210. expect[1] >>= 3;
  8211. TEST_TARGET(set_target_to_pdiff, true, expect, 0x10);
  8212. expect[1] >>= 4;
  8213. TEST_TARGET(set_target_to_pdiff, true, expect, 0x100);
  8214. }
  8215. void stratum_work_cpy(struct stratum_work * const dst, const struct stratum_work * const src)
  8216. {
  8217. *dst = *src;
  8218. if (dst->tr)
  8219. tmpl_incref(dst->tr);
  8220. dst->nonce1 = maybe_strdup(src->nonce1);
  8221. dst->job_id = maybe_strdup(src->job_id);
  8222. bytes_cpy(&dst->coinbase, &src->coinbase);
  8223. bytes_cpy(&dst->merkle_bin, &src->merkle_bin);
  8224. }
  8225. void stratum_work_clean(struct stratum_work * const swork)
  8226. {
  8227. if (swork->tr)
  8228. tmpl_decref(swork->tr);
  8229. free(swork->nonce1);
  8230. free(swork->job_id);
  8231. bytes_free(&swork->coinbase);
  8232. bytes_free(&swork->merkle_bin);
  8233. }
  8234. bool pool_has_usable_swork(const struct pool * const pool)
  8235. {
  8236. if (opt_benchmark)
  8237. return true;
  8238. if (pool->swork.tr)
  8239. {
  8240. // GBT
  8241. struct timeval tv_now;
  8242. timer_set_now(&tv_now);
  8243. return blkmk_time_left(pool->swork.tr->tmpl, tv_now.tv_sec);
  8244. }
  8245. return pool->stratum_notify;
  8246. }
  8247. /* Generates stratum based work based on the most recent notify information
  8248. * from the pool. This will keep generating work while a pool is down so we use
  8249. * other means to detect when the pool has died in stratum_thread */
  8250. static void gen_stratum_work(struct pool *pool, struct work *work)
  8251. {
  8252. clean_work(work);
  8253. cg_wlock(&pool->data_lock);
  8254. pool->swork.data_lock_p = &pool->data_lock;
  8255. const int n2size = pool->swork.n2size;
  8256. bytes_resize(&work->nonce2, n2size);
  8257. if (pool->nonce2sz < n2size)
  8258. memset(&bytes_buf(&work->nonce2)[pool->nonce2sz], 0, n2size - pool->nonce2sz);
  8259. memcpy(bytes_buf(&work->nonce2),
  8260. #ifdef WORDS_BIGENDIAN
  8261. // NOTE: On big endian, the most significant bits are stored at the end, so skip the LSBs
  8262. &((char*)&pool->nonce2)[pool->nonce2off],
  8263. #else
  8264. &pool->nonce2,
  8265. #endif
  8266. pool->nonce2sz);
  8267. pool->nonce2++;
  8268. work->pool = pool;
  8269. work->work_restart_id = pool->swork.work_restart_id;
  8270. gen_stratum_work2(work, &pool->swork);
  8271. cgtime(&work->tv_staged);
  8272. }
  8273. void gen_stratum_work2(struct work *work, struct stratum_work *swork)
  8274. {
  8275. unsigned char *coinbase, merkle_root[32], merkle_sha[64];
  8276. uint8_t *merkle_bin;
  8277. uint32_t *data32, *swap32;
  8278. int i;
  8279. /* Generate coinbase */
  8280. coinbase = bytes_buf(&swork->coinbase);
  8281. memcpy(&coinbase[swork->nonce2_offset], bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  8282. /* Downgrade to a read lock to read off the variables */
  8283. if (swork->data_lock_p)
  8284. cg_dwlock(swork->data_lock_p);
  8285. /* Generate merkle root */
  8286. gen_hash(coinbase, merkle_root, bytes_len(&swork->coinbase));
  8287. memcpy(merkle_sha, merkle_root, 32);
  8288. merkle_bin = bytes_buf(&swork->merkle_bin);
  8289. for (i = 0; i < swork->merkles; ++i, merkle_bin += 32) {
  8290. memcpy(merkle_sha + 32, merkle_bin, 32);
  8291. gen_hash(merkle_sha, merkle_root, 64);
  8292. memcpy(merkle_sha, merkle_root, 32);
  8293. }
  8294. data32 = (uint32_t *)merkle_sha;
  8295. swap32 = (uint32_t *)merkle_root;
  8296. flip32(swap32, data32);
  8297. memcpy(&work->data[0], swork->header1, 36);
  8298. memcpy(&work->data[36], merkle_root, 32);
  8299. *((uint32_t*)&work->data[68]) = htobe32(swork->ntime + timer_elapsed(&swork->tv_received, NULL));
  8300. memcpy(&work->data[72], swork->diffbits, 4);
  8301. memset(&work->data[76], 0, 4); // nonce
  8302. memcpy(&work->data[80], workpadding_bin, 48);
  8303. work->ntime_roll_limits = swork->ntime_roll_limits;
  8304. /* Copy parameters required for share submission */
  8305. memcpy(work->target, swork->target, sizeof(work->target));
  8306. work->job_id = maybe_strdup(swork->job_id);
  8307. work->nonce1 = maybe_strdup(swork->nonce1);
  8308. if (swork->data_lock_p)
  8309. cg_runlock(swork->data_lock_p);
  8310. if (opt_debug)
  8311. {
  8312. char header[161];
  8313. char nonce2hex[(bytes_len(&work->nonce2) * 2) + 1];
  8314. bin2hex(header, work->data, 80);
  8315. bin2hex(nonce2hex, bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  8316. applog(LOG_DEBUG, "Generated stratum header %s", header);
  8317. applog(LOG_DEBUG, "Work job_id %s nonce2 %s", work->job_id, nonce2hex);
  8318. }
  8319. calc_midstate(work);
  8320. local_work++;
  8321. work->stratum = true;
  8322. work->blk.nonce = 0;
  8323. work->id = total_work++;
  8324. work->longpoll = false;
  8325. work->getwork_mode = GETWORK_MODE_STRATUM;
  8326. calc_diff(work, 0);
  8327. }
  8328. void request_work(struct thr_info *thr)
  8329. {
  8330. struct cgpu_info *cgpu = thr->cgpu;
  8331. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  8332. /* Tell the watchdog thread this thread is waiting on getwork and
  8333. * should not be restarted */
  8334. thread_reportout(thr);
  8335. // HACK: Since get_work still blocks, reportout all processors dependent on this thread
  8336. for (struct cgpu_info *proc = thr->cgpu->next_proc; proc; proc = proc->next_proc)
  8337. {
  8338. if (proc->threads)
  8339. break;
  8340. thread_reportout(proc->thr[0]);
  8341. }
  8342. cgtime(&dev_stats->_get_start);
  8343. }
  8344. // FIXME: Make this non-blocking (and remove HACK above)
  8345. struct work *get_work(struct thr_info *thr)
  8346. {
  8347. const int thr_id = thr->id;
  8348. struct cgpu_info *cgpu = thr->cgpu;
  8349. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  8350. struct cgminer_stats *pool_stats;
  8351. struct timeval tv_get;
  8352. struct work *work = NULL;
  8353. applog(LOG_DEBUG, "%"PRIpreprv": Popping work from get queue to get work", cgpu->proc_repr);
  8354. while (!work) {
  8355. work = hash_pop();
  8356. if (stale_work(work, false)) {
  8357. staged_full = false; // It wasn't really full, since it was stale :(
  8358. discard_work(work);
  8359. work = NULL;
  8360. wake_gws();
  8361. }
  8362. }
  8363. last_getwork = time(NULL);
  8364. applog(LOG_DEBUG, "%"PRIpreprv": Got work %d from get queue to get work for thread %d",
  8365. cgpu->proc_repr, work->id, thr_id);
  8366. work->thr_id = thr_id;
  8367. thread_reportin(thr);
  8368. // HACK: Since get_work still blocks, reportin all processors dependent on this thread
  8369. for (struct cgpu_info *proc = thr->cgpu->next_proc; proc; proc = proc->next_proc)
  8370. {
  8371. if (proc->threads)
  8372. break;
  8373. thread_reportin(proc->thr[0]);
  8374. }
  8375. work->mined = true;
  8376. work->blk.nonce = 0;
  8377. cgtime(&tv_get);
  8378. timersub(&tv_get, &dev_stats->_get_start, &tv_get);
  8379. timeradd(&tv_get, &dev_stats->getwork_wait, &dev_stats->getwork_wait);
  8380. if (timercmp(&tv_get, &dev_stats->getwork_wait_max, >))
  8381. dev_stats->getwork_wait_max = tv_get;
  8382. if (timercmp(&tv_get, &dev_stats->getwork_wait_min, <))
  8383. dev_stats->getwork_wait_min = tv_get;
  8384. ++dev_stats->getwork_calls;
  8385. pool_stats = &(work->pool->cgminer_stats);
  8386. timeradd(&tv_get, &pool_stats->getwork_wait, &pool_stats->getwork_wait);
  8387. if (timercmp(&tv_get, &pool_stats->getwork_wait_max, >))
  8388. pool_stats->getwork_wait_max = tv_get;
  8389. if (timercmp(&tv_get, &pool_stats->getwork_wait_min, <))
  8390. pool_stats->getwork_wait_min = tv_get;
  8391. ++pool_stats->getwork_calls;
  8392. if (work->work_difficulty < 1)
  8393. {
  8394. if (unlikely(work->work_difficulty < cgpu->min_nonce_diff))
  8395. {
  8396. if (cgpu->min_nonce_diff - work->work_difficulty > 1./0x10000000)
  8397. applog(LOG_WARNING, "%"PRIpreprv": Using work with lower difficulty than device supports",
  8398. cgpu->proc_repr);
  8399. work->nonce_diff = cgpu->min_nonce_diff;
  8400. }
  8401. else
  8402. work->nonce_diff = work->work_difficulty;
  8403. }
  8404. else
  8405. work->nonce_diff = 1;
  8406. return work;
  8407. }
  8408. struct dupe_hash_elem {
  8409. uint8_t hash[0x20];
  8410. struct timeval tv_prune;
  8411. UT_hash_handle hh;
  8412. };
  8413. static
  8414. void _submit_work_async(struct work *work)
  8415. {
  8416. applog(LOG_DEBUG, "Pushing submit work to work thread");
  8417. if (opt_benchmark)
  8418. {
  8419. json_t * const jn = json_null(), *result = NULL;
  8420. work_check_for_block(work);
  8421. {
  8422. static struct dupe_hash_elem *dupe_hashes;
  8423. struct dupe_hash_elem *dhe, *dhetmp;
  8424. HASH_FIND(hh, dupe_hashes, &work->hash, sizeof(dhe->hash), dhe);
  8425. if (dhe)
  8426. result = json_string("duplicate");
  8427. else
  8428. {
  8429. struct timeval tv_now;
  8430. timer_set_now(&tv_now);
  8431. // Prune old entries
  8432. HASH_ITER(hh, dupe_hashes, dhe, dhetmp)
  8433. {
  8434. if (!timer_passed(&dhe->tv_prune, &tv_now))
  8435. break;
  8436. HASH_DEL(dupe_hashes, dhe);
  8437. free(dhe);
  8438. }
  8439. dhe = malloc(sizeof(*dhe));
  8440. memcpy(dhe->hash, work->hash, sizeof(dhe->hash));
  8441. timer_set_delay(&dhe->tv_prune, &tv_now, 337500000);
  8442. HASH_ADD(hh, dupe_hashes, hash, sizeof(dhe->hash), dhe);
  8443. }
  8444. }
  8445. if (result)
  8446. {}
  8447. else
  8448. if (stale_work(work, true))
  8449. {
  8450. char stalemsg[0x10];
  8451. snprintf(stalemsg, sizeof(stalemsg), "stale %us", benchmark_update_interval * (work->pool->work_restart_id - work->work_restart_id));
  8452. result = json_string(stalemsg);
  8453. }
  8454. else
  8455. result = json_incref(jn);
  8456. share_result(jn, result, jn, work, false, "");
  8457. free_work(work);
  8458. json_decref(result);
  8459. json_decref(jn);
  8460. return;
  8461. }
  8462. mutex_lock(&submitting_lock);
  8463. ++total_submitting;
  8464. DL_APPEND(submit_waiting, work);
  8465. mutex_unlock(&submitting_lock);
  8466. notifier_wake(submit_waiting_notifier);
  8467. }
  8468. /* Submit a copy of the tested, statistic recorded work item asynchronously */
  8469. static void submit_work_async2(struct work *work, struct timeval *tv_work_found)
  8470. {
  8471. if (tv_work_found)
  8472. copy_time(&work->tv_work_found, tv_work_found);
  8473. _submit_work_async(work);
  8474. }
  8475. void inc_hw_errors3(struct thr_info *thr, const struct work *work, const uint32_t *bad_nonce_p, float nonce_diff)
  8476. {
  8477. struct cgpu_info * const cgpu = thr->cgpu;
  8478. if (bad_nonce_p)
  8479. {
  8480. if (bad_nonce_p == UNKNOWN_NONCE)
  8481. applog(LOG_DEBUG, "%"PRIpreprv": invalid nonce - HW error",
  8482. cgpu->proc_repr);
  8483. else
  8484. applog(LOG_DEBUG, "%"PRIpreprv": invalid nonce (%08lx) - HW error",
  8485. cgpu->proc_repr, (unsigned long)be32toh(*bad_nonce_p));
  8486. }
  8487. mutex_lock(&stats_lock);
  8488. hw_errors++;
  8489. ++cgpu->hw_errors;
  8490. if (bad_nonce_p)
  8491. {
  8492. total_bad_diff1 += nonce_diff;
  8493. cgpu->bad_diff1 += nonce_diff;
  8494. }
  8495. mutex_unlock(&stats_lock);
  8496. if (thr->cgpu->drv->hw_error)
  8497. thr->cgpu->drv->hw_error(thr);
  8498. }
  8499. void work_hash(struct work * const work)
  8500. {
  8501. #ifdef USE_SCRYPT
  8502. if (opt_scrypt)
  8503. scrypt_hash_data(work->hash, work->data);
  8504. else
  8505. #endif
  8506. hash_data(work->hash, work->data);
  8507. }
  8508. static
  8509. bool test_hash(const void * const phash, const float diff)
  8510. {
  8511. const uint32_t * const hash = phash;
  8512. if (diff >= 1.)
  8513. // FIXME: > 1 should check more
  8514. return !hash[7];
  8515. const uint32_t Htarg = (uint32_t)ceil((1. / diff) - 1);
  8516. const uint32_t tmp_hash7 = le32toh(hash[7]);
  8517. applog(LOG_DEBUG, "htarget %08lx hash %08lx",
  8518. (long unsigned int)Htarg,
  8519. (long unsigned int)tmp_hash7);
  8520. return (tmp_hash7 <= Htarg);
  8521. }
  8522. enum test_nonce2_result _test_nonce2(struct work *work, uint32_t nonce, bool checktarget)
  8523. {
  8524. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  8525. *work_nonce = htole32(nonce);
  8526. work_hash(work);
  8527. if (!test_hash(work->hash, work->nonce_diff))
  8528. return TNR_BAD;
  8529. if (checktarget && !hash_target_check_v(work->hash, work->target))
  8530. {
  8531. bool high_hash = true;
  8532. struct pool * const pool = work->pool;
  8533. if (pool->stratum_active)
  8534. {
  8535. // Some stratum pools are buggy and expect difficulty changes to be immediate retroactively, so if the target has changed, check and submit just in case
  8536. if (memcmp(pool->next_target, work->target, sizeof(work->target)))
  8537. {
  8538. applog(LOG_DEBUG, "Stratum pool %u target has changed since work job issued, checking that too",
  8539. pool->pool_no);
  8540. if (hash_target_check_v(work->hash, pool->next_target))
  8541. high_hash = false;
  8542. }
  8543. }
  8544. if (high_hash)
  8545. return TNR_HIGH;
  8546. }
  8547. return TNR_GOOD;
  8548. }
  8549. /* Returns true if nonce for work was a valid share */
  8550. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  8551. {
  8552. return submit_noffset_nonce(thr, work, nonce, 0);
  8553. }
  8554. /* Allows drivers to submit work items where the driver has changed the ntime
  8555. * value by noffset. Must be only used with a work protocol that does not ntime
  8556. * roll itself intrinsically to generate work (eg stratum). We do not touch
  8557. * the original work struct, but the copy of it only. */
  8558. bool submit_noffset_nonce(struct thr_info *thr, struct work *work_in, uint32_t nonce,
  8559. int noffset)
  8560. {
  8561. struct work *work = make_work();
  8562. _copy_work(work, work_in, noffset);
  8563. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  8564. struct timeval tv_work_found;
  8565. enum test_nonce2_result res;
  8566. bool ret = true;
  8567. thread_reportout(thr);
  8568. cgtime(&tv_work_found);
  8569. *work_nonce = htole32(nonce);
  8570. work->thr_id = thr->id;
  8571. /* Do one last check before attempting to submit the work */
  8572. /* Side effect: sets work->data and work->hash for us */
  8573. res = test_nonce2(work, nonce);
  8574. if (unlikely(res == TNR_BAD))
  8575. {
  8576. inc_hw_errors(thr, work, nonce);
  8577. ret = false;
  8578. goto out;
  8579. }
  8580. mutex_lock(&stats_lock);
  8581. total_diff1 += work->nonce_diff;
  8582. thr ->cgpu->diff1 += work->nonce_diff;
  8583. work->pool->diff1 += work->nonce_diff;
  8584. thr->cgpu->last_device_valid_work = time(NULL);
  8585. mutex_unlock(&stats_lock);
  8586. if (noncelog_file)
  8587. noncelog(work);
  8588. if (res == TNR_HIGH)
  8589. {
  8590. // Share above target, normal
  8591. /* Check the diff of the share, even if it didn't reach the
  8592. * target, just to set the best share value if it's higher. */
  8593. share_diff(work);
  8594. goto out;
  8595. }
  8596. submit_work_async2(work, &tv_work_found);
  8597. work = NULL; // Taken by submit_work_async2
  8598. out:
  8599. if (work)
  8600. free_work(work);
  8601. thread_reportin(thr);
  8602. return ret;
  8603. }
  8604. // return true of we should stop working on this piece of work
  8605. // returning false means we will keep scanning for a nonce
  8606. // assumptions: work->blk.nonce is the number of nonces completed in the work
  8607. // see minerloop_scanhash comments for more details & usage
  8608. bool abandon_work(struct work *work, struct timeval *wdiff, uint64_t max_hashes)
  8609. {
  8610. if (work->blk.nonce == 0xffffffff || // known we are scanning a full nonce range
  8611. wdiff->tv_sec > opt_scantime || // scan-time has elapsed (user specified, default 60s)
  8612. work->blk.nonce >= 0xfffffffe - max_hashes || // are there enough nonces left in the work
  8613. max_hashes >= 0xfffffffe || // assume we are scanning a full nonce range
  8614. stale_work(work, false)) // work is stale
  8615. return true;
  8616. return false;
  8617. }
  8618. void __thr_being_msg(int prio, struct thr_info *thr, const char *being)
  8619. {
  8620. struct cgpu_info *proc = thr->cgpu;
  8621. if (proc->threads > 1)
  8622. applog(prio, "%"PRIpreprv" (thread %d) %s", proc->proc_repr, thr->id, being);
  8623. else
  8624. applog(prio, "%"PRIpreprv" %s", proc->proc_repr, being);
  8625. }
  8626. // Called by asynchronous minerloops, when they find their processor should be disabled
  8627. void mt_disable_start(struct thr_info *mythr)
  8628. {
  8629. struct cgpu_info *cgpu = mythr->cgpu;
  8630. struct device_drv *drv = cgpu->drv;
  8631. if (drv->thread_disable)
  8632. drv->thread_disable(mythr);
  8633. hashmeter2(mythr);
  8634. __thr_being_msg(LOG_WARNING, mythr, "being disabled");
  8635. mythr->rolling = mythr->cgpu->rolling = 0;
  8636. thread_reportout(mythr);
  8637. mythr->_mt_disable_called = true;
  8638. }
  8639. /* Put a new unqueued work item in cgpu->unqueued_work under cgpu->qlock till
  8640. * the driver tells us it's full so that it may extract the work item using
  8641. * the get_queued() function which adds it to the hashtable on
  8642. * cgpu->queued_work. */
  8643. static void fill_queue(struct thr_info *mythr, struct cgpu_info *cgpu, struct device_drv *drv, const int thr_id)
  8644. {
  8645. thread_reportout(mythr);
  8646. do {
  8647. bool need_work;
  8648. /* Do this lockless just to know if we need more unqueued work. */
  8649. need_work = (!cgpu->unqueued_work);
  8650. /* get_work is a blocking function so do it outside of lock
  8651. * to prevent deadlocks with other locks. */
  8652. if (need_work) {
  8653. struct work *work = get_work(mythr);
  8654. wr_lock(&cgpu->qlock);
  8655. /* Check we haven't grabbed work somehow between
  8656. * checking and picking up the lock. */
  8657. if (likely(!cgpu->unqueued_work))
  8658. cgpu->unqueued_work = work;
  8659. else
  8660. need_work = false;
  8661. wr_unlock(&cgpu->qlock);
  8662. if (unlikely(!need_work))
  8663. discard_work(work);
  8664. }
  8665. /* The queue_full function should be used by the driver to
  8666. * actually place work items on the physical device if it
  8667. * does have a queue. */
  8668. } while (drv->queue_full && !drv->queue_full(cgpu));
  8669. }
  8670. /* Add a work item to a cgpu's queued hashlist */
  8671. void __add_queued(struct cgpu_info *cgpu, struct work *work)
  8672. {
  8673. cgpu->queued_count++;
  8674. HASH_ADD_INT(cgpu->queued_work, id, work);
  8675. }
  8676. /* This function is for retrieving one work item from the unqueued pointer and
  8677. * adding it to the hashtable of queued work. Code using this function must be
  8678. * able to handle NULL as a return which implies there is no work available. */
  8679. struct work *get_queued(struct cgpu_info *cgpu)
  8680. {
  8681. struct work *work = NULL;
  8682. wr_lock(&cgpu->qlock);
  8683. if (cgpu->unqueued_work) {
  8684. work = cgpu->unqueued_work;
  8685. if (unlikely(stale_work(work, false))) {
  8686. discard_work(work);
  8687. work = NULL;
  8688. wake_gws();
  8689. } else
  8690. __add_queued(cgpu, work);
  8691. cgpu->unqueued_work = NULL;
  8692. }
  8693. wr_unlock(&cgpu->qlock);
  8694. return work;
  8695. }
  8696. void add_queued(struct cgpu_info *cgpu, struct work *work)
  8697. {
  8698. wr_lock(&cgpu->qlock);
  8699. __add_queued(cgpu, work);
  8700. wr_unlock(&cgpu->qlock);
  8701. }
  8702. /* Get fresh work and add it to cgpu's queued hashlist */
  8703. struct work *get_queue_work(struct thr_info *thr, struct cgpu_info *cgpu, int thr_id)
  8704. {
  8705. struct work *work = get_work(thr);
  8706. add_queued(cgpu, work);
  8707. return work;
  8708. }
  8709. /* This function is for finding an already queued work item in the
  8710. * given que hashtable. Code using this function must be able
  8711. * to handle NULL as a return which implies there is no matching work.
  8712. * The calling function must lock access to the que if it is required.
  8713. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  8714. struct work *__find_work_bymidstate(struct work *que, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  8715. {
  8716. struct work *work, *tmp, *ret = NULL;
  8717. HASH_ITER(hh, que, work, tmp) {
  8718. if (memcmp(work->midstate, midstate, midstatelen) == 0 &&
  8719. memcmp(work->data + offset, data, datalen) == 0) {
  8720. ret = work;
  8721. break;
  8722. }
  8723. }
  8724. return ret;
  8725. }
  8726. /* This function is for finding an already queued work item in the
  8727. * device's queued_work hashtable. Code using this function must be able
  8728. * to handle NULL as a return which implies there is no matching work.
  8729. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  8730. struct work *find_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  8731. {
  8732. struct work *ret;
  8733. rd_lock(&cgpu->qlock);
  8734. ret = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  8735. rd_unlock(&cgpu->qlock);
  8736. return ret;
  8737. }
  8738. struct work *clone_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  8739. {
  8740. struct work *work, *ret = NULL;
  8741. rd_lock(&cgpu->qlock);
  8742. work = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  8743. if (work)
  8744. ret = copy_work(work);
  8745. rd_unlock(&cgpu->qlock);
  8746. return ret;
  8747. }
  8748. void __work_completed(struct cgpu_info *cgpu, struct work *work)
  8749. {
  8750. cgpu->queued_count--;
  8751. HASH_DEL(cgpu->queued_work, work);
  8752. }
  8753. /* This iterates over a queued hashlist finding work started more than secs
  8754. * seconds ago and discards the work as completed. The driver must set the
  8755. * work->tv_work_start value appropriately. Returns the number of items aged. */
  8756. int age_queued_work(struct cgpu_info *cgpu, double secs)
  8757. {
  8758. struct work *work, *tmp;
  8759. struct timeval tv_now;
  8760. int aged = 0;
  8761. cgtime(&tv_now);
  8762. wr_lock(&cgpu->qlock);
  8763. HASH_ITER(hh, cgpu->queued_work, work, tmp) {
  8764. if (tdiff(&tv_now, &work->tv_work_start) > secs) {
  8765. __work_completed(cgpu, work);
  8766. aged++;
  8767. }
  8768. }
  8769. wr_unlock(&cgpu->qlock);
  8770. return aged;
  8771. }
  8772. /* This function should be used by queued device drivers when they're sure
  8773. * the work struct is no longer in use. */
  8774. void work_completed(struct cgpu_info *cgpu, struct work *work)
  8775. {
  8776. wr_lock(&cgpu->qlock);
  8777. __work_completed(cgpu, work);
  8778. wr_unlock(&cgpu->qlock);
  8779. free_work(work);
  8780. }
  8781. /* Combines find_queued_work_bymidstate and work_completed in one function
  8782. * withOUT destroying the work so the driver must free it. */
  8783. struct work *take_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  8784. {
  8785. struct work *work;
  8786. wr_lock(&cgpu->qlock);
  8787. work = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  8788. if (work)
  8789. __work_completed(cgpu, work);
  8790. wr_unlock(&cgpu->qlock);
  8791. return work;
  8792. }
  8793. void flush_queue(struct cgpu_info *cgpu)
  8794. {
  8795. struct work *work = NULL;
  8796. wr_lock(&cgpu->qlock);
  8797. work = cgpu->unqueued_work;
  8798. cgpu->unqueued_work = NULL;
  8799. wr_unlock(&cgpu->qlock);
  8800. if (work) {
  8801. free_work(work);
  8802. applog(LOG_DEBUG, "Discarded queued work item");
  8803. }
  8804. }
  8805. /* This version of hash work is for devices that are fast enough to always
  8806. * perform a full nonce range and need a queue to maintain the device busy.
  8807. * Work creation and destruction is not done from within this function
  8808. * directly. */
  8809. void hash_queued_work(struct thr_info *mythr)
  8810. {
  8811. const long cycle = opt_log_interval / 5 ? : 1;
  8812. struct timeval tv_start = {0, 0}, tv_end;
  8813. struct cgpu_info *cgpu = mythr->cgpu;
  8814. struct device_drv *drv = cgpu->drv;
  8815. const int thr_id = mythr->id;
  8816. int64_t hashes_done = 0;
  8817. if (unlikely(cgpu->deven != DEV_ENABLED))
  8818. mt_disable(mythr);
  8819. while (likely(!cgpu->shutdown)) {
  8820. struct timeval diff;
  8821. int64_t hashes;
  8822. fill_queue(mythr, cgpu, drv, thr_id);
  8823. thread_reportin(mythr);
  8824. hashes = drv->scanwork(mythr);
  8825. /* Reset the bool here in case the driver looks for it
  8826. * synchronously in the scanwork loop. */
  8827. mythr->work_restart = false;
  8828. if (unlikely(hashes == -1 )) {
  8829. applog(LOG_ERR, "%s %d failure, disabling!", drv->name, cgpu->device_id);
  8830. cgpu->deven = DEV_DISABLED;
  8831. dev_error(cgpu, REASON_THREAD_ZERO_HASH);
  8832. mt_disable(mythr);
  8833. }
  8834. hashes_done += hashes;
  8835. cgtime(&tv_end);
  8836. timersub(&tv_end, &tv_start, &diff);
  8837. if (diff.tv_sec >= cycle) {
  8838. hashmeter(thr_id, &diff, hashes_done);
  8839. hashes_done = 0;
  8840. copy_time(&tv_start, &tv_end);
  8841. }
  8842. if (unlikely(mythr->pause || cgpu->deven != DEV_ENABLED))
  8843. mt_disable(mythr);
  8844. if (unlikely(mythr->work_restart)) {
  8845. flush_queue(cgpu);
  8846. if (drv->flush_work)
  8847. drv->flush_work(cgpu);
  8848. }
  8849. }
  8850. // cgpu->deven = DEV_DISABLED; set in miner_thread
  8851. }
  8852. // Called by minerloop, when it is re-enabling a processor
  8853. void mt_disable_finish(struct thr_info *mythr)
  8854. {
  8855. struct device_drv *drv = mythr->cgpu->drv;
  8856. thread_reportin(mythr);
  8857. __thr_being_msg(LOG_WARNING, mythr, "being re-enabled");
  8858. if (drv->thread_enable)
  8859. drv->thread_enable(mythr);
  8860. mythr->_mt_disable_called = false;
  8861. }
  8862. // Called by synchronous minerloops, when they find their processor should be disabled
  8863. // Calls mt_disable_start, waits until it's re-enabled, then calls mt_disable_finish
  8864. void mt_disable(struct thr_info *mythr)
  8865. {
  8866. const struct cgpu_info * const cgpu = mythr->cgpu;
  8867. mt_disable_start(mythr);
  8868. applog(LOG_DEBUG, "Waiting for wakeup notification in miner thread");
  8869. do {
  8870. notifier_read(mythr->notifier);
  8871. } while (mythr->pause || cgpu->deven != DEV_ENABLED);
  8872. mt_disable_finish(mythr);
  8873. }
  8874. enum {
  8875. STAT_SLEEP_INTERVAL = 1,
  8876. STAT_CTR_INTERVAL = 10000000,
  8877. FAILURE_INTERVAL = 30,
  8878. };
  8879. /* Stage another work item from the work returned in a longpoll */
  8880. 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)
  8881. {
  8882. bool rc;
  8883. work->rolltime = rolltime;
  8884. rc = work_decode(pool, work, val);
  8885. if (unlikely(!rc)) {
  8886. applog(LOG_ERR, "Could not convert longpoll data to work");
  8887. free_work(work);
  8888. return;
  8889. }
  8890. total_getworks++;
  8891. pool->getwork_requested++;
  8892. work->pool = pool;
  8893. copy_time(&work->tv_getwork, tv_lp);
  8894. copy_time(&work->tv_getwork_reply, tv_lp_reply);
  8895. calc_diff(work, 0);
  8896. if (pool->enabled == POOL_REJECTING)
  8897. work->mandatory = true;
  8898. work->longpoll = true;
  8899. work->getwork_mode = GETWORK_MODE_LP;
  8900. update_last_work(work);
  8901. /* We'll be checking this work item twice, but we already know it's
  8902. * from a new block so explicitly force the new block detection now
  8903. * rather than waiting for it to hit the stage thread. This also
  8904. * allows testwork to know whether LP discovered the block or not. */
  8905. test_work_current(work);
  8906. /* Don't use backup LPs as work if we have failover-only enabled. Use
  8907. * the longpoll work from a pool that has been rejecting shares as a
  8908. * way to detect when the pool has recovered.
  8909. */
  8910. if (pool != current_pool() && opt_fail_only && pool->enabled != POOL_REJECTING) {
  8911. free_work(work);
  8912. return;
  8913. }
  8914. work = clone_work(work);
  8915. applog(LOG_DEBUG, "Pushing converted work to stage thread");
  8916. stage_work(work);
  8917. applog(LOG_DEBUG, "Converted longpoll data to work");
  8918. }
  8919. /* If we want longpoll, enable it for the chosen default pool, or, if
  8920. * the pool does not support longpoll, find the first one that does
  8921. * and use its longpoll support */
  8922. static
  8923. struct pool *_select_longpoll_pool(struct pool *cp, bool(*func)(struct pool *))
  8924. {
  8925. int i;
  8926. if (func(cp))
  8927. return cp;
  8928. for (i = 0; i < total_pools; i++) {
  8929. struct pool *pool = pools[i];
  8930. if (func(pool))
  8931. return pool;
  8932. }
  8933. return NULL;
  8934. }
  8935. /* This will make the longpoll thread wait till it's the current pool, or it
  8936. * has been flagged as rejecting, before attempting to open any connections.
  8937. */
  8938. static void wait_lpcurrent(struct pool *pool)
  8939. {
  8940. mutex_lock(&lp_lock);
  8941. while (!cnx_needed(pool))
  8942. {
  8943. pool->lp_active = false;
  8944. pthread_cond_wait(&lp_cond, &lp_lock);
  8945. }
  8946. mutex_unlock(&lp_lock);
  8947. }
  8948. static curl_socket_t save_curl_socket(void *vpool, __maybe_unused curlsocktype purpose, struct curl_sockaddr *addr) {
  8949. struct pool *pool = vpool;
  8950. curl_socket_t sock = bfg_socket(addr->family, addr->socktype, addr->protocol);
  8951. pool->lp_socket = sock;
  8952. return sock;
  8953. }
  8954. static void *longpoll_thread(void *userdata)
  8955. {
  8956. struct pool *cp = (struct pool *)userdata;
  8957. /* This *pool is the source of the actual longpoll, not the pool we've
  8958. * tied it to */
  8959. struct timeval start, reply, end;
  8960. struct pool *pool = NULL;
  8961. char threadname[20];
  8962. CURL *curl = NULL;
  8963. int failures = 0;
  8964. char *lp_url;
  8965. int rolltime;
  8966. #ifndef HAVE_PTHREAD_CANCEL
  8967. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  8968. #endif
  8969. snprintf(threadname, 20, "longpoll%u", cp->pool_no);
  8970. RenameThread(threadname);
  8971. curl = curl_easy_init();
  8972. if (unlikely(!curl)) {
  8973. applog(LOG_ERR, "CURL initialisation failed");
  8974. return NULL;
  8975. }
  8976. retry_pool:
  8977. pool = select_longpoll_pool(cp);
  8978. if (!pool) {
  8979. applog(LOG_WARNING, "No suitable long-poll found for %s", cp->rpc_url);
  8980. while (!pool) {
  8981. cgsleep_ms(60000);
  8982. pool = select_longpoll_pool(cp);
  8983. }
  8984. }
  8985. if (pool->has_stratum) {
  8986. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  8987. cp->rpc_url, pool->rpc_url);
  8988. goto out;
  8989. }
  8990. /* Any longpoll from any pool is enough for this to be true */
  8991. have_longpoll = true;
  8992. wait_lpcurrent(cp);
  8993. {
  8994. lp_url = pool->lp_url;
  8995. if (cp == pool)
  8996. applog(LOG_WARNING, "Long-polling activated for %s (%s)", lp_url, pool_protocol_name(pool->lp_proto));
  8997. else
  8998. applog(LOG_WARNING, "Long-polling activated for %s via %s (%s)", cp->rpc_url, lp_url, pool_protocol_name(pool->lp_proto));
  8999. }
  9000. while (42) {
  9001. json_t *val, *soval;
  9002. struct work *work = make_work();
  9003. char *lpreq;
  9004. lpreq = prepare_rpc_req(work, pool->lp_proto, pool->lp_id);
  9005. work->pool = pool;
  9006. if (!lpreq)
  9007. {
  9008. free_work(work);
  9009. goto lpfail;
  9010. }
  9011. wait_lpcurrent(cp);
  9012. cgtime(&start);
  9013. /* Longpoll connections can be persistent for a very long time
  9014. * and any number of issues could have come up in the meantime
  9015. * so always establish a fresh connection instead of relying on
  9016. * a persistent one. */
  9017. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  9018. curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, save_curl_socket);
  9019. curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, pool);
  9020. val = json_rpc_call(curl, lp_url, pool->rpc_userpass,
  9021. lpreq, false, true, &rolltime, pool, false);
  9022. pool->lp_socket = CURL_SOCKET_BAD;
  9023. cgtime(&reply);
  9024. free(lpreq);
  9025. if (likely(val)) {
  9026. soval = json_object_get(json_object_get(val, "result"), "submitold");
  9027. if (soval)
  9028. pool->submit_old = json_is_true(soval);
  9029. else
  9030. pool->submit_old = false;
  9031. convert_to_work(val, rolltime, pool, work, &start, &reply);
  9032. failures = 0;
  9033. json_decref(val);
  9034. } else {
  9035. /* Some pools regularly drop the longpoll request so
  9036. * only see this as longpoll failure if it happens
  9037. * immediately and just restart it the rest of the
  9038. * time. */
  9039. cgtime(&end);
  9040. free_work(work);
  9041. if (end.tv_sec - start.tv_sec <= 30)
  9042. {
  9043. if (failures == 1)
  9044. applog(LOG_WARNING, "longpoll failed for %s, retrying every 30s", lp_url);
  9045. lpfail:
  9046. cgsleep_ms(30000);
  9047. }
  9048. }
  9049. if (pool != cp) {
  9050. pool = select_longpoll_pool(cp);
  9051. if (pool->has_stratum) {
  9052. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  9053. cp->rpc_url, pool->rpc_url);
  9054. break;
  9055. }
  9056. if (unlikely(!pool))
  9057. goto retry_pool;
  9058. }
  9059. if (unlikely(pool->removed))
  9060. break;
  9061. }
  9062. out:
  9063. pool->lp_active = false;
  9064. curl_easy_cleanup(curl);
  9065. return NULL;
  9066. }
  9067. static void stop_longpoll(void)
  9068. {
  9069. int i;
  9070. want_longpoll = false;
  9071. for (i = 0; i < total_pools; ++i)
  9072. {
  9073. struct pool *pool = pools[i];
  9074. if (unlikely(!pool->lp_started))
  9075. continue;
  9076. pool->lp_started = false;
  9077. pthread_cancel(pool->longpoll_thread);
  9078. }
  9079. have_longpoll = false;
  9080. }
  9081. static void start_longpoll(void)
  9082. {
  9083. int i;
  9084. want_longpoll = true;
  9085. for (i = 0; i < total_pools; ++i)
  9086. {
  9087. struct pool *pool = pools[i];
  9088. if (unlikely(pool->removed || pool->lp_started || !pool->lp_url))
  9089. continue;
  9090. pool->lp_started = true;
  9091. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  9092. quit(1, "Failed to create pool longpoll thread");
  9093. }
  9094. }
  9095. void reinit_device(struct cgpu_info *cgpu)
  9096. {
  9097. if (cgpu->drv->reinit_device)
  9098. cgpu->drv->reinit_device(cgpu);
  9099. }
  9100. static struct timeval rotate_tv;
  9101. /* We reap curls if they are unused for over a minute */
  9102. static void reap_curl(struct pool *pool)
  9103. {
  9104. struct curl_ent *ent, *iter;
  9105. struct timeval now;
  9106. int reaped = 0;
  9107. cgtime(&now);
  9108. mutex_lock(&pool->pool_lock);
  9109. LL_FOREACH_SAFE(pool->curllist, ent, iter) {
  9110. if (pool->curls < 2)
  9111. break;
  9112. if (now.tv_sec - ent->tv.tv_sec > 300) {
  9113. reaped++;
  9114. pool->curls--;
  9115. LL_DELETE(pool->curllist, ent);
  9116. curl_easy_cleanup(ent->curl);
  9117. free(ent);
  9118. }
  9119. }
  9120. mutex_unlock(&pool->pool_lock);
  9121. if (reaped)
  9122. applog(LOG_DEBUG, "Reaped %d curl%s from pool %d", reaped, reaped > 1 ? "s" : "", pool->pool_no);
  9123. }
  9124. static void *watchpool_thread(void __maybe_unused *userdata)
  9125. {
  9126. int intervals = 0;
  9127. #ifndef HAVE_PTHREAD_CANCEL
  9128. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  9129. #endif
  9130. RenameThread("watchpool");
  9131. while (42) {
  9132. struct timeval now;
  9133. int i;
  9134. if (++intervals > 20)
  9135. intervals = 0;
  9136. cgtime(&now);
  9137. for (i = 0; i < total_pools; i++) {
  9138. struct pool *pool = pools[i];
  9139. if (!opt_benchmark)
  9140. reap_curl(pool);
  9141. /* Get a rolling utility per pool over 10 mins */
  9142. if (intervals > 19) {
  9143. int shares = pool->diff1 - pool->last_shares;
  9144. pool->last_shares = pool->diff1;
  9145. pool->utility = (pool->utility + (double)shares * 0.63) / 1.63;
  9146. pool->shares = pool->utility;
  9147. }
  9148. if (pool->enabled == POOL_DISABLED)
  9149. continue;
  9150. /* Don't start testing any pools if the test threads
  9151. * from startup are still doing their first attempt. */
  9152. if (unlikely(pool->testing)) {
  9153. pthread_join(pool->test_thread, NULL);
  9154. }
  9155. /* Test pool is idle once every minute */
  9156. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 30) {
  9157. if (pool_active(pool, true) && pool_tclear(pool, &pool->idle))
  9158. pool_resus(pool);
  9159. }
  9160. /* Only switch pools if the failback pool has been
  9161. * alive for more than 5 minutes (default) to prevent
  9162. * intermittently failing pools from being used. */
  9163. if (!pool->idle && pool->enabled == POOL_ENABLED && pool_strategy == POOL_FAILOVER && pool->prio < cp_prio() && now.tv_sec - pool->tv_idle.tv_sec > opt_fail_switch_delay)
  9164. {
  9165. if (opt_fail_switch_delay % 60)
  9166. applog(LOG_WARNING, "Pool %d %s stable for %d second%s",
  9167. pool->pool_no, pool->rpc_url,
  9168. opt_fail_switch_delay,
  9169. (opt_fail_switch_delay == 1 ? "" : "s"));
  9170. else
  9171. applog(LOG_WARNING, "Pool %d %s stable for %d minute%s",
  9172. pool->pool_no, pool->rpc_url,
  9173. opt_fail_switch_delay / 60,
  9174. (opt_fail_switch_delay == 60 ? "" : "s"));
  9175. switch_pools(NULL);
  9176. }
  9177. }
  9178. if (current_pool()->idle)
  9179. switch_pools(NULL);
  9180. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  9181. cgtime(&rotate_tv);
  9182. switch_pools(NULL);
  9183. }
  9184. cgsleep_ms(30000);
  9185. }
  9186. return NULL;
  9187. }
  9188. void mt_enable(struct thr_info *thr)
  9189. {
  9190. applog(LOG_DEBUG, "Waking up thread %d", thr->id);
  9191. notifier_wake(thr->notifier);
  9192. }
  9193. void proc_enable(struct cgpu_info *cgpu)
  9194. {
  9195. int j;
  9196. cgpu->deven = DEV_ENABLED;
  9197. for (j = cgpu->threads ?: 1; j--; )
  9198. mt_enable(cgpu->thr[j]);
  9199. }
  9200. #define device_recovered(cgpu) proc_enable(cgpu)
  9201. void cgpu_set_defaults(struct cgpu_info * const cgpu)
  9202. {
  9203. struct string_elist *setstr_elist;
  9204. const char *p, *p2;
  9205. char replybuf[0x2000];
  9206. size_t L;
  9207. DL_FOREACH(opt_set_device_list, setstr_elist)
  9208. {
  9209. const char * const setstr = setstr_elist->string;
  9210. p = strchr(setstr, ':');
  9211. if (!p)
  9212. p = setstr;
  9213. {
  9214. L = p - setstr;
  9215. char pattern[L + 1];
  9216. if (L)
  9217. memcpy(pattern, setstr, L);
  9218. pattern[L] = '\0';
  9219. if (!cgpu_match(pattern, cgpu))
  9220. continue;
  9221. }
  9222. applog(LOG_DEBUG, "%"PRIpreprv": %s: Matched with set default: %s",
  9223. cgpu->proc_repr, __func__, setstr);
  9224. if (p[0] == ':')
  9225. ++p;
  9226. p2 = strchr(p, '=');
  9227. if (!p2)
  9228. {
  9229. L = strlen(p);
  9230. p2 = "";
  9231. }
  9232. else
  9233. {
  9234. L = p2 - p;
  9235. ++p2;
  9236. }
  9237. char opt[L + 1];
  9238. if (L)
  9239. memcpy(opt, p, L);
  9240. opt[L] = '\0';
  9241. L = strlen(p2);
  9242. char setval[L + 1];
  9243. if (L)
  9244. memcpy(setval, p2, L);
  9245. setval[L] = '\0';
  9246. enum bfg_set_device_replytype success;
  9247. p = proc_set_device(cgpu, opt, setval, replybuf, &success);
  9248. switch (success)
  9249. {
  9250. case SDR_OK:
  9251. applog(LOG_DEBUG, "%"PRIpreprv": Applied rule %s%s%s",
  9252. cgpu->proc_repr, setstr,
  9253. p ? ": " : "", p ?: "");
  9254. break;
  9255. case SDR_ERR:
  9256. case SDR_HELP:
  9257. case SDR_UNKNOWN:
  9258. applog(LOG_DEBUG, "%"PRIpreprv": Applying rule %s: %s",
  9259. cgpu->proc_repr, setstr, p);
  9260. break;
  9261. case SDR_AUTO:
  9262. case SDR_NOSUPP:
  9263. applog(LOG_DEBUG, "%"PRIpreprv": set_device is not implemented (trying to apply rule: %s)",
  9264. cgpu->proc_repr, setstr);
  9265. }
  9266. }
  9267. cgpu->already_set_defaults = true;
  9268. }
  9269. void drv_set_defaults(const struct device_drv * const drv, const void *datap, void *userp, const char * const devpath, const char * const serial, const int mode)
  9270. {
  9271. struct device_drv dummy_drv = *drv;
  9272. struct cgpu_info dummy_cgpu = {
  9273. .drv = &dummy_drv,
  9274. .device = &dummy_cgpu,
  9275. .device_id = -1,
  9276. .proc_id = -1,
  9277. .device_data = userp,
  9278. .device_path = devpath,
  9279. .dev_serial = serial,
  9280. };
  9281. strcpy(dummy_cgpu.proc_repr, drv->name);
  9282. switch (mode)
  9283. {
  9284. case 0:
  9285. dummy_drv.set_device = datap;
  9286. break;
  9287. case 1:
  9288. dummy_drv.set_device = NULL;
  9289. dummy_cgpu.set_device_funcs = datap;
  9290. break;
  9291. }
  9292. cgpu_set_defaults(&dummy_cgpu);
  9293. }
  9294. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  9295. * the screen at regular intervals, and restarts threads if they appear to have
  9296. * died. */
  9297. #define WATCHDOG_SICK_TIME 60
  9298. #define WATCHDOG_DEAD_TIME 600
  9299. #define WATCHDOG_SICK_COUNT (WATCHDOG_SICK_TIME/WATCHDOG_INTERVAL)
  9300. #define WATCHDOG_DEAD_COUNT (WATCHDOG_DEAD_TIME/WATCHDOG_INTERVAL)
  9301. static void *watchdog_thread(void __maybe_unused *userdata)
  9302. {
  9303. const unsigned int interval = WATCHDOG_INTERVAL;
  9304. struct timeval zero_tv;
  9305. #ifndef HAVE_PTHREAD_CANCEL
  9306. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  9307. #endif
  9308. RenameThread("watchdog");
  9309. memset(&zero_tv, 0, sizeof(struct timeval));
  9310. cgtime(&rotate_tv);
  9311. while (1) {
  9312. int i;
  9313. struct timeval now;
  9314. sleep(interval);
  9315. discard_stale();
  9316. hashmeter(-1, &zero_tv, 0);
  9317. #ifdef HAVE_CURSES
  9318. const int ts = total_staged();
  9319. if (curses_active_locked()) {
  9320. change_logwinsize();
  9321. curses_print_status(ts);
  9322. _refresh_devstatus(true);
  9323. touchwin(logwin);
  9324. wrefresh(logwin);
  9325. unlock_curses();
  9326. }
  9327. #endif
  9328. cgtime(&now);
  9329. if (!sched_paused && !should_run()) {
  9330. applog(LOG_WARNING, "Pausing execution as per stop time %02d:%02d scheduled",
  9331. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  9332. if (!schedstart.enable) {
  9333. quit(0, "Terminating execution as planned");
  9334. break;
  9335. }
  9336. applog(LOG_WARNING, "Will restart execution as scheduled at %02d:%02d",
  9337. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  9338. sched_paused = true;
  9339. rd_lock(&mining_thr_lock);
  9340. for (i = 0; i < mining_threads; i++)
  9341. mining_thr[i]->pause = true;
  9342. rd_unlock(&mining_thr_lock);
  9343. } else if (sched_paused && should_run()) {
  9344. applog(LOG_WARNING, "Restarting execution as per start time %02d:%02d scheduled",
  9345. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  9346. if (schedstop.enable)
  9347. applog(LOG_WARNING, "Will pause execution as scheduled at %02d:%02d",
  9348. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  9349. sched_paused = false;
  9350. for (i = 0; i < mining_threads; i++) {
  9351. struct thr_info *thr;
  9352. thr = get_thread(i);
  9353. thr->pause = false;
  9354. }
  9355. for (i = 0; i < total_devices; ++i)
  9356. {
  9357. struct cgpu_info *cgpu = get_devices(i);
  9358. /* Don't touch disabled devices */
  9359. if (cgpu->deven == DEV_DISABLED)
  9360. continue;
  9361. proc_enable(cgpu);
  9362. }
  9363. }
  9364. for (i = 0; i < total_devices; ++i) {
  9365. struct cgpu_info *cgpu = get_devices(i);
  9366. if (!cgpu->disable_watchdog)
  9367. bfg_watchdog(cgpu, &now);
  9368. }
  9369. }
  9370. return NULL;
  9371. }
  9372. void bfg_watchdog(struct cgpu_info * const cgpu, struct timeval * const tvp_now)
  9373. {
  9374. struct thr_info *thr = cgpu->thr[0];
  9375. enum dev_enable *denable;
  9376. char *dev_str = cgpu->proc_repr;
  9377. if (likely(drv_ready(cgpu)))
  9378. {
  9379. if (unlikely(!cgpu->already_set_defaults))
  9380. cgpu_set_defaults(cgpu);
  9381. if (cgpu->drv->get_stats)
  9382. cgpu->drv->get_stats(cgpu);
  9383. }
  9384. denable = &cgpu->deven;
  9385. if (cgpu->drv->watchdog)
  9386. cgpu->drv->watchdog(cgpu, tvp_now);
  9387. /* Thread is disabled */
  9388. if (*denable == DEV_DISABLED)
  9389. return;
  9390. else
  9391. if (*denable == DEV_RECOVER_ERR) {
  9392. if (opt_restart && timer_elapsed(&cgpu->tv_device_last_not_well, NULL) > cgpu->reinit_backoff) {
  9393. applog(LOG_NOTICE, "Attempting to reinitialize %s",
  9394. dev_str);
  9395. if (cgpu->reinit_backoff < 300)
  9396. cgpu->reinit_backoff *= 2;
  9397. device_recovered(cgpu);
  9398. }
  9399. return;
  9400. }
  9401. else
  9402. if (*denable == DEV_RECOVER) {
  9403. if (opt_restart && cgpu->temp < cgpu->targettemp) {
  9404. applog(LOG_NOTICE, "%s recovered to temperature below target, re-enabling",
  9405. dev_str);
  9406. device_recovered(cgpu);
  9407. }
  9408. dev_error_update(cgpu, REASON_DEV_THERMAL_CUTOFF);
  9409. return;
  9410. }
  9411. else
  9412. if (cgpu->temp > cgpu->cutofftemp)
  9413. {
  9414. applog(LOG_WARNING, "%s hit thermal cutoff limit at %dC, disabling!",
  9415. dev_str, (int)cgpu->temp);
  9416. *denable = DEV_RECOVER;
  9417. dev_error(cgpu, REASON_DEV_THERMAL_CUTOFF);
  9418. run_cmd(cmd_idle);
  9419. }
  9420. if (thr->getwork) {
  9421. if (cgpu->status == LIFE_WELL && thr->getwork < tvp_now->tv_sec - opt_log_interval) {
  9422. int thrid;
  9423. bool cgpu_idle = true;
  9424. thr->rolling = 0;
  9425. for (thrid = 0; thrid < cgpu->threads; ++thrid)
  9426. if (!cgpu->thr[thrid]->getwork)
  9427. cgpu_idle = false;
  9428. if (cgpu_idle) {
  9429. cgpu->rolling = 0;
  9430. cgpu->status = LIFE_WAIT;
  9431. }
  9432. }
  9433. return;
  9434. }
  9435. else if (cgpu->status == LIFE_WAIT)
  9436. cgpu->status = LIFE_WELL;
  9437. #ifdef WANT_CPUMINE
  9438. if (!strcmp(cgpu->drv->dname, "cpu"))
  9439. return;
  9440. #endif
  9441. if (cgpu->status != LIFE_WELL && (tvp_now->tv_sec - thr->last.tv_sec < WATCHDOG_SICK_TIME)) {
  9442. if (likely(cgpu->status != LIFE_INIT && cgpu->status != LIFE_INIT2))
  9443. applog(LOG_ERR, "%s: Recovered, declaring WELL!", dev_str);
  9444. cgpu->status = LIFE_WELL;
  9445. cgpu->device_last_well = time(NULL);
  9446. } else if (cgpu->status == LIFE_WELL && (tvp_now->tv_sec - thr->last.tv_sec > WATCHDOG_SICK_TIME)) {
  9447. thr->rolling = cgpu->rolling = 0;
  9448. cgpu->status = LIFE_SICK;
  9449. applog(LOG_ERR, "%s: Idle for more than 60 seconds, declaring SICK!", dev_str);
  9450. cgtime(&thr->sick);
  9451. dev_error(cgpu, REASON_DEV_SICK_IDLE_60);
  9452. run_cmd(cmd_sick);
  9453. if (opt_restart && cgpu->drv->reinit_device) {
  9454. applog(LOG_ERR, "%s: Attempting to restart", dev_str);
  9455. reinit_device(cgpu);
  9456. }
  9457. } else if (cgpu->status == LIFE_SICK && (tvp_now->tv_sec - thr->last.tv_sec > WATCHDOG_DEAD_TIME)) {
  9458. cgpu->status = LIFE_DEAD;
  9459. applog(LOG_ERR, "%s: Not responded for more than 10 minutes, declaring DEAD!", dev_str);
  9460. cgtime(&thr->sick);
  9461. dev_error(cgpu, REASON_DEV_DEAD_IDLE_600);
  9462. run_cmd(cmd_dead);
  9463. } else if (tvp_now->tv_sec - thr->sick.tv_sec > 60 &&
  9464. (cgpu->status == LIFE_SICK || cgpu->status == LIFE_DEAD)) {
  9465. /* Attempt to restart a GPU that's sick or dead once every minute */
  9466. cgtime(&thr->sick);
  9467. if (opt_restart)
  9468. reinit_device(cgpu);
  9469. }
  9470. }
  9471. static void log_print_status(struct cgpu_info *cgpu)
  9472. {
  9473. char logline[255];
  9474. get_statline(logline, sizeof(logline), cgpu);
  9475. applog(LOG_WARNING, "%s", logline);
  9476. }
  9477. void print_summary(void)
  9478. {
  9479. struct timeval diff;
  9480. int hours, mins, secs, i;
  9481. double utility, efficiency = 0.0;
  9482. char xfer[(ALLOC_H2B_SPACED*2)+4+1], bw[(ALLOC_H2B_SPACED*2)+6+1];
  9483. int pool_secs;
  9484. timersub(&total_tv_end, &total_tv_start, &diff);
  9485. hours = diff.tv_sec / 3600;
  9486. mins = (diff.tv_sec % 3600) / 60;
  9487. secs = diff.tv_sec % 60;
  9488. utility = total_accepted / total_secs * 60;
  9489. efficiency = total_bytes_xfer ? total_diff_accepted * 2048. / total_bytes_xfer : 0.0;
  9490. applog(LOG_WARNING, "\nSummary of runtime statistics:\n");
  9491. applog(LOG_WARNING, "Started at %s", datestamp);
  9492. if (total_pools == 1)
  9493. applog(LOG_WARNING, "Pool: %s", pools[0]->rpc_url);
  9494. #ifdef WANT_CPUMINE
  9495. if (opt_n_threads > 0)
  9496. applog(LOG_WARNING, "CPU hasher algorithm used: %s", algo_names[opt_algo]);
  9497. #endif
  9498. applog(LOG_WARNING, "Runtime: %d hrs : %d mins : %d secs", hours, mins, secs);
  9499. applog(LOG_WARNING, "Average hashrate: %.1f Megahash/s", total_mhashes_done / total_secs);
  9500. applog(LOG_WARNING, "Solved blocks: %d", found_blocks);
  9501. applog(LOG_WARNING, "Best share difficulty: %s", best_share);
  9502. applog(LOG_WARNING, "Share submissions: %d", total_accepted + total_rejected);
  9503. applog(LOG_WARNING, "Accepted shares: %d", total_accepted);
  9504. applog(LOG_WARNING, "Rejected shares: %d + %d stale (%.2f%%)",
  9505. total_rejected, total_stale,
  9506. (float)(total_rejected + total_stale) / (float)(total_rejected + total_stale + total_accepted)
  9507. );
  9508. applog(LOG_WARNING, "Accepted difficulty shares: %1.f", total_diff_accepted);
  9509. applog(LOG_WARNING, "Rejected difficulty shares: %1.f", total_diff_rejected);
  9510. applog(LOG_WARNING, "Hardware errors: %d", hw_errors);
  9511. applog(LOG_WARNING, "Network transfer: %s (%s)",
  9512. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  9513. (float)total_bytes_rcvd,
  9514. (float)total_bytes_sent),
  9515. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  9516. (float)(total_bytes_rcvd / total_secs),
  9517. (float)(total_bytes_sent / total_secs)));
  9518. applog(LOG_WARNING, "Efficiency (accepted shares * difficulty / 2 KB): %.2f", efficiency);
  9519. applog(LOG_WARNING, "Utility (accepted shares / min): %.2f/min\n", utility);
  9520. applog(LOG_WARNING, "Unable to get work from server occasions: %d", total_go);
  9521. applog(LOG_WARNING, "Work items generated locally: %d", local_work);
  9522. applog(LOG_WARNING, "Submitting work remotely delay occasions: %d", total_ro);
  9523. applog(LOG_WARNING, "New blocks detected on network: %d\n", new_blocks);
  9524. if (total_pools > 1) {
  9525. for (i = 0; i < total_pools; i++) {
  9526. struct pool *pool = pools[i];
  9527. applog(LOG_WARNING, "Pool: %s", pool->rpc_url);
  9528. if (pool->solved)
  9529. applog(LOG_WARNING, "SOLVED %d BLOCK%s!", pool->solved, pool->solved > 1 ? "S" : "");
  9530. applog(LOG_WARNING, " Share submissions: %d", pool->accepted + pool->rejected);
  9531. applog(LOG_WARNING, " Accepted shares: %d", pool->accepted);
  9532. applog(LOG_WARNING, " Rejected shares: %d + %d stale (%.2f%%)",
  9533. pool->rejected, pool->stale_shares,
  9534. (float)(pool->rejected + pool->stale_shares) / (float)(pool->rejected + pool->stale_shares + pool->accepted)
  9535. );
  9536. applog(LOG_WARNING, " Accepted difficulty shares: %1.f", pool->diff_accepted);
  9537. applog(LOG_WARNING, " Rejected difficulty shares: %1.f", pool->diff_rejected);
  9538. pool_secs = timer_elapsed(&pool->cgminer_stats.start_tv, NULL);
  9539. applog(LOG_WARNING, " Network transfer: %s (%s)",
  9540. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  9541. (float)pool->cgminer_pool_stats.net_bytes_received,
  9542. (float)pool->cgminer_pool_stats.net_bytes_sent),
  9543. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  9544. (float)(pool->cgminer_pool_stats.net_bytes_received / pool_secs),
  9545. (float)(pool->cgminer_pool_stats.net_bytes_sent / pool_secs)));
  9546. uint64_t pool_bytes_xfer = pool->cgminer_pool_stats.net_bytes_received + pool->cgminer_pool_stats.net_bytes_sent;
  9547. efficiency = pool_bytes_xfer ? pool->diff_accepted * 2048. / pool_bytes_xfer : 0.0;
  9548. applog(LOG_WARNING, " Efficiency (accepted * difficulty / 2 KB): %.2f", efficiency);
  9549. applog(LOG_WARNING, " Items worked on: %d", pool->works);
  9550. applog(LOG_WARNING, " Unable to get work from server occasions: %d", pool->getfail_occasions);
  9551. applog(LOG_WARNING, " Submitting work remotely delay occasions: %d\n", pool->remotefail_occasions);
  9552. }
  9553. }
  9554. if (opt_quit_summary != BQS_NONE)
  9555. {
  9556. if (opt_quit_summary == BQS_DEFAULT)
  9557. {
  9558. if (total_devices < 25)
  9559. opt_quit_summary = BQS_PROCS;
  9560. else
  9561. opt_quit_summary = BQS_DEVS;
  9562. }
  9563. if (opt_quit_summary == BQS_DETAILED)
  9564. include_serial_in_statline = true;
  9565. applog(LOG_WARNING, "Summary of per device statistics:\n");
  9566. for (i = 0; i < total_devices; ++i) {
  9567. struct cgpu_info *cgpu = get_devices(i);
  9568. if (!cgpu->proc_id)
  9569. {
  9570. // Device summary line
  9571. opt_show_procs = false;
  9572. log_print_status(cgpu);
  9573. opt_show_procs = true;
  9574. }
  9575. if ((opt_quit_summary == BQS_PROCS || opt_quit_summary == BQS_DETAILED) && cgpu->procs > 1)
  9576. log_print_status(cgpu);
  9577. }
  9578. }
  9579. if (opt_shares) {
  9580. applog(LOG_WARNING, "Mined %g accepted shares of %g requested\n", total_diff_accepted, opt_shares);
  9581. if (opt_shares > total_diff_accepted)
  9582. applog(LOG_WARNING, "WARNING - Mined only %g shares of %g requested.", total_diff_accepted, opt_shares);
  9583. }
  9584. applog(LOG_WARNING, " ");
  9585. fflush(stderr);
  9586. fflush(stdout);
  9587. }
  9588. void _bfg_clean_up(bool restarting)
  9589. {
  9590. #ifdef HAVE_OPENCL
  9591. clear_adl(nDevs);
  9592. #endif
  9593. #ifdef HAVE_LIBUSB
  9594. if (likely(have_libusb))
  9595. libusb_exit(NULL);
  9596. #endif
  9597. cgtime(&total_tv_end);
  9598. #ifdef WIN32
  9599. timeEndPeriod(1);
  9600. #endif
  9601. if (!restarting) {
  9602. /* Attempting to disable curses or print a summary during a
  9603. * restart can lead to a deadlock. */
  9604. #ifdef HAVE_CURSES
  9605. disable_curses();
  9606. #endif
  9607. if (!opt_realquiet && successful_connect)
  9608. print_summary();
  9609. }
  9610. if (opt_n_threads > 0)
  9611. free(cpus);
  9612. curl_global_cleanup();
  9613. #ifdef WIN32
  9614. WSACleanup();
  9615. #endif
  9616. }
  9617. void _quit(int status)
  9618. {
  9619. if (status) {
  9620. const char *ev = getenv("__BFGMINER_SEGFAULT_ERRQUIT");
  9621. if (unlikely(ev && ev[0] && ev[0] != '0')) {
  9622. int *p = NULL;
  9623. // NOTE debugger can bypass with: p = &p
  9624. *p = status; // Segfault, hopefully dumping core
  9625. }
  9626. }
  9627. #if defined(unix) || defined(__APPLE__)
  9628. if (forkpid > 0) {
  9629. kill(forkpid, SIGTERM);
  9630. forkpid = 0;
  9631. }
  9632. #endif
  9633. exit(status);
  9634. }
  9635. #ifdef HAVE_CURSES
  9636. char *curses_input(const char *query)
  9637. {
  9638. char *input;
  9639. echo();
  9640. input = malloc(255);
  9641. if (!input)
  9642. quit(1, "Failed to malloc input");
  9643. leaveok(logwin, false);
  9644. wlogprint("%s:\n", query);
  9645. wgetnstr(logwin, input, 255);
  9646. if (!strlen(input))
  9647. {
  9648. free(input);
  9649. input = NULL;
  9650. }
  9651. leaveok(logwin, true);
  9652. noecho();
  9653. return input;
  9654. }
  9655. #endif
  9656. static void *test_pool_thread(void *arg)
  9657. {
  9658. struct pool *pool = (struct pool *)arg;
  9659. if (pool_active(pool, false)) {
  9660. pool_tset(pool, &pool->lagging);
  9661. pool_tclear(pool, &pool->idle);
  9662. bool first_pool = false;
  9663. cg_wlock(&control_lock);
  9664. if (!pools_active) {
  9665. currentpool = pool;
  9666. if (pool->pool_no != 0)
  9667. first_pool = true;
  9668. pools_active = true;
  9669. }
  9670. cg_wunlock(&control_lock);
  9671. if (unlikely(first_pool))
  9672. applog(LOG_NOTICE, "Switching to pool %d %s - first alive pool", pool->pool_no, pool->rpc_url);
  9673. else
  9674. applog(LOG_NOTICE, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  9675. switch_pools(NULL);
  9676. } else
  9677. pool_died(pool);
  9678. pool->testing = false;
  9679. return NULL;
  9680. }
  9681. /* Always returns true that the pool details were added unless we are not
  9682. * live, implying this is the only pool being added, so if no pools are
  9683. * active it returns false. */
  9684. bool add_pool_details(struct pool *pool, bool live, char *url, char *user, char *pass)
  9685. {
  9686. size_t siz;
  9687. pool_set_uri(pool, url);
  9688. pool->rpc_user = user;
  9689. pool->rpc_pass = pass;
  9690. siz = strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2;
  9691. pool->rpc_userpass = malloc(siz);
  9692. if (!pool->rpc_userpass)
  9693. quit(1, "Failed to malloc userpass");
  9694. snprintf(pool->rpc_userpass, siz, "%s:%s", pool->rpc_user, pool->rpc_pass);
  9695. pool->testing = true;
  9696. pool->idle = true;
  9697. enable_pool(pool);
  9698. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  9699. if (!live) {
  9700. pthread_join(pool->test_thread, NULL);
  9701. return pools_active;
  9702. }
  9703. return true;
  9704. }
  9705. #ifdef HAVE_CURSES
  9706. static bool input_pool(bool live)
  9707. {
  9708. char *url = NULL, *user = NULL, *pass = NULL;
  9709. struct pool *pool;
  9710. bool ret = false;
  9711. immedok(logwin, true);
  9712. wlogprint("Input server details.\n");
  9713. url = curses_input("URL");
  9714. if (!url)
  9715. goto out;
  9716. user = curses_input("Username");
  9717. if (!user)
  9718. goto out;
  9719. pass = curses_input("Password");
  9720. if (!pass)
  9721. pass = calloc(1, 1);
  9722. pool = add_pool();
  9723. if (!detect_stratum(pool, url) && strncmp(url, "http://", 7) &&
  9724. strncmp(url, "https://", 8)) {
  9725. char *httpinput;
  9726. httpinput = malloc(256);
  9727. if (!httpinput)
  9728. quit(1, "Failed to malloc httpinput");
  9729. strcpy(httpinput, "http://");
  9730. strncat(httpinput, url, 248);
  9731. free(url);
  9732. url = httpinput;
  9733. }
  9734. ret = add_pool_details(pool, live, url, user, pass);
  9735. out:
  9736. immedok(logwin, false);
  9737. if (!ret) {
  9738. if (url)
  9739. free(url);
  9740. if (user)
  9741. free(user);
  9742. if (pass)
  9743. free(pass);
  9744. }
  9745. return ret;
  9746. }
  9747. #endif
  9748. #if BLKMAKER_VERSION > 1
  9749. static
  9750. bool _add_local_gbt(const char * const filepath, void *userp)
  9751. {
  9752. const bool * const live_p = userp;
  9753. struct pool *pool;
  9754. char buf[0x100];
  9755. char *rpcuser = NULL, *rpcpass = NULL, *rpcconnect = NULL;
  9756. int rpcport = 0, rpcssl = -101;
  9757. FILE * const F = fopen(filepath, "r");
  9758. if (!F)
  9759. applogr(false, LOG_WARNING, "%s: Failed to open %s for reading", "add_local_gbt", filepath);
  9760. while (fgets(buf, sizeof(buf), F))
  9761. {
  9762. if (!strncasecmp(buf, "rpcuser=", 8))
  9763. rpcuser = trimmed_strdup(&buf[8]);
  9764. else
  9765. if (!strncasecmp(buf, "rpcpassword=", 12))
  9766. rpcpass = trimmed_strdup(&buf[12]);
  9767. else
  9768. if (!strncasecmp(buf, "rpcport=", 8))
  9769. rpcport = atoi(&buf[8]);
  9770. else
  9771. if (!strncasecmp(buf, "rpcssl=", 7))
  9772. rpcssl = atoi(&buf[7]);
  9773. else
  9774. if (!strncasecmp(buf, "rpcconnect=", 11))
  9775. rpcconnect = trimmed_strdup(&buf[11]);
  9776. else
  9777. continue;
  9778. if (rpcuser && rpcpass && rpcport && rpcssl != -101 && rpcconnect)
  9779. break;
  9780. }
  9781. fclose(F);
  9782. if (!rpcpass)
  9783. {
  9784. applog(LOG_DEBUG, "%s: Did not find rpcpassword in %s", "add_local_gbt", filepath);
  9785. err:
  9786. free(rpcuser);
  9787. free(rpcpass);
  9788. goto out;
  9789. }
  9790. if (!rpcport)
  9791. rpcport = 8332;
  9792. if (rpcssl == -101)
  9793. rpcssl = 0;
  9794. const bool have_cbaddr = bytes_len(&opt_coinbase_script);
  9795. const int uri_sz = 0x30;
  9796. char * const uri = malloc(uri_sz);
  9797. snprintf(uri, uri_sz, "http%s://%s:%d/%s#allblocks", rpcssl ? "s" : "", rpcconnect ?: "localhost", rpcport, have_cbaddr ? "" : "#getcbaddr");
  9798. char hfuri[0x40];
  9799. if (rpcconnect)
  9800. snprintf(hfuri, sizeof(hfuri), "%s:%d", rpcconnect, rpcport);
  9801. else
  9802. snprintf(hfuri, sizeof(hfuri), "port %d", rpcport);
  9803. applog(LOG_DEBUG, "Local bitcoin RPC server on %s found in %s", hfuri, filepath);
  9804. for (int i = 0; i < total_pools; ++i)
  9805. {
  9806. struct pool *pool = pools[i];
  9807. if (!(strcmp(pool->rpc_url, uri) || strcmp(pool->rpc_pass, rpcpass)))
  9808. {
  9809. applog(LOG_DEBUG, "Server on %s is already configured, not adding as failover", hfuri);
  9810. free(uri);
  9811. goto err;
  9812. }
  9813. }
  9814. pool = add_pool();
  9815. if (!pool)
  9816. {
  9817. applog(LOG_ERR, "%s: Error adding pool for bitcoin configured in %s", "add_local_gbt", filepath);
  9818. goto err;
  9819. }
  9820. if (!rpcuser)
  9821. rpcuser = "";
  9822. pool->quota = 0;
  9823. adjust_quota_gcd();
  9824. pool->failover_only = true;
  9825. add_pool_details(pool, *live_p, uri, rpcuser, rpcpass);
  9826. applog(LOG_NOTICE, "Added local bitcoin RPC server on %s as pool %d", hfuri, pool->pool_no);
  9827. out:
  9828. return false;
  9829. }
  9830. static
  9831. void add_local_gbt(bool live)
  9832. {
  9833. appdata_file_call("Bitcoin", "bitcoin.conf", _add_local_gbt, &live);
  9834. }
  9835. #endif
  9836. #if defined(unix) || defined(__APPLE__)
  9837. static void fork_monitor()
  9838. {
  9839. // Make a pipe: [readFD, writeFD]
  9840. int pfd[2];
  9841. int r = pipe(pfd);
  9842. if (r < 0) {
  9843. perror("pipe - failed to create pipe for --monitor");
  9844. exit(1);
  9845. }
  9846. // Make stderr write end of pipe
  9847. fflush(stderr);
  9848. r = dup2(pfd[1], 2);
  9849. if (r < 0) {
  9850. perror("dup2 - failed to alias stderr to write end of pipe for --monitor");
  9851. exit(1);
  9852. }
  9853. r = close(pfd[1]);
  9854. if (r < 0) {
  9855. perror("close - failed to close write end of pipe for --monitor");
  9856. exit(1);
  9857. }
  9858. // Don't allow a dying monitor to kill the main process
  9859. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  9860. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  9861. if (SIG_ERR == sr0 || SIG_ERR == sr1) {
  9862. perror("signal - failed to edit signal mask for --monitor");
  9863. exit(1);
  9864. }
  9865. // Fork a child process
  9866. forkpid = fork();
  9867. if (forkpid < 0) {
  9868. perror("fork - failed to fork child process for --monitor");
  9869. exit(1);
  9870. }
  9871. // Child: launch monitor command
  9872. if (0 == forkpid) {
  9873. // Make stdin read end of pipe
  9874. r = dup2(pfd[0], 0);
  9875. if (r < 0) {
  9876. perror("dup2 - in child, failed to alias read end of pipe to stdin for --monitor");
  9877. exit(1);
  9878. }
  9879. close(pfd[0]);
  9880. if (r < 0) {
  9881. perror("close - in child, failed to close read end of pipe for --monitor");
  9882. exit(1);
  9883. }
  9884. // Launch user specified command
  9885. execl("/bin/bash", "/bin/bash", "-c", opt_stderr_cmd, (char*)NULL);
  9886. perror("execl - in child failed to exec user specified command for --monitor");
  9887. exit(1);
  9888. }
  9889. // Parent: clean up unused fds and bail
  9890. r = close(pfd[0]);
  9891. if (r < 0) {
  9892. perror("close - failed to close read end of pipe for --monitor");
  9893. exit(1);
  9894. }
  9895. }
  9896. #endif // defined(unix)
  9897. #ifdef HAVE_CURSES
  9898. #ifdef USE_UNICODE
  9899. static
  9900. wchar_t select_unicode_char(const wchar_t *opt)
  9901. {
  9902. for ( ; *opt; ++opt)
  9903. if (iswprint(*opt))
  9904. return *opt;
  9905. return '?';
  9906. }
  9907. #endif
  9908. void enable_curses(void) {
  9909. int x;
  9910. __maybe_unused int y;
  9911. lock_curses();
  9912. if (curses_active) {
  9913. unlock_curses();
  9914. return;
  9915. }
  9916. #ifdef USE_UNICODE
  9917. if (use_unicode)
  9918. {
  9919. setlocale(LC_CTYPE, "");
  9920. if (iswprint(0xb0))
  9921. have_unicode_degrees = true;
  9922. unicode_micro = select_unicode_char(L"\xb5\u03bcu");
  9923. }
  9924. #endif
  9925. mainwin = initscr();
  9926. start_color();
  9927. #if defined(PDCURSES) || defined(NCURSES_VERSION)
  9928. if (ERR != use_default_colors())
  9929. default_bgcolor = -1;
  9930. #endif
  9931. if (has_colors() && ERR != init_pair(1, COLOR_WHITE, COLOR_BLUE))
  9932. {
  9933. menu_attr = COLOR_PAIR(1);
  9934. if (ERR != init_pair(2, COLOR_RED, default_bgcolor))
  9935. attr_bad |= COLOR_PAIR(2);
  9936. }
  9937. keypad(mainwin, true);
  9938. getmaxyx(mainwin, y, x);
  9939. statuswin = newwin(logstart, x, 0, 0);
  9940. leaveok(statuswin, true);
  9941. // For whatever reason, PDCurses crashes if the logwin is initialized to height y-logcursor
  9942. // We resize the window later anyway, so just start it off at 1 :)
  9943. logwin = newwin(1, 0, logcursor, 0);
  9944. idlok(logwin, true);
  9945. scrollok(logwin, true);
  9946. leaveok(logwin, true);
  9947. cbreak();
  9948. noecho();
  9949. nonl();
  9950. curses_active = true;
  9951. statusy = logstart;
  9952. unlock_curses();
  9953. }
  9954. #endif
  9955. /* TODO: fix need a dummy CPU device_drv even if no support for CPU mining */
  9956. #ifndef WANT_CPUMINE
  9957. struct device_drv cpu_drv;
  9958. struct device_drv cpu_drv = {
  9959. .name = "CPU",
  9960. };
  9961. #endif
  9962. static int cgminer_id_count = 0;
  9963. static int device_line_id_count;
  9964. void register_device(struct cgpu_info *cgpu)
  9965. {
  9966. cgpu->deven = DEV_ENABLED;
  9967. wr_lock(&devices_lock);
  9968. devices[cgpu->cgminer_id = cgminer_id_count++] = cgpu;
  9969. wr_unlock(&devices_lock);
  9970. if (!cgpu->proc_id)
  9971. cgpu->device_line_id = device_line_id_count++;
  9972. mining_threads += cgpu->threads ?: 1;
  9973. #ifdef HAVE_CURSES
  9974. adj_width(mining_threads, &dev_width);
  9975. #endif
  9976. rwlock_init(&cgpu->qlock);
  9977. cgpu->queued_work = NULL;
  9978. }
  9979. struct _cgpu_devid_counter {
  9980. char name[4];
  9981. int lastid;
  9982. UT_hash_handle hh;
  9983. };
  9984. void renumber_cgpu(struct cgpu_info *cgpu)
  9985. {
  9986. static struct _cgpu_devid_counter *devids = NULL;
  9987. struct _cgpu_devid_counter *d;
  9988. HASH_FIND_STR(devids, cgpu->drv->name, d);
  9989. if (d)
  9990. cgpu->device_id = ++d->lastid;
  9991. else {
  9992. d = malloc(sizeof(*d));
  9993. memcpy(d->name, cgpu->drv->name, sizeof(d->name));
  9994. cgpu->device_id = d->lastid = 0;
  9995. HASH_ADD_STR(devids, name, d);
  9996. }
  9997. // Build repr strings
  9998. sprintf(cgpu->dev_repr, "%s%2u", cgpu->drv->name, cgpu->device_id % 100);
  9999. sprintf(cgpu->dev_repr_ns, "%s%u", cgpu->drv->name, cgpu->device_id % 100);
  10000. strcpy(cgpu->proc_repr, cgpu->dev_repr);
  10001. sprintf(cgpu->proc_repr_ns, "%s%u", cgpu->drv->name, cgpu->device_id);
  10002. const int lpcount = cgpu->procs;
  10003. if (lpcount > 1)
  10004. {
  10005. int ns;
  10006. struct cgpu_info *slave;
  10007. int lpdigits = 1;
  10008. for (int i = lpcount; i > 26 && lpdigits < 3; i /= 26)
  10009. ++lpdigits;
  10010. if (lpdigits > max_lpdigits)
  10011. max_lpdigits = lpdigits;
  10012. memset(&cgpu->proc_repr[5], 'a', lpdigits);
  10013. cgpu->proc_repr[5 + lpdigits] = '\0';
  10014. ns = strlen(cgpu->proc_repr_ns);
  10015. strcpy(&cgpu->proc_repr_ns[ns], &cgpu->proc_repr[5]);
  10016. slave = cgpu;
  10017. for (int i = 1; i < lpcount; ++i)
  10018. {
  10019. slave = slave->next_proc;
  10020. strcpy(slave->proc_repr, cgpu->proc_repr);
  10021. strcpy(slave->proc_repr_ns, cgpu->proc_repr_ns);
  10022. for (int x = i, y = lpdigits; --y, x; x /= 26)
  10023. {
  10024. slave->proc_repr_ns[ns + y] =
  10025. slave->proc_repr[5 + y] += (x % 26);
  10026. }
  10027. }
  10028. }
  10029. }
  10030. static bool my_blkmaker_sha256_callback(void *digest, const void *buffer, size_t length)
  10031. {
  10032. sha256(buffer, length, digest);
  10033. return true;
  10034. }
  10035. static
  10036. int drv_algo_check(const struct device_drv * const drv)
  10037. {
  10038. const int algomatch = opt_scrypt ? POW_SCRYPT : POW_SHA256D;
  10039. const supported_algos_t algos = drv->supported_algos ?: POW_SHA256D;
  10040. return (algos & algomatch);
  10041. }
  10042. #ifndef HAVE_PTHREAD_CANCEL
  10043. extern void setup_pthread_cancel_workaround();
  10044. extern struct sigaction pcwm_orig_term_handler;
  10045. #endif
  10046. bool bfg_need_detect_rescan;
  10047. extern void probe_device(struct lowlevel_device_info *);
  10048. static void schedule_rescan(const struct timeval *);
  10049. static
  10050. void drv_detect_all()
  10051. {
  10052. bool rescanning = false;
  10053. rescan:
  10054. bfg_need_detect_rescan = false;
  10055. #ifdef HAVE_BFG_LOWLEVEL
  10056. struct lowlevel_device_info * const infolist = lowlevel_scan(), *info, *infotmp;
  10057. LL_FOREACH_SAFE(infolist, info, infotmp)
  10058. probe_device(info);
  10059. LL_FOREACH_SAFE(infolist, info, infotmp)
  10060. pthread_join(info->probe_pth, NULL);
  10061. #endif
  10062. struct driver_registration *reg, *tmp;
  10063. BFG_FOREACH_DRIVER_BY_PRIORITY(reg, tmp)
  10064. {
  10065. const struct device_drv * const drv = reg->drv;
  10066. if (!(drv_algo_check(drv) && drv->drv_detect))
  10067. continue;
  10068. drv->drv_detect();
  10069. }
  10070. #ifdef HAVE_BFG_LOWLEVEL
  10071. lowlevel_scan_free();
  10072. #endif
  10073. if (bfg_need_detect_rescan)
  10074. {
  10075. if (rescanning)
  10076. {
  10077. applog(LOG_DEBUG, "Device rescan requested a second time, delaying");
  10078. struct timeval tv_when;
  10079. timer_set_delay_from_now(&tv_when, rescan_delay_ms * 1000);
  10080. schedule_rescan(&tv_when);
  10081. }
  10082. else
  10083. {
  10084. rescanning = true;
  10085. applog(LOG_DEBUG, "Device rescan requested");
  10086. goto rescan;
  10087. }
  10088. }
  10089. }
  10090. static
  10091. void allocate_cgpu(struct cgpu_info *cgpu, unsigned int *kp)
  10092. {
  10093. struct thr_info *thr;
  10094. int j;
  10095. struct device_drv *api = cgpu->drv;
  10096. cgpu->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  10097. int threadobj = cgpu->threads;
  10098. if (!threadobj)
  10099. // Create a fake thread object to handle hashmeter etc
  10100. threadobj = 1;
  10101. cgpu->thr = calloc(threadobj + 1, sizeof(*cgpu->thr));
  10102. cgpu->thr[threadobj] = NULL;
  10103. cgpu->status = LIFE_INIT;
  10104. if (opt_devices_enabled_list)
  10105. {
  10106. struct string_elist *enablestr_elist;
  10107. cgpu->deven = DEV_DISABLED;
  10108. DL_FOREACH(opt_devices_enabled_list, enablestr_elist)
  10109. {
  10110. const char * const enablestr = enablestr_elist->string;
  10111. if (cgpu_match(enablestr, cgpu))
  10112. {
  10113. cgpu->deven = DEV_ENABLED;
  10114. break;
  10115. }
  10116. }
  10117. }
  10118. cgpu->max_hashes = 0;
  10119. BFGINIT(cgpu->min_nonce_diff, 1);
  10120. BFGINIT(cgpu->cutofftemp, opt_cutofftemp);
  10121. BFGINIT(cgpu->targettemp, cgpu->cutofftemp - 6);
  10122. // Setup thread structs before starting any of the threads, in case they try to interact
  10123. for (j = 0; j < threadobj; ++j, ++*kp) {
  10124. thr = get_thread(*kp);
  10125. thr->id = *kp;
  10126. thr->cgpu = cgpu;
  10127. thr->device_thread = j;
  10128. thr->work_restart_notifier[1] = INVSOCK;
  10129. thr->mutex_request[1] = INVSOCK;
  10130. thr->_job_transition_in_progress = true;
  10131. timerclear(&thr->tv_morework);
  10132. thr->scanhash_working = true;
  10133. thr->hashes_done = 0;
  10134. timerclear(&thr->tv_hashes_done);
  10135. cgtime(&thr->tv_lastupdate);
  10136. thr->tv_poll.tv_sec = -1;
  10137. thr->_max_nonce = api->can_limit_work ? api->can_limit_work(thr) : 0xffffffff;
  10138. cgpu->thr[j] = thr;
  10139. }
  10140. if (!cgpu->device->threads)
  10141. notifier_init_invalid(cgpu->thr[0]->notifier);
  10142. else
  10143. if (!cgpu->threads)
  10144. memcpy(&cgpu->thr[0]->notifier, &cgpu->device->thr[0]->notifier, sizeof(cgpu->thr[0]->notifier));
  10145. else
  10146. for (j = 0; j < cgpu->threads; ++j)
  10147. {
  10148. thr = cgpu->thr[j];
  10149. notifier_init(thr->notifier);
  10150. }
  10151. }
  10152. static
  10153. void start_cgpu(struct cgpu_info *cgpu)
  10154. {
  10155. struct thr_info *thr;
  10156. int j;
  10157. for (j = 0; j < cgpu->threads; ++j) {
  10158. thr = cgpu->thr[j];
  10159. /* Enable threads for devices set not to mine but disable
  10160. * their queue in case we wish to enable them later */
  10161. if (cgpu->drv->thread_prepare && !cgpu->drv->thread_prepare(thr))
  10162. continue;
  10163. thread_reportout(thr);
  10164. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  10165. quit(1, "thread %d create failed", thr->id);
  10166. notifier_wake(thr->notifier);
  10167. }
  10168. if (cgpu->deven == DEV_ENABLED)
  10169. proc_enable(cgpu);
  10170. }
  10171. static
  10172. void _scan_serial(void *p)
  10173. {
  10174. const char *s = p;
  10175. struct string_elist *iter, *tmp;
  10176. struct string_elist *orig_scan_devices = scan_devices;
  10177. if (s)
  10178. {
  10179. // Make temporary scan_devices list
  10180. scan_devices = NULL;
  10181. string_elist_add("noauto", &scan_devices);
  10182. add_serial(s);
  10183. }
  10184. drv_detect_all();
  10185. if (s)
  10186. {
  10187. DL_FOREACH_SAFE(scan_devices, iter, tmp)
  10188. {
  10189. string_elist_del(&scan_devices, iter);
  10190. }
  10191. scan_devices = orig_scan_devices;
  10192. }
  10193. }
  10194. #ifdef HAVE_BFG_LOWLEVEL
  10195. static
  10196. bool _probe_device_match(const struct lowlevel_device_info * const info, const char * const ser)
  10197. {
  10198. if (!(false
  10199. || (info->serial && !strcasecmp(ser, info->serial))
  10200. || (info->path && !strcasecmp(ser, info->path ))
  10201. || (info->devid && !strcasecmp(ser, info->devid ))
  10202. ))
  10203. {
  10204. char *devid = devpath_to_devid(ser);
  10205. if (!devid)
  10206. return false;
  10207. const bool different = strcmp(info->devid, devid);
  10208. free(devid);
  10209. if (different)
  10210. return false;
  10211. }
  10212. return true;
  10213. }
  10214. static
  10215. const struct device_drv *_probe_device_find_drv(const char * const _dname, const size_t dnamelen)
  10216. {
  10217. struct driver_registration *dreg;
  10218. char dname[dnamelen];
  10219. int i;
  10220. for (i = 0; i < dnamelen; ++i)
  10221. dname[i] = tolower(_dname[i]);
  10222. BFG_FIND_DRV_BY_DNAME(dreg, dname, dnamelen);
  10223. if (!dreg)
  10224. {
  10225. for (i = 0; i < dnamelen; ++i)
  10226. dname[i] = toupper(_dname[i]);
  10227. BFG_FIND_DRV_BY_NAME(dreg, dname, dnamelen);
  10228. if (!dreg)
  10229. return NULL;
  10230. }
  10231. if (!drv_algo_check(dreg->drv))
  10232. return NULL;
  10233. return dreg->drv;
  10234. }
  10235. static
  10236. bool _probe_device_do_probe(const struct device_drv * const drv, const struct lowlevel_device_info * const info, bool * const request_rescan_p)
  10237. {
  10238. bfg_probe_result_flags = 0;
  10239. if (drv->lowl_probe(info))
  10240. {
  10241. if (!(bfg_probe_result_flags & BPR_CONTINUE_PROBES))
  10242. return true;
  10243. }
  10244. else
  10245. if (request_rescan_p && opt_hotplug && !(bfg_probe_result_flags & BPR_DONT_RESCAN))
  10246. *request_rescan_p = true;
  10247. return false;
  10248. }
  10249. bool dummy_check_never_true = false;
  10250. static
  10251. void *probe_device_thread(void *p)
  10252. {
  10253. struct lowlevel_device_info * const infolist = p;
  10254. struct lowlevel_device_info *info = infolist;
  10255. bool request_rescan = false;
  10256. {
  10257. char threadname[5 + strlen(info->devid) + 1];
  10258. sprintf(threadname, "probe_%s", info->devid);
  10259. RenameThread(threadname);
  10260. }
  10261. // If already in use, ignore
  10262. if (bfg_claim_any(NULL, NULL, info->devid))
  10263. applogr(NULL, LOG_DEBUG, "%s: \"%s\" already in use",
  10264. __func__, info->product);
  10265. // if lowlevel device matches specific user assignment, probe requested driver(s)
  10266. struct string_elist *sd_iter, *sd_tmp;
  10267. struct driver_registration *dreg, *dreg_tmp;
  10268. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  10269. {
  10270. const char * const dname = sd_iter->string;
  10271. const char * const colon = strpbrk(dname, ":@");
  10272. if (!(colon && colon != dname))
  10273. continue;
  10274. const char * const ser = &colon[1];
  10275. LL_FOREACH2(infolist, info, same_devid_next)
  10276. {
  10277. if (!_probe_device_match(info, ser))
  10278. continue;
  10279. const size_t dnamelen = (colon - dname);
  10280. const struct device_drv * const drv = _probe_device_find_drv(dname, dnamelen);
  10281. if (!(drv && drv->lowl_probe && drv_algo_check(drv)))
  10282. continue;
  10283. if (_probe_device_do_probe(drv, info, &request_rescan))
  10284. return NULL;
  10285. }
  10286. }
  10287. // probe driver(s) with auto enabled and matching VID/PID/Product/etc of device
  10288. BFG_FOREACH_DRIVER_BY_PRIORITY(dreg, dreg_tmp)
  10289. {
  10290. const struct device_drv * const drv = dreg->drv;
  10291. if (!drv_algo_check(drv))
  10292. continue;
  10293. // Check for "noauto" flag
  10294. // NOTE: driver-specific configuration overrides general
  10295. bool doauto = true;
  10296. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  10297. {
  10298. const char * const dname = sd_iter->string;
  10299. // NOTE: Only checking flags here, NOT path/serial, so @ is unacceptable
  10300. const char *colon = strchr(dname, ':');
  10301. if (!colon)
  10302. colon = &dname[-1];
  10303. if (strcasecmp("noauto", &colon[1]) && strcasecmp("auto", &colon[1]))
  10304. continue;
  10305. const ssize_t dnamelen = (colon - dname);
  10306. if (dnamelen >= 0 && _probe_device_find_drv(dname, dnamelen) != drv)
  10307. continue;
  10308. doauto = (tolower(colon[1]) == 'a');
  10309. if (dnamelen != -1)
  10310. break;
  10311. }
  10312. if (doauto && drv->lowl_match)
  10313. {
  10314. LL_FOREACH2(infolist, info, same_devid_next)
  10315. {
  10316. /*
  10317. The below call to applog is absolutely necessary
  10318. Starting with commit 76d0cc183b1c9ddcc0ef34d2e43bc696ef9de92e installing BFGMiner on
  10319. Mac OS X using Homebrew results in a binary that segfaults on startup
  10320. There are two unresolved issues:
  10321. 1) The BFGMiner authors cannot find a way to install BFGMiner with Homebrew that results
  10322. in debug symbols being available to help troubleshoot the issue
  10323. 2) The issue disappears when unrelated code changes are made, such as adding the following
  10324. call to applog with infolist and / or p
  10325. We would encourage revisiting this in the future to come up with a more concrete solution
  10326. Reproducing should only require commenting / removing the following line and installing
  10327. BFGMiner using "brew install bfgminer --HEAD"
  10328. */
  10329. if (dummy_check_never_true)
  10330. applog(LOG_DEBUG, "lowl_match: %p(%s) %p %p %p", drv, drv->dname, info, infolist, p);
  10331. if (!drv->lowl_match(info))
  10332. continue;
  10333. if (_probe_device_do_probe(drv, info, &request_rescan))
  10334. return NULL;
  10335. }
  10336. }
  10337. }
  10338. // probe driver(s) with 'all' enabled
  10339. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  10340. {
  10341. const char * const dname = sd_iter->string;
  10342. // NOTE: Only checking flags here, NOT path/serial, so @ is unacceptable
  10343. const char * const colon = strchr(dname, ':');
  10344. if (!colon)
  10345. {
  10346. LL_FOREACH2(infolist, info, same_devid_next)
  10347. {
  10348. if (
  10349. #ifdef NEED_BFG_LOWL_VCOM
  10350. (info->lowl == &lowl_vcom && !strcasecmp(dname, "all")) ||
  10351. #endif
  10352. _probe_device_match(info, (dname[0] == '@') ? &dname[1] : dname))
  10353. {
  10354. bool dont_rescan = false;
  10355. BFG_FOREACH_DRIVER_BY_PRIORITY(dreg, dreg_tmp)
  10356. {
  10357. const struct device_drv * const drv = dreg->drv;
  10358. if (!drv_algo_check(drv))
  10359. continue;
  10360. if (drv->lowl_probe_by_name_only)
  10361. continue;
  10362. if (!drv->lowl_probe)
  10363. continue;
  10364. if (_probe_device_do_probe(drv, info, NULL))
  10365. return NULL;
  10366. if (bfg_probe_result_flags & BPR_DONT_RESCAN)
  10367. dont_rescan = true;
  10368. }
  10369. if (opt_hotplug && !dont_rescan)
  10370. request_rescan = true;
  10371. break;
  10372. }
  10373. }
  10374. continue;
  10375. }
  10376. if (strcasecmp(&colon[1], "all"))
  10377. continue;
  10378. const size_t dnamelen = (colon - dname);
  10379. const struct device_drv * const drv = _probe_device_find_drv(dname, dnamelen);
  10380. if (!(drv && drv->lowl_probe && drv_algo_check(drv)))
  10381. continue;
  10382. LL_FOREACH2(infolist, info, same_devid_next)
  10383. {
  10384. if (info->lowl->exclude_from_all)
  10385. continue;
  10386. if (_probe_device_do_probe(drv, info, NULL))
  10387. return NULL;
  10388. }
  10389. }
  10390. // Only actually request a rescan if we never found any cgpu
  10391. if (request_rescan)
  10392. bfg_need_detect_rescan = true;
  10393. return NULL;
  10394. }
  10395. void probe_device(struct lowlevel_device_info * const info)
  10396. {
  10397. pthread_create(&info->probe_pth, NULL, probe_device_thread, info);
  10398. }
  10399. #endif
  10400. int create_new_cgpus(void (*addfunc)(void*), void *arg)
  10401. {
  10402. static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  10403. int devcount, i, mining_threads_new = 0;
  10404. unsigned int k;
  10405. struct cgpu_info *cgpu;
  10406. struct thr_info *thr;
  10407. void *p;
  10408. mutex_lock(&mutex);
  10409. devcount = total_devices;
  10410. addfunc(arg);
  10411. if (!total_devices_new)
  10412. goto out;
  10413. wr_lock(&devices_lock);
  10414. p = realloc(devices, sizeof(struct cgpu_info *) * (total_devices + total_devices_new + 1));
  10415. if (unlikely(!p))
  10416. {
  10417. wr_unlock(&devices_lock);
  10418. applog(LOG_ERR, "scan_serial: realloc failed trying to grow devices array");
  10419. goto out;
  10420. }
  10421. devices = p;
  10422. wr_unlock(&devices_lock);
  10423. for (i = 0; i < total_devices_new; ++i)
  10424. {
  10425. cgpu = devices_new[i];
  10426. mining_threads_new += cgpu->threads ?: 1;
  10427. }
  10428. wr_lock(&mining_thr_lock);
  10429. mining_threads_new += mining_threads;
  10430. p = realloc(mining_thr, sizeof(struct thr_info *) * mining_threads_new);
  10431. if (unlikely(!p))
  10432. {
  10433. wr_unlock(&mining_thr_lock);
  10434. applog(LOG_ERR, "scan_serial: realloc failed trying to grow mining_thr");
  10435. goto out;
  10436. }
  10437. mining_thr = p;
  10438. wr_unlock(&mining_thr_lock);
  10439. for (i = mining_threads; i < mining_threads_new; ++i) {
  10440. mining_thr[i] = calloc(1, sizeof(*thr));
  10441. if (!mining_thr[i])
  10442. {
  10443. applog(LOG_ERR, "scan_serial: Failed to calloc mining_thr[%d]", i);
  10444. for ( ; --i >= mining_threads; )
  10445. free(mining_thr[i]);
  10446. goto out;
  10447. }
  10448. }
  10449. k = mining_threads;
  10450. for (i = 0; i < total_devices_new; ++i)
  10451. {
  10452. cgpu = devices_new[i];
  10453. allocate_cgpu(cgpu, &k);
  10454. }
  10455. for (i = 0; i < total_devices_new; ++i)
  10456. {
  10457. cgpu = devices_new[i];
  10458. start_cgpu(cgpu);
  10459. register_device(cgpu);
  10460. ++total_devices;
  10461. }
  10462. #ifdef HAVE_CURSES
  10463. switch_logsize();
  10464. #endif
  10465. out:
  10466. total_devices_new = 0;
  10467. devcount = total_devices - devcount;
  10468. mutex_unlock(&mutex);
  10469. return devcount;
  10470. }
  10471. int scan_serial(const char *s)
  10472. {
  10473. return create_new_cgpus(_scan_serial, (void*)s);
  10474. }
  10475. static pthread_mutex_t rescan_mutex = PTHREAD_MUTEX_INITIALIZER;
  10476. static bool rescan_active;
  10477. static struct timeval tv_rescan;
  10478. static notifier_t rescan_notifier;
  10479. static
  10480. void *rescan_thread(__maybe_unused void *p)
  10481. {
  10482. pthread_detach(pthread_self());
  10483. RenameThread("rescan");
  10484. struct timeval tv_timeout, tv_now;
  10485. fd_set rfds;
  10486. while (true)
  10487. {
  10488. mutex_lock(&rescan_mutex);
  10489. tv_timeout = tv_rescan;
  10490. if (!timer_isset(&tv_timeout))
  10491. {
  10492. rescan_active = false;
  10493. mutex_unlock(&rescan_mutex);
  10494. break;
  10495. }
  10496. mutex_unlock(&rescan_mutex);
  10497. FD_ZERO(&rfds);
  10498. FD_SET(rescan_notifier[0], &rfds);
  10499. const int maxfd = rescan_notifier[0];
  10500. timer_set_now(&tv_now);
  10501. if (select(maxfd+1, &rfds, NULL, NULL, select_timeout(&tv_timeout, &tv_now)) > 0)
  10502. notifier_read(rescan_notifier);
  10503. mutex_lock(&rescan_mutex);
  10504. if (timer_passed(&tv_rescan, NULL))
  10505. {
  10506. timer_unset(&tv_rescan);
  10507. mutex_unlock(&rescan_mutex);
  10508. applog(LOG_DEBUG, "Rescan timer expired, triggering");
  10509. scan_serial(NULL);
  10510. }
  10511. else
  10512. mutex_unlock(&rescan_mutex);
  10513. }
  10514. return NULL;
  10515. }
  10516. static
  10517. void _schedule_rescan(const struct timeval * const tvp_when)
  10518. {
  10519. if (rescan_active)
  10520. {
  10521. if (timercmp(tvp_when, &tv_rescan, <))
  10522. applog(LOG_DEBUG, "schedule_rescan: New schedule is before current, waiting it out");
  10523. else
  10524. {
  10525. applog(LOG_DEBUG, "schedule_rescan: New schedule is after current, delaying rescan");
  10526. tv_rescan = *tvp_when;
  10527. }
  10528. return;
  10529. }
  10530. applog(LOG_DEBUG, "schedule_rescan: Scheduling rescan (no rescans currently pending)");
  10531. tv_rescan = *tvp_when;
  10532. rescan_active = true;
  10533. static pthread_t pth;
  10534. if (unlikely(pthread_create(&pth, NULL, rescan_thread, NULL)))
  10535. applog(LOG_ERR, "Failed to start rescan thread");
  10536. }
  10537. static
  10538. void schedule_rescan(const struct timeval * const tvp_when)
  10539. {
  10540. mutex_lock(&rescan_mutex);
  10541. _schedule_rescan(tvp_when);
  10542. mutex_unlock(&rescan_mutex);
  10543. }
  10544. #ifdef HAVE_BFG_HOTPLUG
  10545. static
  10546. void hotplug_trigger()
  10547. {
  10548. applog(LOG_DEBUG, "%s: Scheduling rescan immediately", __func__);
  10549. struct timeval tv_now;
  10550. timer_set_now(&tv_now);
  10551. schedule_rescan(&tv_now);
  10552. }
  10553. #endif
  10554. #if defined(HAVE_LIBUDEV) && defined(HAVE_SYS_EPOLL_H)
  10555. static
  10556. void *hotplug_thread(__maybe_unused void *p)
  10557. {
  10558. pthread_detach(pthread_self());
  10559. RenameThread("hotplug");
  10560. struct udev * const udev = udev_new();
  10561. if (unlikely(!udev))
  10562. applogfailr(NULL, LOG_ERR, "udev_new");
  10563. struct udev_monitor * const mon = udev_monitor_new_from_netlink(udev, "udev");
  10564. if (unlikely(!mon))
  10565. applogfailr(NULL, LOG_ERR, "udev_monitor_new_from_netlink");
  10566. if (unlikely(udev_monitor_enable_receiving(mon)))
  10567. applogfailr(NULL, LOG_ERR, "udev_monitor_enable_receiving");
  10568. const int epfd = epoll_create(1);
  10569. if (unlikely(epfd == -1))
  10570. applogfailr(NULL, LOG_ERR, "epoll_create");
  10571. {
  10572. const int fd = udev_monitor_get_fd(mon);
  10573. struct epoll_event ev = {
  10574. .events = EPOLLIN | EPOLLPRI,
  10575. .data.fd = fd,
  10576. };
  10577. if (epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev))
  10578. applogfailr(NULL, LOG_ERR, "epoll_ctl");
  10579. }
  10580. struct epoll_event ev;
  10581. int rv;
  10582. bool pending = false;
  10583. while (true)
  10584. {
  10585. rv = epoll_wait(epfd, &ev, 1, pending ? hotplug_delay_ms : -1);
  10586. if (rv == -1)
  10587. {
  10588. if (errno == EAGAIN || errno == EINTR)
  10589. continue;
  10590. break;
  10591. }
  10592. if (!rv)
  10593. {
  10594. hotplug_trigger();
  10595. pending = false;
  10596. continue;
  10597. }
  10598. struct udev_device * const device = udev_monitor_receive_device(mon);
  10599. if (!device)
  10600. continue;
  10601. const char * const action = udev_device_get_action(device);
  10602. applog(LOG_DEBUG, "%s: Received %s event", __func__, action);
  10603. if (!strcmp(action, "add"))
  10604. pending = true;
  10605. udev_device_unref(device);
  10606. }
  10607. applogfailr(NULL, LOG_ERR, "epoll_wait");
  10608. }
  10609. #elif defined(WIN32)
  10610. static UINT_PTR _hotplug_wintimer_id;
  10611. VOID CALLBACK hotplug_win_timer(HWND hwnd, UINT msg, UINT_PTR idEvent, DWORD dwTime)
  10612. {
  10613. KillTimer(NULL, _hotplug_wintimer_id);
  10614. _hotplug_wintimer_id = 0;
  10615. hotplug_trigger();
  10616. }
  10617. LRESULT CALLBACK hotplug_win_callback(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
  10618. {
  10619. if (msg == WM_DEVICECHANGE && wParam == DBT_DEVNODES_CHANGED)
  10620. {
  10621. applog(LOG_DEBUG, "%s: Received DBT_DEVNODES_CHANGED event", __func__);
  10622. _hotplug_wintimer_id = SetTimer(NULL, _hotplug_wintimer_id, hotplug_delay_ms, hotplug_win_timer);
  10623. }
  10624. return DefWindowProc(hwnd, msg, wParam, lParam);
  10625. }
  10626. static
  10627. void *hotplug_thread(__maybe_unused void *p)
  10628. {
  10629. pthread_detach(pthread_self());
  10630. WNDCLASS DummyWinCls = {
  10631. .lpszClassName = "BFGDummyWinCls",
  10632. .lpfnWndProc = hotplug_win_callback,
  10633. };
  10634. ATOM a = RegisterClass(&DummyWinCls);
  10635. if (unlikely(!a))
  10636. applogfailinfor(NULL, LOG_ERR, "RegisterClass", "%d", (int)GetLastError());
  10637. HWND hwnd = CreateWindow((void*)(intptr_t)a, NULL, WS_OVERLAPPED, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, NULL, NULL);
  10638. if (unlikely(!hwnd))
  10639. applogfailinfor(NULL, LOG_ERR, "CreateWindow", "%d", (int)GetLastError());
  10640. MSG msg;
  10641. while (GetMessage(&msg, NULL, 0, 0))
  10642. {
  10643. TranslateMessage(&msg);
  10644. DispatchMessage(&msg);
  10645. }
  10646. quit(0, "WM_QUIT received");
  10647. return NULL;
  10648. }
  10649. #endif
  10650. #ifdef HAVE_BFG_HOTPLUG
  10651. static
  10652. void hotplug_start()
  10653. {
  10654. pthread_t pth;
  10655. if (unlikely(pthread_create(&pth, NULL, hotplug_thread, NULL)))
  10656. applog(LOG_ERR, "Failed to start hotplug thread");
  10657. }
  10658. #endif
  10659. static void probe_pools(void)
  10660. {
  10661. int i;
  10662. for (i = 0; i < total_pools; i++) {
  10663. struct pool *pool = pools[i];
  10664. pool->testing = true;
  10665. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  10666. }
  10667. }
  10668. static void raise_fd_limits(void)
  10669. {
  10670. #ifdef HAVE_SETRLIMIT
  10671. struct rlimit fdlimit;
  10672. rlim_t old_soft_limit;
  10673. char frombuf[0x10] = "unlimited";
  10674. char hardbuf[0x10] = "unlimited";
  10675. if (getrlimit(RLIMIT_NOFILE, &fdlimit))
  10676. applogr(, LOG_DEBUG, "setrlimit: Failed to getrlimit(RLIMIT_NOFILE)");
  10677. old_soft_limit = fdlimit.rlim_cur;
  10678. if (fdlimit.rlim_max > FD_SETSIZE || fdlimit.rlim_max == RLIM_INFINITY)
  10679. fdlimit.rlim_cur = FD_SETSIZE;
  10680. else
  10681. fdlimit.rlim_cur = fdlimit.rlim_max;
  10682. if (fdlimit.rlim_max != RLIM_INFINITY)
  10683. snprintf(hardbuf, sizeof(hardbuf), "%lu", (unsigned long)fdlimit.rlim_max);
  10684. if (old_soft_limit != RLIM_INFINITY)
  10685. snprintf(frombuf, sizeof(frombuf), "%lu", (unsigned long)old_soft_limit);
  10686. if (fdlimit.rlim_cur == old_soft_limit)
  10687. applogr(, LOG_DEBUG, "setrlimit: Soft fd limit not being changed from %lu (FD_SETSIZE=%lu; hard limit=%s)",
  10688. (unsigned long)old_soft_limit, (unsigned long)FD_SETSIZE, hardbuf);
  10689. if (setrlimit(RLIMIT_NOFILE, &fdlimit))
  10690. applogr(, LOG_DEBUG, "setrlimit: Failed to change soft fd limit from %s to %lu (FD_SETSIZE=%lu; hard limit=%s)",
  10691. frombuf, (unsigned long)fdlimit.rlim_cur, (unsigned long)FD_SETSIZE, hardbuf);
  10692. applog(LOG_DEBUG, "setrlimit: Changed soft fd limit from %s to %lu (FD_SETSIZE=%lu; hard limit=%s)",
  10693. frombuf, (unsigned long)fdlimit.rlim_cur, (unsigned long)FD_SETSIZE, hardbuf);
  10694. #else
  10695. applog(LOG_DEBUG, "setrlimit: Not supported by platform");
  10696. #endif
  10697. }
  10698. static
  10699. void bfg_atexit(void)
  10700. {
  10701. puts("");
  10702. }
  10703. extern void bfg_init_threadlocal();
  10704. extern void stratumsrv_start();
  10705. extern void test_aan_pll(void);
  10706. int main(int argc, char *argv[])
  10707. {
  10708. struct sigaction handler;
  10709. struct thr_info *thr;
  10710. struct block *block;
  10711. unsigned int k;
  10712. int i;
  10713. int rearrange_pools = 0;
  10714. char *s;
  10715. #ifdef WIN32
  10716. LoadLibrary("backtrace.dll");
  10717. #endif
  10718. atexit(bfg_atexit);
  10719. blkmk_sha256_impl = my_blkmaker_sha256_callback;
  10720. bfg_init_threadlocal();
  10721. #ifndef HAVE_PTHREAD_CANCEL
  10722. setup_pthread_cancel_workaround();
  10723. #endif
  10724. bfg_init_checksums();
  10725. #ifdef WIN32
  10726. {
  10727. WSADATA wsa;
  10728. i = WSAStartup(MAKEWORD(2, 2), &wsa);
  10729. if (i)
  10730. quit(1, "Failed to initialise Winsock: %s", bfg_strerror(i, BST_SOCKET));
  10731. }
  10732. #endif
  10733. /* This dangerous functions tramples random dynamically allocated
  10734. * variables so do it before anything at all */
  10735. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  10736. quit(1, "Failed to curl_global_init");
  10737. initial_args = malloc(sizeof(char *) * (argc + 1));
  10738. for (i = 0; i < argc; i++)
  10739. initial_args[i] = strdup(argv[i]);
  10740. initial_args[argc] = NULL;
  10741. mutex_init(&hash_lock);
  10742. mutex_init(&console_lock);
  10743. cglock_init(&control_lock);
  10744. mutex_init(&stats_lock);
  10745. mutex_init(&sharelog_lock);
  10746. cglock_init(&ch_lock);
  10747. mutex_init(&sshare_lock);
  10748. rwlock_init(&blk_lock);
  10749. rwlock_init(&netacc_lock);
  10750. rwlock_init(&mining_thr_lock);
  10751. rwlock_init(&devices_lock);
  10752. mutex_init(&lp_lock);
  10753. if (unlikely(pthread_cond_init(&lp_cond, bfg_condattr)))
  10754. quit(1, "Failed to pthread_cond_init lp_cond");
  10755. if (unlikely(pthread_cond_init(&gws_cond, bfg_condattr)))
  10756. quit(1, "Failed to pthread_cond_init gws_cond");
  10757. notifier_init(submit_waiting_notifier);
  10758. timer_unset(&tv_rescan);
  10759. notifier_init(rescan_notifier);
  10760. /* Create a unique get work queue */
  10761. getq = tq_new();
  10762. if (!getq)
  10763. quit(1, "Failed to create getq");
  10764. /* We use the getq mutex as the staged lock */
  10765. stgd_lock = &getq->mutex;
  10766. snprintf(packagename, sizeof(packagename), "%s %s", PACKAGE, VERSION);
  10767. #ifdef WANT_CPUMINE
  10768. init_max_name_len();
  10769. #endif
  10770. handler.sa_handler = &sighandler;
  10771. handler.sa_flags = 0;
  10772. sigemptyset(&handler.sa_mask);
  10773. #ifdef HAVE_PTHREAD_CANCEL
  10774. sigaction(SIGTERM, &handler, &termhandler);
  10775. #else
  10776. // Need to let pthread_cancel emulation handle SIGTERM first
  10777. termhandler = pcwm_orig_term_handler;
  10778. pcwm_orig_term_handler = handler;
  10779. #endif
  10780. sigaction(SIGINT, &handler, &inthandler);
  10781. #ifndef WIN32
  10782. signal(SIGPIPE, SIG_IGN);
  10783. #else
  10784. timeBeginPeriod(1);
  10785. #endif
  10786. opt_kernel_path = CGMINER_PREFIX;
  10787. cgminer_path = alloca(PATH_MAX);
  10788. s = strdup(argv[0]);
  10789. strcpy(cgminer_path, dirname(s));
  10790. free(s);
  10791. strcat(cgminer_path, "/");
  10792. #if defined(WANT_CPUMINE) && defined(WIN32)
  10793. {
  10794. char buf[32];
  10795. int gev = GetEnvironmentVariable("BFGMINER_BENCH_ALGO", buf, sizeof(buf));
  10796. if (gev > 0 && gev < sizeof(buf))
  10797. {
  10798. setup_benchmark_pool();
  10799. double rate = bench_algo_stage3(atoi(buf));
  10800. // Write result to shared memory for parent
  10801. char unique_name[64];
  10802. if (GetEnvironmentVariable("BFGMINER_SHARED_MEM", unique_name, 32))
  10803. {
  10804. HANDLE map_handle = CreateFileMapping(
  10805. INVALID_HANDLE_VALUE, // use paging file
  10806. NULL, // default security attributes
  10807. PAGE_READWRITE, // read/write access
  10808. 0, // size: high 32-bits
  10809. 4096, // size: low 32-bits
  10810. unique_name // name of map object
  10811. );
  10812. if (NULL != map_handle) {
  10813. void *shared_mem = MapViewOfFile(
  10814. map_handle, // object to map view of
  10815. FILE_MAP_WRITE, // read/write access
  10816. 0, // high offset: map from
  10817. 0, // low offset: beginning
  10818. 0 // default: map entire file
  10819. );
  10820. if (NULL != shared_mem)
  10821. CopyMemory(shared_mem, &rate, sizeof(rate));
  10822. (void)UnmapViewOfFile(shared_mem);
  10823. }
  10824. (void)CloseHandle(map_handle);
  10825. }
  10826. exit(0);
  10827. }
  10828. }
  10829. #endif
  10830. devcursor = 8;
  10831. logstart = devcursor;
  10832. logcursor = logstart;
  10833. block = calloc(sizeof(struct block), 1);
  10834. if (unlikely(!block))
  10835. quit (1, "main OOM");
  10836. for (i = 0; i < 36; i++)
  10837. strcat(block->hash, "0");
  10838. HASH_ADD_STR(blocks, hash, block);
  10839. strcpy(current_block, block->hash);
  10840. mutex_init(&submitting_lock);
  10841. #ifdef HAVE_OPENCL
  10842. opencl_early_init();
  10843. #endif
  10844. schedstart.tm.tm_sec = 1;
  10845. schedstop .tm.tm_sec = 1;
  10846. opt_register_table(opt_early_table, NULL);
  10847. opt_register_table(opt_config_table, NULL);
  10848. opt_register_table(opt_cmdline_table, NULL);
  10849. opt_early_parse(argc, argv, applog_and_exit);
  10850. if (!config_loaded)
  10851. {
  10852. load_default_config();
  10853. rearrange_pools = total_pools;
  10854. }
  10855. opt_free_table();
  10856. /* parse command line */
  10857. opt_register_table(opt_config_table,
  10858. "Options for both config file and command line");
  10859. opt_register_table(opt_cmdline_table,
  10860. "Options for command line only");
  10861. opt_parse(&argc, argv, applog_and_exit);
  10862. if (argc != 1)
  10863. quit(1, "Unexpected extra commandline arguments");
  10864. if (rearrange_pools && rearrange_pools < total_pools)
  10865. {
  10866. // Prioritise commandline pools before default-config pools
  10867. for (i = 0; i < rearrange_pools; ++i)
  10868. pools[i]->prio += rearrange_pools;
  10869. for ( ; i < total_pools; ++i)
  10870. pools[i]->prio -= rearrange_pools;
  10871. }
  10872. #ifndef HAVE_PTHREAD_CANCEL
  10873. // Can't do this any earlier, or config isn't loaded
  10874. applog(LOG_DEBUG, "pthread_cancel workaround in use");
  10875. #endif
  10876. #ifdef HAVE_PWD_H
  10877. struct passwd *user_info = NULL;
  10878. if (opt_setuid != NULL) {
  10879. if ((user_info = getpwnam(opt_setuid)) == NULL) {
  10880. quit(1, "Unable to find setuid user information");
  10881. }
  10882. }
  10883. #endif
  10884. #ifdef HAVE_CHROOT
  10885. if (chroot_dir != NULL) {
  10886. #ifdef HAVE_PWD_H
  10887. if (user_info == NULL && getuid() == 0) {
  10888. applog(LOG_WARNING, "Running as root inside chroot");
  10889. }
  10890. #endif
  10891. if (chroot(chroot_dir) != 0) {
  10892. quit(1, "Unable to chroot");
  10893. }
  10894. if (chdir("/"))
  10895. quit(1, "Unable to chdir to chroot");
  10896. }
  10897. #endif
  10898. #ifdef HAVE_PWD_H
  10899. if (user_info != NULL) {
  10900. if (setgid((*user_info).pw_gid) != 0)
  10901. quit(1, "Unable to setgid");
  10902. if (setuid((*user_info).pw_uid) != 0)
  10903. quit(1, "Unable to setuid");
  10904. }
  10905. #endif
  10906. raise_fd_limits();
  10907. if (opt_benchmark) {
  10908. while (total_pools)
  10909. remove_pool(pools[0]);
  10910. setup_benchmark_pool();
  10911. }
  10912. if (opt_unittest) {
  10913. test_cgpu_match();
  10914. test_intrange();
  10915. test_decimal_width();
  10916. test_domain_funcs();
  10917. #ifdef USE_SCRYPT
  10918. test_scrypt();
  10919. #endif
  10920. test_target();
  10921. test_uri_get_param();
  10922. utf8_test();
  10923. #ifdef USE_JINGTIAN
  10924. test_aan_pll();
  10925. #endif
  10926. }
  10927. #ifdef HAVE_CURSES
  10928. if (opt_realquiet || opt_display_devs)
  10929. use_curses = false;
  10930. setlocale(LC_ALL, "C");
  10931. if (use_curses)
  10932. enable_curses();
  10933. #endif
  10934. #ifdef HAVE_LIBUSB
  10935. int err = libusb_init(NULL);
  10936. if (err)
  10937. applog(LOG_WARNING, "libusb_init() failed err %d", err);
  10938. else
  10939. have_libusb = true;
  10940. #endif
  10941. applog(LOG_WARNING, "Started %s", packagename);
  10942. {
  10943. struct bfg_loaded_configfile *configfile;
  10944. LL_FOREACH(bfg_loaded_configfiles, configfile)
  10945. {
  10946. char * const cnfbuf = configfile->filename;
  10947. int fileconf_load = configfile->fileconf_load;
  10948. applog(LOG_NOTICE, "Loaded configuration file %s", cnfbuf);
  10949. switch (fileconf_load) {
  10950. case 0:
  10951. applog(LOG_WARNING, "Fatal JSON error in configuration file.");
  10952. applog(LOG_WARNING, "Configuration file could not be used.");
  10953. break;
  10954. case -1:
  10955. applog(LOG_WARNING, "Error in configuration file, partially loaded.");
  10956. if (use_curses)
  10957. applog(LOG_WARNING, "Start BFGMiner with -T to see what failed to load.");
  10958. break;
  10959. default:
  10960. break;
  10961. }
  10962. }
  10963. }
  10964. i = strlen(opt_kernel_path) + 2;
  10965. char __kernel_path[i];
  10966. snprintf(__kernel_path, i, "%s/", opt_kernel_path);
  10967. opt_kernel_path = __kernel_path;
  10968. if (want_per_device_stats)
  10969. opt_log_output = true;
  10970. #ifdef WANT_CPUMINE
  10971. #ifdef USE_SCRYPT
  10972. if (opt_scrypt)
  10973. set_scrypt_algo(&opt_algo);
  10974. #endif
  10975. #endif
  10976. bfg_devapi_init();
  10977. drv_detect_all();
  10978. total_devices = total_devices_new;
  10979. devices = devices_new;
  10980. total_devices_new = 0;
  10981. devices_new = NULL;
  10982. if (opt_display_devs) {
  10983. int devcount = 0;
  10984. applog(LOG_ERR, "Devices detected:");
  10985. for (i = 0; i < total_devices; ++i) {
  10986. struct cgpu_info *cgpu = devices[i];
  10987. char buf[0x100];
  10988. if (cgpu->device != cgpu)
  10989. continue;
  10990. if (cgpu->name)
  10991. snprintf(buf, sizeof(buf), " %s", cgpu->name);
  10992. else
  10993. if (cgpu->dev_manufacturer)
  10994. snprintf(buf, sizeof(buf), " %s by %s", (cgpu->dev_product ?: "Device"), cgpu->dev_manufacturer);
  10995. else
  10996. if (cgpu->dev_product)
  10997. snprintf(buf, sizeof(buf), " %s", cgpu->dev_product);
  10998. else
  10999. strcpy(buf, " Device");
  11000. tailsprintf(buf, sizeof(buf), " (driver=%s; procs=%d", cgpu->drv->dname, cgpu->procs);
  11001. if (cgpu->dev_serial)
  11002. tailsprintf(buf, sizeof(buf), "; serial=%s", cgpu->dev_serial);
  11003. if (cgpu->device_path)
  11004. tailsprintf(buf, sizeof(buf), "; path=%s", cgpu->device_path);
  11005. tailsprintf(buf, sizeof(buf), ")");
  11006. _applog(LOG_NOTICE, buf);
  11007. ++devcount;
  11008. }
  11009. quit(0, "%d devices listed", devcount);
  11010. }
  11011. mining_threads = 0;
  11012. for (i = 0; i < total_devices; ++i)
  11013. register_device(devices[i]);
  11014. if (!total_devices) {
  11015. applog(LOG_WARNING, "No devices detected!");
  11016. if (use_curses)
  11017. applog(LOG_WARNING, "Waiting for devices; press 'M+' to add, or 'Q' to quit");
  11018. else
  11019. applog(LOG_WARNING, "Waiting for devices");
  11020. }
  11021. #ifdef HAVE_CURSES
  11022. switch_logsize();
  11023. #endif
  11024. #if BLKMAKER_VERSION > 1
  11025. if (opt_load_bitcoin_conf && !(opt_scrypt || opt_benchmark))
  11026. add_local_gbt(total_pools);
  11027. #endif
  11028. if (!total_pools) {
  11029. applog(LOG_WARNING, "Need to specify at least one pool server.");
  11030. #ifdef HAVE_CURSES
  11031. if (!use_curses || !input_pool(false))
  11032. #endif
  11033. quit(1, "Pool setup failed");
  11034. }
  11035. for (i = 0; i < total_pools; i++) {
  11036. struct pool *pool = pools[i];
  11037. size_t siz;
  11038. if (!pool->rpc_url)
  11039. quit(1, "No URI supplied for pool %u", i);
  11040. if (!pool->rpc_userpass) {
  11041. if (!pool->rpc_user || !pool->rpc_pass)
  11042. quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  11043. siz = strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2;
  11044. pool->rpc_userpass = malloc(siz);
  11045. if (!pool->rpc_userpass)
  11046. quit(1, "Failed to malloc userpass");
  11047. snprintf(pool->rpc_userpass, siz, "%s:%s", pool->rpc_user, pool->rpc_pass);
  11048. }
  11049. }
  11050. /* Set the currentpool to pool with priority 0 */
  11051. validate_pool_priorities();
  11052. for (i = 0; i < total_pools; i++) {
  11053. struct pool *pool = pools[i];
  11054. if (!pool->prio)
  11055. currentpool = pool;
  11056. }
  11057. #ifdef HAVE_SYSLOG_H
  11058. if (use_syslog)
  11059. openlog(PACKAGE, LOG_PID, LOG_USER);
  11060. #endif
  11061. #if defined(unix) || defined(__APPLE__)
  11062. if (opt_stderr_cmd)
  11063. fork_monitor();
  11064. #endif // defined(unix)
  11065. mining_thr = calloc(mining_threads, sizeof(thr));
  11066. if (!mining_thr)
  11067. quit(1, "Failed to calloc mining_thr");
  11068. for (i = 0; i < mining_threads; i++) {
  11069. mining_thr[i] = calloc(1, sizeof(*thr));
  11070. if (!mining_thr[i])
  11071. quit(1, "Failed to calloc mining_thr[%d]", i);
  11072. }
  11073. total_control_threads = 6;
  11074. control_thr = calloc(total_control_threads, sizeof(*thr));
  11075. if (!control_thr)
  11076. quit(1, "Failed to calloc control_thr");
  11077. if (opt_benchmark)
  11078. goto begin_bench;
  11079. applog(LOG_NOTICE, "Probing for an alive pool");
  11080. do {
  11081. bool still_testing;
  11082. int i;
  11083. /* Look for at least one active pool before starting */
  11084. probe_pools();
  11085. do {
  11086. sleep(1);
  11087. if (pools_active)
  11088. break;
  11089. still_testing = false;
  11090. for (int i = 0; i < total_pools; ++i)
  11091. if (pools[i]->testing)
  11092. still_testing = true;
  11093. } while (still_testing);
  11094. if (!pools_active) {
  11095. applog(LOG_ERR, "No servers were found that could be used to get work from.");
  11096. applog(LOG_ERR, "Please check the details from the list below of the servers you have input");
  11097. applog(LOG_ERR, "Most likely you have input the wrong URL, forgotten to add a port, or have not set up workers");
  11098. for (i = 0; i < total_pools; i++) {
  11099. struct pool *pool;
  11100. pool = pools[i];
  11101. applog(LOG_WARNING, "Pool: %d URL: %s User: %s Password: %s",
  11102. i, pool->rpc_url, pool->rpc_user, pool->rpc_pass);
  11103. }
  11104. #ifdef HAVE_CURSES
  11105. if (use_curses) {
  11106. halfdelay(150);
  11107. applog(LOG_ERR, "Press any key to exit, or BFGMiner will try again in 15s.");
  11108. if (getch() != ERR)
  11109. quit(0, "No servers could be used! Exiting.");
  11110. cbreak();
  11111. } else
  11112. #endif
  11113. quit(0, "No servers could be used! Exiting.");
  11114. }
  11115. } while (!pools_active);
  11116. #ifdef USE_SCRYPT
  11117. if (detect_algo == 1 && !opt_scrypt) {
  11118. applog(LOG_NOTICE, "Detected scrypt algorithm");
  11119. opt_scrypt = true;
  11120. }
  11121. #endif
  11122. detect_algo = 0;
  11123. begin_bench:
  11124. total_mhashes_done = 0;
  11125. for (i = 0; i < total_devices; i++) {
  11126. struct cgpu_info *cgpu = devices[i];
  11127. cgpu->rolling = cgpu->total_mhashes = 0;
  11128. }
  11129. cgtime(&total_tv_start);
  11130. cgtime(&total_tv_end);
  11131. miner_started = total_tv_start;
  11132. time_t miner_start_ts = time(NULL);
  11133. if (schedstart.tm.tm_sec)
  11134. localtime_r(&miner_start_ts, &schedstart.tm);
  11135. if (schedstop.tm.tm_sec)
  11136. localtime_r(&miner_start_ts, &schedstop .tm);
  11137. get_datestamp(datestamp, sizeof(datestamp), miner_start_ts);
  11138. // Initialise processors and threads
  11139. k = 0;
  11140. for (i = 0; i < total_devices; ++i) {
  11141. struct cgpu_info *cgpu = devices[i];
  11142. allocate_cgpu(cgpu, &k);
  11143. }
  11144. // Start threads
  11145. for (i = 0; i < total_devices; ++i) {
  11146. struct cgpu_info *cgpu = devices[i];
  11147. start_cgpu(cgpu);
  11148. }
  11149. #ifdef HAVE_OPENCL
  11150. for (i = 0; i < nDevs; i++)
  11151. pause_dynamic_threads(i);
  11152. #endif
  11153. #ifdef WANT_CPUMINE
  11154. if (opt_n_threads > 0)
  11155. applog(LOG_INFO, "%d cpu miner threads started, using '%s' algorithm.",
  11156. opt_n_threads, algo_names[opt_algo]);
  11157. #endif
  11158. cgtime(&total_tv_start);
  11159. cgtime(&total_tv_end);
  11160. if (!opt_benchmark)
  11161. {
  11162. pthread_t submit_thread;
  11163. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, NULL)))
  11164. quit(1, "submit_work thread create failed");
  11165. }
  11166. watchpool_thr_id = 1;
  11167. thr = &control_thr[watchpool_thr_id];
  11168. /* start watchpool thread */
  11169. if (thr_info_create(thr, NULL, watchpool_thread, NULL))
  11170. quit(1, "watchpool thread create failed");
  11171. pthread_detach(thr->pth);
  11172. watchdog_thr_id = 2;
  11173. thr = &control_thr[watchdog_thr_id];
  11174. /* start watchdog thread */
  11175. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  11176. quit(1, "watchdog thread create failed");
  11177. pthread_detach(thr->pth);
  11178. #ifdef HAVE_OPENCL
  11179. /* Create reinit gpu thread */
  11180. gpur_thr_id = 3;
  11181. thr = &control_thr[gpur_thr_id];
  11182. thr->q = tq_new();
  11183. if (!thr->q)
  11184. quit(1, "tq_new failed for gpur_thr_id");
  11185. if (thr_info_create(thr, NULL, reinit_gpu, thr))
  11186. quit(1, "reinit_gpu thread create failed");
  11187. #endif
  11188. /* Create API socket thread */
  11189. api_thr_id = 4;
  11190. thr = &control_thr[api_thr_id];
  11191. if (thr_info_create(thr, NULL, api_thread, thr))
  11192. quit(1, "API thread create failed");
  11193. #ifdef USE_LIBMICROHTTPD
  11194. if (httpsrv_port != -1)
  11195. httpsrv_start(httpsrv_port);
  11196. #endif
  11197. #ifdef USE_LIBEVENT
  11198. if (stratumsrv_port != -1)
  11199. stratumsrv_start();
  11200. #endif
  11201. #ifdef HAVE_BFG_HOTPLUG
  11202. if (opt_hotplug)
  11203. hotplug_start();
  11204. #endif
  11205. #ifdef HAVE_CURSES
  11206. /* Create curses input thread for keyboard input. Create this last so
  11207. * that we know all threads are created since this can call kill_work
  11208. * to try and shut down ll previous threads. */
  11209. input_thr_id = 5;
  11210. thr = &control_thr[input_thr_id];
  11211. if (thr_info_create(thr, NULL, input_thread, thr))
  11212. quit(1, "input thread create failed");
  11213. pthread_detach(thr->pth);
  11214. #endif
  11215. /* Just to be sure */
  11216. if (total_control_threads != 6)
  11217. quit(1, "incorrect total_control_threads (%d) should be 7", total_control_threads);
  11218. /* Once everything is set up, main() becomes the getwork scheduler */
  11219. while (42) {
  11220. int ts, max_staged = opt_queue;
  11221. struct pool *pool, *cp;
  11222. bool lagging = false;
  11223. struct curl_ent *ce;
  11224. struct work *work;
  11225. cp = current_pool();
  11226. // Generally, each processor needs a new work, and all at once during work restarts
  11227. max_staged += mining_threads;
  11228. mutex_lock(stgd_lock);
  11229. ts = __total_staged();
  11230. if (!pool_localgen(cp) && !ts && !opt_fail_only)
  11231. lagging = true;
  11232. /* Wait until hash_pop tells us we need to create more work */
  11233. if (ts > max_staged) {
  11234. staged_full = true;
  11235. pthread_cond_wait(&gws_cond, stgd_lock);
  11236. ts = __total_staged();
  11237. }
  11238. mutex_unlock(stgd_lock);
  11239. if (ts > max_staged)
  11240. continue;
  11241. work = make_work();
  11242. if (lagging && !pool_tset(cp, &cp->lagging)) {
  11243. applog(LOG_WARNING, "Pool %d not providing work fast enough", cp->pool_no);
  11244. cp->getfail_occasions++;
  11245. total_go++;
  11246. }
  11247. pool = select_pool(lagging);
  11248. retry:
  11249. if (pool->has_stratum) {
  11250. while (!pool->stratum_active || !pool->stratum_notify) {
  11251. struct pool *altpool = select_pool(true);
  11252. if (altpool == pool && pool->has_stratum)
  11253. cgsleep_ms(5000);
  11254. pool = altpool;
  11255. goto retry;
  11256. }
  11257. gen_stratum_work(pool, work);
  11258. applog(LOG_DEBUG, "Generated stratum work");
  11259. stage_work(work);
  11260. continue;
  11261. }
  11262. if (pool->last_work_copy) {
  11263. mutex_lock(&pool->last_work_lock);
  11264. struct work *last_work = pool->last_work_copy;
  11265. if (!last_work)
  11266. {}
  11267. else
  11268. if (can_roll(last_work) && should_roll(last_work)) {
  11269. struct timeval tv_now;
  11270. cgtime(&tv_now);
  11271. free_work(work);
  11272. work = make_clone(pool->last_work_copy);
  11273. mutex_unlock(&pool->last_work_lock);
  11274. roll_work(work);
  11275. applog(LOG_DEBUG, "Generated work from latest GBT job in get_work_thread with %d seconds left", (int)blkmk_time_left(work->tr->tmpl, tv_now.tv_sec));
  11276. stage_work(work);
  11277. continue;
  11278. } else if (last_work->tr && pool->proto == PLP_GETBLOCKTEMPLATE && blkmk_work_left(last_work->tr->tmpl) > (unsigned long)mining_threads) {
  11279. // Don't free last_work_copy, since it is used to detect upstream provides plenty of work per template
  11280. } else {
  11281. free_work(last_work);
  11282. pool->last_work_copy = NULL;
  11283. }
  11284. mutex_unlock(&pool->last_work_lock);
  11285. }
  11286. if (clone_available()) {
  11287. applog(LOG_DEBUG, "Cloned getwork work");
  11288. free_work(work);
  11289. continue;
  11290. }
  11291. if (opt_benchmark) {
  11292. get_benchmark_work(work, opt_benchmark_intense);
  11293. applog(LOG_DEBUG, "Generated benchmark work");
  11294. stage_work(work);
  11295. continue;
  11296. }
  11297. work->pool = pool;
  11298. ce = pop_curl_entry3(pool, 2);
  11299. /* obtain new work from bitcoin via JSON-RPC */
  11300. if (!get_upstream_work(work, ce->curl)) {
  11301. struct pool *next_pool;
  11302. /* Make sure the pool just hasn't stopped serving
  11303. * requests but is up as we'll keep hammering it */
  11304. push_curl_entry(ce, pool);
  11305. ++pool->seq_getfails;
  11306. pool_died(pool);
  11307. next_pool = select_pool(!opt_fail_only);
  11308. if (pool == next_pool) {
  11309. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, retrying in 5s", pool->pool_no);
  11310. cgsleep_ms(5000);
  11311. } else {
  11312. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, failover activated", pool->pool_no);
  11313. pool = next_pool;
  11314. }
  11315. goto retry;
  11316. }
  11317. if (ts >= max_staged)
  11318. pool_tclear(pool, &pool->lagging);
  11319. if (pool_tclear(pool, &pool->idle))
  11320. pool_resus(pool);
  11321. applog(LOG_DEBUG, "Generated getwork work");
  11322. stage_work(work);
  11323. push_curl_entry(ce, pool);
  11324. }
  11325. return 0;
  11326. }