miner.c 345 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387
  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 <libbase58.h>
  68. #include "compat.h"
  69. #include "deviceapi.h"
  70. #include "logging.h"
  71. #include "miner.h"
  72. #include "adl.h"
  73. #include "driver-cpu.h"
  74. #include "driver-opencl.h"
  75. #include "scrypt.h"
  76. #include "util.h"
  77. #ifdef USE_AVALON
  78. #include "driver-avalon.h"
  79. #endif
  80. #ifdef HAVE_BFG_LOWLEVEL
  81. #include "lowlevel.h"
  82. #endif
  83. #if defined(unix) || defined(__APPLE__)
  84. #include <errno.h>
  85. #include <fcntl.h>
  86. #include <sys/wait.h>
  87. #endif
  88. #ifdef USE_SCRYPT
  89. #include "scrypt.h"
  90. #endif
  91. #include "version.h"
  92. #if defined(USE_AVALON) || defined(USE_BITFORCE) || defined(USE_ICARUS) || defined(USE_MODMINER) || defined(USE_NANOFURY) || defined(USE_X6500) || defined(USE_ZTEX)
  93. # define USE_FPGA
  94. #endif
  95. enum bfg_quit_summary {
  96. BQS_DEFAULT,
  97. BQS_NONE,
  98. BQS_DEVS,
  99. BQS_PROCS,
  100. BQS_DETAILED,
  101. };
  102. struct strategies strategies[] = {
  103. { "Failover" },
  104. { "Round Robin" },
  105. { "Rotate" },
  106. { "Load Balance" },
  107. { "Balance" },
  108. };
  109. static char packagename[256];
  110. bool opt_protocol;
  111. bool opt_dev_protocol;
  112. static bool opt_benchmark, opt_benchmark_intense;
  113. static bool want_longpoll = true;
  114. static bool want_gbt = true;
  115. static bool want_getwork = true;
  116. #if BLKMAKER_VERSION > 1
  117. static bool opt_load_bitcoin_conf = true;
  118. static bool have_at_least_one_getcbaddr;
  119. static bytes_t opt_coinbase_script = BYTES_INIT;
  120. static uint32_t coinbase_script_block_id;
  121. static uint32_t template_nonce;
  122. #endif
  123. #if BLKMAKER_VERSION > 0
  124. char *opt_coinbase_sig;
  125. #endif
  126. static enum bfg_quit_summary opt_quit_summary = BQS_DEFAULT;
  127. static bool include_serial_in_statline;
  128. char *request_target_str;
  129. float request_pdiff = 1.0;
  130. double request_bdiff;
  131. static bool want_stratum = true;
  132. bool have_longpoll;
  133. int opt_skip_checks;
  134. bool want_per_device_stats;
  135. bool use_syslog;
  136. bool opt_quiet_work_updates = true;
  137. bool opt_quiet;
  138. bool opt_realquiet;
  139. int loginput_size;
  140. bool opt_compact;
  141. bool opt_show_procs;
  142. const int opt_cutofftemp = 95;
  143. int opt_hysteresis = 3;
  144. static int opt_retries = -1;
  145. int opt_fail_pause = 5;
  146. int opt_log_interval = 20;
  147. int opt_queue = 1;
  148. int opt_scantime = 60;
  149. int opt_expiry = 120;
  150. int opt_expiry_lp = 3600;
  151. unsigned long long global_hashrate;
  152. static bool opt_unittest = false;
  153. unsigned unittest_failures;
  154. unsigned long global_quota_gcd = 1;
  155. time_t last_getwork;
  156. #ifdef HAVE_OPENCL
  157. int opt_dynamic_interval = 7;
  158. int nDevs;
  159. int opt_g_threads = -1;
  160. #endif
  161. #ifdef USE_SCRYPT
  162. static char detect_algo = 1;
  163. bool opt_scrypt;
  164. #else
  165. static char detect_algo;
  166. #endif
  167. bool opt_restart = true;
  168. #ifdef USE_LIBMICROHTTPD
  169. #include "httpsrv.h"
  170. int httpsrv_port = -1;
  171. #endif
  172. #ifdef USE_LIBEVENT
  173. int stratumsrv_port = -1;
  174. #endif
  175. const
  176. int rescan_delay_ms = 1000;
  177. #ifdef HAVE_BFG_HOTPLUG
  178. bool opt_hotplug = 1;
  179. const
  180. int hotplug_delay_ms = 100;
  181. #else
  182. const bool opt_hotplug;
  183. #endif
  184. struct string_elist *scan_devices;
  185. static struct string_elist *opt_set_device_list;
  186. bool opt_force_dev_init;
  187. static struct string_elist *opt_devices_enabled_list;
  188. static bool opt_display_devs;
  189. int total_devices;
  190. struct cgpu_info **devices;
  191. int total_devices_new;
  192. struct cgpu_info **devices_new;
  193. bool have_opencl;
  194. int opt_n_threads = -1;
  195. int mining_threads;
  196. int base_queue;
  197. int num_processors;
  198. #ifdef HAVE_CURSES
  199. bool use_curses = true;
  200. #else
  201. bool use_curses;
  202. #endif
  203. int last_logstatusline_len;
  204. #ifdef HAVE_LIBUSB
  205. bool have_libusb;
  206. #endif
  207. static bool opt_submit_stale = true;
  208. static float opt_shares;
  209. static int opt_submit_threads = 0x40;
  210. bool opt_fail_only;
  211. int opt_fail_switch_delay = 300;
  212. bool opt_autofan;
  213. bool opt_autoengine;
  214. bool opt_noadl;
  215. char *opt_api_allow = NULL;
  216. char *opt_api_groups;
  217. char *opt_api_description = PACKAGE_STRING;
  218. int opt_api_port = 4028;
  219. bool opt_api_listen;
  220. bool opt_api_mcast;
  221. char *opt_api_mcast_addr = API_MCAST_ADDR;
  222. char *opt_api_mcast_code = API_MCAST_CODE;
  223. char *opt_api_mcast_des = "";
  224. int opt_api_mcast_port = 4028;
  225. bool opt_api_network;
  226. bool opt_delaynet;
  227. bool opt_disable_pool;
  228. bool opt_disable_client_reconnect = false;
  229. static bool no_work;
  230. bool opt_worktime;
  231. bool opt_weighed_stats;
  232. char *opt_kernel_path;
  233. char *cgminer_path;
  234. #if defined(USE_BITFORCE)
  235. bool opt_bfl_noncerange;
  236. #endif
  237. #define QUIET (opt_quiet || opt_realquiet)
  238. struct thr_info *control_thr;
  239. struct thr_info **mining_thr;
  240. static int watchpool_thr_id;
  241. static int watchdog_thr_id;
  242. #ifdef HAVE_CURSES
  243. static int input_thr_id;
  244. #endif
  245. int gpur_thr_id;
  246. static int api_thr_id;
  247. static int total_control_threads;
  248. pthread_mutex_t hash_lock;
  249. static pthread_mutex_t *stgd_lock;
  250. pthread_mutex_t console_lock;
  251. cglock_t ch_lock;
  252. static pthread_rwlock_t blk_lock;
  253. static pthread_mutex_t sshare_lock;
  254. pthread_rwlock_t netacc_lock;
  255. pthread_rwlock_t mining_thr_lock;
  256. pthread_rwlock_t devices_lock;
  257. static pthread_mutex_t lp_lock;
  258. static pthread_cond_t lp_cond;
  259. pthread_cond_t gws_cond;
  260. bool shutting_down;
  261. double total_rolling;
  262. double total_mhashes_done;
  263. static struct timeval total_tv_start, total_tv_end;
  264. static struct timeval miner_started;
  265. cglock_t control_lock;
  266. pthread_mutex_t stats_lock;
  267. static pthread_mutex_t submitting_lock;
  268. static int total_submitting;
  269. static struct work *submit_waiting;
  270. notifier_t submit_waiting_notifier;
  271. int hw_errors;
  272. int total_accepted, total_rejected;
  273. int total_getworks, total_stale, total_discarded;
  274. uint64_t total_bytes_rcvd, total_bytes_sent;
  275. double total_diff1, total_bad_diff1;
  276. double total_diff_accepted, total_diff_rejected, total_diff_stale;
  277. static int staged_rollable;
  278. unsigned int new_blocks;
  279. unsigned int found_blocks;
  280. unsigned int local_work;
  281. unsigned int total_go, total_ro;
  282. struct pool **pools;
  283. static struct pool *currentpool = NULL;
  284. int total_pools, enabled_pools;
  285. enum pool_strategy pool_strategy = POOL_FAILOVER;
  286. int opt_rotate_period;
  287. static int total_urls, total_users, total_passes;
  288. static
  289. #ifndef HAVE_CURSES
  290. const
  291. #endif
  292. bool curses_active;
  293. #ifdef HAVE_CURSES
  294. #if !(defined(PDCURSES) || defined(NCURSES_VERSION))
  295. const
  296. #endif
  297. short default_bgcolor = COLOR_BLACK;
  298. static int attr_title = A_BOLD;
  299. #endif
  300. static
  301. #if defined(HAVE_CURSES) && defined(USE_UNICODE)
  302. bool use_unicode;
  303. static
  304. bool have_unicode_degrees;
  305. static
  306. wchar_t unicode_micro = 'u';
  307. #else
  308. const bool use_unicode;
  309. static
  310. const bool have_unicode_degrees;
  311. #ifdef HAVE_CURSES
  312. static
  313. const char unicode_micro = 'u';
  314. #endif
  315. #endif
  316. #ifdef HAVE_CURSES
  317. #define U8_BAD_START "\xef\x80\x81"
  318. #define U8_BAD_END "\xef\x80\x80"
  319. #define AS_BAD(x) U8_BAD_START x U8_BAD_END
  320. /* logstart is where the log window should start */
  321. static int devcursor, logstart, logcursor;
  322. bool selecting_device;
  323. unsigned selected_device;
  324. #endif
  325. static int max_lpdigits;
  326. // current_hash was replaced with goal->current_goal_detail
  327. // current_block_id was replaced with blkchain->currentblk->block_id
  328. static char datestamp[40];
  329. static char best_share[ALLOC_H2B_SHORTV] = "0";
  330. double best_diff = 0;
  331. struct mining_goal_info *mining_goals;
  332. int active_goals = 1;
  333. int swork_id;
  334. /* For creating a hash database of stratum shares submitted that have not had
  335. * a response yet */
  336. struct stratum_share {
  337. UT_hash_handle hh;
  338. bool block;
  339. struct work *work;
  340. int id;
  341. };
  342. static struct stratum_share *stratum_shares = NULL;
  343. char *opt_socks_proxy = NULL;
  344. static const char def_conf[] = "bfgminer.conf";
  345. static bool config_loaded;
  346. static int include_count;
  347. #define JSON_INCLUDE_CONF "include"
  348. #define JSON_LOAD_ERROR "JSON decode of file '%s' failed\n %s"
  349. #define JSON_LOAD_ERROR_LEN strlen(JSON_LOAD_ERROR)
  350. #define JSON_MAX_DEPTH 10
  351. #define JSON_MAX_DEPTH_ERR "Too many levels of JSON includes (limit 10) or a loop"
  352. char *cmd_idle, *cmd_sick, *cmd_dead;
  353. #if defined(unix) || defined(__APPLE__)
  354. static char *opt_stderr_cmd = NULL;
  355. static int forkpid;
  356. #endif // defined(unix)
  357. #ifdef HAVE_CHROOT
  358. char *chroot_dir;
  359. #endif
  360. #ifdef HAVE_PWD_H
  361. char *opt_setuid;
  362. #endif
  363. struct sigaction termhandler, inthandler;
  364. struct thread_q *getq;
  365. static int total_work;
  366. static bool staged_full;
  367. struct work *staged_work = NULL;
  368. struct schedtime {
  369. bool enable;
  370. struct tm tm;
  371. };
  372. struct schedtime schedstart;
  373. struct schedtime schedstop;
  374. bool sched_paused;
  375. static bool time_before(struct tm *tm1, struct tm *tm2)
  376. {
  377. if (tm1->tm_hour < tm2->tm_hour)
  378. return true;
  379. if (tm1->tm_hour == tm2->tm_hour && tm1->tm_min < tm2->tm_min)
  380. return true;
  381. return false;
  382. }
  383. static bool should_run(void)
  384. {
  385. struct tm tm;
  386. time_t tt;
  387. bool within_range;
  388. if (!schedstart.enable && !schedstop.enable)
  389. return true;
  390. tt = time(NULL);
  391. localtime_r(&tt, &tm);
  392. // NOTE: This is delicately balanced so that should_run is always false if schedstart==schedstop
  393. if (time_before(&schedstop.tm, &schedstart.tm))
  394. within_range = (time_before(&tm, &schedstop.tm) || !time_before(&tm, &schedstart.tm));
  395. else
  396. within_range = (time_before(&tm, &schedstop.tm) && !time_before(&tm, &schedstart.tm));
  397. if (within_range && !schedstop.enable)
  398. /* This is a once off event with no stop time set */
  399. schedstart.enable = false;
  400. return within_range;
  401. }
  402. void get_datestamp(char *f, size_t fsiz, time_t tt)
  403. {
  404. struct tm _tm;
  405. struct tm *tm = &_tm;
  406. if (tt == INVALID_TIMESTAMP)
  407. tt = time(NULL);
  408. localtime_r(&tt, tm);
  409. snprintf(f, fsiz, "[%d-%02d-%02d %02d:%02d:%02d]",
  410. tm->tm_year + 1900,
  411. tm->tm_mon + 1,
  412. tm->tm_mday,
  413. tm->tm_hour,
  414. tm->tm_min,
  415. tm->tm_sec);
  416. }
  417. static
  418. void get_timestamp(char *f, size_t fsiz, time_t tt)
  419. {
  420. struct tm _tm;
  421. struct tm *tm = &_tm;
  422. localtime_r(&tt, tm);
  423. snprintf(f, fsiz, "[%02d:%02d:%02d]",
  424. tm->tm_hour,
  425. tm->tm_min,
  426. tm->tm_sec);
  427. }
  428. static void applog_and_exit(const char *fmt, ...) FORMAT_SYNTAX_CHECK(printf, 1, 2);
  429. static char exit_buf[512];
  430. static void applog_and_exit(const char *fmt, ...)
  431. {
  432. va_list ap;
  433. va_start(ap, fmt);
  434. vsnprintf(exit_buf, sizeof(exit_buf), fmt, ap);
  435. va_end(ap);
  436. _applog(LOG_ERR, exit_buf);
  437. exit(1);
  438. }
  439. char *devpath_to_devid(const char *devpath)
  440. {
  441. #ifndef WIN32
  442. if (devpath[0] != '/')
  443. return NULL;
  444. struct stat my_stat;
  445. if (stat(devpath, &my_stat))
  446. return NULL;
  447. char *devs = malloc(6 + (sizeof(dev_t) * 2) + 1);
  448. memcpy(devs, "dev_t:", 6);
  449. bin2hex(&devs[6], &my_stat.st_rdev, sizeof(dev_t));
  450. #else
  451. if (!strncmp(devpath, "\\\\.\\", 4))
  452. devpath += 4;
  453. if (strncasecmp(devpath, "COM", 3) || !devpath[3])
  454. return NULL;
  455. devpath += 3;
  456. char *p;
  457. strtol(devpath, &p, 10);
  458. if (p[0])
  459. return NULL;
  460. const int sz = (p - devpath);
  461. char *devs = malloc(4 + sz + 1);
  462. sprintf(devs, "com:%s", devpath);
  463. #endif
  464. return devs;
  465. }
  466. static
  467. bool devpaths_match(const char * const ap, const char * const bp)
  468. {
  469. char * const a = devpath_to_devid(ap);
  470. if (!a)
  471. return false;
  472. char * const b = devpath_to_devid(bp);
  473. bool rv = false;
  474. if (b)
  475. {
  476. rv = !strcmp(a, b);
  477. free(b);
  478. }
  479. free(a);
  480. return rv;
  481. }
  482. static
  483. int proc_letter_to_number(const char *s, const char ** const rem)
  484. {
  485. int n = 0, c;
  486. for ( ; s[0]; ++s)
  487. {
  488. if (unlikely(n > INT_MAX / 26))
  489. break;
  490. c = tolower(s[0]) - 'a';
  491. if (unlikely(c < 0 || c > 25))
  492. break;
  493. if (unlikely(INT_MAX - c < n))
  494. break;
  495. n = (n * 26) + c;
  496. }
  497. *rem = s;
  498. return n;
  499. }
  500. static
  501. bool cgpu_match(const char * const pattern, const struct cgpu_info * const cgpu)
  502. {
  503. // all - matches anything
  504. // d0 - matches all processors of device 0
  505. // d0-3 - matches all processors of device 0, 1, 2, or 3
  506. // d0a - matches first processor of device 0
  507. // 0 - matches processor 0
  508. // 0-4 - matches processors 0, 1, 2, 3, or 4
  509. // ___ - matches all processors on all devices using driver/name ___
  510. // ___0 - matches all processors of 0th device using driver/name ___
  511. // ___0a - matches first processor of 0th device using driver/name ___
  512. // @* - matches device with serial or path *
  513. // @*@a - matches first processor of device with serial or path *
  514. // ___@* - matches device with serial or path * using driver/name ___
  515. if (!strcasecmp(pattern, "all"))
  516. return true;
  517. const struct device_drv * const drv = cgpu->drv;
  518. const char *p = pattern, *p2;
  519. size_t L;
  520. int n, i, c = -1;
  521. int n2;
  522. int proc_first = -1, proc_last = -1;
  523. struct cgpu_info *device;
  524. if (!(strncasecmp(drv->dname, p, (L = strlen(drv->dname)))
  525. && strncasecmp(drv-> name, p, (L = strlen(drv-> name)))))
  526. // dname or name
  527. p = &pattern[L];
  528. else
  529. if (p[0] == 'd' && (isdigit(p[1]) || p[1] == '-'))
  530. // d#
  531. ++p;
  532. else
  533. if (isdigit(p[0]) || p[0] == '@' || p[0] == '-')
  534. // # or @
  535. {}
  536. else
  537. return false;
  538. L = p - pattern;
  539. while (isspace(p[0]))
  540. ++p;
  541. if (p[0] == '@')
  542. {
  543. // Serial/path
  544. const char * const ser = &p[1];
  545. for (p = ser; p[0] != '@' && p[0] != '\0'; ++p)
  546. {}
  547. p2 = (p[0] == '@') ? &p[1] : p;
  548. const size_t serlen = (p - ser);
  549. p = "";
  550. n = n2 = 0;
  551. const char * const devpath = cgpu->device_path ?: "";
  552. const char * const devser = cgpu->dev_serial ?: "";
  553. if ((!strncmp(devpath, ser, serlen)) && devpath[serlen] == '\0')
  554. {} // Match
  555. else
  556. if ((!strncmp(devser, ser, serlen)) && devser[serlen] == '\0')
  557. {} // Match
  558. else
  559. {
  560. char devpath2[serlen + 1];
  561. memcpy(devpath2, ser, serlen);
  562. devpath2[serlen] = '\0';
  563. if (!devpaths_match(devpath, ser))
  564. return false;
  565. }
  566. }
  567. else
  568. {
  569. if (isdigit(p[0]))
  570. n = strtol(p, (void*)&p2, 0);
  571. else
  572. {
  573. n = 0;
  574. p2 = p;
  575. }
  576. if (p2[0] == '-')
  577. {
  578. ++p2;
  579. if (p2[0] && isdigit(p2[0]))
  580. n2 = strtol(p2, (void*)&p2, 0);
  581. else
  582. n2 = INT_MAX;
  583. }
  584. else
  585. n2 = n;
  586. if (p == pattern)
  587. {
  588. if (!p[0])
  589. return true;
  590. if (p2 && p2[0])
  591. goto invsyntax;
  592. for (i = n; i <= n2; ++i)
  593. {
  594. if (i >= total_devices)
  595. break;
  596. if (cgpu == devices[i])
  597. return true;
  598. }
  599. return false;
  600. }
  601. }
  602. if (p2[0])
  603. {
  604. proc_first = proc_letter_to_number(&p2[0], &p2);
  605. if (p2[0] == '-')
  606. {
  607. ++p2;
  608. if (p2[0])
  609. proc_last = proc_letter_to_number(p2, &p2);
  610. else
  611. proc_last = INT_MAX;
  612. }
  613. else
  614. proc_last = proc_first;
  615. if (p2[0])
  616. goto invsyntax;
  617. }
  618. if (L > 1 || tolower(pattern[0]) != 'd' || !p[0])
  619. {
  620. if ((L == 3 && !strncasecmp(pattern, drv->name, 3)) ||
  621. (!L) ||
  622. (L == strlen(drv->dname) && !strncasecmp(pattern, drv->dname, L)))
  623. {} // Matched name or dname
  624. else
  625. return false;
  626. if (p[0] && (cgpu->device_id < n || cgpu->device_id > n2))
  627. return false;
  628. if (proc_first != -1 && (cgpu->proc_id < proc_first || cgpu->proc_id > proc_last))
  629. return false;
  630. return true;
  631. }
  632. // d#
  633. c = -1;
  634. for (i = 0; ; ++i)
  635. {
  636. if (i == total_devices)
  637. return false;
  638. if (devices[i]->device != devices[i])
  639. continue;
  640. ++c;
  641. if (c < n)
  642. continue;
  643. if (c > n2)
  644. break;
  645. for (device = devices[i]; device; device = device->next_proc)
  646. {
  647. if (proc_first != -1 && (device->proc_id < proc_first || device->proc_id > proc_last))
  648. continue;
  649. if (device == cgpu)
  650. return true;
  651. }
  652. }
  653. return false;
  654. invsyntax:
  655. applog(LOG_WARNING, "%s: Invalid syntax: %s", __func__, pattern);
  656. return false;
  657. }
  658. #define TEST_CGPU_MATCH(pattern) \
  659. if (!cgpu_match(pattern, &cgpu)) \
  660. { \
  661. ++unittest_failures; \
  662. applog(LOG_ERR, "%s: Pattern \"%s\" should have matched!", __func__, pattern); \
  663. } \
  664. // END TEST_CGPU_MATCH
  665. #define TEST_CGPU_NOMATCH(pattern) \
  666. if (cgpu_match(pattern, &cgpu)) \
  667. { \
  668. ++unittest_failures; \
  669. applog(LOG_ERR, "%s: Pattern \"%s\" should NOT have matched!", __func__, pattern); \
  670. } \
  671. // END TEST_CGPU_MATCH
  672. static __maybe_unused
  673. void test_cgpu_match()
  674. {
  675. struct device_drv drv = {
  676. .dname = "test",
  677. .name = "TST",
  678. };
  679. struct cgpu_info cgpu = {
  680. .drv = &drv,
  681. .device = &cgpu,
  682. .device_id = 1,
  683. .proc_id = 1,
  684. .proc_repr = "TST 1b",
  685. }, cgpu0a = {
  686. .drv = &drv,
  687. .device = &cgpu0a,
  688. .device_id = 0,
  689. .proc_id = 0,
  690. .proc_repr = "TST 0a",
  691. }, cgpu1a = {
  692. .drv = &drv,
  693. .device = &cgpu0a,
  694. .device_id = 1,
  695. .proc_id = 0,
  696. .proc_repr = "TST 1a",
  697. };
  698. struct cgpu_info *devices_list[3] = {&cgpu0a, &cgpu1a, &cgpu,};
  699. devices = devices_list;
  700. total_devices = 3;
  701. TEST_CGPU_MATCH("all")
  702. TEST_CGPU_MATCH("d1")
  703. TEST_CGPU_NOMATCH("d2")
  704. TEST_CGPU_MATCH("d0-5")
  705. TEST_CGPU_NOMATCH("d0-0")
  706. TEST_CGPU_NOMATCH("d2-5")
  707. TEST_CGPU_MATCH("d-1")
  708. TEST_CGPU_MATCH("d1-")
  709. TEST_CGPU_NOMATCH("d-0")
  710. TEST_CGPU_NOMATCH("d2-")
  711. TEST_CGPU_MATCH("2")
  712. TEST_CGPU_NOMATCH("3")
  713. TEST_CGPU_MATCH("1-2")
  714. TEST_CGPU_MATCH("2-3")
  715. TEST_CGPU_NOMATCH("1-1")
  716. TEST_CGPU_NOMATCH("3-4")
  717. TEST_CGPU_MATCH("TST")
  718. TEST_CGPU_MATCH("test")
  719. TEST_CGPU_MATCH("tst")
  720. TEST_CGPU_MATCH("TEST")
  721. TEST_CGPU_NOMATCH("TSF")
  722. TEST_CGPU_NOMATCH("TS")
  723. TEST_CGPU_NOMATCH("TSTF")
  724. TEST_CGPU_MATCH("TST1")
  725. TEST_CGPU_MATCH("test1")
  726. TEST_CGPU_MATCH("TST0-1")
  727. TEST_CGPU_MATCH("TST 1")
  728. TEST_CGPU_MATCH("TST 1-2")
  729. TEST_CGPU_MATCH("TEST 1-2")
  730. TEST_CGPU_NOMATCH("TST2")
  731. TEST_CGPU_NOMATCH("TST2-3")
  732. TEST_CGPU_NOMATCH("TST0-0")
  733. TEST_CGPU_MATCH("TST1b")
  734. TEST_CGPU_MATCH("tst1b")
  735. TEST_CGPU_NOMATCH("TST1c")
  736. TEST_CGPU_NOMATCH("TST1bb")
  737. TEST_CGPU_MATCH("TST0-1b")
  738. TEST_CGPU_NOMATCH("TST0-1c")
  739. TEST_CGPU_MATCH("TST1a-d")
  740. TEST_CGPU_NOMATCH("TST1a-a")
  741. TEST_CGPU_NOMATCH("TST1-a")
  742. TEST_CGPU_NOMATCH("TST1c-z")
  743. TEST_CGPU_NOMATCH("TST1c-")
  744. TEST_CGPU_MATCH("@")
  745. TEST_CGPU_NOMATCH("@abc")
  746. TEST_CGPU_MATCH("@@b")
  747. TEST_CGPU_NOMATCH("@@c")
  748. TEST_CGPU_MATCH("TST@")
  749. TEST_CGPU_NOMATCH("TST@abc")
  750. TEST_CGPU_MATCH("TST@@b")
  751. TEST_CGPU_NOMATCH("TST@@c")
  752. TEST_CGPU_MATCH("TST@@b-f")
  753. TEST_CGPU_NOMATCH("TST@@c-f")
  754. TEST_CGPU_NOMATCH("TST@@-a")
  755. cgpu.device_path = "/dev/test";
  756. cgpu.dev_serial = "testy";
  757. TEST_CGPU_MATCH("TST@/dev/test")
  758. TEST_CGPU_MATCH("TST@testy")
  759. TEST_CGPU_NOMATCH("TST@")
  760. TEST_CGPU_NOMATCH("TST@/dev/test5@b")
  761. TEST_CGPU_NOMATCH("TST@testy3@b")
  762. TEST_CGPU_MATCH("TST@/dev/test@b")
  763. TEST_CGPU_MATCH("TST@testy@b")
  764. TEST_CGPU_NOMATCH("TST@/dev/test@c")
  765. TEST_CGPU_NOMATCH("TST@testy@c")
  766. cgpu.device_path = "usb:000:999";
  767. TEST_CGPU_MATCH("TST@usb:000:999")
  768. drv.dname = "test7";
  769. TEST_CGPU_MATCH("test7")
  770. TEST_CGPU_MATCH("TEST7")
  771. TEST_CGPU_NOMATCH("test&")
  772. TEST_CGPU_MATCH("test7 1-2")
  773. TEST_CGPU_MATCH("test7@testy@b")
  774. }
  775. static
  776. int cgpu_search(const char * const pattern, const int first)
  777. {
  778. int i;
  779. struct cgpu_info *cgpu;
  780. #define CHECK_CGPU_SEARCH do{ \
  781. cgpu = get_devices(i); \
  782. if (cgpu_match(pattern, cgpu)) \
  783. return i; \
  784. }while(0)
  785. for (i = first; i < total_devices; ++i)
  786. CHECK_CGPU_SEARCH;
  787. for (i = 0; i < first; ++i)
  788. CHECK_CGPU_SEARCH;
  789. #undef CHECK_CGPU_SEARCH
  790. return -1;
  791. }
  792. static pthread_mutex_t sharelog_lock;
  793. static FILE *sharelog_file = NULL;
  794. struct thr_info *get_thread(int thr_id)
  795. {
  796. struct thr_info *thr;
  797. rd_lock(&mining_thr_lock);
  798. thr = mining_thr[thr_id];
  799. rd_unlock(&mining_thr_lock);
  800. return thr;
  801. }
  802. static struct cgpu_info *get_thr_cgpu(int thr_id)
  803. {
  804. struct thr_info *thr = get_thread(thr_id);
  805. return thr->cgpu;
  806. }
  807. struct cgpu_info *get_devices(int id)
  808. {
  809. struct cgpu_info *cgpu;
  810. rd_lock(&devices_lock);
  811. cgpu = devices[id];
  812. rd_unlock(&devices_lock);
  813. return cgpu;
  814. }
  815. static pthread_mutex_t noncelog_lock = PTHREAD_MUTEX_INITIALIZER;
  816. static FILE *noncelog_file = NULL;
  817. static
  818. void noncelog(const struct work * const work)
  819. {
  820. const int thr_id = work->thr_id;
  821. const struct cgpu_info *proc = get_thr_cgpu(thr_id);
  822. char buf[0x200], hash[65], data[161], midstate[65];
  823. int rv;
  824. size_t ret;
  825. bin2hex(hash, work->hash, 32);
  826. bin2hex(data, work->data, 80);
  827. bin2hex(midstate, work->midstate, 32);
  828. // timestamp,proc,hash,data,midstate
  829. rv = snprintf(buf, sizeof(buf), "%lu,%s,%s,%s,%s\n",
  830. (unsigned long)time(NULL), proc->proc_repr_ns,
  831. hash, data, midstate);
  832. if (unlikely(rv < 1))
  833. {
  834. applog(LOG_ERR, "noncelog printf error");
  835. return;
  836. }
  837. mutex_lock(&noncelog_lock);
  838. ret = fwrite(buf, rv, 1, noncelog_file);
  839. fflush(noncelog_file);
  840. mutex_unlock(&noncelog_lock);
  841. if (ret != 1)
  842. applog(LOG_ERR, "noncelog fwrite error");
  843. }
  844. static void sharelog(const char*disposition, const struct work*work)
  845. {
  846. char target[(sizeof(work->target) * 2) + 1];
  847. char hash[(sizeof(work->hash) * 2) + 1];
  848. char data[(sizeof(work->data) * 2) + 1];
  849. struct cgpu_info *cgpu;
  850. unsigned long int t;
  851. struct pool *pool;
  852. int thr_id, rv;
  853. char s[1024];
  854. size_t ret;
  855. if (!sharelog_file)
  856. return;
  857. thr_id = work->thr_id;
  858. cgpu = get_thr_cgpu(thr_id);
  859. pool = work->pool;
  860. t = work->ts_getwork + timer_elapsed(&work->tv_getwork, &work->tv_work_found);
  861. bin2hex(target, work->target, sizeof(work->target));
  862. bin2hex(hash, work->hash, sizeof(work->hash));
  863. bin2hex(data, work->data, sizeof(work->data));
  864. // timestamp,disposition,target,pool,dev,thr,sharehash,sharedata
  865. 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);
  866. if (rv >= (int)(sizeof(s)))
  867. s[sizeof(s) - 1] = '\0';
  868. else if (rv < 0) {
  869. applog(LOG_ERR, "sharelog printf error");
  870. return;
  871. }
  872. mutex_lock(&sharelog_lock);
  873. ret = fwrite(s, rv, 1, sharelog_file);
  874. fflush(sharelog_file);
  875. mutex_unlock(&sharelog_lock);
  876. if (ret != 1)
  877. applog(LOG_ERR, "sharelog fwrite error");
  878. }
  879. #ifdef HAVE_CURSES
  880. static void switch_logsize(void);
  881. #endif
  882. static
  883. int mining_goals_name_cmp(const struct mining_goal_info * const a, const struct mining_goal_info * const b)
  884. {
  885. // default always goes first
  886. if (a->is_default)
  887. return -1;
  888. if (b->is_default)
  889. return 1;
  890. return strcmp(a->name, b->name);
  891. }
  892. struct mining_goal_info *get_mining_goal(const char * const name)
  893. {
  894. struct mining_goal_info *goal;
  895. HASH_FIND_STR(mining_goals, name, goal);
  896. if (!goal)
  897. {
  898. struct block_info * const dummy_block = calloc(sizeof(*dummy_block), 1);
  899. memset(dummy_block->prevblkhash, 0, 0x20);
  900. struct blockchain_info * const blkchain = malloc(sizeof(*blkchain) + sizeof(*goal));
  901. goal = (void*)(&blkchain[1]);
  902. *blkchain = (struct blockchain_info){
  903. .currentblk = dummy_block,
  904. };
  905. HASH_ADD(hh, blkchain->blocks, prevblkhash, sizeof(dummy_block->prevblkhash), dummy_block);
  906. *goal = (struct mining_goal_info){
  907. .name = strdup(name),
  908. .is_default = !strcmp(name, "default"),
  909. .blkchain = blkchain,
  910. .current_diff = 0xFFFFFFFFFFFFFFFFULL,
  911. };
  912. HASH_ADD_STR(mining_goals, name, goal);
  913. HASH_SORT(mining_goals, mining_goals_name_cmp);
  914. #ifdef HAVE_CURSES
  915. devcursor = 7 + active_goals;
  916. switch_logsize();
  917. #endif
  918. }
  919. return goal;
  920. }
  921. static char *getwork_req = "{\"method\": \"getwork\", \"params\": [], \"id\":0}\n";
  922. /* Adjust all the pools' quota to the greatest common denominator after a pool
  923. * has been added or the quotas changed. */
  924. void adjust_quota_gcd(void)
  925. {
  926. unsigned long gcd, lowest_quota = ~0UL, quota;
  927. struct pool *pool;
  928. int i;
  929. for (i = 0; i < total_pools; i++) {
  930. pool = pools[i];
  931. quota = pool->quota;
  932. if (!quota)
  933. continue;
  934. if (quota < lowest_quota)
  935. lowest_quota = quota;
  936. }
  937. if (likely(lowest_quota < ~0UL)) {
  938. gcd = lowest_quota;
  939. for (i = 0; i < total_pools; i++) {
  940. pool = pools[i];
  941. quota = pool->quota;
  942. if (!quota)
  943. continue;
  944. while (quota % gcd)
  945. gcd--;
  946. }
  947. } else
  948. gcd = 1;
  949. for (i = 0; i < total_pools; i++) {
  950. pool = pools[i];
  951. pool->quota_used *= global_quota_gcd;
  952. pool->quota_used /= gcd;
  953. pool->quota_gcd = pool->quota / gcd;
  954. }
  955. global_quota_gcd = gcd;
  956. applog(LOG_DEBUG, "Global quota greatest common denominator set to %lu", gcd);
  957. }
  958. /* Return value is ignored if not called from add_pool_details */
  959. struct pool *add_pool(void)
  960. {
  961. struct pool *pool;
  962. pool = calloc(sizeof(struct pool), 1);
  963. if (!pool)
  964. quit(1, "Failed to malloc pool in add_pool");
  965. pool->pool_no = pool->prio = total_pools;
  966. mutex_init(&pool->last_work_lock);
  967. mutex_init(&pool->pool_lock);
  968. mutex_init(&pool->pool_test_lock);
  969. if (unlikely(pthread_cond_init(&pool->cr_cond, bfg_condattr)))
  970. quit(1, "Failed to pthread_cond_init in add_pool");
  971. cglock_init(&pool->data_lock);
  972. mutex_init(&pool->stratum_lock);
  973. timer_unset(&pool->swork.tv_transparency);
  974. pool->swork.pool = pool;
  975. pool->goal = get_mining_goal("default");
  976. pool->idle = true;
  977. /* Make sure the pool doesn't think we've been idle since time 0 */
  978. pool->tv_idle.tv_sec = ~0UL;
  979. cgtime(&pool->cgminer_stats.start_tv);
  980. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  981. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  982. pool->rpc_proxy = NULL;
  983. pool->quota = 1;
  984. pool->sock = INVSOCK;
  985. pool->lp_socket = CURL_SOCKET_BAD;
  986. pools = realloc(pools, sizeof(struct pool *) * (total_pools + 2));
  987. pools[total_pools++] = pool;
  988. if (opt_benchmark)
  989. {
  990. // Immediately remove it
  991. remove_pool(pool);
  992. return pool;
  993. }
  994. adjust_quota_gcd();
  995. if (!currentpool)
  996. currentpool = pool;
  997. enable_pool(pool);
  998. return pool;
  999. }
  1000. static
  1001. void pool_set_uri(struct pool * const pool, char * const uri)
  1002. {
  1003. pool->rpc_url = uri;
  1004. #if BLKMAKER_VERSION > 1
  1005. if (uri_get_param_bool(uri, "getcbaddr", false))
  1006. have_at_least_one_getcbaddr = true;
  1007. #endif
  1008. }
  1009. /* Pool variant of test and set */
  1010. static bool pool_tset(struct pool *pool, bool *var)
  1011. {
  1012. bool ret;
  1013. mutex_lock(&pool->pool_lock);
  1014. ret = *var;
  1015. *var = true;
  1016. mutex_unlock(&pool->pool_lock);
  1017. return ret;
  1018. }
  1019. bool pool_tclear(struct pool *pool, bool *var)
  1020. {
  1021. bool ret;
  1022. mutex_lock(&pool->pool_lock);
  1023. ret = *var;
  1024. *var = false;
  1025. mutex_unlock(&pool->pool_lock);
  1026. return ret;
  1027. }
  1028. struct pool *current_pool(void)
  1029. {
  1030. struct pool *pool;
  1031. cg_rlock(&control_lock);
  1032. pool = currentpool;
  1033. cg_runlock(&control_lock);
  1034. return pool;
  1035. }
  1036. static
  1037. char *set_bool_ignore_arg(const char * const arg, bool * const b)
  1038. {
  1039. return opt_set_bool(b);
  1040. }
  1041. char *set_int_range(const char *arg, int *i, int min, int max)
  1042. {
  1043. char *err = opt_set_intval(arg, i);
  1044. if (err)
  1045. return err;
  1046. if (*i < min || *i > max)
  1047. return "Value out of range";
  1048. return NULL;
  1049. }
  1050. static char *set_int_0_to_9999(const char *arg, int *i)
  1051. {
  1052. return set_int_range(arg, i, 0, 9999);
  1053. }
  1054. static char *set_int_1_to_65535(const char *arg, int *i)
  1055. {
  1056. return set_int_range(arg, i, 1, 65535);
  1057. }
  1058. static char *set_int_0_to_10(const char *arg, int *i)
  1059. {
  1060. return set_int_range(arg, i, 0, 10);
  1061. }
  1062. static char *set_int_1_to_10(const char *arg, int *i)
  1063. {
  1064. return set_int_range(arg, i, 1, 10);
  1065. }
  1066. char *set_strdup(const char *arg, char **p)
  1067. {
  1068. *p = strdup((char *)arg);
  1069. return NULL;
  1070. }
  1071. #if BLKMAKER_VERSION > 1
  1072. static
  1073. char *set_b58addr(const char * const arg, bytes_t * const b)
  1074. {
  1075. size_t scriptsz = blkmk_address_to_script(NULL, 0, arg);
  1076. if (!scriptsz)
  1077. return "Invalid address";
  1078. char *script = malloc(scriptsz);
  1079. if (blkmk_address_to_script(script, scriptsz, arg) != scriptsz) {
  1080. free(script);
  1081. return "Failed to convert address to script";
  1082. }
  1083. bytes_assimilate_raw(b, script, scriptsz, scriptsz);
  1084. return NULL;
  1085. }
  1086. #endif
  1087. static
  1088. char *set_quit_summary(const char * const arg)
  1089. {
  1090. if (!(strcasecmp(arg, "none") && strcasecmp(arg, "no")))
  1091. opt_quit_summary = BQS_NONE;
  1092. else
  1093. if (!(strcasecmp(arg, "devs") && strcasecmp(arg, "devices")))
  1094. opt_quit_summary = BQS_DEVS;
  1095. else
  1096. if (!(strcasecmp(arg, "procs") && strcasecmp(arg, "processors") && strcasecmp(arg, "chips") && strcasecmp(arg, "cores")))
  1097. opt_quit_summary = BQS_PROCS;
  1098. else
  1099. if (!(strcasecmp(arg, "detailed") && strcasecmp(arg, "detail") && strcasecmp(arg, "all")))
  1100. opt_quit_summary = BQS_DETAILED;
  1101. else
  1102. return "Quit summary must be one of none/devs/procs/detailed";
  1103. return NULL;
  1104. }
  1105. static void pdiff_target_leadzero(void *, double);
  1106. char *set_request_diff(const char *arg, float *p)
  1107. {
  1108. unsigned char target[32];
  1109. char *e = opt_set_floatval(arg, p);
  1110. if (e)
  1111. return e;
  1112. request_bdiff = (double)*p * 0.9999847412109375;
  1113. pdiff_target_leadzero(target, *p);
  1114. request_target_str = malloc(65);
  1115. bin2hex(request_target_str, target, 32);
  1116. return NULL;
  1117. }
  1118. #ifdef NEED_BFG_LOWL_VCOM
  1119. extern struct lowlevel_device_info *_vcom_devinfo_findorcreate(struct lowlevel_device_info **, const char *);
  1120. #ifdef WIN32
  1121. void _vcom_devinfo_scan_querydosdevice(struct lowlevel_device_info ** const devinfo_list)
  1122. {
  1123. char dev[PATH_MAX];
  1124. char *devp = dev;
  1125. size_t bufLen = 0x100;
  1126. tryagain: ;
  1127. char buf[bufLen];
  1128. if (!QueryDosDevice(NULL, buf, bufLen)) {
  1129. if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
  1130. bufLen *= 2;
  1131. applog(LOG_DEBUG, "QueryDosDevice returned insufficent buffer error; enlarging to %lx", (unsigned long)bufLen);
  1132. goto tryagain;
  1133. }
  1134. applogr(, LOG_WARNING, "Error occurred trying to enumerate COM ports with QueryDosDevice");
  1135. }
  1136. size_t tLen;
  1137. memcpy(devp, "\\\\.\\", 4);
  1138. devp = &devp[4];
  1139. for (char *t = buf; *t; t += tLen) {
  1140. tLen = strlen(t) + 1;
  1141. if (strncmp("COM", t, 3))
  1142. continue;
  1143. memcpy(devp, t, tLen);
  1144. // NOTE: We depend on _vcom_devinfo_findorcreate to further check that there's a number (and only a number) on the end
  1145. _vcom_devinfo_findorcreate(devinfo_list, dev);
  1146. }
  1147. }
  1148. #else
  1149. void _vcom_devinfo_scan_lsdev(struct lowlevel_device_info ** const devinfo_list)
  1150. {
  1151. char dev[PATH_MAX];
  1152. char *devp = dev;
  1153. DIR *D;
  1154. struct dirent *de;
  1155. const char devdir[] = "/dev";
  1156. const size_t devdirlen = sizeof(devdir) - 1;
  1157. char *devpath = devp;
  1158. char *devfile = devpath + devdirlen + 1;
  1159. D = opendir(devdir);
  1160. if (!D)
  1161. applogr(, LOG_DEBUG, "No /dev directory to look for VCOM devices in");
  1162. memcpy(devpath, devdir, devdirlen);
  1163. devpath[devdirlen] = '/';
  1164. while ( (de = readdir(D)) ) {
  1165. if (!strncmp(de->d_name, "cu.", 3)
  1166. //don't probe Bluetooth devices - causes bus errors and segfaults
  1167. && strncmp(de->d_name, "cu.Bluetooth", 12))
  1168. goto trydev;
  1169. if (strncmp(de->d_name, "tty", 3))
  1170. continue;
  1171. if (strncmp(&de->d_name[3], "USB", 3) && strncmp(&de->d_name[3], "ACM", 3))
  1172. continue;
  1173. trydev:
  1174. strcpy(devfile, de->d_name);
  1175. _vcom_devinfo_findorcreate(devinfo_list, dev);
  1176. }
  1177. closedir(D);
  1178. }
  1179. #endif
  1180. #endif
  1181. static char *add_serial(const char *arg)
  1182. {
  1183. string_elist_add(arg, &scan_devices);
  1184. return NULL;
  1185. }
  1186. static
  1187. char *opt_string_elist_add(const char *arg, struct string_elist **elist)
  1188. {
  1189. string_elist_add(arg, elist);
  1190. return NULL;
  1191. }
  1192. bool get_intrange(const char *arg, int *val1, int *val2)
  1193. {
  1194. // NOTE: This could be done with sscanf, but its %n is broken in strange ways on Windows
  1195. char *p, *p2;
  1196. *val1 = strtol(arg, &p, 0);
  1197. if (arg == p)
  1198. // Zero-length ending number, invalid
  1199. return false;
  1200. while (true)
  1201. {
  1202. if (!p[0])
  1203. {
  1204. *val2 = *val1;
  1205. return true;
  1206. }
  1207. if (p[0] == '-')
  1208. break;
  1209. if (!isspace(p[0]))
  1210. // Garbage, invalid
  1211. return false;
  1212. ++p;
  1213. }
  1214. p2 = &p[1];
  1215. *val2 = strtol(p2, &p, 0);
  1216. if (p2 == p)
  1217. // Zero-length ending number, invalid
  1218. return false;
  1219. while (true)
  1220. {
  1221. if (!p[0])
  1222. return true;
  1223. if (!isspace(p[0]))
  1224. // Garbage, invalid
  1225. return false;
  1226. ++p;
  1227. }
  1228. }
  1229. static
  1230. void _test_intrange(const char *s, const int v[2])
  1231. {
  1232. int a[2];
  1233. if (!get_intrange(s, &a[0], &a[1]))
  1234. {
  1235. ++unittest_failures;
  1236. applog(LOG_ERR, "Test \"%s\" failed: returned false", s);
  1237. }
  1238. for (int i = 0; i < 2; ++i)
  1239. if (unlikely(a[i] != v[i]))
  1240. {
  1241. ++unittest_failures;
  1242. applog(LOG_ERR, "Test \"%s\" failed: value %d should be %d but got %d", s, i, v[i], a[i]);
  1243. }
  1244. }
  1245. #define _test_intrange(s, ...) _test_intrange(s, (int[]){ __VA_ARGS__ })
  1246. static
  1247. void _test_intrange_fail(const char *s)
  1248. {
  1249. int a[2];
  1250. if (get_intrange(s, &a[0], &a[1]))
  1251. {
  1252. ++unittest_failures;
  1253. applog(LOG_ERR, "Test !\"%s\" failed: returned true with %d and %d", s, a[0], a[1]);
  1254. }
  1255. }
  1256. static
  1257. void test_intrange()
  1258. {
  1259. _test_intrange("-1--2", -1, -2);
  1260. _test_intrange("-1-2", -1, 2);
  1261. _test_intrange("1--2", 1, -2);
  1262. _test_intrange("1-2", 1, 2);
  1263. _test_intrange("111-222", 111, 222);
  1264. _test_intrange(" 11 - 22 ", 11, 22);
  1265. _test_intrange("+11-+22", 11, 22);
  1266. _test_intrange("-1", -1, -1);
  1267. _test_intrange_fail("all");
  1268. _test_intrange_fail("1-");
  1269. _test_intrange_fail("");
  1270. _test_intrange_fail("1-54x");
  1271. }
  1272. static char *set_devices(char *arg)
  1273. {
  1274. if (*arg) {
  1275. if (*arg == '?') {
  1276. opt_display_devs = true;
  1277. return NULL;
  1278. }
  1279. } else
  1280. return "Invalid device parameters";
  1281. string_elist_add(arg, &opt_devices_enabled_list);
  1282. return NULL;
  1283. }
  1284. static char *set_balance(enum pool_strategy *strategy)
  1285. {
  1286. *strategy = POOL_BALANCE;
  1287. return NULL;
  1288. }
  1289. static char *set_loadbalance(enum pool_strategy *strategy)
  1290. {
  1291. *strategy = POOL_LOADBALANCE;
  1292. return NULL;
  1293. }
  1294. static char *set_rotate(const char *arg, int *i)
  1295. {
  1296. pool_strategy = POOL_ROTATE;
  1297. return set_int_range(arg, i, 0, 9999);
  1298. }
  1299. static char *set_rr(enum pool_strategy *strategy)
  1300. {
  1301. *strategy = POOL_ROUNDROBIN;
  1302. return NULL;
  1303. }
  1304. static
  1305. char *set_benchmark_intense()
  1306. {
  1307. opt_benchmark = true;
  1308. opt_benchmark_intense = true;
  1309. return NULL;
  1310. }
  1311. /* Detect that url is for a stratum protocol either via the presence of
  1312. * stratum+tcp or by detecting a stratum server response */
  1313. bool detect_stratum(struct pool *pool, char *url)
  1314. {
  1315. if (!extract_sockaddr(url, &pool->sockaddr_url, &pool->stratum_port))
  1316. return false;
  1317. if (!strncasecmp(url, "stratum+tcp://", 14)) {
  1318. pool_set_uri(pool, strdup(url));
  1319. pool->has_stratum = true;
  1320. pool->stratum_url = pool->sockaddr_url;
  1321. return true;
  1322. }
  1323. return false;
  1324. }
  1325. static struct pool *add_url(void)
  1326. {
  1327. total_urls++;
  1328. if (total_urls > total_pools)
  1329. add_pool();
  1330. return pools[total_urls - 1];
  1331. }
  1332. static void setup_url(struct pool *pool, char *arg)
  1333. {
  1334. if (detect_stratum(pool, arg))
  1335. return;
  1336. opt_set_charp(arg, &pool->rpc_url);
  1337. if (strncmp(arg, "http://", 7) &&
  1338. strncmp(arg, "https://", 8)) {
  1339. const size_t L = strlen(arg);
  1340. char *httpinput;
  1341. httpinput = malloc(8 + L);
  1342. if (!httpinput)
  1343. quit(1, "Failed to malloc httpinput");
  1344. sprintf(httpinput, "http://%s", arg);
  1345. pool_set_uri(pool, httpinput);
  1346. }
  1347. }
  1348. static char *set_url(char *arg)
  1349. {
  1350. struct pool *pool = add_url();
  1351. setup_url(pool, arg);
  1352. return NULL;
  1353. }
  1354. static char *set_quota(char *arg)
  1355. {
  1356. char *semicolon = strchr(arg, ';'), *url;
  1357. int len, qlen, quota;
  1358. struct pool *pool;
  1359. if (!semicolon)
  1360. return "No semicolon separated quota;URL pair found";
  1361. len = strlen(arg);
  1362. *semicolon = '\0';
  1363. qlen = strlen(arg);
  1364. if (!qlen)
  1365. return "No parameter for quota found";
  1366. len -= qlen + 1;
  1367. if (len < 1)
  1368. return "No parameter for URL found";
  1369. quota = atoi(arg);
  1370. if (quota < 0)
  1371. return "Invalid negative parameter for quota set";
  1372. url = arg + qlen + 1;
  1373. pool = add_url();
  1374. setup_url(pool, url);
  1375. pool->quota = quota;
  1376. applog(LOG_INFO, "Setting pool %d to quota %d", pool->pool_no, pool->quota);
  1377. adjust_quota_gcd();
  1378. return NULL;
  1379. }
  1380. static char *set_user(const char *arg)
  1381. {
  1382. struct pool *pool;
  1383. total_users++;
  1384. if (total_users > total_pools)
  1385. add_pool();
  1386. pool = pools[total_users - 1];
  1387. opt_set_charp(arg, &pool->rpc_user);
  1388. return NULL;
  1389. }
  1390. static char *set_pass(const char *arg)
  1391. {
  1392. struct pool *pool;
  1393. total_passes++;
  1394. if (total_passes > total_pools)
  1395. add_pool();
  1396. pool = pools[total_passes - 1];
  1397. opt_set_charp(arg, &pool->rpc_pass);
  1398. return NULL;
  1399. }
  1400. static char *set_userpass(const char *arg)
  1401. {
  1402. struct pool *pool;
  1403. char *updup;
  1404. if (total_users != total_passes)
  1405. return "User + pass options must be balanced before userpass";
  1406. ++total_users;
  1407. ++total_passes;
  1408. if (total_users > total_pools)
  1409. add_pool();
  1410. pool = pools[total_users - 1];
  1411. updup = strdup(arg);
  1412. opt_set_charp(arg, &pool->rpc_userpass);
  1413. pool->rpc_user = updup;
  1414. pool->rpc_pass = strchr(updup, ':');
  1415. if (pool->rpc_pass)
  1416. pool->rpc_pass++[0] = '\0';
  1417. else
  1418. pool->rpc_pass = &updup[strlen(updup)];
  1419. return NULL;
  1420. }
  1421. static char *set_cbcaddr(char *arg)
  1422. {
  1423. struct pool *pool;
  1424. char *p, *addr;
  1425. bytes_t target_script = BYTES_INIT;
  1426. if (!total_pools)
  1427. return "Define pool first, then the --coinbase-check-addr list";
  1428. pool = pools[total_pools - 1];
  1429. /* NOTE: 'x' is a new prefix which leads both mainnet and testnet address, we would
  1430. * need support it later, but now leave the code just so.
  1431. *
  1432. * Regarding details of address prefix 'x', check the below URL:
  1433. * https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#Serialization_format
  1434. */
  1435. pool->cb_param.testnet = (arg[0] != '1' && arg[0] != '3' && arg[0] != 'x');
  1436. for (; (addr = strtok_r(arg, ",", &p)); arg = NULL)
  1437. {
  1438. struct bytes_hashtbl *ah;
  1439. if (set_b58addr(addr, &target_script))
  1440. /* No bother to free memory since we are going to exit anyway */
  1441. return "Invalid address in --coinbase-check-address list";
  1442. HASH_FIND(hh, pool->cb_param.scripts, bytes_buf(&target_script), bytes_len(&target_script), ah);
  1443. if (!ah)
  1444. {
  1445. /* Note: for the below allocated memory we have good way to release its memory
  1446. * since we can't be sure there are no reference to the pool struct when remove_pool()
  1447. * get called.
  1448. *
  1449. * We just hope the remove_pool() would not be called many many times during
  1450. * the whole running life of this program.
  1451. */
  1452. ah = malloc(sizeof(*ah));
  1453. bytes_init(&ah->b);
  1454. bytes_assimilate(&ah->b, &target_script);
  1455. HASH_ADD(hh, pool->cb_param.scripts, b.buf, bytes_len(&ah->b), ah);
  1456. }
  1457. }
  1458. bytes_free(&target_script);
  1459. return NULL;
  1460. }
  1461. static char *set_cbctotal(const char *arg)
  1462. {
  1463. struct pool *pool;
  1464. if (!total_pools)
  1465. return "Define pool first, then the --coinbase-check-total argument";
  1466. pool = pools[total_pools - 1];
  1467. pool->cb_param.total = atoll(arg);
  1468. if (pool->cb_param.total < 0)
  1469. return "The total payout amount in coinbase should be greater than 0";
  1470. return NULL;
  1471. }
  1472. static char *set_cbcperc(const char *arg)
  1473. {
  1474. struct pool *pool;
  1475. if (!total_pools)
  1476. return "Define pool first, then the --coinbase-check-percent argument";
  1477. pool = pools[total_pools - 1];
  1478. if (!pool->cb_param.scripts)
  1479. return "Define --coinbase-check-addr list first, then the --coinbase-check-total argument";
  1480. pool->cb_param.perc = atof(arg) / 100;
  1481. if (pool->cb_param.perc < 0.0 || pool->cb_param.perc > 1.0)
  1482. return "The percentage should be between 0 and 100";
  1483. return NULL;
  1484. }
  1485. static
  1486. char *set_pool_goal(const char * const arg)
  1487. {
  1488. struct pool *pool;
  1489. if (!total_pools)
  1490. return "Usage of --pool-goal before pools are defined does not make sense";
  1491. pool = pools[total_pools - 1];
  1492. pool->goal = get_mining_goal(arg);
  1493. return NULL;
  1494. }
  1495. static char *set_pool_priority(const char *arg)
  1496. {
  1497. struct pool *pool;
  1498. if (!total_pools)
  1499. return "Usage of --pool-priority before pools are defined does not make sense";
  1500. pool = pools[total_pools - 1];
  1501. opt_set_intval(arg, &pool->prio);
  1502. return NULL;
  1503. }
  1504. static char *set_pool_proxy(const char *arg)
  1505. {
  1506. struct pool *pool;
  1507. if (!total_pools)
  1508. return "Usage of --pool-proxy before pools are defined does not make sense";
  1509. if (!our_curl_supports_proxy_uris())
  1510. return "Your installed cURL library does not support proxy URIs. At least version 7.21.7 is required.";
  1511. pool = pools[total_pools - 1];
  1512. opt_set_charp(arg, &pool->rpc_proxy);
  1513. return NULL;
  1514. }
  1515. static char *set_pool_force_rollntime(const char *arg)
  1516. {
  1517. struct pool *pool;
  1518. if (!total_pools)
  1519. return "Usage of --force-rollntime before pools are defined does not make sense";
  1520. pool = pools[total_pools - 1];
  1521. opt_set_intval(arg, &pool->force_rollntime);
  1522. return NULL;
  1523. }
  1524. static char *enable_debug(bool *flag)
  1525. {
  1526. *flag = true;
  1527. opt_debug_console = true;
  1528. /* Turn on verbose output, too. */
  1529. opt_log_output = true;
  1530. return NULL;
  1531. }
  1532. static char *set_schedtime(const char *arg, struct schedtime *st)
  1533. {
  1534. if (sscanf(arg, "%d:%d", &st->tm.tm_hour, &st->tm.tm_min) != 2)
  1535. {
  1536. if (strcasecmp(arg, "now"))
  1537. return "Invalid time set, should be HH:MM";
  1538. } else
  1539. schedstop.tm.tm_sec = 0;
  1540. if (st->tm.tm_hour > 23 || st->tm.tm_min > 59 || st->tm.tm_hour < 0 || st->tm.tm_min < 0)
  1541. return "Invalid time set.";
  1542. st->enable = true;
  1543. return NULL;
  1544. }
  1545. static
  1546. char *set_log_file(char *arg)
  1547. {
  1548. char *r = "";
  1549. long int i = strtol(arg, &r, 10);
  1550. int fd, stderr_fd = fileno(stderr);
  1551. if ((!*r) && i >= 0 && i <= INT_MAX)
  1552. fd = i;
  1553. else
  1554. if (!strcmp(arg, "-"))
  1555. {
  1556. fd = fileno(stdout);
  1557. if (unlikely(fd == -1))
  1558. return "Standard output missing for log-file";
  1559. }
  1560. else
  1561. {
  1562. fd = open(arg, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR);
  1563. if (unlikely(fd == -1))
  1564. return "Failed to open log-file";
  1565. }
  1566. close(stderr_fd);
  1567. if (unlikely(-1 == dup2(fd, stderr_fd)))
  1568. return "Failed to dup2 for log-file";
  1569. close(fd);
  1570. return NULL;
  1571. }
  1572. static
  1573. char *_bfgopt_set_file(const char *arg, FILE **F, const char *mode, const char *purpose)
  1574. {
  1575. char *r = "";
  1576. long int i = strtol(arg, &r, 10);
  1577. static char *err = NULL;
  1578. const size_t errbufsz = 0x100;
  1579. free(err);
  1580. err = NULL;
  1581. if ((!*r) && i >= 0 && i <= INT_MAX) {
  1582. *F = fdopen((int)i, mode);
  1583. if (!*F)
  1584. {
  1585. err = malloc(errbufsz);
  1586. snprintf(err, errbufsz, "Failed to open fd %d for %s",
  1587. (int)i, purpose);
  1588. return err;
  1589. }
  1590. } else if (!strcmp(arg, "-")) {
  1591. *F = (mode[0] == 'a') ? stdout : stdin;
  1592. if (!*F)
  1593. {
  1594. err = malloc(errbufsz);
  1595. snprintf(err, errbufsz, "Standard %sput missing for %s",
  1596. (mode[0] == 'a') ? "out" : "in", purpose);
  1597. return err;
  1598. }
  1599. } else {
  1600. *F = fopen(arg, mode);
  1601. if (!*F)
  1602. {
  1603. err = malloc(errbufsz);
  1604. snprintf(err, errbufsz, "Failed to open %s for %s",
  1605. arg, purpose);
  1606. return err;
  1607. }
  1608. }
  1609. return NULL;
  1610. }
  1611. static char *set_noncelog(char *arg)
  1612. {
  1613. return _bfgopt_set_file(arg, &noncelog_file, "a", "nonce log");
  1614. }
  1615. static char *set_sharelog(char *arg)
  1616. {
  1617. return _bfgopt_set_file(arg, &sharelog_file, "a", "share log");
  1618. }
  1619. static
  1620. void _add_set_device_option(const char * const func, const char * const buf)
  1621. {
  1622. applog(LOG_DEBUG, "%s: Using --set-device %s", func, buf);
  1623. string_elist_add(buf, &opt_set_device_list);
  1624. }
  1625. #define add_set_device_option(...) do{ \
  1626. char _tmp1718[0x100]; \
  1627. snprintf(_tmp1718, sizeof(_tmp1718), __VA_ARGS__); \
  1628. _add_set_device_option(__func__, _tmp1718); \
  1629. }while(0)
  1630. char *set_temp_cutoff(char *arg)
  1631. {
  1632. if (strchr(arg, ','))
  1633. return "temp-cutoff no longer supports comma-delimited syntax, use --set-device for better control";
  1634. applog(LOG_WARNING, "temp-cutoff is deprecated! Use --set-device for better control");
  1635. add_set_device_option("all:temp-cutoff=%s", arg);
  1636. return NULL;
  1637. }
  1638. char *set_temp_target(char *arg)
  1639. {
  1640. if (strchr(arg, ','))
  1641. return "temp-target no longer supports comma-delimited syntax, use --set-device for better control";
  1642. applog(LOG_WARNING, "temp-target is deprecated! Use --set-device for better control");
  1643. add_set_device_option("all:temp-target=%s", arg);
  1644. return NULL;
  1645. }
  1646. #ifdef HAVE_OPENCL
  1647. static
  1648. char *set_no_opencl_binaries(__maybe_unused void * const dummy)
  1649. {
  1650. applog(LOG_WARNING, "The --no-opencl-binaries option is deprecated! Use --set-device OCL:binary=no");
  1651. add_set_device_option("OCL:binary=no");
  1652. return NULL;
  1653. }
  1654. #endif
  1655. static
  1656. char *disable_pool_redirect(__maybe_unused void * const dummy)
  1657. {
  1658. opt_disable_client_reconnect = true;
  1659. want_stratum = false;
  1660. return NULL;
  1661. }
  1662. static char *set_api_allow(const char *arg)
  1663. {
  1664. opt_set_charp(arg, &opt_api_allow);
  1665. return NULL;
  1666. }
  1667. static char *set_api_groups(const char *arg)
  1668. {
  1669. opt_set_charp(arg, &opt_api_groups);
  1670. return NULL;
  1671. }
  1672. static char *set_api_description(const char *arg)
  1673. {
  1674. opt_set_charp(arg, &opt_api_description);
  1675. return NULL;
  1676. }
  1677. static char *set_api_mcast_des(const char *arg)
  1678. {
  1679. opt_set_charp(arg, &opt_api_mcast_des);
  1680. return NULL;
  1681. }
  1682. #ifdef USE_ICARUS
  1683. extern const struct bfg_set_device_definition icarus_set_device_funcs[];
  1684. static char *set_icarus_options(const char *arg)
  1685. {
  1686. if (strchr(arg, ','))
  1687. return "icarus-options no longer supports comma-delimited syntax, see README.FPGA for better control";
  1688. applog(LOG_WARNING, "icarus-options is deprecated! See README.FPGA for better control");
  1689. char *opts = strdup(arg), *argdup;
  1690. argdup = opts;
  1691. const struct bfg_set_device_definition *sdf = icarus_set_device_funcs;
  1692. const char *drivers[] = {"antminer", "cairnsmore", "erupter", "icarus"};
  1693. char *saveptr, *opt;
  1694. for (int i = 0; i < 4; ++i, ++sdf)
  1695. {
  1696. opt = strtok_r(opts, ":", &saveptr);
  1697. opts = NULL;
  1698. if (!opt)
  1699. break;
  1700. if (!opt[0])
  1701. continue;
  1702. for (int j = 0; j < 4; ++j)
  1703. add_set_device_option("%s:%s=%s", drivers[j], sdf->optname, opt);
  1704. }
  1705. free(argdup);
  1706. return NULL;
  1707. }
  1708. static char *set_icarus_timing(const char *arg)
  1709. {
  1710. if (strchr(arg, ','))
  1711. return "icarus-timing no longer supports comma-delimited syntax, see README.FPGA for better control";
  1712. applog(LOG_WARNING, "icarus-timing is deprecated! See README.FPGA for better control");
  1713. const char *drivers[] = {"antminer", "cairnsmore", "erupter", "icarus"};
  1714. for (int j = 0; j < 4; ++j)
  1715. add_set_device_option("%s:timing=%s", drivers[j], arg);
  1716. return NULL;
  1717. }
  1718. #endif
  1719. #ifdef USE_AVALON
  1720. extern const struct bfg_set_device_definition avalon_set_device_funcs[];
  1721. static char *set_avalon_options(const char *arg)
  1722. {
  1723. if (strchr(arg, ','))
  1724. return "avalon-options no longer supports comma-delimited syntax, see README.FPGA for better control";
  1725. applog(LOG_WARNING, "avalon-options is deprecated! See README.FPGA for better control");
  1726. char *opts = strdup(arg), *argdup;
  1727. argdup = opts;
  1728. const struct bfg_set_device_definition *sdf = avalon_set_device_funcs;
  1729. char *saveptr, *opt;
  1730. for (int i = 0; i < 5; ++i, ++sdf)
  1731. {
  1732. opt = strtok_r(opts, ":", &saveptr);
  1733. opts = NULL;
  1734. if (!opt)
  1735. break;
  1736. if (!opt[0])
  1737. continue;
  1738. add_set_device_option("avalon:%s=%s", sdf->optname, opt);
  1739. }
  1740. free(argdup);
  1741. return NULL;
  1742. }
  1743. #endif
  1744. #ifdef USE_KLONDIKE
  1745. static char *set_klondike_options(const char *arg)
  1746. {
  1747. int hashclock;
  1748. double temptarget;
  1749. switch (sscanf(arg, "%d:%lf", &hashclock, &temptarget))
  1750. {
  1751. default:
  1752. return "Unrecognised --klondike-options";
  1753. case 2:
  1754. add_set_device_option("klondike:temp-target=%lf", temptarget);
  1755. // fallthru
  1756. case 1:
  1757. add_set_device_option("klondike:clock=%d", hashclock);
  1758. }
  1759. applog(LOG_WARNING, "klondike-options is deprecated! Use --set-device for better control");
  1760. return NULL;
  1761. }
  1762. #endif
  1763. __maybe_unused
  1764. static char *set_null(const char __maybe_unused *arg)
  1765. {
  1766. return NULL;
  1767. }
  1768. /* These options are available from config file or commandline */
  1769. static struct opt_table opt_config_table[] = {
  1770. #ifdef WANT_CPUMINE
  1771. OPT_WITH_ARG("--algo",
  1772. set_algo, show_algo, &opt_algo,
  1773. "Specify sha256 implementation for CPU mining:\n"
  1774. "\tfastauto*\tQuick benchmark at startup to pick a working algorithm\n"
  1775. "\tauto\t\tBenchmark at startup and pick fastest algorithm"
  1776. "\n\tc\t\tLinux kernel sha256, implemented in C"
  1777. #ifdef WANT_SSE2_4WAY
  1778. "\n\t4way\t\ttcatm's 4-way SSE2 implementation"
  1779. #endif
  1780. #ifdef WANT_VIA_PADLOCK
  1781. "\n\tvia\t\tVIA padlock implementation"
  1782. #endif
  1783. "\n\tcryptopp\tCrypto++ C/C++ implementation"
  1784. #ifdef WANT_CRYPTOPP_ASM32
  1785. "\n\tcryptopp_asm32\tCrypto++ 32-bit assembler implementation"
  1786. #endif
  1787. #ifdef WANT_X8632_SSE2
  1788. "\n\tsse2_32\t\tSSE2 32 bit implementation for i386 machines"
  1789. #endif
  1790. #ifdef WANT_X8664_SSE2
  1791. "\n\tsse2_64\t\tSSE2 64 bit implementation for x86_64 machines"
  1792. #endif
  1793. #ifdef WANT_X8664_SSE4
  1794. "\n\tsse4_64\t\tSSE4.1 64 bit implementation for x86_64 machines"
  1795. #endif
  1796. #ifdef WANT_ALTIVEC_4WAY
  1797. "\n\taltivec_4way\tAltivec implementation for PowerPC G4 and G5 machines"
  1798. #endif
  1799. ),
  1800. OPT_WITH_ARG("-a",
  1801. set_algo, show_algo, &opt_algo,
  1802. opt_hidden),
  1803. #endif
  1804. OPT_WITH_ARG("--api-allow",
  1805. set_api_allow, NULL, NULL,
  1806. "Allow API access only to the given list of [G:]IP[/Prefix] addresses[/subnets]"),
  1807. OPT_WITH_ARG("--api-description",
  1808. set_api_description, NULL, NULL,
  1809. "Description placed in the API status header, default: BFGMiner version"),
  1810. OPT_WITH_ARG("--api-groups",
  1811. set_api_groups, NULL, NULL,
  1812. "API one letter groups G:cmd:cmd[,P:cmd:*...] defining the cmds a groups can use"),
  1813. OPT_WITHOUT_ARG("--api-listen",
  1814. opt_set_bool, &opt_api_listen,
  1815. "Enable API, default: disabled"),
  1816. OPT_WITHOUT_ARG("--api-mcast",
  1817. opt_set_bool, &opt_api_mcast,
  1818. "Enable API Multicast listener, default: disabled"),
  1819. OPT_WITH_ARG("--api-mcast-addr",
  1820. opt_set_charp, opt_show_charp, &opt_api_mcast_addr,
  1821. "API Multicast listen address"),
  1822. OPT_WITH_ARG("--api-mcast-code",
  1823. opt_set_charp, opt_show_charp, &opt_api_mcast_code,
  1824. "Code expected in the API Multicast message, don't use '-'"),
  1825. OPT_WITH_ARG("--api-mcast-des",
  1826. set_api_mcast_des, NULL, NULL,
  1827. "Description appended to the API Multicast reply, default: ''"),
  1828. OPT_WITH_ARG("--api-mcast-port",
  1829. set_int_1_to_65535, opt_show_intval, &opt_api_mcast_port,
  1830. "API Multicast listen port"),
  1831. OPT_WITHOUT_ARG("--api-network",
  1832. opt_set_bool, &opt_api_network,
  1833. "Allow API (if enabled) to listen on/for any address, default: only 127.0.0.1"),
  1834. OPT_WITH_ARG("--api-port",
  1835. set_int_1_to_65535, opt_show_intval, &opt_api_port,
  1836. "Port number of miner API"),
  1837. #ifdef HAVE_ADL
  1838. OPT_WITHOUT_ARG("--auto-fan",
  1839. opt_set_bool, &opt_autofan,
  1840. opt_hidden),
  1841. OPT_WITHOUT_ARG("--auto-gpu",
  1842. opt_set_bool, &opt_autoengine,
  1843. opt_hidden),
  1844. #endif
  1845. OPT_WITHOUT_ARG("--balance",
  1846. set_balance, &pool_strategy,
  1847. "Change multipool strategy from failover to even share balance"),
  1848. OPT_WITHOUT_ARG("--benchmark",
  1849. opt_set_bool, &opt_benchmark,
  1850. "Run BFGMiner in benchmark mode - produces no shares"),
  1851. OPT_WITHOUT_ARG("--benchmark-intense",
  1852. set_benchmark_intense, &opt_benchmark_intense,
  1853. "Run BFGMiner in intensive benchmark mode - produces no shares"),
  1854. #if defined(USE_BITFORCE)
  1855. OPT_WITHOUT_ARG("--bfl-range",
  1856. opt_set_bool, &opt_bfl_noncerange,
  1857. "Use nonce range on bitforce devices if supported"),
  1858. #endif
  1859. #ifdef HAVE_CHROOT
  1860. OPT_WITH_ARG("--chroot-dir",
  1861. opt_set_charp, NULL, &chroot_dir,
  1862. "Chroot to a directory right after startup"),
  1863. #endif
  1864. OPT_WITH_ARG("--cmd-idle",
  1865. opt_set_charp, NULL, &cmd_idle,
  1866. "Execute a command when a device is allowed to be idle (rest or wait)"),
  1867. OPT_WITH_ARG("--cmd-sick",
  1868. opt_set_charp, NULL, &cmd_sick,
  1869. "Execute a command when a device is declared sick"),
  1870. OPT_WITH_ARG("--cmd-dead",
  1871. opt_set_charp, NULL, &cmd_dead,
  1872. "Execute a command when a device is declared dead"),
  1873. #if BLKMAKER_VERSION > 1
  1874. OPT_WITH_ARG("--coinbase-addr",
  1875. set_b58addr, NULL, &opt_coinbase_script,
  1876. "Set coinbase payout address for solo mining"),
  1877. OPT_WITH_ARG("--coinbase-address|--coinbase-payout|--cbaddress|--cbaddr|--cb-address|--cb-addr|--payout",
  1878. set_b58addr, NULL, &opt_coinbase_script,
  1879. opt_hidden),
  1880. #endif
  1881. #if BLKMAKER_VERSION > 0
  1882. OPT_WITH_ARG("--coinbase-sig",
  1883. set_strdup, NULL, &opt_coinbase_sig,
  1884. "Set coinbase signature when possible"),
  1885. OPT_WITH_ARG("--coinbase|--cbsig|--cb-sig|--cb|--prayer",
  1886. set_strdup, NULL, &opt_coinbase_sig,
  1887. opt_hidden),
  1888. #endif
  1889. #ifdef HAVE_CURSES
  1890. OPT_WITHOUT_ARG("--compact",
  1891. opt_set_bool, &opt_compact,
  1892. "Use compact display without per device statistics"),
  1893. #endif
  1894. #ifdef WANT_CPUMINE
  1895. OPT_WITH_ARG("--cpu-threads",
  1896. force_nthreads_int, opt_show_intval, &opt_n_threads,
  1897. "Number of miner CPU threads"),
  1898. OPT_WITH_ARG("-t",
  1899. force_nthreads_int, opt_show_intval, &opt_n_threads,
  1900. opt_hidden),
  1901. #endif
  1902. OPT_WITHOUT_ARG("--debug|-D",
  1903. enable_debug, &opt_debug,
  1904. "Enable debug output"),
  1905. OPT_WITHOUT_ARG("--debuglog",
  1906. opt_set_bool, &opt_debug,
  1907. "Enable debug logging"),
  1908. OPT_WITHOUT_ARG("--device-protocol-dump",
  1909. opt_set_bool, &opt_dev_protocol,
  1910. "Verbose dump of device protocol-level activities"),
  1911. OPT_WITH_ARG("--device|-d",
  1912. set_devices, NULL, NULL,
  1913. "Enable only devices matching pattern (default: all)"),
  1914. OPT_WITHOUT_ARG("--disable-rejecting",
  1915. opt_set_bool, &opt_disable_pool,
  1916. "Automatically disable pools that continually reject shares"),
  1917. #ifdef USE_LIBMICROHTTPD
  1918. OPT_WITH_ARG("--http-port",
  1919. opt_set_intval, opt_show_intval, &httpsrv_port,
  1920. "Port number to listen on for HTTP getwork miners (-1 means disabled)"),
  1921. #endif
  1922. OPT_WITH_ARG("--expiry",
  1923. set_int_0_to_9999, opt_show_intval, &opt_expiry,
  1924. "Upper bound on how many seconds after getting work we consider a share from it stale (w/o longpoll active)"),
  1925. OPT_WITH_ARG("-E",
  1926. set_int_0_to_9999, opt_show_intval, &opt_expiry,
  1927. opt_hidden),
  1928. OPT_WITH_ARG("--expiry-lp",
  1929. set_int_0_to_9999, opt_show_intval, &opt_expiry_lp,
  1930. "Upper bound on how many seconds after getting work we consider a share from it stale (with longpoll active)"),
  1931. OPT_WITHOUT_ARG("--failover-only",
  1932. opt_set_bool, &opt_fail_only,
  1933. "Don't leak work to backup pools when primary pool is lagging"),
  1934. OPT_WITH_ARG("--failover-switch-delay",
  1935. set_int_1_to_65535, opt_show_intval, &opt_fail_switch_delay,
  1936. "Delay in seconds before switching back to a failed pool"),
  1937. #ifdef USE_FPGA
  1938. OPT_WITHOUT_ARG("--force-dev-init",
  1939. opt_set_bool, &opt_force_dev_init,
  1940. "Always initialize devices when possible (such as bitstream uploads to some FPGAs)"),
  1941. #endif
  1942. #ifdef HAVE_OPENCL
  1943. OPT_WITH_ARG("--gpu-dyninterval",
  1944. set_int_1_to_65535, opt_show_intval, &opt_dynamic_interval,
  1945. opt_hidden),
  1946. OPT_WITH_ARG("--gpu-platform",
  1947. set_int_0_to_9999, opt_show_intval, &opt_platform_id,
  1948. "Select OpenCL platform ID to use for GPU mining"),
  1949. OPT_WITH_ARG("--gpu-threads|-g",
  1950. set_gpu_threads, opt_show_intval, &opt_g_threads,
  1951. opt_hidden),
  1952. #ifdef HAVE_ADL
  1953. OPT_WITH_ARG("--gpu-engine",
  1954. set_gpu_engine, NULL, NULL,
  1955. opt_hidden),
  1956. OPT_WITH_ARG("--gpu-fan",
  1957. set_gpu_fan, NULL, NULL,
  1958. opt_hidden),
  1959. OPT_WITH_ARG("--gpu-map",
  1960. set_gpu_map, NULL, NULL,
  1961. "Map OpenCL to ADL device order manually, paired CSV (e.g. 1:0,2:1 maps OpenCL 1 to ADL 0, 2 to 1)"),
  1962. OPT_WITH_ARG("--gpu-memclock",
  1963. set_gpu_memclock, NULL, NULL,
  1964. opt_hidden),
  1965. OPT_WITH_ARG("--gpu-memdiff",
  1966. set_gpu_memdiff, NULL, NULL,
  1967. opt_hidden),
  1968. OPT_WITH_ARG("--gpu-powertune",
  1969. set_gpu_powertune, NULL, NULL,
  1970. opt_hidden),
  1971. OPT_WITHOUT_ARG("--gpu-reorder",
  1972. opt_set_bool, &opt_reorder,
  1973. "Attempt to reorder GPU devices according to PCI Bus ID"),
  1974. OPT_WITH_ARG("--gpu-vddc",
  1975. set_gpu_vddc, NULL, NULL,
  1976. opt_hidden),
  1977. #endif
  1978. #ifdef USE_SCRYPT
  1979. OPT_WITH_ARG("--lookup-gap",
  1980. set_lookup_gap, NULL, NULL,
  1981. opt_hidden),
  1982. #endif
  1983. OPT_WITH_ARG("--intensity|-I",
  1984. set_intensity, NULL, NULL,
  1985. opt_hidden),
  1986. #endif
  1987. #if defined(HAVE_OPENCL) || defined(USE_MODMINER) || defined(USE_X6500) || defined(USE_ZTEX)
  1988. OPT_WITH_ARG("--kernel-path",
  1989. opt_set_charp, opt_show_charp, &opt_kernel_path,
  1990. "Specify a path to where bitstream and kernel files are"),
  1991. OPT_WITH_ARG("-K",
  1992. opt_set_charp, opt_show_charp, &opt_kernel_path,
  1993. opt_hidden),
  1994. #endif
  1995. #ifdef HAVE_OPENCL
  1996. OPT_WITH_ARG("--kernel|-k",
  1997. set_kernel, NULL, NULL,
  1998. opt_hidden),
  1999. #endif
  2000. #ifdef USE_ICARUS
  2001. OPT_WITH_ARG("--icarus-options",
  2002. set_icarus_options, NULL, NULL,
  2003. opt_hidden),
  2004. OPT_WITH_ARG("--icarus-timing",
  2005. set_icarus_timing, NULL, NULL,
  2006. opt_hidden),
  2007. #endif
  2008. #ifdef USE_AVALON
  2009. OPT_WITH_ARG("--avalon-options",
  2010. set_avalon_options, NULL, NULL,
  2011. opt_hidden),
  2012. #endif
  2013. #ifdef USE_KLONDIKE
  2014. OPT_WITH_ARG("--klondike-options",
  2015. set_klondike_options, NULL, NULL,
  2016. "Set klondike options clock:temptarget"),
  2017. #endif
  2018. OPT_WITHOUT_ARG("--load-balance",
  2019. set_loadbalance, &pool_strategy,
  2020. "Change multipool strategy from failover to quota based balance"),
  2021. OPT_WITH_ARG("--log|-l",
  2022. set_int_0_to_9999, opt_show_intval, &opt_log_interval,
  2023. "Interval in seconds between log output"),
  2024. OPT_WITH_ARG("--log-file|-L",
  2025. set_log_file, NULL, NULL,
  2026. "Append log file for output messages"),
  2027. OPT_WITH_ARG("--logfile",
  2028. set_log_file, NULL, NULL,
  2029. opt_hidden),
  2030. OPT_WITHOUT_ARG("--log-microseconds",
  2031. opt_set_bool, &opt_log_microseconds,
  2032. "Include microseconds in log output"),
  2033. #if defined(unix) || defined(__APPLE__)
  2034. OPT_WITH_ARG("--monitor|-m",
  2035. opt_set_charp, NULL, &opt_stderr_cmd,
  2036. "Use custom pipe cmd for output messages"),
  2037. #endif // defined(unix)
  2038. OPT_WITHOUT_ARG("--net-delay",
  2039. opt_set_bool, &opt_delaynet,
  2040. "Impose small delays in networking to avoid overloading slow routers"),
  2041. OPT_WITHOUT_ARG("--no-adl",
  2042. opt_set_bool, &opt_noadl,
  2043. #ifdef HAVE_ADL
  2044. "Disable the ATI display library used for monitoring and setting GPU parameters"
  2045. #else
  2046. opt_hidden
  2047. #endif
  2048. ),
  2049. OPT_WITHOUT_ARG("--no-gbt",
  2050. opt_set_invbool, &want_gbt,
  2051. "Disable getblocktemplate support"),
  2052. OPT_WITHOUT_ARG("--no-getwork",
  2053. opt_set_invbool, &want_getwork,
  2054. "Disable getwork support"),
  2055. OPT_WITHOUT_ARG("--no-hotplug",
  2056. #ifdef HAVE_BFG_HOTPLUG
  2057. opt_set_invbool, &opt_hotplug,
  2058. "Disable hotplug detection"
  2059. #else
  2060. set_null, &opt_hotplug,
  2061. opt_hidden
  2062. #endif
  2063. ),
  2064. OPT_WITHOUT_ARG("--no-local-bitcoin",
  2065. #if BLKMAKER_VERSION > 1
  2066. opt_set_invbool, &opt_load_bitcoin_conf,
  2067. "Disable adding pools for local bitcoin RPC servers"),
  2068. #else
  2069. set_null, NULL, opt_hidden),
  2070. #endif
  2071. OPT_WITHOUT_ARG("--no-longpoll",
  2072. opt_set_invbool, &want_longpoll,
  2073. "Disable X-Long-Polling support"),
  2074. OPT_WITHOUT_ARG("--no-pool-disable",
  2075. opt_set_invbool, &opt_disable_pool,
  2076. opt_hidden),
  2077. OPT_WITHOUT_ARG("--no-client-reconnect",
  2078. opt_set_invbool, &opt_disable_client_reconnect,
  2079. opt_hidden),
  2080. OPT_WITHOUT_ARG("--no-pool-redirect",
  2081. disable_pool_redirect, NULL,
  2082. "Ignore pool requests to redirect to another server"),
  2083. OPT_WITHOUT_ARG("--no-restart",
  2084. opt_set_invbool, &opt_restart,
  2085. "Do not attempt to restart devices that hang"
  2086. ),
  2087. OPT_WITHOUT_ARG("--no-show-processors",
  2088. opt_set_invbool, &opt_show_procs,
  2089. opt_hidden),
  2090. OPT_WITHOUT_ARG("--no-show-procs",
  2091. opt_set_invbool, &opt_show_procs,
  2092. opt_hidden),
  2093. OPT_WITHOUT_ARG("--no-stratum",
  2094. opt_set_invbool, &want_stratum,
  2095. "Disable Stratum detection"),
  2096. OPT_WITHOUT_ARG("--no-submit-stale",
  2097. opt_set_invbool, &opt_submit_stale,
  2098. "Don't submit shares if they are detected as stale"),
  2099. #ifdef HAVE_OPENCL
  2100. OPT_WITHOUT_ARG("--no-opencl-binaries",
  2101. set_no_opencl_binaries, NULL,
  2102. opt_hidden),
  2103. #endif
  2104. OPT_WITHOUT_ARG("--no-unicode",
  2105. #ifdef USE_UNICODE
  2106. opt_set_invbool, &use_unicode,
  2107. "Don't use Unicode characters in TUI"
  2108. #else
  2109. set_null, &use_unicode,
  2110. opt_hidden
  2111. #endif
  2112. ),
  2113. OPT_WITH_ARG("--noncelog",
  2114. set_noncelog, NULL, NULL,
  2115. "Create log of all nonces found"),
  2116. OPT_WITH_ARG("--pass|-p",
  2117. set_pass, NULL, NULL,
  2118. "Password for bitcoin JSON-RPC server"),
  2119. OPT_WITHOUT_ARG("--per-device-stats",
  2120. opt_set_bool, &want_per_device_stats,
  2121. "Force verbose mode and output per-device statistics"),
  2122. OPT_WITH_ARG("--userpass|-O",
  2123. set_userpass, NULL, NULL,
  2124. "Username:Password pair for bitcoin JSON-RPC server"),
  2125. OPT_WITH_ARG("--pool-goal",
  2126. set_pool_goal, NULL, NULL,
  2127. "Named goal for the previous-defined pool"),
  2128. OPT_WITH_ARG("--pool-priority",
  2129. set_pool_priority, NULL, NULL,
  2130. "Priority for just the previous-defined pool"),
  2131. OPT_WITH_ARG("--pool-proxy|-x",
  2132. set_pool_proxy, NULL, NULL,
  2133. "Proxy URI to use for connecting to just the previous-defined pool"),
  2134. OPT_WITH_ARG("--force-rollntime", // NOTE: must be after --pass for config file ordering
  2135. set_pool_force_rollntime, NULL, NULL,
  2136. opt_hidden),
  2137. OPT_WITHOUT_ARG("--protocol-dump|-P",
  2138. opt_set_bool, &opt_protocol,
  2139. "Verbose dump of protocol-level activities"),
  2140. OPT_WITH_ARG("--queue|-Q",
  2141. set_int_0_to_9999, opt_show_intval, &opt_queue,
  2142. "Minimum number of work items to have queued (0+)"),
  2143. OPT_WITHOUT_ARG("--quiet|-q",
  2144. opt_set_bool, &opt_quiet,
  2145. "Disable logging output, display status and errors"),
  2146. OPT_WITHOUT_ARG("--quiet-work-updates|--quiet-work-update",
  2147. opt_set_bool, &opt_quiet_work_updates,
  2148. opt_hidden),
  2149. OPT_WITH_ARG("--quit-summary",
  2150. set_quit_summary, NULL, NULL,
  2151. "Summary printed when you quit: none/devs/procs/detailed"),
  2152. OPT_WITH_ARG("--quota|-U",
  2153. set_quota, NULL, NULL,
  2154. "quota;URL combination for server with load-balance strategy quotas"),
  2155. OPT_WITHOUT_ARG("--real-quiet",
  2156. opt_set_bool, &opt_realquiet,
  2157. "Disable all output"),
  2158. OPT_WITH_ARG("--request-diff",
  2159. set_request_diff, opt_show_floatval, &request_pdiff,
  2160. "Request a specific difficulty from pools"),
  2161. OPT_WITH_ARG("--retries",
  2162. opt_set_intval, opt_show_intval, &opt_retries,
  2163. "Number of times to retry failed submissions before giving up (-1 means never)"),
  2164. OPT_WITH_ARG("--retry-pause",
  2165. set_null, NULL, NULL,
  2166. opt_hidden),
  2167. OPT_WITH_ARG("--rotate",
  2168. set_rotate, opt_show_intval, &opt_rotate_period,
  2169. "Change multipool strategy from failover to regularly rotate at N minutes"),
  2170. OPT_WITHOUT_ARG("--round-robin",
  2171. set_rr, &pool_strategy,
  2172. "Change multipool strategy from failover to round robin on failure"),
  2173. OPT_WITH_ARG("--scan|-S",
  2174. add_serial, NULL, NULL,
  2175. "Configure how to scan for mining devices"),
  2176. OPT_WITH_ARG("--scan-device|--scan-serial|--devscan",
  2177. add_serial, NULL, NULL,
  2178. opt_hidden),
  2179. OPT_WITH_ARG("--scan-time",
  2180. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  2181. "Upper bound on time spent scanning current work, in seconds"),
  2182. OPT_WITH_ARG("-s",
  2183. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  2184. opt_hidden),
  2185. OPT_WITH_ARG("--scantime",
  2186. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  2187. opt_hidden),
  2188. OPT_WITH_ARG("--sched-start",
  2189. set_schedtime, NULL, &schedstart,
  2190. "Set a time of day in HH:MM to start mining (a once off without a stop time)"),
  2191. OPT_WITH_ARG("--sched-stop",
  2192. set_schedtime, NULL, &schedstop,
  2193. "Set a time of day in HH:MM to stop mining (will quit without a start time)"),
  2194. #ifdef USE_SCRYPT
  2195. OPT_WITHOUT_ARG("--scrypt",
  2196. opt_set_bool, &opt_scrypt,
  2197. "Use the scrypt algorithm for mining (non-bitcoin)"),
  2198. #endif
  2199. OPT_WITH_ARG("--set-device|--set",
  2200. opt_string_elist_add, NULL, &opt_set_device_list,
  2201. "Set default parameters on devices; eg, NFY:osc6_bits=50"),
  2202. #if defined(USE_SCRYPT) && defined(HAVE_OPENCL)
  2203. OPT_WITH_ARG("--shaders",
  2204. set_shaders, NULL, NULL,
  2205. opt_hidden),
  2206. #endif
  2207. #ifdef HAVE_PWD_H
  2208. OPT_WITH_ARG("--setuid",
  2209. opt_set_charp, NULL, &opt_setuid,
  2210. "Username of an unprivileged user to run as"),
  2211. #endif
  2212. OPT_WITH_ARG("--sharelog",
  2213. set_sharelog, NULL, NULL,
  2214. "Append share log to file"),
  2215. OPT_WITH_ARG("--shares",
  2216. opt_set_floatval, NULL, &opt_shares,
  2217. "Quit after mining 2^32 * N hashes worth of shares (default: unlimited)"),
  2218. OPT_WITHOUT_ARG("--show-processors",
  2219. opt_set_bool, &opt_show_procs,
  2220. "Show per processor statistics in summary"),
  2221. OPT_WITHOUT_ARG("--show-procs",
  2222. opt_set_bool, &opt_show_procs,
  2223. opt_hidden),
  2224. OPT_WITH_ARG("--skip-security-checks",
  2225. set_int_0_to_9999, NULL, &opt_skip_checks,
  2226. "Skip security checks sometimes to save bandwidth; only check 1/<arg>th of the time (default: never skip)"),
  2227. OPT_WITH_ARG("--socks-proxy",
  2228. opt_set_charp, NULL, &opt_socks_proxy,
  2229. "Set socks proxy (host:port)"),
  2230. #ifdef USE_LIBEVENT
  2231. OPT_WITH_ARG("--stratum-port",
  2232. opt_set_intval, opt_show_intval, &stratumsrv_port,
  2233. "Port number to listen on for stratum miners (-1 means disabled)"),
  2234. #endif
  2235. OPT_WITHOUT_ARG("--submit-stale",
  2236. opt_set_bool, &opt_submit_stale,
  2237. opt_hidden),
  2238. OPT_WITH_ARG("--submit-threads",
  2239. opt_set_intval, opt_show_intval, &opt_submit_threads,
  2240. "Minimum number of concurrent share submissions (default: 64)"),
  2241. #ifdef HAVE_SYSLOG_H
  2242. OPT_WITHOUT_ARG("--syslog",
  2243. opt_set_bool, &use_syslog,
  2244. "Use system log for output messages (default: standard error)"),
  2245. #endif
  2246. OPT_WITH_ARG("--temp-cutoff",
  2247. set_temp_cutoff, NULL, &opt_cutofftemp,
  2248. opt_hidden),
  2249. OPT_WITH_ARG("--temp-hysteresis",
  2250. set_int_1_to_10, opt_show_intval, &opt_hysteresis,
  2251. "Set how much the temperature can fluctuate outside limits when automanaging speeds"),
  2252. #ifdef HAVE_ADL
  2253. OPT_WITH_ARG("--temp-overheat",
  2254. set_temp_overheat, opt_show_intval, &opt_overheattemp,
  2255. opt_hidden),
  2256. #endif
  2257. OPT_WITH_ARG("--temp-target",
  2258. set_temp_target, NULL, NULL,
  2259. opt_hidden),
  2260. OPT_WITHOUT_ARG("--text-only|-T",
  2261. opt_set_invbool, &use_curses,
  2262. #ifdef HAVE_CURSES
  2263. "Disable ncurses formatted screen output"
  2264. #else
  2265. opt_hidden
  2266. #endif
  2267. ),
  2268. #if defined(USE_SCRYPT) && defined(HAVE_OPENCL)
  2269. OPT_WITH_ARG("--thread-concurrency",
  2270. set_thread_concurrency, NULL, NULL,
  2271. opt_hidden),
  2272. #endif
  2273. #ifdef USE_UNICODE
  2274. OPT_WITHOUT_ARG("--unicode",
  2275. opt_set_bool, &use_unicode,
  2276. "Use Unicode characters in TUI"),
  2277. #endif
  2278. OPT_WITH_ARG("--url|-o",
  2279. set_url, NULL, NULL,
  2280. "URL for bitcoin JSON-RPC server"),
  2281. OPT_WITH_ARG("--user|-u",
  2282. set_user, NULL, NULL,
  2283. "Username for bitcoin JSON-RPC server"),
  2284. #ifdef HAVE_OPENCL
  2285. OPT_WITH_ARG("--vectors|-v",
  2286. set_vector, NULL, NULL,
  2287. opt_hidden),
  2288. #endif
  2289. OPT_WITHOUT_ARG("--verbose",
  2290. opt_set_bool, &opt_log_output,
  2291. "Log verbose output to stderr as well as status output"),
  2292. OPT_WITHOUT_ARG("--verbose-work-updates|--verbose-work-update",
  2293. opt_set_invbool, &opt_quiet_work_updates,
  2294. opt_hidden),
  2295. OPT_WITHOUT_ARG("--weighed-stats",
  2296. opt_set_bool, &opt_weighed_stats,
  2297. "Display statistics weighed to difficulty 1"),
  2298. #ifdef HAVE_OPENCL
  2299. OPT_WITH_ARG("--worksize|-w",
  2300. set_worksize, NULL, NULL,
  2301. opt_hidden),
  2302. #endif
  2303. OPT_WITHOUT_ARG("--unittest",
  2304. opt_set_bool, &opt_unittest, opt_hidden),
  2305. OPT_WITH_ARG("--coinbase-check-addr",
  2306. set_cbcaddr, NULL, NULL,
  2307. "A list of address to check against in coinbase payout list received from the previous-defined pool, separated by ','"),
  2308. OPT_WITH_ARG("--cbcheck-addr|--cbc-addr|--cbcaddr",
  2309. set_cbcaddr, NULL, NULL,
  2310. opt_hidden),
  2311. OPT_WITH_ARG("--coinbase-check-total",
  2312. set_cbctotal, NULL, NULL,
  2313. "The least total payout amount expected in coinbase received from the previous-defined pool"),
  2314. OPT_WITH_ARG("--cbcheck-total|--cbc-total|--cbctotal",
  2315. set_cbctotal, NULL, NULL,
  2316. opt_hidden),
  2317. OPT_WITH_ARG("--coinbase-check-percent",
  2318. set_cbcperc, NULL, NULL,
  2319. "The least benefit percentage expected for the sum of addr(s) listed in --cbaddr argument for previous-defined pool"),
  2320. OPT_WITH_ARG("--cbcheck-percent|--cbc-percent|--cbcpercent|--cbcperc",
  2321. set_cbcperc, NULL, NULL,
  2322. opt_hidden),
  2323. OPT_WITHOUT_ARG("--worktime",
  2324. opt_set_bool, &opt_worktime,
  2325. "Display extra work time debug information"),
  2326. OPT_WITH_ARG("--pools",
  2327. opt_set_bool, NULL, NULL, opt_hidden),
  2328. OPT_ENDTABLE
  2329. };
  2330. static char *load_config(const char *arg, void __maybe_unused *unused);
  2331. static char *parse_config(json_t *config, bool fileconf, int * const fileconf_load_p)
  2332. {
  2333. static char err_buf[200];
  2334. struct opt_table *opt;
  2335. json_t *val;
  2336. if (fileconf && !*fileconf_load_p)
  2337. *fileconf_load_p = 1;
  2338. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  2339. char *p, *name, *sp;
  2340. /* We don't handle subtables. */
  2341. assert(!(opt->type & OPT_SUBTABLE));
  2342. if (!opt->names)
  2343. continue;
  2344. /* Pull apart the option name(s). */
  2345. name = strdup(opt->names);
  2346. for (p = strtok_r(name, "|", &sp); p; p = strtok_r(NULL, "|", &sp)) {
  2347. char *err = "Invalid value";
  2348. /* Ignore short options. */
  2349. if (p[1] != '-')
  2350. continue;
  2351. val = json_object_get(config, p+2);
  2352. if (!val)
  2353. continue;
  2354. if (opt->type & OPT_HASARG) {
  2355. if (json_is_string(val)) {
  2356. err = opt->cb_arg(json_string_value(val),
  2357. opt->u.arg);
  2358. } else if (json_is_number(val)) {
  2359. char buf[256], *p, *q;
  2360. snprintf(buf, 256, "%f", json_number_value(val));
  2361. if ( (p = strchr(buf, '.')) ) {
  2362. // Trim /\.0*$/ to work properly with integer-only arguments
  2363. q = p;
  2364. while (*(++q) == '0') {}
  2365. if (*q == '\0')
  2366. *p = '\0';
  2367. }
  2368. err = opt->cb_arg(buf, opt->u.arg);
  2369. } else if (json_is_array(val)) {
  2370. int n, size = json_array_size(val);
  2371. err = NULL;
  2372. for (n = 0; n < size && !err; n++) {
  2373. if (json_is_string(json_array_get(val, n)))
  2374. err = opt->cb_arg(json_string_value(json_array_get(val, n)), opt->u.arg);
  2375. else if (json_is_object(json_array_get(val, n)))
  2376. err = parse_config(json_array_get(val, n), false, fileconf_load_p);
  2377. }
  2378. }
  2379. } else if (opt->type & OPT_NOARG) {
  2380. if (json_is_true(val))
  2381. err = opt->cb(opt->u.arg);
  2382. else if (json_is_boolean(val)) {
  2383. if (opt->cb == (void*)opt_set_bool)
  2384. err = opt_set_invbool(opt->u.arg);
  2385. else if (opt->cb == (void*)opt_set_invbool)
  2386. err = opt_set_bool(opt->u.arg);
  2387. }
  2388. }
  2389. if (err) {
  2390. /* Allow invalid values to be in configuration
  2391. * file, just skipping over them provided the
  2392. * JSON is still valid after that. */
  2393. if (fileconf) {
  2394. applog(LOG_ERR, "Invalid config option %s: %s", p, err);
  2395. *fileconf_load_p = -1;
  2396. } else {
  2397. snprintf(err_buf, sizeof(err_buf), "Parsing JSON option %s: %s",
  2398. p, err);
  2399. return err_buf;
  2400. }
  2401. }
  2402. }
  2403. free(name);
  2404. }
  2405. val = json_object_get(config, JSON_INCLUDE_CONF);
  2406. if (val && json_is_string(val))
  2407. return load_config(json_string_value(val), NULL);
  2408. return NULL;
  2409. }
  2410. struct bfg_loaded_configfile *bfg_loaded_configfiles;
  2411. static char *load_config(const char *arg, void __maybe_unused *unused)
  2412. {
  2413. json_error_t err;
  2414. json_t *config;
  2415. char *json_error;
  2416. size_t siz;
  2417. struct bfg_loaded_configfile *cfginfo;
  2418. cfginfo = malloc(sizeof(*cfginfo));
  2419. *cfginfo = (struct bfg_loaded_configfile){
  2420. .filename = strdup(arg),
  2421. };
  2422. LL_APPEND(bfg_loaded_configfiles, cfginfo);
  2423. if (++include_count > JSON_MAX_DEPTH)
  2424. return JSON_MAX_DEPTH_ERR;
  2425. #if JANSSON_MAJOR_VERSION > 1
  2426. config = json_load_file(arg, 0, &err);
  2427. #else
  2428. config = json_load_file(arg, &err);
  2429. #endif
  2430. if (!json_is_object(config)) {
  2431. siz = JSON_LOAD_ERROR_LEN + strlen(arg) + strlen(err.text);
  2432. json_error = malloc(siz);
  2433. if (!json_error)
  2434. quit(1, "Malloc failure in json error");
  2435. snprintf(json_error, siz, JSON_LOAD_ERROR, arg, err.text);
  2436. return json_error;
  2437. }
  2438. config_loaded = true;
  2439. /* Parse the config now, so we can override it. That can keep pointers
  2440. * so don't free config object. */
  2441. return parse_config(config, true, &cfginfo->fileconf_load);
  2442. }
  2443. static
  2444. bool _load_default_configs(const char * const filepath, void * __maybe_unused userp)
  2445. {
  2446. bool * const found_defcfg_p = userp;
  2447. *found_defcfg_p = true;
  2448. load_config(filepath, NULL);
  2449. // Regardless of status of loading the config file, we should continue loading other defaults
  2450. return false;
  2451. }
  2452. static void load_default_config(void)
  2453. {
  2454. bool found_defcfg = false;
  2455. appdata_file_call("BFGMiner", def_conf, _load_default_configs, &found_defcfg);
  2456. if (!found_defcfg)
  2457. {
  2458. // No BFGMiner config, try Cgminer's...
  2459. appdata_file_call("cgminer", "cgminer.conf", _load_default_configs, &found_defcfg);
  2460. }
  2461. }
  2462. extern const char *opt_argv0;
  2463. static char *opt_verusage_and_exit(const char *extra)
  2464. {
  2465. puts(packagename);
  2466. printf(" Lowlevel:%s\n", BFG_LOWLLIST);
  2467. printf(" Drivers:%s\n", BFG_DRIVERLIST);
  2468. printf(" Algorithms:%s\n", BFG_ALGOLIST);
  2469. printf(" Options:%s\n", BFG_OPTLIST);
  2470. printf("%s", opt_usage(opt_argv0, extra));
  2471. fflush(stdout);
  2472. exit(0);
  2473. }
  2474. /* These options are parsed before anything else */
  2475. static struct opt_table opt_early_table[] = {
  2476. // Default config is loaded in command line order, like a regular config
  2477. OPT_EARLY_WITH_ARG("--config|-c|--default-config",
  2478. set_bool_ignore_arg, NULL, &config_loaded,
  2479. opt_hidden),
  2480. OPT_EARLY_WITHOUT_ARG("--no-config|--no-default-config",
  2481. opt_set_bool, &config_loaded,
  2482. "Inhibit loading default config file"),
  2483. OPT_ENDTABLE
  2484. };
  2485. /* These options are available from commandline only */
  2486. static struct opt_table opt_cmdline_table[] = {
  2487. OPT_WITH_ARG("--config|-c",
  2488. load_config, NULL, NULL,
  2489. "Load a JSON-format configuration file\n"
  2490. "See example.conf for an example configuration."),
  2491. OPT_EARLY_WITHOUT_ARG("--no-config",
  2492. opt_set_bool, &config_loaded,
  2493. opt_hidden),
  2494. OPT_EARLY_WITHOUT_ARG("--no-default-config",
  2495. opt_set_bool, &config_loaded,
  2496. "Inhibit loading default config file"),
  2497. OPT_WITHOUT_ARG("--default-config",
  2498. load_default_config, NULL,
  2499. "Always load the default config file"),
  2500. OPT_WITHOUT_ARG("--help|-h",
  2501. opt_verusage_and_exit, NULL,
  2502. "Print this message"),
  2503. #ifdef HAVE_OPENCL
  2504. OPT_WITHOUT_ARG("--ndevs|-n",
  2505. print_ndevs_and_exit, &nDevs,
  2506. opt_hidden),
  2507. #endif
  2508. OPT_WITHOUT_ARG("--version|-V",
  2509. opt_version_and_exit, packagename,
  2510. "Display version and exit"),
  2511. OPT_ENDTABLE
  2512. };
  2513. static bool jobj_binary(const json_t *obj, const char *key,
  2514. void *buf, size_t buflen, bool required)
  2515. {
  2516. const char *hexstr;
  2517. json_t *tmp;
  2518. tmp = json_object_get(obj, key);
  2519. if (unlikely(!tmp)) {
  2520. if (unlikely(required))
  2521. applog(LOG_ERR, "JSON key '%s' not found", key);
  2522. return false;
  2523. }
  2524. hexstr = json_string_value(tmp);
  2525. if (unlikely(!hexstr)) {
  2526. applog(LOG_ERR, "JSON key '%s' is not a string", key);
  2527. return false;
  2528. }
  2529. if (!hex2bin(buf, hexstr, buflen))
  2530. return false;
  2531. return true;
  2532. }
  2533. static void calc_midstate(struct work *work)
  2534. {
  2535. union {
  2536. unsigned char c[64];
  2537. uint32_t i[16];
  2538. } data;
  2539. swap32yes(&data.i[0], work->data, 16);
  2540. sha256_ctx ctx;
  2541. sha256_init(&ctx);
  2542. sha256_update(&ctx, data.c, 64);
  2543. memcpy(work->midstate, ctx.h, sizeof(work->midstate));
  2544. swap32tole(work->midstate, work->midstate, 8);
  2545. }
  2546. static
  2547. struct bfg_tmpl_ref *tmpl_makeref(blktemplate_t * const tmpl)
  2548. {
  2549. struct bfg_tmpl_ref * const tr = malloc(sizeof(*tr));
  2550. *tr = (struct bfg_tmpl_ref){
  2551. .tmpl = tmpl,
  2552. .refcount = 1,
  2553. };
  2554. mutex_init(&tr->mutex);
  2555. return tr;
  2556. }
  2557. static
  2558. void tmpl_incref(struct bfg_tmpl_ref * const tr)
  2559. {
  2560. mutex_lock(&tr->mutex);
  2561. ++tr->refcount;
  2562. mutex_unlock(&tr->mutex);
  2563. }
  2564. void tmpl_decref(struct bfg_tmpl_ref * const tr)
  2565. {
  2566. mutex_lock(&tr->mutex);
  2567. bool free_tmpl = !--tr->refcount;
  2568. mutex_unlock(&tr->mutex);
  2569. if (free_tmpl)
  2570. {
  2571. blktmpl_free(tr->tmpl);
  2572. mutex_destroy(&tr->mutex);
  2573. free(tr);
  2574. }
  2575. }
  2576. static struct work *make_work(void)
  2577. {
  2578. struct work *work = calloc(1, sizeof(struct work));
  2579. if (unlikely(!work))
  2580. quit(1, "Failed to calloc work in make_work");
  2581. cg_wlock(&control_lock);
  2582. work->id = total_work++;
  2583. cg_wunlock(&control_lock);
  2584. return work;
  2585. }
  2586. /* This is the central place all work that is about to be retired should be
  2587. * cleaned to remove any dynamically allocated arrays within the struct */
  2588. void clean_work(struct work *work)
  2589. {
  2590. free(work->job_id);
  2591. bytes_free(&work->nonce2);
  2592. free(work->nonce1);
  2593. if (work->device_data_free_func)
  2594. work->device_data_free_func(work);
  2595. if (work->tr)
  2596. tmpl_decref(work->tr);
  2597. memset(work, 0, sizeof(struct work));
  2598. }
  2599. /* All dynamically allocated work structs should be freed here to not leak any
  2600. * ram from arrays allocated within the work struct */
  2601. void free_work(struct work *work)
  2602. {
  2603. clean_work(work);
  2604. free(work);
  2605. }
  2606. 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";
  2607. #define workpadding_bin bfg_workpadding_bin
  2608. static const size_t block_info_str_sz = 3 /* ... */ + 16 /* block hash segment */ + 1;
  2609. static
  2610. void block_info_str(char * const out, const struct block_info * const blkinfo)
  2611. {
  2612. unsigned char hash_swap[32];
  2613. swap256(hash_swap, blkinfo->prevblkhash);
  2614. swap32tole(hash_swap, hash_swap, 32 / 4);
  2615. memset(out, '.', 3);
  2616. // FIXME: The block number will overflow this sometime around AD 2025-2027
  2617. if (blkinfo->height > 0 && blkinfo->height < 1000000)
  2618. {
  2619. bin2hex(&out[3], &hash_swap[0x1c], 4);
  2620. snprintf(&out[11], block_info_str_sz-11, " #%6u", blkinfo->height);
  2621. }
  2622. else
  2623. bin2hex(&out[3], &hash_swap[0x18], 8);
  2624. }
  2625. #ifdef HAVE_CURSES
  2626. static void update_block_display(void);
  2627. #endif
  2628. // Must only be called with ch_lock held!
  2629. static
  2630. void __update_block_title(struct mining_goal_info * const goal)
  2631. {
  2632. struct blockchain_info * const blkchain = goal->blkchain;
  2633. if (!goal->current_goal_detail)
  2634. goal->current_goal_detail = malloc(block_info_str_sz);
  2635. block_info_str(goal->current_goal_detail, blkchain->currentblk);
  2636. #ifdef HAVE_CURSES
  2637. update_block_display();
  2638. #endif
  2639. }
  2640. static struct block_info *block_exists(const struct blockchain_info *, const void *);
  2641. static
  2642. void have_block_height(struct mining_goal_info * const goal, const void * const prevblkhash, uint32_t blkheight)
  2643. {
  2644. struct blockchain_info * const blkchain = goal->blkchain;
  2645. struct block_info * const blkinfo = block_exists(blkchain, prevblkhash);
  2646. if ((!blkinfo) || blkinfo->height)
  2647. return;
  2648. uint32_t block_id = ((uint32_t*)prevblkhash)[0];
  2649. applog(LOG_DEBUG, "Learned that block id %08" PRIx32 " is height %" PRIu32, (uint32_t)be32toh(block_id), blkheight);
  2650. cg_wlock(&ch_lock);
  2651. blkinfo->height = blkheight;
  2652. if (blkinfo == blkchain->currentblk)
  2653. {
  2654. blkchain->currentblk_subsidy = 5000000000LL >> (blkheight / 210000);
  2655. __update_block_title(goal);
  2656. }
  2657. cg_wunlock(&ch_lock);
  2658. }
  2659. static
  2660. void pool_set_opaque(struct pool *pool, bool opaque)
  2661. {
  2662. if (pool->swork.opaque == opaque)
  2663. return;
  2664. pool->swork.opaque = opaque;
  2665. if (opaque)
  2666. applog(LOG_WARNING, "Pool %u is hiding block contents from us",
  2667. pool->pool_no);
  2668. else
  2669. applog(LOG_NOTICE, "Pool %u now providing block contents to us",
  2670. pool->pool_no);
  2671. }
  2672. bool pool_may_redirect_to(struct pool * const pool, const char * const uri)
  2673. {
  2674. if (uri_get_param_bool(pool->rpc_url, "redirect", false))
  2675. return true;
  2676. return match_domains(pool->rpc_url, strlen(pool->rpc_url), uri, strlen(uri));
  2677. }
  2678. void pool_check_coinbase(struct pool * const pool, const uint8_t * const cbtxn, const size_t cbtxnsz)
  2679. {
  2680. if (uri_get_param_bool(pool->rpc_url, "skipcbcheck", false))
  2681. {}
  2682. else
  2683. if (!check_coinbase(cbtxn, cbtxnsz, &pool->cb_param))
  2684. {
  2685. if (pool->enabled == POOL_ENABLED)
  2686. {
  2687. applog(LOG_ERR, "Pool %d misbehaving (%s), disabling!", pool->pool_no, "coinbase check");
  2688. disable_pool(pool, POOL_MISBEHAVING);
  2689. }
  2690. }
  2691. else
  2692. if (pool->enabled == POOL_MISBEHAVING)
  2693. {
  2694. applog(LOG_NOTICE, "Pool %d no longer misbehaving, re-enabling!", pool->pool_no);
  2695. enable_pool(pool);
  2696. }
  2697. }
  2698. 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)
  2699. {
  2700. const int offsets = max(ntime_roll, 60);
  2701. *nrl = (struct ntime_roll_limits){
  2702. .min = ntime_base,
  2703. .max = ntime_base + ntime_roll,
  2704. .tv_ref = *tvp_ref,
  2705. .minoff = -offsets,
  2706. .maxoff = offsets,
  2707. };
  2708. }
  2709. void work_set_simple_ntime_roll_limit(struct work * const work, const int ntime_roll, const struct timeval * const tvp_ref)
  2710. {
  2711. set_simple_ntime_roll_limit(&work->ntime_roll_limits, upk_u32be(work->data, 0x44), ntime_roll, tvp_ref);
  2712. }
  2713. int work_ntime_range(struct work * const work, const struct timeval * const tvp_earliest, const struct timeval * const tvp_latest, const int desired_roll)
  2714. {
  2715. const struct ntime_roll_limits * const nrl = &work->ntime_roll_limits;
  2716. const uint32_t ref_ntime = work_get_ntime(work);
  2717. const int earliest_elapsed = timer_elapsed(&nrl->tv_ref, tvp_earliest);
  2718. const int latest_elapsed = timer_elapsed(&nrl->tv_ref, tvp_latest);
  2719. // minimum ntime is the latest possible result (add a second to spare) adjusted for minimum offset (or fixed minimum ntime)
  2720. uint32_t min_ntime = max(nrl->min, ref_ntime + latest_elapsed+1 + nrl->minoff);
  2721. // maximum ntime is the earliest possible result adjusted for maximum offset (or fixed maximum ntime)
  2722. uint32_t max_ntime = min(nrl->max, ref_ntime + earliest_elapsed + nrl->maxoff);
  2723. if (max_ntime < min_ntime)
  2724. return -1;
  2725. if (max_ntime - min_ntime > desired_roll)
  2726. {
  2727. // Adjust min_ntime upward for accuracy, when possible
  2728. const int mid_elapsed = ((latest_elapsed - earliest_elapsed) / 2) + earliest_elapsed;
  2729. uint32_t ideal_ntime = ref_ntime + mid_elapsed;
  2730. if (ideal_ntime > min_ntime)
  2731. min_ntime = min(ideal_ntime, max_ntime - desired_roll);
  2732. }
  2733. work_set_ntime(work, min_ntime);
  2734. return max_ntime - min_ntime;
  2735. }
  2736. #if BLKMAKER_VERSION > 1
  2737. static
  2738. void refresh_bitcoind_address(const bool fresh)
  2739. {
  2740. struct mining_goal_info * const goal = get_mining_goal("default");
  2741. struct blockchain_info * const blkchain = goal->blkchain;
  2742. if (!have_at_least_one_getcbaddr)
  2743. return;
  2744. char getcbaddr_req[60];
  2745. CURL *curl = NULL;
  2746. json_t *json, *j2;
  2747. const char *s, *s2;
  2748. bytes_t newscript = BYTES_INIT;
  2749. snprintf(getcbaddr_req, sizeof(getcbaddr_req), "{\"method\":\"get%saddress\",\"id\":0,\"params\":[\"BFGMiner\"]}", fresh ? "new" : "account");
  2750. for (int i = 0; i < total_pools; ++i)
  2751. {
  2752. struct pool * const pool = pools[i];
  2753. if (!uri_get_param_bool(pool->rpc_url, "getcbaddr", false))
  2754. continue;
  2755. if (pool->goal != goal)
  2756. // TODO: Multi-blockchain support
  2757. continue;
  2758. applog(LOG_DEBUG, "Refreshing coinbase address from pool %d", pool->pool_no);
  2759. if (!curl)
  2760. {
  2761. curl = curl_easy_init();
  2762. if (unlikely(!curl))
  2763. {
  2764. applogfail(LOG_ERR, "curl_easy_init");
  2765. break;
  2766. }
  2767. }
  2768. json = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, getcbaddr_req, false, false, NULL, pool, true);
  2769. if (unlikely((!json) || !json_is_null( (j2 = json_object_get(json, "error")) )))
  2770. {
  2771. const char *estrc;
  2772. char *estr = NULL;
  2773. if (!(json && j2))
  2774. estrc = NULL;
  2775. else
  2776. {
  2777. estrc = json_string_value(j2);
  2778. if (!estrc)
  2779. estrc = estr = json_dumps_ANY(j2, JSON_ENSURE_ASCII | JSON_SORT_KEYS);
  2780. }
  2781. applog(LOG_WARNING, "Error %cetting coinbase address from pool %d: %s", 'g', pool->pool_no, estrc);
  2782. free(estr);
  2783. continue;
  2784. }
  2785. s = bfg_json_obj_string(json, "result", NULL);
  2786. if (unlikely(!s))
  2787. {
  2788. applog(LOG_WARNING, "Error %cetting coinbase address from pool %d: %s", 'g', pool->pool_no, "(return value was not a String)");
  2789. continue;
  2790. }
  2791. s2 = set_b58addr(s, &newscript);
  2792. if (unlikely(s2))
  2793. {
  2794. applog(LOG_WARNING, "Error %cetting coinbase address from pool %d: %s", 's', pool->pool_no, s2);
  2795. continue;
  2796. }
  2797. if (bytes_eq(&newscript, &opt_coinbase_script))
  2798. {
  2799. applog(LOG_DEBUG, "Pool %d returned coinbase address already in use (%s)", pool->pool_no, s2);
  2800. break;
  2801. }
  2802. bytes_assimilate(&opt_coinbase_script, &newscript);
  2803. coinbase_script_block_id = blkchain->currentblk->block_id;
  2804. applog(LOG_NOTICE, "Now using coinbase address %s, provided by pool %d", s, pool->pool_no);
  2805. break;
  2806. }
  2807. bytes_free(&newscript);
  2808. if (curl)
  2809. curl_easy_cleanup(curl);
  2810. }
  2811. #endif
  2812. #define GBT_XNONCESZ (sizeof(uint32_t))
  2813. #if BLKMAKER_VERSION > 4
  2814. #define blkmk_append_coinbase_safe(tmpl, append, appendsz) \
  2815. blkmk_append_coinbase_safe2(tmpl, append, appendsz, GBT_XNONCESZ, false)
  2816. #endif
  2817. static bool work_decode(struct pool *pool, struct work *work, json_t *val)
  2818. {
  2819. json_t *res_val = json_object_get(val, "result");
  2820. json_t *tmp_val;
  2821. bool ret = false;
  2822. struct timeval tv_now;
  2823. if (unlikely(detect_algo == 1)) {
  2824. json_t *tmp = json_object_get(res_val, "algorithm");
  2825. const char *v = tmp ? json_string_value(tmp) : "";
  2826. if (strncasecmp(v, "scrypt", 6))
  2827. detect_algo = 2;
  2828. }
  2829. timer_set_now(&tv_now);
  2830. if (work->tr)
  2831. {
  2832. blktemplate_t * const tmpl = work->tr->tmpl;
  2833. const char *err = blktmpl_add_jansson(tmpl, res_val, tv_now.tv_sec);
  2834. if (err) {
  2835. applog(LOG_ERR, "blktmpl error: %s", err);
  2836. return false;
  2837. }
  2838. work->rolltime = blkmk_time_left(tmpl, tv_now.tv_sec);
  2839. #if BLKMAKER_VERSION > 1
  2840. const uint32_t tmpl_block_id = ((uint32_t*)tmpl->prevblk)[0];
  2841. if ((!tmpl->cbtxn) && coinbase_script_block_id != tmpl_block_id)
  2842. refresh_bitcoind_address(false);
  2843. if (bytes_len(&opt_coinbase_script))
  2844. {
  2845. bool newcb;
  2846. #if BLKMAKER_VERSION > 2
  2847. blkmk_init_generation2(tmpl, bytes_buf(&opt_coinbase_script), bytes_len(&opt_coinbase_script), &newcb);
  2848. #else
  2849. newcb = !tmpl->cbtxn;
  2850. blkmk_init_generation(tmpl, bytes_buf(&opt_coinbase_script), bytes_len(&opt_coinbase_script));
  2851. #endif
  2852. if (newcb)
  2853. {
  2854. ssize_t ae = blkmk_append_coinbase_safe(tmpl, &template_nonce, sizeof(template_nonce));
  2855. if (ae < (ssize_t)sizeof(template_nonce))
  2856. 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);
  2857. ++template_nonce;
  2858. }
  2859. }
  2860. #endif
  2861. #if BLKMAKER_VERSION > 0
  2862. {
  2863. ssize_t ae = blkmk_append_coinbase_safe(tmpl, opt_coinbase_sig, 101);
  2864. static bool appenderr = false;
  2865. if (ae <= 0) {
  2866. if (opt_coinbase_sig) {
  2867. applog((appenderr ? LOG_DEBUG : LOG_WARNING), "Cannot append coinbase signature at all on pool %u (%"PRId64")", pool->pool_no, (int64_t)ae);
  2868. appenderr = true;
  2869. }
  2870. } else if (ae >= 3 || opt_coinbase_sig) {
  2871. const char *cbappend = opt_coinbase_sig;
  2872. const char full[] = PACKAGE " " VERSION;
  2873. char *need_free = NULL;
  2874. if (!cbappend) {
  2875. if ((size_t)ae >= sizeof(full) - 1)
  2876. cbappend = full;
  2877. else if ((size_t)ae >= sizeof(PACKAGE) - 1)
  2878. {
  2879. const char *pos = strchr(full, '-');
  2880. size_t sz = (pos - full);
  2881. if (pos && ae > sz)
  2882. {
  2883. cbappend = need_free = malloc(sz + 1);
  2884. memcpy(need_free, full, sz);
  2885. need_free[sz] = '\0';
  2886. }
  2887. else
  2888. cbappend = PACKAGE;
  2889. }
  2890. else
  2891. cbappend = "BFG";
  2892. }
  2893. size_t cbappendsz = strlen(cbappend);
  2894. static bool truncatewarning = false;
  2895. if (cbappendsz <= (size_t)ae) {
  2896. if (cbappendsz < (size_t)ae)
  2897. // If we have space, include the trailing \0
  2898. ++cbappendsz;
  2899. ae = cbappendsz;
  2900. truncatewarning = false;
  2901. } else {
  2902. char *tmp = malloc(ae + 1);
  2903. memcpy(tmp, opt_coinbase_sig, ae);
  2904. tmp[ae] = '\0';
  2905. applog((truncatewarning ? LOG_DEBUG : LOG_WARNING),
  2906. "Pool %u truncating appended coinbase signature at %"PRId64" bytes: %s(%s)",
  2907. pool->pool_no, (int64_t)ae, tmp, &opt_coinbase_sig[ae]);
  2908. free(tmp);
  2909. truncatewarning = true;
  2910. }
  2911. ae = blkmk_append_coinbase_safe(tmpl, cbappend, ae);
  2912. free(need_free);
  2913. if (ae <= 0) {
  2914. applog((appenderr ? LOG_DEBUG : LOG_WARNING), "Error appending coinbase signature (%"PRId64")", (int64_t)ae);
  2915. appenderr = true;
  2916. } else
  2917. appenderr = false;
  2918. }
  2919. }
  2920. #endif
  2921. if (blkmk_get_data(tmpl, work->data, 80, tv_now.tv_sec, NULL, &work->dataid) < 76)
  2922. return false;
  2923. swap32yes(work->data, work->data, 80 / 4);
  2924. memcpy(&work->data[80], workpadding_bin, 48);
  2925. work->ntime_roll_limits = (struct ntime_roll_limits){
  2926. .min = tmpl->mintime,
  2927. .max = tmpl->maxtime,
  2928. .tv_ref = tv_now,
  2929. .minoff = tmpl->mintimeoff,
  2930. .maxoff = tmpl->maxtimeoff,
  2931. };
  2932. const struct blktmpl_longpoll_req *lp;
  2933. if ((lp = blktmpl_get_longpoll(tmpl)) && ((!pool->lp_id) || strcmp(lp->id, pool->lp_id))) {
  2934. free(pool->lp_id);
  2935. pool->lp_id = strdup(lp->id);
  2936. #if 0 /* This just doesn't work :( */
  2937. curl_socket_t sock = pool->lp_socket;
  2938. if (sock != CURL_SOCKET_BAD) {
  2939. pool->lp_socket = CURL_SOCKET_BAD;
  2940. applog(LOG_WARNING, "Pool %u long poll request hanging, reconnecting", pool->pool_no);
  2941. shutdown(sock, SHUT_RDWR);
  2942. }
  2943. #endif
  2944. }
  2945. }
  2946. else
  2947. if (unlikely(!jobj_binary(res_val, "data", work->data, sizeof(work->data), true))) {
  2948. applog(LOG_ERR, "JSON inval data");
  2949. return false;
  2950. }
  2951. else
  2952. work_set_simple_ntime_roll_limit(work, 0, &tv_now);
  2953. if (!jobj_binary(res_val, "midstate", work->midstate, sizeof(work->midstate), false)) {
  2954. // Calculate it ourselves
  2955. applog(LOG_DEBUG, "Calculating midstate locally");
  2956. calc_midstate(work);
  2957. }
  2958. if (unlikely(!jobj_binary(res_val, "target", work->target, sizeof(work->target), true))) {
  2959. applog(LOG_ERR, "JSON inval target");
  2960. return false;
  2961. }
  2962. if (work->tr)
  2963. {
  2964. for (size_t i = 0; i < sizeof(work->target) / 2; ++i)
  2965. {
  2966. int p = (sizeof(work->target) - 1) - i;
  2967. unsigned char c = work->target[i];
  2968. work->target[i] = work->target[p];
  2969. work->target[p] = c;
  2970. }
  2971. }
  2972. if ( (tmp_val = json_object_get(res_val, "height")) ) {
  2973. struct mining_goal_info * const goal = pool->goal;
  2974. uint32_t blkheight = json_number_value(tmp_val);
  2975. const void * const prevblkhash = &work->data[4];
  2976. have_block_height(goal, prevblkhash, blkheight);
  2977. }
  2978. memset(work->hash, 0, sizeof(work->hash));
  2979. work->tv_staged = tv_now;
  2980. #if BLKMAKER_VERSION > 4
  2981. if (work->tr)
  2982. {
  2983. blktemplate_t * const tmpl = work->tr->tmpl;
  2984. uint8_t buf[80];
  2985. int16_t expire;
  2986. uint8_t *cbtxn;
  2987. size_t cbtxnsz;
  2988. size_t cbextranonceoffset;
  2989. int branchcount;
  2990. libblkmaker_hash_t *branches;
  2991. if (blkmk_get_mdata(tmpl, buf, sizeof(buf), tv_now.tv_sec, &expire, &cbtxn, &cbtxnsz, &cbextranonceoffset, &branchcount, &branches, GBT_XNONCESZ, false))
  2992. {
  2993. struct stratum_work * const swork = &pool->swork;
  2994. const size_t branchdatasz = branchcount * 0x20;
  2995. pool_check_coinbase(pool, cbtxn, cbtxnsz);
  2996. cg_wlock(&pool->data_lock);
  2997. swork->tr = work->tr;
  2998. bytes_assimilate_raw(&swork->coinbase, cbtxn, cbtxnsz, cbtxnsz);
  2999. swork->nonce2_offset = cbextranonceoffset;
  3000. bytes_assimilate_raw(&swork->merkle_bin, branches, branchdatasz, branchdatasz);
  3001. swork->merkles = branchcount;
  3002. memcpy(swork->header1, &buf[0], 36);
  3003. swork->ntime = le32toh(*(uint32_t *)(&buf[68]));
  3004. swork->tv_received = tv_now;
  3005. memcpy(swork->diffbits, &buf[72], 4);
  3006. memcpy(swork->target, work->target, sizeof(swork->target));
  3007. free(swork->job_id);
  3008. swork->job_id = NULL;
  3009. swork->clean = true;
  3010. swork->work_restart_id = pool->work_restart_id;
  3011. // FIXME: Do something with expire
  3012. pool->nonce2sz = swork->n2size = GBT_XNONCESZ;
  3013. pool->nonce2 = 0;
  3014. cg_wunlock(&pool->data_lock);
  3015. }
  3016. else
  3017. applog(LOG_DEBUG, "blkmk_get_mdata failed for pool %u", pool->pool_no);
  3018. }
  3019. #endif // BLKMAKER_VERSION > 4
  3020. pool_set_opaque(pool, !work->tr);
  3021. ret = true;
  3022. return ret;
  3023. }
  3024. /* Returns whether the pool supports local work generation or not. */
  3025. static bool pool_localgen(struct pool *pool)
  3026. {
  3027. return (pool->last_work_copy || pool->has_stratum);
  3028. }
  3029. int dev_from_id(int thr_id)
  3030. {
  3031. struct cgpu_info *cgpu = get_thr_cgpu(thr_id);
  3032. return cgpu->device_id;
  3033. }
  3034. /* Create an exponentially decaying average over the opt_log_interval */
  3035. void decay_time(double *f, double fadd, double fsecs)
  3036. {
  3037. double ftotal, fprop;
  3038. fprop = 1.0 - 1 / (exp(fsecs / (double)opt_log_interval));
  3039. ftotal = 1.0 + fprop;
  3040. *f += (fadd * fprop);
  3041. *f /= ftotal;
  3042. }
  3043. static int __total_staged(void)
  3044. {
  3045. return HASH_COUNT(staged_work);
  3046. }
  3047. static int total_staged(void)
  3048. {
  3049. int ret;
  3050. mutex_lock(stgd_lock);
  3051. ret = __total_staged();
  3052. mutex_unlock(stgd_lock);
  3053. return ret;
  3054. }
  3055. #ifdef HAVE_CURSES
  3056. WINDOW *mainwin, *statuswin, *logwin;
  3057. #endif
  3058. double total_secs = 1.0;
  3059. #ifdef HAVE_CURSES
  3060. static char statusline[256];
  3061. /* statusy is where the status window goes up to in cases where it won't fit at startup */
  3062. static int statusy;
  3063. static int devsummaryYOffset;
  3064. static int total_lines;
  3065. #endif
  3066. #ifdef HAVE_OPENCL
  3067. struct cgpu_info gpus[MAX_GPUDEVICES]; /* Maximum number apparently possible */
  3068. #endif
  3069. struct cgpu_info *cpus;
  3070. bool _bfg_console_cancel_disabled;
  3071. int _bfg_console_prev_cancelstate;
  3072. #ifdef HAVE_CURSES
  3073. #define lock_curses() bfg_console_lock()
  3074. #define unlock_curses() bfg_console_unlock()
  3075. static bool curses_active_locked(void)
  3076. {
  3077. bool ret;
  3078. lock_curses();
  3079. ret = curses_active;
  3080. if (!ret)
  3081. unlock_curses();
  3082. return ret;
  3083. }
  3084. // Cancellable getch
  3085. int my_cancellable_getch(void)
  3086. {
  3087. // This only works because the macro only hits direct getch() calls
  3088. typedef int (*real_getch_t)(void);
  3089. const real_getch_t real_getch = __real_getch;
  3090. int type, rv;
  3091. bool sct;
  3092. sct = !pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &type);
  3093. rv = real_getch();
  3094. if (sct)
  3095. pthread_setcanceltype(type, &type);
  3096. return rv;
  3097. }
  3098. #ifdef PDCURSES
  3099. static
  3100. int bfg_wresize(WINDOW *win, int lines, int columns)
  3101. {
  3102. int rv = wresize(win, lines, columns);
  3103. int x, y;
  3104. getyx(win, y, x);
  3105. if (unlikely(y >= lines || x >= columns))
  3106. {
  3107. if (y >= lines)
  3108. y = lines - 1;
  3109. if (x >= columns)
  3110. x = columns - 1;
  3111. wmove(win, y, x);
  3112. }
  3113. return rv;
  3114. }
  3115. #else
  3116. # define bfg_wresize wresize
  3117. #endif
  3118. #endif
  3119. void tailsprintf(char *buf, size_t bufsz, const char *fmt, ...)
  3120. {
  3121. va_list ap;
  3122. size_t presz = strlen(buf);
  3123. va_start(ap, fmt);
  3124. vsnprintf(&buf[presz], bufsz - presz, fmt, ap);
  3125. va_end(ap);
  3126. }
  3127. double stats_elapsed(struct cgminer_stats *stats)
  3128. {
  3129. struct timeval now;
  3130. double elapsed;
  3131. if (stats->start_tv.tv_sec == 0)
  3132. elapsed = total_secs;
  3133. else {
  3134. cgtime(&now);
  3135. elapsed = tdiff(&now, &stats->start_tv);
  3136. }
  3137. if (elapsed < 1.0)
  3138. elapsed = 1.0;
  3139. return elapsed;
  3140. }
  3141. bool drv_ready(struct cgpu_info *cgpu)
  3142. {
  3143. switch (cgpu->status) {
  3144. case LIFE_INIT:
  3145. case LIFE_DEAD2:
  3146. return false;
  3147. default:
  3148. return true;
  3149. }
  3150. }
  3151. double cgpu_utility(struct cgpu_info *cgpu)
  3152. {
  3153. double dev_runtime = cgpu_runtime(cgpu);
  3154. return cgpu->utility = cgpu->accepted / dev_runtime * 60;
  3155. }
  3156. #define suffix_string(val, buf, bufsiz, sigdigits) do{ \
  3157. _Static_assert(sigdigits == 0, "suffix_string only supported with sigdigits==0"); \
  3158. format_unit3(buf, bufsiz, FUP_DIFF, "", H2B_SHORTV, val, -1); \
  3159. }while(0)
  3160. static float
  3161. utility_to_hashrate(double utility)
  3162. {
  3163. return utility * 0x4444444;
  3164. }
  3165. static const char*_unitchar = "pn\xb5m kMGTPEZY?";
  3166. static const int _unitbase = 4;
  3167. static
  3168. void pick_unit(float hashrate, unsigned char *unit)
  3169. {
  3170. unsigned char i;
  3171. if (hashrate == 0 || !isfinite(hashrate))
  3172. {
  3173. if (*unit < _unitbase)
  3174. *unit = _unitbase;
  3175. return;
  3176. }
  3177. hashrate *= 1e12;
  3178. for (i = 0; i < *unit; ++i)
  3179. hashrate /= 1e3;
  3180. // 1000 but with tolerance for floating-point rounding, avoid showing "1000.0"
  3181. while (hashrate >= 999.95)
  3182. {
  3183. hashrate /= 1e3;
  3184. if (likely(_unitchar[*unit] != '?'))
  3185. ++*unit;
  3186. }
  3187. }
  3188. #define hashrate_pick_unit(hashrate, unit) pick_unit(hashrate, unit)
  3189. enum h2bs_fmt {
  3190. H2B_NOUNIT, // "xxx.x"
  3191. H2B_SHORT, // "xxx.xMH/s"
  3192. H2B_SPACED, // "xxx.x MH/s"
  3193. H2B_SHORTV, // Like H2B_SHORT, but omit space for base unit
  3194. };
  3195. enum bfu_floatprec {
  3196. FUP_INTEGER,
  3197. FUP_HASHES,
  3198. FUP_BTC,
  3199. FUP_DIFF,
  3200. };
  3201. static
  3202. int format_unit3(char *buf, size_t sz, enum bfu_floatprec fprec, const char *measurement, enum h2bs_fmt fmt, float hashrate, signed char unitin)
  3203. {
  3204. char *s = buf;
  3205. unsigned char prec, i, unit;
  3206. int rv = 0;
  3207. if (unitin == -1)
  3208. {
  3209. unit = 0;
  3210. hashrate_pick_unit(hashrate, &unit);
  3211. }
  3212. else
  3213. unit = unitin;
  3214. hashrate *= 1e12;
  3215. for (i = 0; i < unit; ++i)
  3216. hashrate /= 1000;
  3217. switch (fprec)
  3218. {
  3219. case FUP_HASHES:
  3220. // 100 but with tolerance for floating-point rounding, max "99.99" then "100.0"
  3221. if (hashrate >= 99.995 || unit < 6)
  3222. prec = 1;
  3223. else
  3224. prec = 2;
  3225. _SNP("%5.*f", prec, hashrate);
  3226. break;
  3227. case FUP_INTEGER:
  3228. _SNP("%3d", (int)hashrate);
  3229. break;
  3230. case FUP_BTC:
  3231. if (hashrate >= 99.995)
  3232. prec = 0;
  3233. else
  3234. prec = 2;
  3235. _SNP("%5.*f", prec, hashrate);
  3236. break;
  3237. case FUP_DIFF:
  3238. if (unit > _unitbase)
  3239. _SNP("%.3g", hashrate);
  3240. else
  3241. _SNP("%u", (unsigned int)hashrate);
  3242. }
  3243. if (fmt != H2B_NOUNIT)
  3244. {
  3245. char uc[3] = {_unitchar[unit], '\0'};
  3246. switch (fmt) {
  3247. case H2B_SPACED:
  3248. _SNP(" ");
  3249. default:
  3250. break;
  3251. case H2B_SHORTV:
  3252. if (isspace(uc[0]))
  3253. uc[0] = '\0';
  3254. }
  3255. if (uc[0] == '\xb5')
  3256. // Convert to UTF-8
  3257. snprintf(uc, sizeof(uc), "%s", U8_MICRO);
  3258. _SNP("%s%s", uc, measurement);
  3259. }
  3260. return rv;
  3261. }
  3262. #define format_unit2(buf, sz, floatprec, measurement, fmt, n, unit) \
  3263. format_unit3(buf, sz, floatprec ? FUP_HASHES : FUP_INTEGER, measurement, fmt, n, unit)
  3264. static
  3265. 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)
  3266. {
  3267. unsigned char unit = 0;
  3268. bool allzero = true;
  3269. int i;
  3270. size_t delimsz = 0;
  3271. char *buf = buflist[0];
  3272. size_t bufsz = bufszlist[0];
  3273. size_t itemwidth = (floatprec ? 5 : 3);
  3274. if (!isarray)
  3275. delimsz = strlen(delim);
  3276. for (i = 0; i < count; ++i)
  3277. if (numbers[i] != 0)
  3278. {
  3279. pick_unit(numbers[i], &unit);
  3280. allzero = false;
  3281. }
  3282. if (allzero)
  3283. unit = _unitbase;
  3284. --count;
  3285. for (i = 0; i < count; ++i)
  3286. {
  3287. format_unit2(buf, bufsz, floatprec, NULL, H2B_NOUNIT, numbers[i], unit);
  3288. if (isarray)
  3289. {
  3290. buf = buflist[i + 1];
  3291. bufsz = bufszlist[i + 1];
  3292. }
  3293. else
  3294. {
  3295. buf += itemwidth;
  3296. bufsz -= itemwidth;
  3297. if (delimsz > bufsz)
  3298. delimsz = bufsz;
  3299. memcpy(buf, delim, delimsz);
  3300. buf += delimsz;
  3301. bufsz -= delimsz;
  3302. }
  3303. }
  3304. // Last entry has the unit
  3305. format_unit2(buf, bufsz, floatprec, measurement, fmt, numbers[count], unit);
  3306. return buflist[0];
  3307. }
  3308. #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)
  3309. #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)
  3310. static
  3311. int percentf3(char * const buf, size_t sz, double p, const double t)
  3312. {
  3313. char *s = buf;
  3314. int rv = 0;
  3315. if (!p)
  3316. _SNP("none");
  3317. else
  3318. if (t <= p)
  3319. _SNP("100%%");
  3320. else
  3321. {
  3322. p /= t;
  3323. if (p < 0.00995) // 0.01 but with tolerance for floating-point rounding, max ".99%"
  3324. _SNP(".%02.0f%%", p * 10000); // ".01%"
  3325. else
  3326. if (p < 0.0995) // 0.1 but with tolerance for floating-point rounding, max "9.9%"
  3327. _SNP("%.1f%%", p * 100); // "9.1%"
  3328. else
  3329. _SNP("%3.0f%%", p * 100); // " 99%"
  3330. }
  3331. return rv;
  3332. }
  3333. #define percentf4(buf, bufsz, p, t) percentf3(buf, bufsz, p, p + t)
  3334. static
  3335. void test_decimal_width()
  3336. {
  3337. // The pipe character at end of each line should perfectly line up
  3338. char printbuf[512];
  3339. char testbuf1[64];
  3340. char testbuf2[64];
  3341. char testbuf3[64];
  3342. char testbuf4[64];
  3343. double testn;
  3344. int width;
  3345. int saved;
  3346. // Hotspots around 0.1 and 0.01
  3347. saved = -1;
  3348. for (testn = 0.09; testn <= 0.11; testn += 0.000001) {
  3349. percentf3(testbuf1, sizeof(testbuf1), testn, 1.0);
  3350. percentf3(testbuf2, sizeof(testbuf2), testn, 10.0);
  3351. width = snprintf(printbuf, sizeof(printbuf), "%10g %s %s |", testn, testbuf1, testbuf2);
  3352. if (unlikely((saved != -1) && (width != saved))) {
  3353. ++unittest_failures;
  3354. applog(LOG_ERR, "Test width mismatch in percentf3! %d not %d at %10g", width, saved, testn);
  3355. applog(LOG_ERR, "%s", printbuf);
  3356. }
  3357. saved = width;
  3358. }
  3359. // Hotspot around 100 (but test this in several units because format_unit2 also has unit<2 check)
  3360. saved = -1;
  3361. for (testn = 99.0; testn <= 101.0; testn += 0.0001) {
  3362. format_unit2(testbuf1, sizeof(testbuf1), true, "x", H2B_SHORT, testn , -1);
  3363. format_unit2(testbuf2, sizeof(testbuf2), true, "x", H2B_SHORT, testn * 1e3, -1);
  3364. format_unit2(testbuf3, sizeof(testbuf3), true, "x", H2B_SHORT, testn * 1e6, -1);
  3365. snprintf(printbuf, sizeof(printbuf), "%10g %s %s %s |", testn, testbuf1, testbuf2, testbuf3);
  3366. width = utf8_strlen(printbuf);
  3367. if (unlikely((saved != -1) && (width != saved))) {
  3368. ++unittest_failures;
  3369. applog(LOG_ERR, "Test width mismatch in format_unit2! %d not %d at %10g", width, saved, testn);
  3370. applog(LOG_ERR, "%s", printbuf);
  3371. }
  3372. saved = width;
  3373. }
  3374. // Hotspot around unit transition boundary in pick_unit
  3375. saved = -1;
  3376. for (testn = 999.0; testn <= 1001.0; testn += 0.0001) {
  3377. format_unit2(testbuf1, sizeof(testbuf1), true, "x", H2B_SHORT, testn , -1);
  3378. format_unit2(testbuf2, sizeof(testbuf2), true, "x", H2B_SHORT, testn * 1e3, -1);
  3379. format_unit2(testbuf3, sizeof(testbuf3), true, "x", H2B_SHORT, testn * 1e6, -1);
  3380. format_unit2(testbuf4, sizeof(testbuf4), true, "x", H2B_SHORT, testn * 1e9, -1);
  3381. snprintf(printbuf, sizeof(printbuf), "%10g %s %s %s %s |", testn, testbuf1, testbuf2, testbuf3, testbuf4);
  3382. width = utf8_strlen(printbuf);
  3383. if (unlikely((saved != -1) && (width != saved))) {
  3384. ++unittest_failures;
  3385. applog(LOG_ERR, "Test width mismatch in pick_unit! %d not %d at %10g", width, saved, testn);
  3386. applog(LOG_ERR, "%s", printbuf);
  3387. }
  3388. saved = width;
  3389. }
  3390. }
  3391. #ifdef HAVE_CURSES
  3392. static void adj_width(int var, int *length);
  3393. #endif
  3394. #ifdef HAVE_CURSES
  3395. static int awidth = 1, rwidth = 1, swidth = 1, hwwidth = 1;
  3396. static
  3397. 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)
  3398. {
  3399. char rejpcbuf[6];
  3400. char bnbuf[6];
  3401. adj_width(accepted, &awidth);
  3402. adj_width(rejected, &rwidth);
  3403. adj_width(stale, &swidth);
  3404. adj_width(hwerrs, &hwwidth);
  3405. percentf4(rejpcbuf, sizeof(rejpcbuf), wnotaccepted, waccepted);
  3406. percentf3(bnbuf, sizeof(bnbuf), bad_diff1, allnonces);
  3407. tailsprintf(buf, bufsz, "%s/%s/%s | A:%*d R:%*d+%*d(%s) HW:%*d/%s",
  3408. cHr, aHr, uHr,
  3409. awidth, accepted,
  3410. rwidth, rejected,
  3411. swidth, stale,
  3412. rejpcbuf,
  3413. hwwidth, hwerrs,
  3414. bnbuf
  3415. );
  3416. }
  3417. static
  3418. const char *pool_proto_str(const struct pool * const pool)
  3419. {
  3420. if (pool->idle)
  3421. return "Dead ";
  3422. if (pool->has_stratum)
  3423. return "Strtm";
  3424. if (pool->lp_url && pool->proto != pool->lp_proto)
  3425. return "Mixed";
  3426. switch (pool->proto)
  3427. {
  3428. case PLP_GETBLOCKTEMPLATE:
  3429. return " GBT ";
  3430. case PLP_GETWORK:
  3431. return "GWork";
  3432. default:
  3433. return "Alive";
  3434. }
  3435. }
  3436. #endif
  3437. static inline
  3438. void temperature_column(char *buf, size_t bufsz, bool maybe_unicode, const float * const temp)
  3439. {
  3440. if (!(use_unicode && have_unicode_degrees))
  3441. maybe_unicode = false;
  3442. if (temp && *temp > 0.)
  3443. if (maybe_unicode)
  3444. snprintf(buf, bufsz, "%4.1f"U8_DEGREE"C", *temp);
  3445. else
  3446. snprintf(buf, bufsz, "%4.1fC", *temp);
  3447. else
  3448. {
  3449. if (temp)
  3450. snprintf(buf, bufsz, " ");
  3451. if (maybe_unicode)
  3452. tailsprintf(buf, bufsz, " ");
  3453. }
  3454. tailsprintf(buf, bufsz, " | ");
  3455. }
  3456. void get_statline3(char *buf, size_t bufsz, struct cgpu_info *cgpu, bool for_curses, bool opt_show_procs)
  3457. {
  3458. #ifndef HAVE_CURSES
  3459. assert(for_curses == false);
  3460. #endif
  3461. struct device_drv *drv = cgpu->drv;
  3462. enum h2bs_fmt hashrate_style = for_curses ? H2B_SHORT : H2B_SPACED;
  3463. char cHr[ALLOC_H2B_NOUNIT+1], aHr[ALLOC_H2B_NOUNIT+1], uHr[max(ALLOC_H2B_SHORT, ALLOC_H2B_SPACED)+3+1];
  3464. char rejpcbuf[6];
  3465. char bnbuf[6];
  3466. double dev_runtime;
  3467. if (!opt_show_procs)
  3468. cgpu = cgpu->device;
  3469. dev_runtime = cgpu_runtime(cgpu);
  3470. double rolling, mhashes;
  3471. int accepted, rejected, stale;
  3472. double waccepted;
  3473. double wnotaccepted;
  3474. int hwerrs;
  3475. double bad_diff1, good_diff1;
  3476. rolling = mhashes = waccepted = wnotaccepted = 0;
  3477. accepted = rejected = stale = hwerrs = bad_diff1 = good_diff1 = 0;
  3478. {
  3479. struct cgpu_info *slave = cgpu;
  3480. for (int i = 0; i < cgpu->procs; ++i, (slave = slave->next_proc))
  3481. {
  3482. slave->utility = slave->accepted / dev_runtime * 60;
  3483. slave->utility_diff1 = slave->diff_accepted / dev_runtime * 60;
  3484. rolling += slave->rolling;
  3485. mhashes += slave->total_mhashes;
  3486. if (opt_weighed_stats)
  3487. {
  3488. accepted += slave->diff_accepted;
  3489. rejected += slave->diff_rejected;
  3490. stale += slave->diff_stale;
  3491. }
  3492. else
  3493. {
  3494. accepted += slave->accepted;
  3495. rejected += slave->rejected;
  3496. stale += slave->stale;
  3497. }
  3498. waccepted += slave->diff_accepted;
  3499. wnotaccepted += slave->diff_rejected + slave->diff_stale;
  3500. hwerrs += slave->hw_errors;
  3501. bad_diff1 += slave->bad_diff1;
  3502. good_diff1 += slave->diff1;
  3503. if (opt_show_procs)
  3504. break;
  3505. }
  3506. }
  3507. double wtotal = (waccepted + wnotaccepted);
  3508. multi_format_unit_array2(
  3509. ((char*[]){cHr, aHr, uHr}),
  3510. ((size_t[]){sizeof(cHr), sizeof(aHr), sizeof(uHr)}),
  3511. true, "h/s", hashrate_style,
  3512. 3,
  3513. 1e6*rolling,
  3514. 1e6*mhashes / dev_runtime,
  3515. utility_to_hashrate(good_diff1 * (wtotal ? (waccepted / wtotal) : 1) * 60 / dev_runtime));
  3516. // Processor representation
  3517. #ifdef HAVE_CURSES
  3518. if (for_curses)
  3519. {
  3520. if (opt_show_procs)
  3521. snprintf(buf, bufsz, " %*s: ", -(5 + max_lpdigits), cgpu->proc_repr);
  3522. else
  3523. snprintf(buf, bufsz, " %s: ", cgpu->dev_repr);
  3524. }
  3525. else
  3526. #endif
  3527. snprintf(buf, bufsz, "%s ", opt_show_procs ? cgpu->proc_repr_ns : cgpu->dev_repr_ns);
  3528. if (include_serial_in_statline && cgpu->dev_serial)
  3529. tailsprintf(buf, bufsz, "[serial=%s] ", cgpu->dev_serial);
  3530. if (unlikely(cgpu->status == LIFE_INIT))
  3531. {
  3532. tailsprintf(buf, bufsz, "Initializing...");
  3533. return;
  3534. }
  3535. {
  3536. const size_t bufln = strlen(buf);
  3537. const size_t abufsz = (bufln >= bufsz) ? 0 : (bufsz - bufln);
  3538. if (likely(cgpu->status != LIFE_DEAD2) && drv->override_statline_temp2 && drv->override_statline_temp2(buf, bufsz, cgpu, opt_show_procs))
  3539. temperature_column(&buf[bufln], abufsz, for_curses, NULL);
  3540. else
  3541. {
  3542. float temp = cgpu->temp;
  3543. if (!opt_show_procs)
  3544. {
  3545. // Find the highest temperature of all processors
  3546. struct cgpu_info *proc = cgpu;
  3547. for (int i = 0; i < cgpu->procs; ++i, (proc = proc->next_proc))
  3548. if (proc->temp > temp)
  3549. temp = proc->temp;
  3550. }
  3551. temperature_column(&buf[bufln], abufsz, for_curses, &temp);
  3552. }
  3553. }
  3554. #ifdef HAVE_CURSES
  3555. if (for_curses)
  3556. {
  3557. const char *cHrStatsOpt[] = {AS_BAD("DEAD "), AS_BAD("SICK "), "OFF ", AS_BAD("REST "), AS_BAD(" ERR "), AS_BAD("WAIT "), cHr};
  3558. const char *cHrStats;
  3559. int cHrStatsI = (sizeof(cHrStatsOpt) / sizeof(*cHrStatsOpt)) - 1;
  3560. bool all_dead = true, all_off = true, all_rdrv = true;
  3561. struct cgpu_info *proc = cgpu;
  3562. for (int i = 0; i < cgpu->procs; ++i, (proc = proc->next_proc))
  3563. {
  3564. switch (cHrStatsI) {
  3565. default:
  3566. if (proc->status == LIFE_WAIT)
  3567. cHrStatsI = 5;
  3568. case 5:
  3569. if (proc->deven == DEV_RECOVER_ERR)
  3570. cHrStatsI = 4;
  3571. case 4:
  3572. if (proc->deven == DEV_RECOVER)
  3573. cHrStatsI = 3;
  3574. case 3:
  3575. if (proc->status == LIFE_SICK || proc->status == LIFE_DEAD || proc->status == LIFE_DEAD2)
  3576. {
  3577. cHrStatsI = 1;
  3578. all_off = false;
  3579. }
  3580. else
  3581. {
  3582. if (likely(proc->deven == DEV_ENABLED))
  3583. all_off = false;
  3584. if (proc->deven != DEV_RECOVER_DRV)
  3585. all_rdrv = false;
  3586. }
  3587. case 1:
  3588. break;
  3589. }
  3590. if (likely(proc->status != LIFE_DEAD && proc->status != LIFE_DEAD2))
  3591. all_dead = false;
  3592. if (opt_show_procs)
  3593. break;
  3594. }
  3595. if (unlikely(all_dead))
  3596. cHrStatsI = 0;
  3597. else
  3598. if (unlikely(all_off))
  3599. cHrStatsI = 2;
  3600. cHrStats = cHrStatsOpt[cHrStatsI];
  3601. if (cHrStatsI == 2 && all_rdrv)
  3602. cHrStats = " RST ";
  3603. format_statline(buf, bufsz,
  3604. cHrStats,
  3605. aHr, uHr,
  3606. accepted, rejected, stale,
  3607. wnotaccepted, waccepted,
  3608. hwerrs,
  3609. bad_diff1, bad_diff1 + good_diff1);
  3610. }
  3611. else
  3612. #endif
  3613. {
  3614. percentf4(rejpcbuf, sizeof(rejpcbuf), wnotaccepted, waccepted);
  3615. percentf4(bnbuf, sizeof(bnbuf), bad_diff1, good_diff1);
  3616. tailsprintf(buf, bufsz, "%ds:%s avg:%s u:%s | A:%d R:%d+%d(%s) HW:%d/%s",
  3617. opt_log_interval,
  3618. cHr, aHr, uHr,
  3619. accepted,
  3620. rejected,
  3621. stale,
  3622. rejpcbuf,
  3623. hwerrs,
  3624. bnbuf
  3625. );
  3626. }
  3627. }
  3628. #define get_statline(buf, bufsz, cgpu) get_statline3(buf, bufsz, cgpu, false, opt_show_procs)
  3629. #define get_statline2(buf, bufsz, cgpu, for_curses) get_statline3(buf, bufsz, cgpu, for_curses, opt_show_procs)
  3630. static void text_print_status(int thr_id)
  3631. {
  3632. struct cgpu_info *cgpu;
  3633. char logline[256];
  3634. cgpu = get_thr_cgpu(thr_id);
  3635. if (cgpu) {
  3636. get_statline(logline, sizeof(logline), cgpu);
  3637. printf("\n%s\r", logline);
  3638. fflush(stdout);
  3639. }
  3640. }
  3641. #ifdef HAVE_CURSES
  3642. static int attr_bad = A_BOLD;
  3643. #ifdef WIN32
  3644. #define swprintf snwprintf
  3645. #endif
  3646. static
  3647. void bfg_waddstr(WINDOW *win, const char *s)
  3648. {
  3649. const char *p = s;
  3650. int32_t w;
  3651. int wlen;
  3652. unsigned char stop_ascii = (use_unicode ? '|' : 0x80);
  3653. while (true)
  3654. {
  3655. while (likely(p[0] == '\n' || (p[0] >= 0x20 && p[0] < stop_ascii)))
  3656. {
  3657. // Printable ASCII
  3658. ++p;
  3659. }
  3660. if (p != s)
  3661. waddnstr(win, s, p - s);
  3662. w = utf8_decode(p, &wlen);
  3663. s = p += wlen;
  3664. switch(w)
  3665. {
  3666. // NOTE: U+F000-U+F7FF are reserved for font hacks
  3667. case '\0':
  3668. return;
  3669. case 0xb5: // micro symbol
  3670. w = unicode_micro;
  3671. goto default_addch;
  3672. case 0xf000: // "bad" off
  3673. wattroff(win, attr_bad);
  3674. break;
  3675. case 0xf001: // "bad" on
  3676. wattron(win, attr_bad);
  3677. break;
  3678. #ifdef USE_UNICODE
  3679. case '|':
  3680. wadd_wch(win, WACS_VLINE);
  3681. break;
  3682. #endif
  3683. case 0x2500: // BOX DRAWINGS LIGHT HORIZONTAL
  3684. case 0x2534: // BOX DRAWINGS LIGHT UP AND HORIZONTAL
  3685. if (!use_unicode)
  3686. {
  3687. waddch(win, '-');
  3688. break;
  3689. }
  3690. #ifdef USE_UNICODE
  3691. wadd_wch(win, (w == 0x2500) ? WACS_HLINE : WACS_BTEE);
  3692. break;
  3693. #endif
  3694. case 0x2022:
  3695. if (w > WCHAR_MAX || !iswprint(w))
  3696. w = '*';
  3697. default:
  3698. default_addch:
  3699. if (w > WCHAR_MAX || !(iswprint(w) || w == '\n'))
  3700. {
  3701. #if REPLACEMENT_CHAR <= WCHAR_MAX
  3702. if (iswprint(REPLACEMENT_CHAR))
  3703. w = REPLACEMENT_CHAR;
  3704. else
  3705. #endif
  3706. w = '?';
  3707. }
  3708. {
  3709. #ifdef USE_UNICODE
  3710. wchar_t wbuf[0x10];
  3711. int wbuflen = sizeof(wbuf) / sizeof(*wbuf);
  3712. wbuflen = swprintf(wbuf, wbuflen, L"%lc", (wint_t)w);
  3713. waddnwstr(win, wbuf, wbuflen);
  3714. #else
  3715. wprintw(win, "%lc", (wint_t)w);
  3716. #endif
  3717. }
  3718. }
  3719. }
  3720. }
  3721. static inline
  3722. void bfg_hline(WINDOW *win, int y)
  3723. {
  3724. int maxx, __maybe_unused maxy;
  3725. getmaxyx(win, maxy, maxx);
  3726. #ifdef USE_UNICODE
  3727. if (use_unicode)
  3728. mvwhline_set(win, y, 0, WACS_HLINE, maxx);
  3729. else
  3730. #endif
  3731. mvwhline(win, y, 0, '-', maxx);
  3732. }
  3733. static
  3734. int bfg_win_linelen(WINDOW * const win)
  3735. {
  3736. int maxx;
  3737. int __maybe_unused y;
  3738. getmaxyx(win, y, maxx);
  3739. return maxx;
  3740. }
  3741. // Spaces until end of line, using current attributes (ie, not completely clear)
  3742. static
  3743. void bfg_wspctoeol(WINDOW * const win, const int offset)
  3744. {
  3745. int x, maxx;
  3746. int __maybe_unused y;
  3747. getmaxyx(win, y, maxx);
  3748. getyx(win, y, x);
  3749. const int space_count = (maxx - x) - offset;
  3750. // Check for negative - terminal too narrow
  3751. if (space_count <= 0)
  3752. return;
  3753. char buf[space_count];
  3754. memset(buf, ' ', space_count);
  3755. waddnstr(win, buf, space_count);
  3756. }
  3757. static int menu_attr = A_REVERSE;
  3758. #define CURBUFSIZ 256
  3759. #define cg_mvwprintw(win, y, x, fmt, ...) do { \
  3760. char tmp42[CURBUFSIZ]; \
  3761. snprintf(tmp42, sizeof(tmp42), fmt, ##__VA_ARGS__); \
  3762. wmove(win, y, x); \
  3763. bfg_waddstr(win, tmp42); \
  3764. } while (0)
  3765. #define cg_wprintw(win, fmt, ...) do { \
  3766. char tmp42[CURBUFSIZ]; \
  3767. snprintf(tmp42, sizeof(tmp42), fmt, ##__VA_ARGS__); \
  3768. bfg_waddstr(win, tmp42); \
  3769. } while (0)
  3770. static
  3771. void update_block_display_line(const int blky, struct mining_goal_info *goal)
  3772. {
  3773. struct blockchain_info * const blkchain = goal->blkchain;
  3774. struct block_info * const blkinfo = blkchain->currentblk;
  3775. double income;
  3776. char incomestr[ALLOC_H2B_SHORT+6+1];
  3777. if (blkinfo->height)
  3778. {
  3779. income = goal->diff_accepted * 3600 * blkchain->currentblk_subsidy / total_secs / goal->current_diff;
  3780. format_unit3(incomestr, sizeof(incomestr), FUP_BTC, "BTC/hr", H2B_SHORT, income/1e8, -1);
  3781. }
  3782. else
  3783. strcpy(incomestr, "?");
  3784. int linelen = bfg_win_linelen(statuswin);
  3785. wmove(statuswin, blky, 0);
  3786. bfg_waddstr(statuswin, " Block");
  3787. if (!goal->is_default)
  3788. linelen -= strlen(goal->name) + 1;
  3789. linelen -= 6; // " Block"
  3790. if (blkinfo->height && blkinfo->height < 1000000)
  3791. {
  3792. cg_wprintw(statuswin, " #%6u", blkinfo->height);
  3793. linelen -= 8;
  3794. }
  3795. bfg_waddstr(statuswin, ":");
  3796. if (linelen > 55)
  3797. bfg_waddstr(statuswin, " ");
  3798. if (linelen >= 65)
  3799. bfg_waddstr(statuswin, "...");
  3800. {
  3801. char hexpbh[0x11];
  3802. if (!(blkinfo->height && blkinfo->height < 1000000))
  3803. {
  3804. bin2hex(hexpbh, &blkinfo->prevblkhash[4], 4);
  3805. bfg_waddstr(statuswin, hexpbh);
  3806. }
  3807. bin2hex(hexpbh, &blkinfo->prevblkhash[0], 4);
  3808. bfg_waddstr(statuswin, hexpbh);
  3809. }
  3810. if (linelen >= 55)
  3811. bfg_waddstr(statuswin, " ");
  3812. cg_wprintw(statuswin, " Diff:%s", goal->current_diff_str);
  3813. if (linelen >= 69)
  3814. bfg_waddstr(statuswin, " ");
  3815. cg_wprintw(statuswin, "(%s) ", goal->net_hashrate);
  3816. if (linelen >= 62)
  3817. {
  3818. if (linelen >= 69)
  3819. bfg_waddstr(statuswin, " ");
  3820. bfg_waddstr(statuswin, "Started:");
  3821. }
  3822. else
  3823. bfg_waddstr(statuswin, "S:");
  3824. if (linelen >= 69)
  3825. bfg_waddstr(statuswin, " ");
  3826. bfg_waddstr(statuswin, blkchain->currentblk_first_seen_time_str);
  3827. if (linelen >= 69)
  3828. bfg_waddstr(statuswin, " ");
  3829. cg_wprintw(statuswin, " I:%s", incomestr);
  3830. if (!goal->is_default)
  3831. cg_wprintw(statuswin, " %s", goal->name);
  3832. wclrtoeol(statuswin);
  3833. }
  3834. static bool pool_actively_in_use(const struct pool *, const struct pool *);
  3835. static
  3836. void update_block_display(void)
  3837. {
  3838. struct mining_goal_info *goal, *tmpgoal;
  3839. int blky = 3, i, total_found_goals = 0;
  3840. HASH_ITER(hh, mining_goals, goal, tmpgoal)
  3841. {
  3842. for (i = 0; i < total_pools; ++i)
  3843. {
  3844. struct pool * const pool = pools[i];
  3845. if (pool->goal == goal && pool_actively_in_use(pool, NULL))
  3846. break;
  3847. }
  3848. if (i >= total_pools)
  3849. // no pools using this goal, so it's probably stale anyway
  3850. continue;
  3851. update_block_display_line(blky++, goal);
  3852. ++total_found_goals;
  3853. }
  3854. if (total_found_goals != active_goals)
  3855. {
  3856. active_goals = total_found_goals;
  3857. devcursor = 7 + active_goals;
  3858. switch_logsize();
  3859. }
  3860. }
  3861. static bool pool_unworkable(const struct pool *);
  3862. /* Must be called with curses mutex lock held and curses_active */
  3863. static void curses_print_status(const int ts)
  3864. {
  3865. struct pool *pool = currentpool;
  3866. struct timeval now, tv;
  3867. float efficiency;
  3868. int logdiv;
  3869. efficiency = total_bytes_xfer ? total_diff_accepted * 2048. / total_bytes_xfer : 0.0;
  3870. wattron(statuswin, attr_title);
  3871. const int linelen = bfg_win_linelen(statuswin);
  3872. int titlelen = 1 + strlen(PACKAGE) + 1 + strlen(VERSION) + 3 + 21 + 3 + 19;
  3873. cg_mvwprintw(statuswin, 0, 0, " " PACKAGE " ");
  3874. if (titlelen + 17 < linelen)
  3875. cg_wprintw(statuswin, "version ");
  3876. cg_wprintw(statuswin, VERSION " - ");
  3877. if (titlelen + 9 < linelen)
  3878. cg_wprintw(statuswin, "Started: ");
  3879. else
  3880. if (titlelen + 7 <= linelen)
  3881. cg_wprintw(statuswin, "Start: ");
  3882. cg_wprintw(statuswin, "%s", datestamp);
  3883. timer_set_now(&now);
  3884. {
  3885. unsigned int days, hours;
  3886. div_t d;
  3887. timersub(&now, &miner_started, &tv);
  3888. d = div(tv.tv_sec, 86400);
  3889. days = d.quot;
  3890. d = div(d.rem, 3600);
  3891. hours = d.quot;
  3892. d = div(d.rem, 60);
  3893. cg_wprintw(statuswin, " - [%3u day%c %02d:%02d:%02d]"
  3894. , days
  3895. , (days == 1) ? ' ' : 's'
  3896. , hours
  3897. , d.quot
  3898. , d.rem
  3899. );
  3900. }
  3901. bfg_wspctoeol(statuswin, 0);
  3902. wattroff(statuswin, attr_title);
  3903. wattron(statuswin, menu_attr);
  3904. wmove(statuswin, 1, 0);
  3905. bfg_waddstr(statuswin, " [M]anage devices [P]ool management [S]ettings [D]isplay options ");
  3906. bfg_wspctoeol(statuswin, 14);
  3907. bfg_waddstr(statuswin, "[H]elp [Q]uit ");
  3908. wattroff(statuswin, menu_attr);
  3909. if ((pool_strategy == POOL_LOADBALANCE || pool_strategy == POOL_BALANCE) && enabled_pools > 1) {
  3910. char poolinfo[20], poolinfo2[20];
  3911. int poolinfooff = 0, poolinfo2off, workable_pools = 0;
  3912. double lowdiff = DBL_MAX, highdiff = -1;
  3913. struct pool *lowdiff_pool = pools[0], *highdiff_pool = pools[0];
  3914. time_t oldest_work_restart = time(NULL) + 1;
  3915. struct pool *oldest_work_restart_pool = pools[0];
  3916. for (int i = 0; i < total_pools; ++i)
  3917. {
  3918. if (pool_unworkable(pools[i]))
  3919. continue;
  3920. // NOTE: Only set pool var when it's workable; if only one is, it gets used by single-pool code
  3921. pool = pools[i];
  3922. ++workable_pools;
  3923. if (poolinfooff < sizeof(poolinfo))
  3924. poolinfooff += snprintf(&poolinfo[poolinfooff], sizeof(poolinfo) - poolinfooff, "%u,", pool->pool_no);
  3925. struct cgminer_pool_stats * const pool_stats = &pool->cgminer_pool_stats;
  3926. if (pool_stats->last_diff < lowdiff)
  3927. {
  3928. lowdiff = pool_stats->last_diff;
  3929. lowdiff_pool = pool;
  3930. }
  3931. if (pool_stats->last_diff > highdiff)
  3932. {
  3933. highdiff = pool_stats->last_diff;
  3934. highdiff_pool = pool;
  3935. }
  3936. if (oldest_work_restart >= pool->work_restart_time)
  3937. {
  3938. oldest_work_restart = pool->work_restart_time;
  3939. oldest_work_restart_pool = pool;
  3940. }
  3941. }
  3942. if (unlikely(!workable_pools))
  3943. goto no_workable_pools;
  3944. if (workable_pools == 1)
  3945. goto one_workable_pool;
  3946. poolinfo2off = snprintf(poolinfo2, sizeof(poolinfo2), "%u (", workable_pools);
  3947. if (poolinfooff > sizeof(poolinfo2) - poolinfo2off - 1)
  3948. snprintf(&poolinfo2[poolinfo2off], sizeof(poolinfo2) - poolinfo2off, "%.*s...)", (int)(sizeof(poolinfo2) - poolinfo2off - 5), poolinfo);
  3949. else
  3950. snprintf(&poolinfo2[poolinfo2off], sizeof(poolinfo2) - poolinfo2off, "%.*s)%*s", (int)(poolinfooff - 1), poolinfo, (int)(sizeof(poolinfo2)), "");
  3951. cg_mvwprintw(statuswin, 2, 0, " Pools: %s Diff:%s%s%s %c LU:%s",
  3952. poolinfo2,
  3953. lowdiff_pool->diff,
  3954. (lowdiff == highdiff) ? "" : "-",
  3955. (lowdiff == highdiff) ? "" : highdiff_pool->diff,
  3956. have_longpoll ? '+' : '-',
  3957. oldest_work_restart_pool->work_restart_timestamp);
  3958. }
  3959. else
  3960. if (pool_unworkable(pool))
  3961. {
  3962. no_workable_pools: ;
  3963. wattron(statuswin, attr_bad);
  3964. cg_mvwprintw(statuswin, 2, 0, " (all pools are dead) ");
  3965. wattroff(statuswin, attr_bad);
  3966. }
  3967. else
  3968. {
  3969. one_workable_pool: ;
  3970. char pooladdr[19];
  3971. {
  3972. const char *rawaddr = pool->sockaddr_url;
  3973. BFGINIT(rawaddr, pool->rpc_url);
  3974. size_t pooladdrlen = strlen(rawaddr);
  3975. if (pooladdrlen > 20)
  3976. snprintf(pooladdr, sizeof(pooladdr), "...%s", &rawaddr[pooladdrlen - (sizeof(pooladdr) - 4)]);
  3977. else
  3978. snprintf(pooladdr, sizeof(pooladdr), "%*s", -(int)(sizeof(pooladdr) - 1), rawaddr);
  3979. }
  3980. cg_mvwprintw(statuswin, 2, 0, " Pool%2u: %s Diff:%s %c%s LU:%s User:%s",
  3981. pool->pool_no, pooladdr, pool->diff,
  3982. have_longpoll ? '+' : '-', pool_proto_str(pool),
  3983. pool->work_restart_timestamp,
  3984. pool->rpc_user);
  3985. }
  3986. wclrtoeol(statuswin);
  3987. char bwstr[(ALLOC_H2B_SHORT*2)+3+1];
  3988. cg_mvwprintw(statuswin, devcursor - 4, 0, " ST:%d F:%d NB:%d AS:%d BW:[%s] E:%.2f BS:%s",
  3989. ts,
  3990. total_go + total_ro,
  3991. new_blocks,
  3992. total_submitting,
  3993. multi_format_unit2(bwstr, sizeof(bwstr),
  3994. false, "B/s", H2B_SHORT, "/", 2,
  3995. (float)(total_bytes_rcvd / total_secs),
  3996. (float)(total_bytes_sent / total_secs)),
  3997. efficiency,
  3998. best_share);
  3999. wclrtoeol(statuswin);
  4000. mvwaddstr(statuswin, devcursor - 3, 0, " ");
  4001. bfg_waddstr(statuswin, statusline);
  4002. wclrtoeol(statuswin);
  4003. int devdiv = devcursor - 2;
  4004. logdiv = statusy - 1;
  4005. bfg_hline(statuswin, devdiv);
  4006. bfg_hline(statuswin, logdiv);
  4007. #ifdef USE_UNICODE
  4008. if (use_unicode)
  4009. {
  4010. int offset = 8 /* device */ + 5 /* temperature */ + 1 /* padding space */;
  4011. if (opt_show_procs && !opt_compact)
  4012. offset += max_lpdigits; // proc letter(s)
  4013. if (have_unicode_degrees)
  4014. ++offset; // degrees symbol
  4015. mvwadd_wch(statuswin, devdiv, offset, WACS_PLUS);
  4016. mvwadd_wch(statuswin, logdiv, offset, WACS_BTEE);
  4017. offset += 24; // hashrates etc
  4018. mvwadd_wch(statuswin, devdiv, offset, WACS_PLUS);
  4019. mvwadd_wch(statuswin, logdiv, offset, WACS_BTEE);
  4020. }
  4021. #endif
  4022. }
  4023. static void adj_width(int var, int *length)
  4024. {
  4025. if ((int)(log10(var) + 1) > *length)
  4026. (*length)++;
  4027. }
  4028. static int dev_width;
  4029. static void curses_print_devstatus(struct cgpu_info *cgpu)
  4030. {
  4031. char logline[256];
  4032. int ypos;
  4033. if (opt_compact)
  4034. return;
  4035. /* Check this isn't out of the window size */
  4036. if (opt_show_procs)
  4037. ypos = cgpu->cgminer_id;
  4038. else
  4039. {
  4040. if (cgpu->proc_id)
  4041. return;
  4042. ypos = cgpu->device_line_id;
  4043. }
  4044. ypos += devsummaryYOffset;
  4045. if (ypos < 0)
  4046. return;
  4047. ypos += devcursor - 1;
  4048. if (ypos >= statusy - 1)
  4049. return;
  4050. if (wmove(statuswin, ypos, 0) == ERR)
  4051. return;
  4052. get_statline2(logline, sizeof(logline), cgpu, true);
  4053. if (selecting_device && (opt_show_procs ? (selected_device == cgpu->cgminer_id) : (devices[selected_device]->device == cgpu)))
  4054. wattron(statuswin, A_REVERSE);
  4055. bfg_waddstr(statuswin, logline);
  4056. wattroff(statuswin, A_REVERSE);
  4057. wclrtoeol(statuswin);
  4058. }
  4059. static
  4060. void _refresh_devstatus(const bool already_have_lock) {
  4061. if ((!opt_compact) && (already_have_lock || curses_active_locked())) {
  4062. int i;
  4063. if (unlikely(!total_devices))
  4064. {
  4065. const int ypos = devcursor - 1;
  4066. if (ypos < statusy - 1 && wmove(statuswin, ypos, 0) != ERR)
  4067. {
  4068. wattron(statuswin, attr_bad);
  4069. bfg_waddstr(statuswin, "NO DEVICES FOUND: Press 'M' and '+' to add");
  4070. wclrtoeol(statuswin);
  4071. wattroff(statuswin, attr_bad);
  4072. }
  4073. }
  4074. for (i = 0; i < total_devices; i++)
  4075. curses_print_devstatus(get_devices(i));
  4076. touchwin(statuswin);
  4077. wrefresh(statuswin);
  4078. if (!already_have_lock)
  4079. unlock_curses();
  4080. }
  4081. }
  4082. #define refresh_devstatus() _refresh_devstatus(false)
  4083. #endif
  4084. static void print_status(int thr_id)
  4085. {
  4086. if (!curses_active)
  4087. text_print_status(thr_id);
  4088. }
  4089. #ifdef HAVE_CURSES
  4090. static
  4091. bool set_statusy(int maxy)
  4092. {
  4093. if (loginput_size)
  4094. {
  4095. maxy -= loginput_size;
  4096. if (maxy < 0)
  4097. maxy = 0;
  4098. }
  4099. if (logstart < maxy)
  4100. maxy = logstart;
  4101. if (statusy == maxy)
  4102. return false;
  4103. statusy = maxy;
  4104. logcursor = statusy;
  4105. return true;
  4106. }
  4107. /* Check for window resize. Called with curses mutex locked */
  4108. static inline void change_logwinsize(void)
  4109. {
  4110. int x, y, logx, logy;
  4111. getmaxyx(mainwin, y, x);
  4112. if (x < 80 || y < 25)
  4113. return;
  4114. if (y > statusy + 2 && statusy < logstart) {
  4115. set_statusy(y - 2);
  4116. mvwin(logwin, logcursor, 0);
  4117. bfg_wresize(statuswin, statusy, x);
  4118. }
  4119. y -= logcursor;
  4120. getmaxyx(logwin, logy, logx);
  4121. /* Detect screen size change */
  4122. if (x != logx || y != logy)
  4123. bfg_wresize(logwin, y, x);
  4124. }
  4125. static void check_winsizes(void)
  4126. {
  4127. if (!use_curses)
  4128. return;
  4129. if (curses_active_locked()) {
  4130. int y, x;
  4131. x = getmaxx(statuswin);
  4132. if (set_statusy(LINES - 2))
  4133. {
  4134. erase();
  4135. bfg_wresize(statuswin, statusy, x);
  4136. getmaxyx(mainwin, y, x);
  4137. y -= logcursor;
  4138. bfg_wresize(logwin, y, x);
  4139. mvwin(logwin, logcursor, 0);
  4140. }
  4141. unlock_curses();
  4142. }
  4143. }
  4144. static int device_line_id_count;
  4145. static void switch_logsize(void)
  4146. {
  4147. if (curses_active_locked()) {
  4148. if (opt_compact) {
  4149. logstart = devcursor - 1;
  4150. logcursor = logstart + 1;
  4151. } else {
  4152. total_lines = (opt_show_procs ? total_devices : device_line_id_count) ?: 1;
  4153. logstart = devcursor + total_lines;
  4154. logcursor = logstart;
  4155. }
  4156. unlock_curses();
  4157. }
  4158. check_winsizes();
  4159. update_block_display();
  4160. }
  4161. /* For mandatory printing when mutex is already locked */
  4162. void _wlog(const char *str)
  4163. {
  4164. static bool newline;
  4165. size_t end = strlen(str) - 1;
  4166. if (newline)
  4167. bfg_waddstr(logwin, "\n");
  4168. if (str[end] == '\n')
  4169. {
  4170. char *s;
  4171. newline = true;
  4172. s = alloca(end + 1);
  4173. memcpy(s, str, end);
  4174. s[end] = '\0';
  4175. str = s;
  4176. }
  4177. else
  4178. newline = false;
  4179. bfg_waddstr(logwin, str);
  4180. }
  4181. /* Mandatory printing */
  4182. void _wlogprint(const char *str)
  4183. {
  4184. if (curses_active_locked()) {
  4185. _wlog(str);
  4186. unlock_curses();
  4187. }
  4188. }
  4189. #endif
  4190. #ifdef HAVE_CURSES
  4191. bool _log_curses_only(int prio, const char *datetime, const char *str)
  4192. {
  4193. bool high_prio;
  4194. high_prio = (prio == LOG_WARNING || prio == LOG_ERR);
  4195. if (curses_active)
  4196. {
  4197. if (!loginput_size || high_prio) {
  4198. wlog(" %s %s\n", datetime, str);
  4199. if (high_prio) {
  4200. touchwin(logwin);
  4201. wrefresh(logwin);
  4202. }
  4203. }
  4204. return true;
  4205. }
  4206. return false;
  4207. }
  4208. void clear_logwin(void)
  4209. {
  4210. if (curses_active_locked()) {
  4211. wclear(logwin);
  4212. unlock_curses();
  4213. }
  4214. }
  4215. void logwin_update(void)
  4216. {
  4217. if (curses_active_locked()) {
  4218. touchwin(logwin);
  4219. wrefresh(logwin);
  4220. unlock_curses();
  4221. }
  4222. }
  4223. #endif
  4224. void enable_pool(struct pool * const pool)
  4225. {
  4226. if (pool->enabled != POOL_ENABLED) {
  4227. mutex_lock(&lp_lock);
  4228. enabled_pools++;
  4229. pool->enabled = POOL_ENABLED;
  4230. pthread_cond_broadcast(&lp_cond);
  4231. mutex_unlock(&lp_lock);
  4232. if (pool->prio < current_pool()->prio)
  4233. switch_pools(pool);
  4234. }
  4235. }
  4236. void disable_pool(struct pool * const pool, const enum pool_enable enable_status)
  4237. {
  4238. if (pool->enabled == POOL_DISABLED)
  4239. /* had been manually disabled before */
  4240. return;
  4241. if (pool->enabled != POOL_ENABLED)
  4242. {
  4243. /* has been programmatically disabled already, just change to the new status directly */
  4244. pool->enabled = enable_status;
  4245. return;
  4246. }
  4247. /* Fall into the lock area */
  4248. mutex_lock(&lp_lock);
  4249. --enabled_pools;
  4250. pool->enabled = enable_status;
  4251. mutex_unlock(&lp_lock);
  4252. if (pool == current_pool())
  4253. switch_pools(NULL);
  4254. }
  4255. static
  4256. void share_result_msg(const struct work *work, const char *disp, const char *reason, bool resubmit, const char *worktime) {
  4257. struct cgpu_info *cgpu;
  4258. const unsigned char *hashpart = &work->hash[opt_scrypt ? 26 : 24];
  4259. char shrdiffdisp[ALLOC_H2B_SHORTV];
  4260. const double tgtdiff = work->work_difficulty;
  4261. char tgtdiffdisp[ALLOC_H2B_SHORTV];
  4262. char where[20];
  4263. cgpu = get_thr_cgpu(work->thr_id);
  4264. suffix_string(work->share_diff, shrdiffdisp, sizeof(shrdiffdisp), 0);
  4265. suffix_string(tgtdiff, tgtdiffdisp, sizeof(tgtdiffdisp), 0);
  4266. if (total_pools > 1)
  4267. snprintf(where, sizeof(where), " pool %d", work->pool->pool_no);
  4268. else
  4269. where[0] = '\0';
  4270. applog(LOG_NOTICE, "%s %02x%02x%02x%02x %"PRIprepr"%s Diff %s/%s%s %s%s",
  4271. disp,
  4272. (unsigned)hashpart[3], (unsigned)hashpart[2], (unsigned)hashpart[1], (unsigned)hashpart[0],
  4273. cgpu->proc_repr,
  4274. where,
  4275. shrdiffdisp, tgtdiffdisp,
  4276. reason,
  4277. resubmit ? "(resubmit)" : "",
  4278. worktime
  4279. );
  4280. }
  4281. static bool test_work_current(struct work *);
  4282. static void _submit_work_async(struct work *);
  4283. static
  4284. void maybe_local_submit(const struct work *work)
  4285. {
  4286. #if BLKMAKER_VERSION > 3
  4287. if (unlikely(work->block && work->tr))
  4288. {
  4289. // This is a block with a full template (GBT)
  4290. // Regardless of the result, submit to local bitcoind(s) as well
  4291. struct work *work_cp;
  4292. for (int i = 0; i < total_pools; ++i)
  4293. {
  4294. if (!uri_get_param_bool(pools[i]->rpc_url, "allblocks", false))
  4295. continue;
  4296. applog(LOG_DEBUG, "Attempting submission of full block to pool %d", pools[i]->pool_no);
  4297. work_cp = copy_work(work);
  4298. work_cp->pool = pools[i];
  4299. work_cp->do_foreign_submit = true;
  4300. _submit_work_async(work_cp);
  4301. }
  4302. }
  4303. #endif
  4304. }
  4305. static
  4306. json_t *extract_reject_reason_j(json_t * const val, json_t *res, json_t * const err, const struct work * const work)
  4307. {
  4308. if (json_is_string(res))
  4309. return res;
  4310. if ( (res = json_object_get(val, "reject-reason")) )
  4311. return res;
  4312. if (work->stratum && err && json_is_array(err) && json_array_size(err) >= 2 && (res = json_array_get(err, 1)) && json_is_string(res))
  4313. return res;
  4314. return NULL;
  4315. }
  4316. static
  4317. const char *extract_reject_reason(json_t * const val, json_t *res, json_t * const err, const struct work * const work)
  4318. {
  4319. json_t * const j = extract_reject_reason_j(val, res, err, work);
  4320. return j ? json_string_value(j) : NULL;
  4321. }
  4322. static
  4323. int put_in_parens(char * const buf, const size_t bufsz, const char * const s)
  4324. {
  4325. if (!s)
  4326. {
  4327. if (bufsz)
  4328. buf[0] = '\0';
  4329. return 0;
  4330. }
  4331. int p = snprintf(buf, bufsz, " (%s", s);
  4332. if (p >= bufsz - 1)
  4333. p = bufsz - 2;
  4334. strcpy(&buf[p], ")");
  4335. return p + 1;
  4336. }
  4337. /* Theoretically threads could race when modifying accepted and
  4338. * rejected values but the chance of two submits completing at the
  4339. * same time is zero so there is no point adding extra locking */
  4340. static void
  4341. share_result(json_t *val, json_t *res, json_t *err, const struct work *work,
  4342. /*char *hashshow,*/ bool resubmit, char *worktime)
  4343. {
  4344. struct pool *pool = work->pool;
  4345. struct cgpu_info *cgpu;
  4346. cgpu = get_thr_cgpu(work->thr_id);
  4347. if ((json_is_null(err) || !err) && (json_is_null(res) || json_is_true(res))) {
  4348. struct mining_goal_info * const goal = pool->goal;
  4349. mutex_lock(&stats_lock);
  4350. cgpu->accepted++;
  4351. total_accepted++;
  4352. pool->accepted++;
  4353. cgpu->diff_accepted += work->work_difficulty;
  4354. total_diff_accepted += work->work_difficulty;
  4355. pool->diff_accepted += work->work_difficulty;
  4356. goal->diff_accepted += work->work_difficulty;
  4357. mutex_unlock(&stats_lock);
  4358. pool->seq_rejects = 0;
  4359. cgpu->last_share_pool = pool->pool_no;
  4360. cgpu->last_share_pool_time = time(NULL);
  4361. cgpu->last_share_diff = work->work_difficulty;
  4362. pool->last_share_time = cgpu->last_share_pool_time;
  4363. pool->last_share_diff = work->work_difficulty;
  4364. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  4365. if (!QUIET) {
  4366. share_result_msg(work, "Accepted", "", resubmit, worktime);
  4367. }
  4368. sharelog("accept", work);
  4369. if (opt_shares && total_diff_accepted >= opt_shares) {
  4370. applog(LOG_WARNING, "Successfully mined %g accepted shares as requested and exiting.", opt_shares);
  4371. kill_work();
  4372. return;
  4373. }
  4374. /* Detect if a pool that has been temporarily disabled for
  4375. * continually rejecting shares has started accepting shares.
  4376. * This will only happen with the work returned from a
  4377. * longpoll */
  4378. if (unlikely(pool->enabled == POOL_REJECTING)) {
  4379. applog(LOG_WARNING, "Rejecting pool %d now accepting shares, re-enabling!", pool->pool_no);
  4380. enable_pool(pool);
  4381. }
  4382. if (unlikely(work->block)) {
  4383. // Force moving on to this new block :)
  4384. struct work fakework;
  4385. memset(&fakework, 0, sizeof(fakework));
  4386. fakework.pool = work->pool;
  4387. // Copy block version, bits, and time from share
  4388. memcpy(&fakework.data[ 0], &work->data[ 0], 4);
  4389. memcpy(&fakework.data[68], &work->data[68], 8);
  4390. // Set prevblock to winning hash (swap32'd)
  4391. swap32yes(&fakework.data[4], &work->hash[0], 32 / 4);
  4392. test_work_current(&fakework);
  4393. }
  4394. }
  4395. else
  4396. if (!hash_target_check(work->hash, work->target))
  4397. {
  4398. // This was submitted despite failing the proper target
  4399. // Quietly ignore the reject
  4400. char reason[32];
  4401. put_in_parens(reason, sizeof(reason), extract_reject_reason(val, res, err, work));
  4402. applog(LOG_DEBUG, "Share above target rejected%s by pool %u as expected, ignoring", reason, pool->pool_no);
  4403. } else {
  4404. mutex_lock(&stats_lock);
  4405. cgpu->rejected++;
  4406. total_rejected++;
  4407. pool->rejected++;
  4408. cgpu->diff_rejected += work->work_difficulty;
  4409. total_diff_rejected += work->work_difficulty;
  4410. pool->diff_rejected += work->work_difficulty;
  4411. pool->seq_rejects++;
  4412. mutex_unlock(&stats_lock);
  4413. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  4414. if (!QUIET) {
  4415. char disposition[36] = "reject";
  4416. char reason[32];
  4417. const char *reasontmp = extract_reject_reason(val, res, err, work);
  4418. int n = put_in_parens(reason, sizeof(reason), reasontmp);
  4419. if (reason[0])
  4420. snprintf(&disposition[6], sizeof(disposition) - 6, ":%.*s", n - 3, &reason[2]);
  4421. share_result_msg(work, "Rejected", reason, resubmit, worktime);
  4422. sharelog(disposition, work);
  4423. }
  4424. /* Once we have more than a nominal amount of sequential rejects,
  4425. * at least 10 and more than 3 mins at the current utility,
  4426. * disable the pool because some pool error is likely to have
  4427. * ensued. Do not do this if we know the share just happened to
  4428. * be stale due to networking delays.
  4429. */
  4430. if (pool->seq_rejects > 10 && !work->stale && opt_disable_pool && enabled_pools > 1) {
  4431. double utility = total_accepted / total_secs * 60;
  4432. if (pool->seq_rejects > utility * 3) {
  4433. applog(LOG_WARNING, "Pool %d rejected %d sequential shares, disabling!",
  4434. pool->pool_no, pool->seq_rejects);
  4435. disable_pool(pool, POOL_REJECTING);
  4436. pool->seq_rejects = 0;
  4437. }
  4438. }
  4439. }
  4440. maybe_local_submit(work);
  4441. }
  4442. static char *submit_upstream_work_request(struct work *work)
  4443. {
  4444. char *hexstr = NULL;
  4445. char *s, *sd;
  4446. struct pool *pool = work->pool;
  4447. if (work->tr)
  4448. {
  4449. blktemplate_t * const tmpl = work->tr->tmpl;
  4450. json_t *req;
  4451. unsigned char data[80];
  4452. swap32yes(data, work->data, 80 / 4);
  4453. #if BLKMAKER_VERSION > 3
  4454. if (work->do_foreign_submit)
  4455. req = blkmk_submit_foreign_jansson(tmpl, data, work->dataid, le32toh(*((uint32_t*)&work->data[76])));
  4456. else
  4457. #endif
  4458. req = blkmk_submit_jansson(tmpl, data, work->dataid, le32toh(*((uint32_t*)&work->data[76])));
  4459. s = json_dumps(req, 0);
  4460. json_decref(req);
  4461. sd = malloc(161);
  4462. bin2hex(sd, data, 80);
  4463. } else {
  4464. /* build hex string */
  4465. hexstr = malloc((sizeof(work->data) * 2) + 1);
  4466. bin2hex(hexstr, work->data, sizeof(work->data));
  4467. /* build JSON-RPC request */
  4468. s = strdup("{\"method\": \"getwork\", \"params\": [ \"");
  4469. s = realloc_strcat(s, hexstr);
  4470. s = realloc_strcat(s, "\" ], \"id\":1}");
  4471. free(hexstr);
  4472. sd = s;
  4473. }
  4474. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->rpc_url, sd);
  4475. if (work->tr)
  4476. free(sd);
  4477. else
  4478. s = realloc_strcat(s, "\n");
  4479. return s;
  4480. }
  4481. static bool submit_upstream_work_completed(struct work *work, bool resubmit, struct timeval *ptv_submit, json_t *val) {
  4482. json_t *res, *err;
  4483. bool rc = false;
  4484. int thr_id = work->thr_id;
  4485. struct pool *pool = work->pool;
  4486. struct timeval tv_submit_reply;
  4487. time_t ts_submit_reply;
  4488. char worktime[200] = "";
  4489. cgtime(&tv_submit_reply);
  4490. ts_submit_reply = time(NULL);
  4491. if (unlikely(!val)) {
  4492. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  4493. if (!pool_tset(pool, &pool->submit_fail)) {
  4494. total_ro++;
  4495. pool->remotefail_occasions++;
  4496. applog(LOG_WARNING, "Pool %d communication failure, caching submissions", pool->pool_no);
  4497. }
  4498. goto out;
  4499. } else if (pool_tclear(pool, &pool->submit_fail))
  4500. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  4501. res = json_object_get(val, "result");
  4502. err = json_object_get(val, "error");
  4503. if (!QUIET) {
  4504. if (opt_worktime) {
  4505. char workclone[20];
  4506. struct tm _tm;
  4507. struct tm *tm, tm_getwork, tm_submit_reply;
  4508. tm = &_tm;
  4509. double getwork_time = tdiff((struct timeval *)&(work->tv_getwork_reply),
  4510. (struct timeval *)&(work->tv_getwork));
  4511. double getwork_to_work = tdiff((struct timeval *)&(work->tv_work_start),
  4512. (struct timeval *)&(work->tv_getwork_reply));
  4513. double work_time = tdiff((struct timeval *)&(work->tv_work_found),
  4514. (struct timeval *)&(work->tv_work_start));
  4515. double work_to_submit = tdiff(ptv_submit,
  4516. (struct timeval *)&(work->tv_work_found));
  4517. double submit_time = tdiff(&tv_submit_reply, ptv_submit);
  4518. int diffplaces = 3;
  4519. localtime_r(&work->ts_getwork, tm);
  4520. memcpy(&tm_getwork, tm, sizeof(struct tm));
  4521. localtime_r(&ts_submit_reply, tm);
  4522. memcpy(&tm_submit_reply, tm, sizeof(struct tm));
  4523. if (work->clone) {
  4524. snprintf(workclone, sizeof(workclone), "C:%1.3f",
  4525. tdiff((struct timeval *)&(work->tv_cloned),
  4526. (struct timeval *)&(work->tv_getwork_reply)));
  4527. }
  4528. else
  4529. strcpy(workclone, "O");
  4530. if (work->work_difficulty < 1)
  4531. diffplaces = 6;
  4532. snprintf(worktime, sizeof(worktime),
  4533. " <-%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",
  4534. (unsigned long)be32toh(*(uint32_t *)&(work->data[opt_scrypt ? 32 : 28])),
  4535. (unsigned long)be32toh(*(uint32_t *)&(work->data[opt_scrypt ? 28 : 24])),
  4536. work->getwork_mode, diffplaces, work->work_difficulty,
  4537. tm_getwork.tm_hour, tm_getwork.tm_min,
  4538. tm_getwork.tm_sec, getwork_time, workclone,
  4539. getwork_to_work, work_time, work_to_submit, submit_time,
  4540. tm_submit_reply.tm_hour, tm_submit_reply.tm_min,
  4541. tm_submit_reply.tm_sec);
  4542. }
  4543. }
  4544. share_result(val, res, err, work, resubmit, worktime);
  4545. if (!opt_realquiet)
  4546. print_status(thr_id);
  4547. if (!want_per_device_stats) {
  4548. char logline[256];
  4549. struct cgpu_info *cgpu;
  4550. cgpu = get_thr_cgpu(thr_id);
  4551. get_statline(logline, sizeof(logline), cgpu);
  4552. applog(LOG_INFO, "%s", logline);
  4553. }
  4554. json_decref(val);
  4555. rc = true;
  4556. out:
  4557. return rc;
  4558. }
  4559. /* Specifies whether we can use this pool for work or not. */
  4560. static bool pool_unworkable(const struct pool * const pool)
  4561. {
  4562. if (pool->idle)
  4563. return true;
  4564. if (pool->enabled != POOL_ENABLED)
  4565. return true;
  4566. if (pool->has_stratum && !pool->stratum_active)
  4567. return true;
  4568. return false;
  4569. }
  4570. static
  4571. bool pool_actively_desired(const struct pool * const pool, const struct pool *cp)
  4572. {
  4573. if (pool->enabled != POOL_ENABLED)
  4574. return false;
  4575. if (pool_strategy == POOL_LOADBALANCE || pool_strategy == POOL_BALANCE)
  4576. return true;
  4577. if (!cp)
  4578. cp = current_pool();
  4579. return (pool == cp);
  4580. }
  4581. static
  4582. bool pool_actively_in_use(const struct pool * const pool, const struct pool *cp)
  4583. {
  4584. return (!pool_unworkable(pool)) && pool_actively_desired(pool, cp);
  4585. }
  4586. static
  4587. bool pool_supports_block_change_notification(struct pool * const pool)
  4588. {
  4589. return pool->has_stratum || pool->lp_url;
  4590. }
  4591. static
  4592. bool pool_has_active_block_change_notification(struct pool * const pool)
  4593. {
  4594. return pool->stratum_active || pool->lp_active;
  4595. }
  4596. static struct pool *_select_longpoll_pool(struct pool *, bool(*)(struct pool *));
  4597. #define select_longpoll_pool(pool) _select_longpoll_pool(pool, pool_supports_block_change_notification)
  4598. #define pool_active_lp_pool(pool) _select_longpoll_pool(pool, pool_has_active_block_change_notification)
  4599. /* In balanced mode, the amount of diff1 solutions per pool is monitored as a
  4600. * rolling average per 10 minutes and if pools start getting more, it biases
  4601. * away from them to distribute work evenly. The share count is reset to the
  4602. * rolling average every 10 minutes to not send all work to one pool after it
  4603. * has been disabled/out for an extended period. */
  4604. static struct pool *select_balanced(struct pool *cp)
  4605. {
  4606. int i, lowest = cp->shares;
  4607. struct pool *ret = cp, *failover_pool = NULL;
  4608. for (i = 0; i < total_pools; i++) {
  4609. struct pool *pool = pools[i];
  4610. if (pool_unworkable(pool))
  4611. continue;
  4612. if (pool->failover_only)
  4613. {
  4614. BFGINIT(failover_pool, pool);
  4615. continue;
  4616. }
  4617. if (pool->shares < lowest) {
  4618. lowest = pool->shares;
  4619. ret = pool;
  4620. }
  4621. }
  4622. if (pool_unworkable(ret) && failover_pool)
  4623. ret = failover_pool;
  4624. ret->shares++;
  4625. return ret;
  4626. }
  4627. static bool pool_active(struct pool *, bool pinging);
  4628. static void pool_died(struct pool *);
  4629. static struct pool *priority_pool(int choice);
  4630. static bool pool_unusable(struct pool *pool);
  4631. /* Select any active pool in a rotating fashion when loadbalance is chosen if
  4632. * it has any quota left. */
  4633. static inline struct pool *select_pool(bool lagging)
  4634. {
  4635. static int rotating_pool = 0;
  4636. struct pool *pool, *cp;
  4637. bool avail = false;
  4638. int tested, i;
  4639. retry:
  4640. cp = current_pool();
  4641. if (pool_strategy == POOL_BALANCE) {
  4642. pool = select_balanced(cp);
  4643. if (pool_unworkable(pool))
  4644. goto simple_failover;
  4645. goto out;
  4646. }
  4647. if (pool_strategy != POOL_LOADBALANCE && (!lagging || opt_fail_only)) {
  4648. pool = cp;
  4649. goto out;
  4650. } else
  4651. pool = NULL;
  4652. for (i = 0; i < total_pools; i++) {
  4653. struct pool *tp = pools[i];
  4654. if (tp->quota_used < tp->quota_gcd) {
  4655. avail = true;
  4656. break;
  4657. }
  4658. }
  4659. /* There are no pools with quota, so reset them. */
  4660. if (!avail) {
  4661. for (i = 0; i < total_pools; i++)
  4662. pools[i]->quota_used = 0;
  4663. if (++rotating_pool >= total_pools)
  4664. rotating_pool = 0;
  4665. }
  4666. /* Try to find the first pool in the rotation that is usable */
  4667. tested = 0;
  4668. while (!pool && tested++ < total_pools) {
  4669. pool = pools[rotating_pool];
  4670. if (pool->quota_used++ < pool->quota_gcd) {
  4671. if (!pool_unworkable(pool))
  4672. break;
  4673. /* Failover-only flag for load-balance means distribute
  4674. * unused quota to priority pool 0. */
  4675. if (opt_fail_only)
  4676. priority_pool(0)->quota_used--;
  4677. }
  4678. pool = NULL;
  4679. if (++rotating_pool >= total_pools)
  4680. rotating_pool = 0;
  4681. }
  4682. simple_failover:
  4683. /* If there are no alive pools with quota, choose according to
  4684. * priority. */
  4685. if (!pool) {
  4686. for (i = 0; i < total_pools; i++) {
  4687. struct pool *tp = priority_pool(i);
  4688. if (!pool_unusable(tp)) {
  4689. pool = tp;
  4690. break;
  4691. }
  4692. }
  4693. }
  4694. /* If still nothing is usable, use the current pool */
  4695. if (!pool)
  4696. pool = cp;
  4697. out:
  4698. if (!pool_actively_in_use(pool, cp))
  4699. {
  4700. if (!pool_active(pool, false))
  4701. {
  4702. pool_died(pool);
  4703. goto retry;
  4704. }
  4705. pool_tclear(pool, &pool->idle);
  4706. }
  4707. applog(LOG_DEBUG, "Selecting pool %d for work", pool->pool_no);
  4708. return pool;
  4709. }
  4710. static double DIFFEXACTONE = 26959946667150639794667015087019630673637144422540572481103610249215.0;
  4711. double target_diff(const unsigned char *target)
  4712. {
  4713. double targ = 0;
  4714. signed int i;
  4715. for (i = 31; i >= 0; --i)
  4716. targ = (targ * 0x100) + target[i];
  4717. return DIFFEXACTONE / (targ ?: 1);
  4718. }
  4719. /*
  4720. * Calculate the work share difficulty
  4721. */
  4722. static void calc_diff(struct work *work, int known)
  4723. {
  4724. struct cgminer_pool_stats *pool_stats = &(work->pool->cgminer_pool_stats);
  4725. double difficulty;
  4726. if (!known) {
  4727. work->work_difficulty = target_diff(work->target);
  4728. } else
  4729. work->work_difficulty = known;
  4730. difficulty = work->work_difficulty;
  4731. pool_stats->last_diff = difficulty;
  4732. suffix_string(difficulty, work->pool->diff, sizeof(work->pool->diff), 0);
  4733. if (difficulty == pool_stats->min_diff)
  4734. pool_stats->min_diff_count++;
  4735. else if (difficulty < pool_stats->min_diff || pool_stats->min_diff == 0) {
  4736. pool_stats->min_diff = difficulty;
  4737. pool_stats->min_diff_count = 1;
  4738. }
  4739. if (difficulty == pool_stats->max_diff)
  4740. pool_stats->max_diff_count++;
  4741. else if (difficulty > pool_stats->max_diff) {
  4742. pool_stats->max_diff = difficulty;
  4743. pool_stats->max_diff_count = 1;
  4744. }
  4745. }
  4746. static void gen_stratum_work(struct pool *, struct work *);
  4747. static void pool_update_work_restart_time(struct pool *);
  4748. static void restart_threads(void);
  4749. static uint32_t benchmark_blkhdr[20];
  4750. static const int benchmark_update_interval = 1;
  4751. static
  4752. void *benchmark_intense_work_update_thread(void *userp)
  4753. {
  4754. pthread_detach(pthread_self());
  4755. RenameThread("benchmark-intense");
  4756. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  4757. struct pool * const pool = userp;
  4758. struct stratum_work * const swork = &pool->swork;
  4759. uint8_t * const blkhdr = swork->header1;
  4760. while (true)
  4761. {
  4762. sleep(benchmark_update_interval);
  4763. cg_wlock(&pool->data_lock);
  4764. for (int i = 36; --i >= 0; )
  4765. if (++blkhdr[i])
  4766. break;
  4767. cg_wunlock(&pool->data_lock);
  4768. struct work *work = make_work();
  4769. gen_stratum_work(pool, work);
  4770. pool->swork.work_restart_id = ++pool->work_restart_id;
  4771. pool_update_work_restart_time(pool);
  4772. test_work_current(work);
  4773. free_work(work);
  4774. restart_threads();
  4775. }
  4776. return NULL;
  4777. }
  4778. static
  4779. void setup_benchmark_pool()
  4780. {
  4781. struct pool *pool;
  4782. want_longpoll = false;
  4783. // Temporarily disable opt_benchmark to avoid auto-removal
  4784. opt_benchmark = false;
  4785. pool = add_pool();
  4786. opt_benchmark = true;
  4787. pool->rpc_url = malloc(255);
  4788. strcpy(pool->rpc_url, "Benchmark");
  4789. pool_set_uri(pool, pool->rpc_url);
  4790. pool->rpc_user = pool->rpc_url;
  4791. pool->rpc_pass = pool->rpc_url;
  4792. enable_pool(pool);
  4793. pool->idle = false;
  4794. successful_connect = true;
  4795. {
  4796. uint32_t * const blkhdr = benchmark_blkhdr;
  4797. blkhdr[2] = htobe32(1);
  4798. blkhdr[17] = htobe32(0x7fffffff); // timestamp
  4799. blkhdr[18] = htobe32(0x1700ffff); // "bits"
  4800. }
  4801. {
  4802. struct stratum_work * const swork = &pool->swork;
  4803. const int branchcount = 15; // 1 MB block
  4804. const size_t branchdatasz = branchcount * 0x20;
  4805. const size_t coinbase_sz = (opt_benchmark_intense ? 250 : 6) * 1024;
  4806. bytes_resize(&swork->coinbase, coinbase_sz);
  4807. memset(bytes_buf(&swork->coinbase), '\xff', coinbase_sz);
  4808. swork->nonce2_offset = 0;
  4809. bytes_resize(&swork->merkle_bin, branchdatasz);
  4810. memset(bytes_buf(&swork->merkle_bin), '\xff', branchdatasz);
  4811. swork->merkles = branchcount;
  4812. swork->header1[0] = '\xff';
  4813. memset(&swork->header1[1], '\0', 34);
  4814. swork->header1[35] = '\x01';
  4815. swork->ntime = 0x7fffffff;
  4816. timer_unset(&swork->tv_received);
  4817. memcpy(swork->diffbits, "\x17\0\xff\xff", 4);
  4818. set_target_to_pdiff(swork->target, opt_scrypt ? (1./0x10000) : 1.);
  4819. pool->nonce2sz = swork->n2size = GBT_XNONCESZ;
  4820. pool->nonce2 = 0;
  4821. }
  4822. if (opt_benchmark_intense)
  4823. {
  4824. pthread_t pth;
  4825. if (unlikely(pthread_create(&pth, NULL, benchmark_intense_work_update_thread, pool)))
  4826. applog(LOG_WARNING, "Failed to start benchmark intense work update thread");
  4827. }
  4828. }
  4829. void get_benchmark_work(struct work *work, bool use_swork)
  4830. {
  4831. if (use_swork)
  4832. {
  4833. struct timeval tv_now;
  4834. timer_set_now(&tv_now);
  4835. gen_stratum_work(pools[0], work);
  4836. work->getwork_mode = GETWORK_MODE_BENCHMARK;
  4837. work_set_simple_ntime_roll_limit(work, 0, &tv_now);
  4838. return;
  4839. }
  4840. struct pool * const pool = pools[0];
  4841. uint32_t * const blkhdr = benchmark_blkhdr;
  4842. for (int i = 16; i >= 0; --i)
  4843. if (++blkhdr[i])
  4844. break;
  4845. memcpy(&work->data[ 0], blkhdr, 80);
  4846. memcpy(&work->data[80], workpadding_bin, 48);
  4847. char hex[161];
  4848. bin2hex(hex, work->data, 80);
  4849. applog(LOG_DEBUG, "Generated benchmark header %s", hex);
  4850. calc_midstate(work);
  4851. memcpy(work->target, pool->swork.target, sizeof(work->target));
  4852. work->mandatory = true;
  4853. work->pool = pools[0];
  4854. cgtime(&work->tv_getwork);
  4855. copy_time(&work->tv_getwork_reply, &work->tv_getwork);
  4856. copy_time(&work->tv_staged, &work->tv_getwork);
  4857. work->getwork_mode = GETWORK_MODE_BENCHMARK;
  4858. calc_diff(work, 0);
  4859. work_set_simple_ntime_roll_limit(work, 60, &work->tv_getwork);
  4860. }
  4861. static void wake_gws(void);
  4862. static void update_last_work(struct work *work)
  4863. {
  4864. if (!work->tr)
  4865. // Only save GBT jobs, since rollntime isn't coordinated well yet
  4866. return;
  4867. struct pool *pool = work->pool;
  4868. mutex_lock(&pool->last_work_lock);
  4869. if (pool->last_work_copy)
  4870. free_work(pool->last_work_copy);
  4871. pool->last_work_copy = copy_work(work);
  4872. pool->last_work_copy->work_restart_id = pool->work_restart_id;
  4873. mutex_unlock(&pool->last_work_lock);
  4874. }
  4875. static
  4876. void gbt_req_target(json_t *req)
  4877. {
  4878. json_t *j;
  4879. json_t *n;
  4880. if (!request_target_str)
  4881. return;
  4882. j = json_object_get(req, "params");
  4883. if (!j)
  4884. {
  4885. n = json_array();
  4886. if (!n)
  4887. return;
  4888. if (json_object_set_new(req, "params", n))
  4889. goto erradd;
  4890. j = n;
  4891. }
  4892. n = json_array_get(j, 0);
  4893. if (!n)
  4894. {
  4895. n = json_object();
  4896. if (!n)
  4897. return;
  4898. if (json_array_append_new(j, n))
  4899. goto erradd;
  4900. }
  4901. j = n;
  4902. n = json_string(request_target_str);
  4903. if (!n)
  4904. return;
  4905. if (json_object_set_new(j, "target", n))
  4906. goto erradd;
  4907. return;
  4908. erradd:
  4909. json_decref(n);
  4910. }
  4911. static char *prepare_rpc_req2(struct work *work, enum pool_protocol proto, const char *lpid, bool probe)
  4912. {
  4913. char *rpc_req;
  4914. clean_work(work);
  4915. switch (proto) {
  4916. case PLP_GETWORK:
  4917. work->getwork_mode = GETWORK_MODE_POOL;
  4918. return strdup(getwork_req);
  4919. case PLP_GETBLOCKTEMPLATE:
  4920. work->getwork_mode = GETWORK_MODE_GBT;
  4921. blktemplate_t * const tmpl = blktmpl_create();
  4922. if (!tmpl)
  4923. goto gbtfail2;
  4924. work->tr = tmpl_makeref(tmpl);
  4925. gbt_capabilities_t caps = blktmpl_addcaps(tmpl);
  4926. if (!caps)
  4927. goto gbtfail;
  4928. caps |= GBT_LONGPOLL;
  4929. #if BLKMAKER_VERSION > 1
  4930. if (bytes_len(&opt_coinbase_script) || have_at_least_one_getcbaddr)
  4931. caps |= GBT_CBVALUE;
  4932. #endif
  4933. json_t *req = blktmpl_request_jansson(caps, lpid);
  4934. if (!req)
  4935. goto gbtfail;
  4936. if (probe)
  4937. gbt_req_target(req);
  4938. rpc_req = json_dumps(req, 0);
  4939. if (!rpc_req)
  4940. goto gbtfail;
  4941. json_decref(req);
  4942. return rpc_req;
  4943. default:
  4944. return NULL;
  4945. }
  4946. return NULL;
  4947. gbtfail:
  4948. tmpl_decref(work->tr);
  4949. work->tr = NULL;
  4950. gbtfail2:
  4951. return NULL;
  4952. }
  4953. #define prepare_rpc_req(work, proto, lpid) prepare_rpc_req2(work, proto, lpid, false)
  4954. #define prepare_rpc_req_probe(work, proto, lpid) prepare_rpc_req2(work, proto, lpid, true)
  4955. static const char *pool_protocol_name(enum pool_protocol proto)
  4956. {
  4957. switch (proto) {
  4958. case PLP_GETBLOCKTEMPLATE:
  4959. return "getblocktemplate";
  4960. case PLP_GETWORK:
  4961. return "getwork";
  4962. default:
  4963. return "UNKNOWN";
  4964. }
  4965. }
  4966. static enum pool_protocol pool_protocol_fallback(enum pool_protocol proto)
  4967. {
  4968. switch (proto) {
  4969. case PLP_GETBLOCKTEMPLATE:
  4970. if (want_getwork)
  4971. return PLP_GETWORK;
  4972. default:
  4973. return PLP_NONE;
  4974. }
  4975. }
  4976. static bool get_upstream_work(struct work *work, CURL *curl)
  4977. {
  4978. struct pool *pool = work->pool;
  4979. struct cgminer_pool_stats *pool_stats = &(pool->cgminer_pool_stats);
  4980. struct timeval tv_elapsed;
  4981. json_t *val = NULL;
  4982. bool rc = false;
  4983. char *url;
  4984. enum pool_protocol proto;
  4985. char *rpc_req;
  4986. if (pool->proto == PLP_NONE)
  4987. pool->proto = PLP_GETBLOCKTEMPLATE;
  4988. tryagain:
  4989. rpc_req = prepare_rpc_req(work, pool->proto, NULL);
  4990. work->pool = pool;
  4991. if (!rpc_req)
  4992. return false;
  4993. applog(LOG_DEBUG, "DBG: sending %s get RPC call: %s", pool->rpc_url, rpc_req);
  4994. url = pool->rpc_url;
  4995. cgtime(&work->tv_getwork);
  4996. val = json_rpc_call(curl, url, pool->rpc_userpass, rpc_req, false,
  4997. false, &work->rolltime, pool, false);
  4998. pool_stats->getwork_attempts++;
  4999. free(rpc_req);
  5000. if (likely(val)) {
  5001. rc = work_decode(pool, work, val);
  5002. if (unlikely(!rc))
  5003. applog(LOG_DEBUG, "Failed to decode work in get_upstream_work");
  5004. } else if (PLP_NONE != (proto = pool_protocol_fallback(pool->proto))) {
  5005. applog(LOG_WARNING, "Pool %u failed getblocktemplate request; falling back to getwork protocol", pool->pool_no);
  5006. pool->proto = proto;
  5007. goto tryagain;
  5008. } else
  5009. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  5010. cgtime(&work->tv_getwork_reply);
  5011. timersub(&(work->tv_getwork_reply), &(work->tv_getwork), &tv_elapsed);
  5012. pool_stats->getwork_wait_rolling += ((double)tv_elapsed.tv_sec + ((double)tv_elapsed.tv_usec / 1000000)) * 0.63;
  5013. pool_stats->getwork_wait_rolling /= 1.63;
  5014. timeradd(&tv_elapsed, &(pool_stats->getwork_wait), &(pool_stats->getwork_wait));
  5015. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_max), >)) {
  5016. pool_stats->getwork_wait_max.tv_sec = tv_elapsed.tv_sec;
  5017. pool_stats->getwork_wait_max.tv_usec = tv_elapsed.tv_usec;
  5018. }
  5019. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_min), <)) {
  5020. pool_stats->getwork_wait_min.tv_sec = tv_elapsed.tv_sec;
  5021. pool_stats->getwork_wait_min.tv_usec = tv_elapsed.tv_usec;
  5022. }
  5023. pool_stats->getwork_calls++;
  5024. work->pool = pool;
  5025. work->longpoll = false;
  5026. calc_diff(work, 0);
  5027. total_getworks++;
  5028. pool->getwork_requested++;
  5029. if (rc)
  5030. update_last_work(work);
  5031. if (likely(val))
  5032. json_decref(val);
  5033. return rc;
  5034. }
  5035. #ifdef HAVE_CURSES
  5036. static void disable_curses(void)
  5037. {
  5038. if (curses_active_locked()) {
  5039. use_curses = false;
  5040. curses_active = false;
  5041. leaveok(logwin, false);
  5042. leaveok(statuswin, false);
  5043. leaveok(mainwin, false);
  5044. nocbreak();
  5045. echo();
  5046. delwin(logwin);
  5047. delwin(statuswin);
  5048. delwin(mainwin);
  5049. endwin();
  5050. #ifdef WIN32
  5051. // Move the cursor to after curses output.
  5052. HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
  5053. CONSOLE_SCREEN_BUFFER_INFO csbi;
  5054. COORD coord;
  5055. if (GetConsoleScreenBufferInfo(hout, &csbi)) {
  5056. coord.X = 0;
  5057. coord.Y = csbi.dwSize.Y - 1;
  5058. SetConsoleCursorPosition(hout, coord);
  5059. }
  5060. #endif
  5061. unlock_curses();
  5062. }
  5063. }
  5064. #endif
  5065. static void __kill_work(void)
  5066. {
  5067. struct cgpu_info *cgpu;
  5068. struct thr_info *thr;
  5069. int i;
  5070. if (!successful_connect)
  5071. return;
  5072. applog(LOG_INFO, "Received kill message");
  5073. shutting_down = true;
  5074. applog(LOG_DEBUG, "Prompting submit_work thread to finish");
  5075. notifier_wake(submit_waiting_notifier);
  5076. #ifdef USE_LIBMICROHTTPD
  5077. httpsrv_stop();
  5078. #endif
  5079. applog(LOG_DEBUG, "Killing off watchpool thread");
  5080. /* Kill the watchpool thread */
  5081. thr = &control_thr[watchpool_thr_id];
  5082. thr_info_cancel(thr);
  5083. applog(LOG_DEBUG, "Killing off watchdog thread");
  5084. /* Kill the watchdog thread */
  5085. thr = &control_thr[watchdog_thr_id];
  5086. thr_info_cancel(thr);
  5087. applog(LOG_DEBUG, "Shutting down mining threads");
  5088. for (i = 0; i < mining_threads; i++) {
  5089. thr = get_thread(i);
  5090. if (!thr)
  5091. continue;
  5092. cgpu = thr->cgpu;
  5093. if (!cgpu)
  5094. continue;
  5095. if (!cgpu->threads)
  5096. continue;
  5097. cgpu->shutdown = true;
  5098. thr->work_restart = true;
  5099. notifier_wake(thr->notifier);
  5100. notifier_wake(thr->work_restart_notifier);
  5101. }
  5102. sleep(1);
  5103. applog(LOG_DEBUG, "Killing off mining threads");
  5104. /* Kill the mining threads*/
  5105. for (i = 0; i < mining_threads; i++) {
  5106. thr = get_thread(i);
  5107. if (!thr)
  5108. continue;
  5109. cgpu = thr->cgpu;
  5110. if (cgpu->threads)
  5111. {
  5112. applog(LOG_WARNING, "Killing %"PRIpreprv, thr->cgpu->proc_repr);
  5113. thr_info_cancel(thr);
  5114. }
  5115. cgpu->status = LIFE_DEAD2;
  5116. }
  5117. /* Stop the others */
  5118. applog(LOG_DEBUG, "Killing off API thread");
  5119. thr = &control_thr[api_thr_id];
  5120. thr_info_cancel(thr);
  5121. }
  5122. /* This should be the common exit path */
  5123. void kill_work(void)
  5124. {
  5125. __kill_work();
  5126. quit(0, "Shutdown signal received.");
  5127. }
  5128. static
  5129. #ifdef WIN32
  5130. #ifndef _WIN64
  5131. const
  5132. #endif
  5133. #endif
  5134. char **initial_args;
  5135. void _bfg_clean_up(bool);
  5136. void app_restart(void)
  5137. {
  5138. applog(LOG_WARNING, "Attempting to restart %s", packagename);
  5139. __kill_work();
  5140. _bfg_clean_up(true);
  5141. #if defined(unix) || defined(__APPLE__)
  5142. if (forkpid > 0) {
  5143. kill(forkpid, SIGTERM);
  5144. forkpid = 0;
  5145. }
  5146. #endif
  5147. execv(initial_args[0], initial_args);
  5148. applog(LOG_WARNING, "Failed to restart application");
  5149. }
  5150. static void sighandler(int __maybe_unused sig)
  5151. {
  5152. /* Restore signal handlers so we can still quit if kill_work fails */
  5153. sigaction(SIGTERM, &termhandler, NULL);
  5154. sigaction(SIGINT, &inthandler, NULL);
  5155. kill_work();
  5156. }
  5157. static void start_longpoll(void);
  5158. static void stop_longpoll(void);
  5159. /* Called with pool_lock held. Recruit an extra curl if none are available for
  5160. * this pool. */
  5161. static void recruit_curl(struct pool *pool)
  5162. {
  5163. struct curl_ent *ce = calloc(sizeof(struct curl_ent), 1);
  5164. if (unlikely(!ce))
  5165. quit(1, "Failed to calloc in recruit_curl");
  5166. ce->curl = curl_easy_init();
  5167. if (unlikely(!ce->curl))
  5168. quit(1, "Failed to init in recruit_curl");
  5169. LL_PREPEND(pool->curllist, ce);
  5170. pool->curls++;
  5171. }
  5172. /* Grab an available curl if there is one. If not, then recruit extra curls
  5173. * unless we are in a submit_fail situation, or we have opt_delaynet enabled
  5174. * and there are already 5 curls in circulation. Limit total number to the
  5175. * number of mining threads per pool as well to prevent blasting a pool during
  5176. * network delays/outages. */
  5177. static struct curl_ent *pop_curl_entry3(struct pool *pool, int blocking)
  5178. {
  5179. int curl_limit = opt_delaynet ? 5 : (mining_threads + opt_queue) * 2;
  5180. bool recruited = false;
  5181. struct curl_ent *ce;
  5182. mutex_lock(&pool->pool_lock);
  5183. retry:
  5184. if (!pool->curls) {
  5185. recruit_curl(pool);
  5186. recruited = true;
  5187. } else if (!pool->curllist) {
  5188. if (blocking < 2 && pool->curls >= curl_limit && (blocking || pool->curls >= opt_submit_threads)) {
  5189. if (!blocking) {
  5190. mutex_unlock(&pool->pool_lock);
  5191. return NULL;
  5192. }
  5193. pthread_cond_wait(&pool->cr_cond, &pool->pool_lock);
  5194. goto retry;
  5195. } else {
  5196. recruit_curl(pool);
  5197. recruited = true;
  5198. }
  5199. }
  5200. ce = pool->curllist;
  5201. LL_DELETE(pool->curllist, ce);
  5202. mutex_unlock(&pool->pool_lock);
  5203. if (recruited)
  5204. applog(LOG_DEBUG, "Recruited curl for pool %d", pool->pool_no);
  5205. return ce;
  5206. }
  5207. static struct curl_ent *pop_curl_entry2(struct pool *pool, bool blocking)
  5208. {
  5209. return pop_curl_entry3(pool, blocking ? 1 : 0);
  5210. }
  5211. __maybe_unused
  5212. static struct curl_ent *pop_curl_entry(struct pool *pool)
  5213. {
  5214. return pop_curl_entry3(pool, 1);
  5215. }
  5216. static void push_curl_entry(struct curl_ent *ce, struct pool *pool)
  5217. {
  5218. mutex_lock(&pool->pool_lock);
  5219. if (!ce || !ce->curl)
  5220. quithere(1, "Attempted to add NULL");
  5221. LL_PREPEND(pool->curllist, ce);
  5222. cgtime(&ce->tv);
  5223. pthread_cond_broadcast(&pool->cr_cond);
  5224. mutex_unlock(&pool->pool_lock);
  5225. }
  5226. bool stale_work(struct work *work, bool share);
  5227. static inline bool should_roll(struct work *work)
  5228. {
  5229. struct timeval now;
  5230. time_t expiry;
  5231. if (!pool_actively_in_use(work->pool, NULL))
  5232. return false;
  5233. if (stale_work(work, false))
  5234. return false;
  5235. if (work->rolltime > opt_scantime)
  5236. expiry = work->rolltime;
  5237. else
  5238. expiry = opt_scantime;
  5239. expiry = expiry * 2 / 3;
  5240. /* We shouldn't roll if we're unlikely to get one shares' duration
  5241. * work out of doing so */
  5242. cgtime(&now);
  5243. if (now.tv_sec - work->tv_staged.tv_sec > expiry)
  5244. return false;
  5245. return true;
  5246. }
  5247. /* Limit rolls to 7000 to not beyond 2 hours in the future where bitcoind will
  5248. * reject blocks as invalid. */
  5249. static inline bool can_roll(struct work *work)
  5250. {
  5251. if (work->stratum)
  5252. return false;
  5253. if (!(work->pool && !work->clone))
  5254. return false;
  5255. if (work->tr)
  5256. {
  5257. if (stale_work(work, false))
  5258. return false;
  5259. return blkmk_work_left(work->tr->tmpl);
  5260. }
  5261. return (work->rolltime &&
  5262. work->rolls < 7000 && !stale_work(work, false));
  5263. }
  5264. static void roll_work(struct work *work)
  5265. {
  5266. if (work->tr)
  5267. {
  5268. struct timeval tv_now;
  5269. cgtime(&tv_now);
  5270. if (blkmk_get_data(work->tr->tmpl, work->data, 80, tv_now.tv_sec, NULL, &work->dataid) < 76)
  5271. applog(LOG_ERR, "Failed to get next data from template; spinning wheels!");
  5272. swap32yes(work->data, work->data, 80 / 4);
  5273. calc_midstate(work);
  5274. applog(LOG_DEBUG, "Successfully rolled extranonce to dataid %u", work->dataid);
  5275. } else {
  5276. uint32_t *work_ntime;
  5277. uint32_t ntime;
  5278. work_ntime = (uint32_t *)(work->data + 68);
  5279. ntime = be32toh(*work_ntime);
  5280. ntime++;
  5281. *work_ntime = htobe32(ntime);
  5282. work_set_simple_ntime_roll_limit(work, 0, &work->ntime_roll_limits.tv_ref);
  5283. applog(LOG_DEBUG, "Successfully rolled time header in work");
  5284. }
  5285. local_work++;
  5286. work->rolls++;
  5287. work->blk.nonce = 0;
  5288. /* This is now a different work item so it needs a different ID for the
  5289. * hashtable */
  5290. work->id = total_work++;
  5291. }
  5292. /* Duplicates any dynamically allocated arrays within the work struct to
  5293. * prevent a copied work struct from freeing ram belonging to another struct */
  5294. static void _copy_work(struct work *work, const struct work *base_work, int noffset)
  5295. {
  5296. int id = work->id;
  5297. clean_work(work);
  5298. memcpy(work, base_work, sizeof(struct work));
  5299. /* Keep the unique new id assigned during make_work to prevent copied
  5300. * work from having the same id. */
  5301. work->id = id;
  5302. if (base_work->job_id)
  5303. work->job_id = strdup(base_work->job_id);
  5304. if (base_work->nonce1)
  5305. work->nonce1 = strdup(base_work->nonce1);
  5306. bytes_cpy(&work->nonce2, &base_work->nonce2);
  5307. if (base_work->tr)
  5308. tmpl_incref(base_work->tr);
  5309. if (noffset)
  5310. {
  5311. uint32_t *work_ntime = (uint32_t *)(work->data + 68);
  5312. uint32_t ntime = be32toh(*work_ntime);
  5313. ntime += noffset;
  5314. *work_ntime = htobe32(ntime);
  5315. }
  5316. if (work->device_data_dup_func)
  5317. work->device_data = work->device_data_dup_func(work);
  5318. }
  5319. /* Generates a copy of an existing work struct, creating fresh heap allocations
  5320. * for all dynamically allocated arrays within the struct. noffset is used for
  5321. * when a driver has internally rolled the ntime, noffset is a relative value.
  5322. * The macro copy_work() calls this function with an noffset of 0. */
  5323. struct work *copy_work_noffset(const struct work *base_work, int noffset)
  5324. {
  5325. struct work *work = make_work();
  5326. _copy_work(work, base_work, noffset);
  5327. return work;
  5328. }
  5329. void __copy_work(struct work *work, const struct work *base_work)
  5330. {
  5331. _copy_work(work, base_work, 0);
  5332. }
  5333. static struct work *make_clone(struct work *work)
  5334. {
  5335. struct work *work_clone = copy_work(work);
  5336. work_clone->clone = true;
  5337. cgtime((struct timeval *)&(work_clone->tv_cloned));
  5338. work_clone->longpoll = false;
  5339. work_clone->mandatory = false;
  5340. /* Make cloned work appear slightly older to bias towards keeping the
  5341. * master work item which can be further rolled */
  5342. work_clone->tv_staged.tv_sec -= 1;
  5343. return work_clone;
  5344. }
  5345. static void stage_work(struct work *work);
  5346. static bool clone_available(void)
  5347. {
  5348. struct work *work_clone = NULL, *work, *tmp;
  5349. bool cloned = false;
  5350. mutex_lock(stgd_lock);
  5351. if (!staged_rollable)
  5352. goto out_unlock;
  5353. HASH_ITER(hh, staged_work, work, tmp) {
  5354. if (can_roll(work) && should_roll(work)) {
  5355. roll_work(work);
  5356. work_clone = make_clone(work);
  5357. applog(LOG_DEBUG, "%s: Rolling work %d to %d", __func__, work->id, work_clone->id);
  5358. roll_work(work);
  5359. cloned = true;
  5360. break;
  5361. }
  5362. }
  5363. out_unlock:
  5364. mutex_unlock(stgd_lock);
  5365. if (cloned) {
  5366. applog(LOG_DEBUG, "Pushing cloned available work to stage thread");
  5367. stage_work(work_clone);
  5368. }
  5369. return cloned;
  5370. }
  5371. static void pool_died(struct pool *pool)
  5372. {
  5373. mutex_lock(&lp_lock);
  5374. if (!pool_tset(pool, &pool->idle)) {
  5375. cgtime(&pool->tv_idle);
  5376. pthread_cond_broadcast(&lp_cond);
  5377. mutex_unlock(&lp_lock);
  5378. if (pool == current_pool()) {
  5379. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  5380. switch_pools(NULL);
  5381. } else
  5382. applog(LOG_INFO, "Pool %d %s failed to return work", pool->pool_no, pool->rpc_url);
  5383. }
  5384. else
  5385. mutex_unlock(&lp_lock);
  5386. }
  5387. bool stale_work(struct work *work, bool share)
  5388. {
  5389. unsigned work_expiry;
  5390. struct pool *pool;
  5391. uint32_t block_id;
  5392. unsigned getwork_delay;
  5393. block_id = ((uint32_t*)work->data)[1];
  5394. pool = work->pool;
  5395. /* Technically the rolltime should be correct but some pools
  5396. * advertise a broken expire= that is lower than a meaningful
  5397. * scantime */
  5398. if (work->rolltime >= opt_scantime || work->tr)
  5399. work_expiry = work->rolltime;
  5400. else
  5401. work_expiry = opt_expiry;
  5402. unsigned max_expiry = (have_longpoll ? opt_expiry_lp : opt_expiry);
  5403. if (work_expiry > max_expiry)
  5404. work_expiry = max_expiry;
  5405. if (share) {
  5406. /* If the share isn't on this pool's latest block, it's stale */
  5407. if (pool->block_id && pool->block_id != block_id)
  5408. {
  5409. applog(LOG_DEBUG, "Share stale due to block mismatch (%08lx != %08lx)", (long)block_id, (long)pool->block_id);
  5410. return true;
  5411. }
  5412. /* If the pool doesn't want old shares, then any found in work before
  5413. * the most recent longpoll is stale */
  5414. if ((!pool->submit_old) && work->work_restart_id != pool->work_restart_id)
  5415. {
  5416. applog(LOG_DEBUG, "Share stale due to mandatory work update (%02x != %02x)", work->work_restart_id, pool->work_restart_id);
  5417. return true;
  5418. }
  5419. } else {
  5420. struct mining_goal_info * const goal = pool->goal;
  5421. struct blockchain_info * const blkchain = goal->blkchain;
  5422. /* If this work isn't for the latest Bitcoin block, it's stale */
  5423. /* But only care about the current pool if failover-only */
  5424. if (enabled_pools <= 1 || opt_fail_only) {
  5425. if (pool->block_id && block_id != pool->block_id)
  5426. {
  5427. applog(LOG_DEBUG, "Work stale due to block mismatch (%08lx != 1 ? %08lx : %08lx)", (long)block_id, (long)pool->block_id, (long)blkchain->currentblk->block_id);
  5428. return true;
  5429. }
  5430. } else {
  5431. if (block_id != blkchain->currentblk->block_id)
  5432. {
  5433. applog(LOG_DEBUG, "Work stale due to block mismatch (%08lx != 0 ? %08lx : %08lx)", (long)block_id, (long)pool->block_id, (long)blkchain->currentblk->block_id);
  5434. return true;
  5435. }
  5436. }
  5437. /* If the pool has asked us to restart since this work, it's stale */
  5438. if (work->work_restart_id != pool->work_restart_id)
  5439. {
  5440. applog(LOG_DEBUG, "Work stale due to work update (%02x != %02x)", work->work_restart_id, pool->work_restart_id);
  5441. return true;
  5442. }
  5443. if (pool->has_stratum && work->job_id) {
  5444. bool same_job;
  5445. if (!pool->stratum_active || !pool->stratum_notify) {
  5446. applog(LOG_DEBUG, "Work stale due to stratum inactive");
  5447. return true;
  5448. }
  5449. same_job = true;
  5450. cg_rlock(&pool->data_lock);
  5451. if (strcmp(work->job_id, pool->swork.job_id))
  5452. same_job = false;
  5453. cg_runlock(&pool->data_lock);
  5454. if (!same_job) {
  5455. applog(LOG_DEBUG, "Work stale due to stratum job_id mismatch");
  5456. return true;
  5457. }
  5458. }
  5459. /* Factor in the average getwork delay of this pool, rounding it up to
  5460. * the nearest second */
  5461. getwork_delay = pool->cgminer_pool_stats.getwork_wait_rolling * 5 + 1;
  5462. if (unlikely(work_expiry <= getwork_delay + 5))
  5463. work_expiry = 5;
  5464. else
  5465. work_expiry -= getwork_delay;
  5466. }
  5467. int elapsed_since_staged = timer_elapsed(&work->tv_staged, NULL);
  5468. if (elapsed_since_staged > work_expiry) {
  5469. applog(LOG_DEBUG, "%s stale due to expiry (%d >= %u)", share?"Share":"Work", elapsed_since_staged, work_expiry);
  5470. return true;
  5471. }
  5472. /* If the user only wants strict failover, any work from a pool other than
  5473. * the current one is always considered stale */
  5474. if (opt_fail_only && !share && !work->mandatory && !pool_actively_in_use(pool, NULL))
  5475. {
  5476. applog(LOG_DEBUG, "Work stale due to fail only pool mismatch (pool %u vs %u)", pool->pool_no, current_pool()->pool_no);
  5477. return true;
  5478. }
  5479. return false;
  5480. }
  5481. double share_diff(const struct work *work)
  5482. {
  5483. double ret;
  5484. bool new_best = false;
  5485. ret = target_diff(work->hash);
  5486. cg_wlock(&control_lock);
  5487. if (unlikely(ret > best_diff)) {
  5488. new_best = true;
  5489. best_diff = ret;
  5490. suffix_string(best_diff, best_share, sizeof(best_share), 0);
  5491. }
  5492. if (unlikely(ret > work->pool->best_diff))
  5493. work->pool->best_diff = ret;
  5494. cg_wunlock(&control_lock);
  5495. if (unlikely(new_best))
  5496. applog(LOG_INFO, "New best share: %s", best_share);
  5497. return ret;
  5498. }
  5499. static
  5500. void work_check_for_block(struct work * const work)
  5501. {
  5502. struct pool * const pool = work->pool;
  5503. struct mining_goal_info * const goal = pool->goal;
  5504. work->share_diff = share_diff(work);
  5505. if (unlikely(work->share_diff >= goal->current_diff)) {
  5506. work->block = true;
  5507. work->pool->solved++;
  5508. found_blocks++;
  5509. work->mandatory = true;
  5510. applog(LOG_NOTICE, "Found block for pool %d!", work->pool->pool_no);
  5511. }
  5512. }
  5513. static void submit_discard_share2(const char *reason, struct work *work)
  5514. {
  5515. struct cgpu_info *cgpu = get_thr_cgpu(work->thr_id);
  5516. sharelog(reason, work);
  5517. mutex_lock(&stats_lock);
  5518. ++total_stale;
  5519. ++cgpu->stale;
  5520. ++(work->pool->stale_shares);
  5521. total_diff_stale += work->work_difficulty;
  5522. cgpu->diff_stale += work->work_difficulty;
  5523. work->pool->diff_stale += work->work_difficulty;
  5524. mutex_unlock(&stats_lock);
  5525. }
  5526. static void submit_discard_share(struct work *work)
  5527. {
  5528. submit_discard_share2("discard", work);
  5529. }
  5530. struct submit_work_state {
  5531. struct work *work;
  5532. bool resubmit;
  5533. struct curl_ent *ce;
  5534. int failures;
  5535. struct timeval tv_staleexpire;
  5536. char *s;
  5537. struct timeval tv_submit;
  5538. struct submit_work_state *next;
  5539. };
  5540. static int my_curl_timer_set(__maybe_unused CURLM *curlm, long timeout_ms, void *userp)
  5541. {
  5542. long *p_timeout_us = userp;
  5543. const long max_ms = LONG_MAX / 1000;
  5544. if (max_ms < timeout_ms)
  5545. timeout_ms = max_ms;
  5546. *p_timeout_us = timeout_ms * 1000;
  5547. return 0;
  5548. }
  5549. static void sws_has_ce(struct submit_work_state *sws)
  5550. {
  5551. struct pool *pool = sws->work->pool;
  5552. sws->s = submit_upstream_work_request(sws->work);
  5553. cgtime(&sws->tv_submit);
  5554. json_rpc_call_async(sws->ce->curl, pool->rpc_url, pool->rpc_userpass, sws->s, false, pool, true, sws);
  5555. }
  5556. static struct submit_work_state *begin_submission(struct work *work)
  5557. {
  5558. struct pool *pool;
  5559. struct submit_work_state *sws = NULL;
  5560. pool = work->pool;
  5561. sws = malloc(sizeof(*sws));
  5562. *sws = (struct submit_work_state){
  5563. .work = work,
  5564. };
  5565. work_check_for_block(work);
  5566. if (stale_work(work, true)) {
  5567. work->stale = true;
  5568. if (opt_submit_stale)
  5569. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as user requested", pool->pool_no);
  5570. else if (pool->submit_old)
  5571. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as pool requested", pool->pool_no);
  5572. else {
  5573. applog(LOG_NOTICE, "Pool %d stale share detected, discarding", pool->pool_no);
  5574. submit_discard_share(work);
  5575. goto out;
  5576. }
  5577. timer_set_delay_from_now(&sws->tv_staleexpire, 300000000);
  5578. }
  5579. if (work->stratum) {
  5580. char *s;
  5581. s = malloc(1024);
  5582. sws->s = s;
  5583. } else {
  5584. /* submit solution to bitcoin via JSON-RPC */
  5585. sws->ce = pop_curl_entry2(pool, false);
  5586. if (sws->ce) {
  5587. sws_has_ce(sws);
  5588. } else {
  5589. sws->next = pool->sws_waiting_on_curl;
  5590. pool->sws_waiting_on_curl = sws;
  5591. if (sws->next)
  5592. applog(LOG_DEBUG, "submit_thread queuing submission");
  5593. else
  5594. applog(LOG_WARNING, "submit_thread queuing submissions (see --submit-threads)");
  5595. }
  5596. }
  5597. return sws;
  5598. out:
  5599. free(sws);
  5600. return NULL;
  5601. }
  5602. static bool retry_submission(struct submit_work_state *sws)
  5603. {
  5604. struct work *work = sws->work;
  5605. struct pool *pool = work->pool;
  5606. sws->resubmit = true;
  5607. if ((!work->stale) && stale_work(work, true)) {
  5608. work->stale = true;
  5609. if (opt_submit_stale)
  5610. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, will retry as user requested", pool->pool_no);
  5611. else if (pool->submit_old)
  5612. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, will retry as pool requested", pool->pool_no);
  5613. else {
  5614. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, discarding", pool->pool_no);
  5615. submit_discard_share(work);
  5616. return false;
  5617. }
  5618. timer_set_delay_from_now(&sws->tv_staleexpire, 300000000);
  5619. }
  5620. if (unlikely((opt_retries >= 0) && (++sws->failures > opt_retries))) {
  5621. applog(LOG_ERR, "Pool %d failed %d submission retries, discarding", pool->pool_no, opt_retries);
  5622. submit_discard_share(work);
  5623. return false;
  5624. }
  5625. else if (work->stale) {
  5626. if (unlikely(opt_retries < 0 && timer_passed(&sws->tv_staleexpire, NULL)))
  5627. {
  5628. applog(LOG_NOTICE, "Pool %d stale share failed to submit for 5 minutes, discarding", pool->pool_no);
  5629. submit_discard_share(work);
  5630. return false;
  5631. }
  5632. }
  5633. /* pause, then restart work-request loop */
  5634. applog(LOG_INFO, "json_rpc_call failed on submit_work, retrying");
  5635. cgtime(&sws->tv_submit);
  5636. json_rpc_call_async(sws->ce->curl, pool->rpc_url, pool->rpc_userpass, sws->s, false, pool, true, sws);
  5637. return true;
  5638. }
  5639. static void free_sws(struct submit_work_state *sws)
  5640. {
  5641. free(sws->s);
  5642. free_work(sws->work);
  5643. free(sws);
  5644. }
  5645. static void *submit_work_thread(__maybe_unused void *userdata)
  5646. {
  5647. int wip = 0;
  5648. CURLM *curlm;
  5649. long curlm_timeout_us = -1;
  5650. struct timeval curlm_timer;
  5651. struct submit_work_state *sws, **swsp;
  5652. struct submit_work_state *write_sws = NULL;
  5653. unsigned tsreduce = 0;
  5654. pthread_detach(pthread_self());
  5655. RenameThread("submit_work");
  5656. applog(LOG_DEBUG, "Creating extra submit work thread");
  5657. curlm = curl_multi_init();
  5658. curlm_timeout_us = -1;
  5659. curl_multi_setopt(curlm, CURLMOPT_TIMERDATA, &curlm_timeout_us);
  5660. curl_multi_setopt(curlm, CURLMOPT_TIMERFUNCTION, my_curl_timer_set);
  5661. fd_set rfds, wfds, efds;
  5662. int maxfd;
  5663. struct timeval tv_timeout, tv_now;
  5664. int n;
  5665. CURLMsg *cm;
  5666. FD_ZERO(&rfds);
  5667. while (1) {
  5668. mutex_lock(&submitting_lock);
  5669. total_submitting -= tsreduce;
  5670. tsreduce = 0;
  5671. if (FD_ISSET(submit_waiting_notifier[0], &rfds)) {
  5672. notifier_read(submit_waiting_notifier);
  5673. }
  5674. // Receive any new submissions
  5675. while (submit_waiting) {
  5676. struct work *work = submit_waiting;
  5677. DL_DELETE(submit_waiting, work);
  5678. if ( (sws = begin_submission(work)) ) {
  5679. if (sws->ce)
  5680. curl_multi_add_handle(curlm, sws->ce->curl);
  5681. else if (sws->s) {
  5682. sws->next = write_sws;
  5683. write_sws = sws;
  5684. }
  5685. ++wip;
  5686. }
  5687. else {
  5688. --total_submitting;
  5689. free_work(work);
  5690. }
  5691. }
  5692. if (unlikely(shutting_down && !wip))
  5693. break;
  5694. mutex_unlock(&submitting_lock);
  5695. FD_ZERO(&rfds);
  5696. FD_ZERO(&wfds);
  5697. FD_ZERO(&efds);
  5698. tv_timeout.tv_sec = -1;
  5699. // Setup cURL with select
  5700. // Need to call perform to ensure the timeout gets updated
  5701. curl_multi_perform(curlm, &n);
  5702. curl_multi_fdset(curlm, &rfds, &wfds, &efds, &maxfd);
  5703. if (curlm_timeout_us >= 0)
  5704. {
  5705. timer_set_delay_from_now(&curlm_timer, curlm_timeout_us);
  5706. reduce_timeout_to(&tv_timeout, &curlm_timer);
  5707. }
  5708. // Setup waiting stratum submissions with select
  5709. for (sws = write_sws; sws; sws = sws->next)
  5710. {
  5711. struct pool *pool = sws->work->pool;
  5712. int fd = pool->sock;
  5713. if (fd == INVSOCK || (!pool->stratum_init) || !pool->stratum_notify)
  5714. continue;
  5715. FD_SET(fd, &wfds);
  5716. set_maxfd(&maxfd, fd);
  5717. }
  5718. // Setup "submit waiting" notifier with select
  5719. FD_SET(submit_waiting_notifier[0], &rfds);
  5720. set_maxfd(&maxfd, submit_waiting_notifier[0]);
  5721. // Wait for something interesting to happen :)
  5722. cgtime(&tv_now);
  5723. if (select(maxfd+1, &rfds, &wfds, &efds, select_timeout(&tv_timeout, &tv_now)) < 0) {
  5724. FD_ZERO(&rfds);
  5725. continue;
  5726. }
  5727. // Handle any stratum ready-to-write results
  5728. for (swsp = &write_sws; (sws = *swsp); ) {
  5729. struct work *work = sws->work;
  5730. struct pool *pool = work->pool;
  5731. int fd = pool->sock;
  5732. bool sessionid_match;
  5733. if (fd == INVSOCK || (!pool->stratum_init) || (!pool->stratum_notify) || !FD_ISSET(fd, &wfds)) {
  5734. next_write_sws:
  5735. // TODO: Check if stale, possibly discard etc
  5736. swsp = &sws->next;
  5737. continue;
  5738. }
  5739. cg_rlock(&pool->data_lock);
  5740. // 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
  5741. // NOTE: Worst case scenario for a false positive: the pool rejects it as H-not-zero
  5742. sessionid_match = (!pool->swork.nonce1) || !strcmp(work->nonce1, pool->swork.nonce1);
  5743. cg_runlock(&pool->data_lock);
  5744. if (!sessionid_match)
  5745. {
  5746. applog(LOG_DEBUG, "No matching session id for resubmitting stratum share");
  5747. submit_discard_share2("disconnect", work);
  5748. ++tsreduce;
  5749. next_write_sws_del:
  5750. // Clear the fd from wfds, to avoid potentially blocking on other submissions to the same socket
  5751. FD_CLR(fd, &wfds);
  5752. // Delete sws for this submission, since we're done with it
  5753. *swsp = sws->next;
  5754. free_sws(sws);
  5755. --wip;
  5756. continue;
  5757. }
  5758. char *s = sws->s;
  5759. struct stratum_share *sshare = calloc(sizeof(struct stratum_share), 1);
  5760. int sshare_id;
  5761. uint32_t nonce;
  5762. char nonce2hex[(bytes_len(&work->nonce2) * 2) + 1];
  5763. char noncehex[9];
  5764. char ntimehex[9];
  5765. sshare->work = copy_work(work);
  5766. bin2hex(nonce2hex, bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  5767. nonce = *((uint32_t *)(work->data + 76));
  5768. bin2hex(noncehex, (const unsigned char *)&nonce, 4);
  5769. bin2hex(ntimehex, (void *)&work->data[68], 4);
  5770. mutex_lock(&sshare_lock);
  5771. /* Give the stratum share a unique id */
  5772. sshare_id =
  5773. sshare->id = swork_id++;
  5774. HASH_ADD_INT(stratum_shares, id, sshare);
  5775. snprintf(s, 1024, "{\"params\": [\"%s\", \"%s\", \"%s\", \"%s\", \"%s\"], \"id\": %d, \"method\": \"mining.submit\"}",
  5776. pool->rpc_user, work->job_id, nonce2hex, ntimehex, noncehex, sshare->id);
  5777. mutex_unlock(&sshare_lock);
  5778. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->stratum_url, s);
  5779. if (likely(stratum_send(pool, s, strlen(s)))) {
  5780. if (pool_tclear(pool, &pool->submit_fail))
  5781. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  5782. applog(LOG_DEBUG, "Successfully submitted, adding to stratum_shares db");
  5783. goto next_write_sws_del;
  5784. } else if (!pool_tset(pool, &pool->submit_fail)) {
  5785. // Undo stuff
  5786. mutex_lock(&sshare_lock);
  5787. // NOTE: Need to find it again in case something else has consumed it already (like the stratum-disconnect resubmitter...)
  5788. HASH_FIND_INT(stratum_shares, &sshare_id, sshare);
  5789. if (sshare)
  5790. HASH_DEL(stratum_shares, sshare);
  5791. mutex_unlock(&sshare_lock);
  5792. if (sshare)
  5793. {
  5794. free_work(sshare->work);
  5795. free(sshare);
  5796. }
  5797. applog(LOG_WARNING, "Pool %d stratum share submission failure", pool->pool_no);
  5798. total_ro++;
  5799. pool->remotefail_occasions++;
  5800. if (!sshare)
  5801. goto next_write_sws_del;
  5802. goto next_write_sws;
  5803. }
  5804. }
  5805. // Handle any cURL activities
  5806. curl_multi_perform(curlm, &n);
  5807. while( (cm = curl_multi_info_read(curlm, &n)) ) {
  5808. if (cm->msg == CURLMSG_DONE)
  5809. {
  5810. bool finished;
  5811. json_t *val = json_rpc_call_completed(cm->easy_handle, cm->data.result, false, NULL, &sws);
  5812. curl_multi_remove_handle(curlm, cm->easy_handle);
  5813. finished = submit_upstream_work_completed(sws->work, sws->resubmit, &sws->tv_submit, val);
  5814. if (!finished) {
  5815. if (retry_submission(sws))
  5816. curl_multi_add_handle(curlm, sws->ce->curl);
  5817. else
  5818. finished = true;
  5819. }
  5820. if (finished) {
  5821. --wip;
  5822. ++tsreduce;
  5823. struct pool *pool = sws->work->pool;
  5824. if (pool->sws_waiting_on_curl) {
  5825. pool->sws_waiting_on_curl->ce = sws->ce;
  5826. sws_has_ce(pool->sws_waiting_on_curl);
  5827. pool->sws_waiting_on_curl = pool->sws_waiting_on_curl->next;
  5828. curl_multi_add_handle(curlm, sws->ce->curl);
  5829. } else {
  5830. push_curl_entry(sws->ce, sws->work->pool);
  5831. }
  5832. free_sws(sws);
  5833. }
  5834. }
  5835. }
  5836. }
  5837. assert(!write_sws);
  5838. mutex_unlock(&submitting_lock);
  5839. curl_multi_cleanup(curlm);
  5840. applog(LOG_DEBUG, "submit_work thread exiting");
  5841. return NULL;
  5842. }
  5843. /* Find the pool that currently has the highest priority */
  5844. static struct pool *priority_pool(int choice)
  5845. {
  5846. struct pool *ret = NULL;
  5847. int i;
  5848. for (i = 0; i < total_pools; i++) {
  5849. struct pool *pool = pools[i];
  5850. if (pool->prio == choice) {
  5851. ret = pool;
  5852. break;
  5853. }
  5854. }
  5855. if (unlikely(!ret)) {
  5856. applog(LOG_ERR, "WTF No pool %d found!", choice);
  5857. return pools[choice];
  5858. }
  5859. return ret;
  5860. }
  5861. int prioritize_pools(char *param, int *pid)
  5862. {
  5863. char *ptr, *next;
  5864. int i, pr, prio = 0;
  5865. if (total_pools == 0) {
  5866. return MSG_NOPOOL;
  5867. }
  5868. if (param == NULL || *param == '\0') {
  5869. return MSG_MISPID;
  5870. }
  5871. bool pools_changed[total_pools];
  5872. int new_prio[total_pools];
  5873. for (i = 0; i < total_pools; ++i)
  5874. pools_changed[i] = false;
  5875. next = param;
  5876. while (next && *next) {
  5877. ptr = next;
  5878. next = strchr(ptr, ',');
  5879. if (next)
  5880. *(next++) = '\0';
  5881. i = atoi(ptr);
  5882. if (i < 0 || i >= total_pools) {
  5883. *pid = i;
  5884. return MSG_INVPID;
  5885. }
  5886. if (pools_changed[i]) {
  5887. *pid = i;
  5888. return MSG_DUPPID;
  5889. }
  5890. pools_changed[i] = true;
  5891. new_prio[i] = prio++;
  5892. }
  5893. // Only change them if no errors
  5894. for (i = 0; i < total_pools; i++) {
  5895. if (pools_changed[i])
  5896. pools[i]->prio = new_prio[i];
  5897. }
  5898. // In priority order, cycle through the unchanged pools and append them
  5899. for (pr = 0; pr < total_pools; pr++)
  5900. for (i = 0; i < total_pools; i++) {
  5901. if (!pools_changed[i] && pools[i]->prio == pr) {
  5902. pools[i]->prio = prio++;
  5903. pools_changed[i] = true;
  5904. break;
  5905. }
  5906. }
  5907. if (current_pool()->prio)
  5908. switch_pools(NULL);
  5909. return MSG_POOLPRIO;
  5910. }
  5911. void validate_pool_priorities(void)
  5912. {
  5913. // TODO: this should probably do some sort of logging
  5914. int i, j;
  5915. bool used[total_pools];
  5916. bool valid[total_pools];
  5917. for (i = 0; i < total_pools; i++)
  5918. used[i] = valid[i] = false;
  5919. for (i = 0; i < total_pools; i++) {
  5920. if (pools[i]->prio >=0 && pools[i]->prio < total_pools) {
  5921. if (!used[pools[i]->prio]) {
  5922. valid[i] = true;
  5923. used[pools[i]->prio] = true;
  5924. }
  5925. }
  5926. }
  5927. for (i = 0; i < total_pools; i++) {
  5928. if (!valid[i]) {
  5929. for (j = 0; j < total_pools; j++) {
  5930. if (!used[j]) {
  5931. applog(LOG_WARNING, "Pool %d priority changed from %d to %d", i, pools[i]->prio, j);
  5932. pools[i]->prio = j;
  5933. used[j] = true;
  5934. break;
  5935. }
  5936. }
  5937. }
  5938. }
  5939. }
  5940. static void clear_pool_work(struct pool *pool);
  5941. /* Specifies whether we can switch to this pool or not. */
  5942. static bool pool_unusable(struct pool *pool)
  5943. {
  5944. if (pool->idle)
  5945. return true;
  5946. if (pool->enabled != POOL_ENABLED)
  5947. return true;
  5948. return false;
  5949. }
  5950. void switch_pools(struct pool *selected)
  5951. {
  5952. struct pool *pool, *last_pool, *failover_pool = NULL;
  5953. int i, pool_no, next_pool;
  5954. if (selected)
  5955. enable_pool(selected);
  5956. cg_wlock(&control_lock);
  5957. last_pool = currentpool;
  5958. pool_no = currentpool->pool_no;
  5959. /* Switch selected to pool number 0 and move the rest down */
  5960. if (selected) {
  5961. if (selected->prio != 0) {
  5962. for (i = 0; i < total_pools; i++) {
  5963. pool = pools[i];
  5964. if (pool->prio < selected->prio)
  5965. pool->prio++;
  5966. }
  5967. selected->prio = 0;
  5968. }
  5969. }
  5970. switch (pool_strategy) {
  5971. /* All of these set to the master pool */
  5972. case POOL_BALANCE:
  5973. case POOL_FAILOVER:
  5974. case POOL_LOADBALANCE:
  5975. for (i = 0; i < total_pools; i++) {
  5976. pool = priority_pool(i);
  5977. if (pool_unusable(pool))
  5978. continue;
  5979. pool_no = pool->pool_no;
  5980. break;
  5981. }
  5982. break;
  5983. /* Both of these simply increment and cycle */
  5984. case POOL_ROUNDROBIN:
  5985. case POOL_ROTATE:
  5986. if (selected && !selected->idle) {
  5987. pool_no = selected->pool_no;
  5988. break;
  5989. }
  5990. next_pool = pool_no;
  5991. /* Select the next alive pool */
  5992. for (i = 1; i < total_pools; i++) {
  5993. next_pool++;
  5994. if (next_pool >= total_pools)
  5995. next_pool = 0;
  5996. pool = pools[next_pool];
  5997. if (pool_unusable(pool))
  5998. continue;
  5999. if (pool->failover_only)
  6000. {
  6001. BFGINIT(failover_pool, pool);
  6002. continue;
  6003. }
  6004. pool_no = next_pool;
  6005. break;
  6006. }
  6007. break;
  6008. default:
  6009. break;
  6010. }
  6011. pool = pools[pool_no];
  6012. if (pool_unusable(pool) && failover_pool)
  6013. pool = failover_pool;
  6014. currentpool = pool;
  6015. cg_wunlock(&control_lock);
  6016. mutex_lock(&lp_lock);
  6017. pthread_cond_broadcast(&lp_cond);
  6018. mutex_unlock(&lp_lock);
  6019. /* Set the lagging flag to avoid pool not providing work fast enough
  6020. * messages in failover only mode since we have to get all fresh work
  6021. * as in restart_threads */
  6022. if (opt_fail_only)
  6023. pool_tset(pool, &pool->lagging);
  6024. if (pool != last_pool)
  6025. {
  6026. pool->block_id = 0;
  6027. if (pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  6028. applog(LOG_WARNING, "Switching to pool %d %s", pool->pool_no, pool->rpc_url);
  6029. if (pool_localgen(pool) || opt_fail_only)
  6030. clear_pool_work(last_pool);
  6031. }
  6032. }
  6033. mutex_lock(&lp_lock);
  6034. pthread_cond_broadcast(&lp_cond);
  6035. mutex_unlock(&lp_lock);
  6036. #ifdef HAVE_CURSES
  6037. update_block_display();
  6038. #endif
  6039. }
  6040. static void discard_work(struct work *work)
  6041. {
  6042. if (!work->clone && !work->rolls && !work->mined) {
  6043. if (work->pool) {
  6044. work->pool->discarded_work++;
  6045. work->pool->quota_used--;
  6046. work->pool->works--;
  6047. }
  6048. total_discarded++;
  6049. applog(LOG_DEBUG, "Discarded work");
  6050. } else
  6051. applog(LOG_DEBUG, "Discarded cloned or rolled work");
  6052. free_work(work);
  6053. }
  6054. static void wake_gws(void)
  6055. {
  6056. mutex_lock(stgd_lock);
  6057. pthread_cond_signal(&gws_cond);
  6058. mutex_unlock(stgd_lock);
  6059. }
  6060. static void discard_stale(void)
  6061. {
  6062. struct work *work, *tmp;
  6063. int stale = 0;
  6064. mutex_lock(stgd_lock);
  6065. HASH_ITER(hh, staged_work, work, tmp) {
  6066. if (stale_work(work, false)) {
  6067. HASH_DEL(staged_work, work);
  6068. discard_work(work);
  6069. stale++;
  6070. staged_full = false;
  6071. }
  6072. }
  6073. pthread_cond_signal(&gws_cond);
  6074. mutex_unlock(stgd_lock);
  6075. if (stale)
  6076. applog(LOG_DEBUG, "Discarded %d stales that didn't match current hash", stale);
  6077. }
  6078. bool stale_work_future(struct work *work, bool share, unsigned long ustime)
  6079. {
  6080. bool rv;
  6081. struct timeval tv, orig;
  6082. ldiv_t d;
  6083. d = ldiv(ustime, 1000000);
  6084. tv = (struct timeval){
  6085. .tv_sec = d.quot,
  6086. .tv_usec = d.rem,
  6087. };
  6088. orig = work->tv_staged;
  6089. timersub(&orig, &tv, &work->tv_staged);
  6090. rv = stale_work(work, share);
  6091. work->tv_staged = orig;
  6092. return rv;
  6093. }
  6094. static
  6095. void pool_update_work_restart_time(struct pool * const pool)
  6096. {
  6097. pool->work_restart_time = time(NULL);
  6098. get_timestamp(pool->work_restart_timestamp, sizeof(pool->work_restart_timestamp), pool->work_restart_time);
  6099. }
  6100. static void restart_threads(void)
  6101. {
  6102. struct pool *cp = current_pool();
  6103. int i;
  6104. struct thr_info *thr;
  6105. /* Artificially set the lagging flag to avoid pool not providing work
  6106. * fast enough messages after every long poll */
  6107. pool_tset(cp, &cp->lagging);
  6108. /* Discard staged work that is now stale */
  6109. discard_stale();
  6110. rd_lock(&mining_thr_lock);
  6111. for (i = 0; i < mining_threads; i++)
  6112. {
  6113. thr = mining_thr[i];
  6114. thr->work_restart = true;
  6115. }
  6116. for (i = 0; i < mining_threads; i++)
  6117. {
  6118. thr = mining_thr[i];
  6119. notifier_wake(thr->work_restart_notifier);
  6120. }
  6121. rd_unlock(&mining_thr_lock);
  6122. }
  6123. void blkhashstr(char *rv, const unsigned char *hash)
  6124. {
  6125. unsigned char hash_swap[32];
  6126. swap256(hash_swap, hash);
  6127. swap32tole(hash_swap, hash_swap, 32 / 4);
  6128. bin2hex(rv, hash_swap, 32);
  6129. }
  6130. static
  6131. void set_curblock(struct mining_goal_info * const goal, struct block_info * const blkinfo)
  6132. {
  6133. struct blockchain_info * const blkchain = goal->blkchain;
  6134. blkchain->currentblk = blkinfo;
  6135. blkchain->currentblk_subsidy = 5000000000LL >> (blkinfo->height / 210000);
  6136. cg_wlock(&ch_lock);
  6137. __update_block_title(goal);
  6138. get_timestamp(blkchain->currentblk_first_seen_time_str, sizeof(blkchain->currentblk_first_seen_time_str), blkinfo->first_seen_time);
  6139. cg_wunlock(&ch_lock);
  6140. applog(LOG_INFO, "New block: %s diff %s (%s)", goal->current_goal_detail, goal->current_diff_str, goal->net_hashrate);
  6141. }
  6142. /* Search to see if this prevblkhash has been seen before */
  6143. static
  6144. struct block_info *block_exists(const struct blockchain_info * const blkchain, const void * const prevblkhash)
  6145. {
  6146. struct block_info *s;
  6147. rd_lock(&blk_lock);
  6148. HASH_FIND(hh, blkchain->blocks, prevblkhash, 0x20, s);
  6149. rd_unlock(&blk_lock);
  6150. return s;
  6151. }
  6152. static int block_sort(struct block_info * const blocka, struct block_info * const blockb)
  6153. {
  6154. return blocka->block_seen_order - blockb->block_seen_order;
  6155. }
  6156. static
  6157. void set_blockdiff(struct mining_goal_info * const goal, const struct work * const work)
  6158. {
  6159. unsigned char target[32];
  6160. double diff;
  6161. uint64_t diff64;
  6162. real_block_target(target, work->data);
  6163. diff = target_diff(target);
  6164. diff64 = diff;
  6165. suffix_string(diff64, goal->current_diff_str, sizeof(goal->current_diff_str), 0);
  6166. format_unit2(goal->net_hashrate, sizeof(goal->net_hashrate),
  6167. true, "h/s", H2B_SHORT, diff * 7158278, -1);
  6168. if (unlikely(goal->current_diff != diff))
  6169. applog(LOG_NOTICE, "Network difficulty changed to %s (%s)", goal->current_diff_str, goal->net_hashrate);
  6170. goal->current_diff = diff;
  6171. }
  6172. static bool test_work_current(struct work *work)
  6173. {
  6174. bool ret = true;
  6175. if (work->mandatory)
  6176. return ret;
  6177. uint32_t block_id = ((uint32_t*)(work->data))[1];
  6178. const uint8_t * const prevblkhash = &work->data[4];
  6179. {
  6180. /* Hack to work around dud work sneaking into test */
  6181. bool dudwork = true;
  6182. for (int i = 8; i < 26; ++i)
  6183. if (work->data[i])
  6184. {
  6185. dudwork = false;
  6186. break;
  6187. }
  6188. if (dudwork)
  6189. goto out_free;
  6190. }
  6191. struct pool * const pool = work->pool;
  6192. struct mining_goal_info * const goal = pool->goal;
  6193. struct blockchain_info * const blkchain = goal->blkchain;
  6194. /* Search to see if this block exists yet and if not, consider it a
  6195. * new block and set the current block details to this one */
  6196. if (!block_exists(blkchain, prevblkhash))
  6197. {
  6198. struct block_info * const s = calloc(sizeof(struct block_info), 1);
  6199. int deleted_block = 0;
  6200. ret = false;
  6201. if (unlikely(!s))
  6202. quit (1, "test_work_current OOM");
  6203. memcpy(s->prevblkhash, prevblkhash, sizeof(s->prevblkhash));
  6204. s->block_id = block_id;
  6205. s->block_seen_order = new_blocks++;
  6206. s->first_seen_time = time(NULL);
  6207. wr_lock(&blk_lock);
  6208. /* Only keep the last hour's worth of blocks in memory since
  6209. * work from blocks before this is virtually impossible and we
  6210. * want to prevent memory usage from continually rising */
  6211. if (HASH_COUNT(blkchain->blocks) > 6)
  6212. {
  6213. struct block_info *oldblock;
  6214. HASH_SORT(blkchain->blocks, block_sort);
  6215. oldblock = blkchain->blocks;
  6216. deleted_block = oldblock->block_seen_order;
  6217. HASH_DEL(blkchain->blocks, oldblock);
  6218. free(oldblock);
  6219. }
  6220. HASH_ADD(hh, blkchain->blocks, prevblkhash, sizeof(s->prevblkhash), s);
  6221. set_blockdiff(goal, work);
  6222. wr_unlock(&blk_lock);
  6223. pool->block_id = block_id;
  6224. pool_update_work_restart_time(pool);
  6225. if (deleted_block)
  6226. applog(LOG_DEBUG, "Deleted block %d from database", deleted_block);
  6227. #if BLKMAKER_VERSION > 1
  6228. template_nonce = 0;
  6229. #endif
  6230. set_curblock(goal, s);
  6231. if (unlikely(new_blocks == 1))
  6232. goto out_free;
  6233. if (!work->stratum)
  6234. {
  6235. if (work->longpoll)
  6236. {
  6237. applog(LOG_NOTICE, "Longpoll from pool %d detected new block",
  6238. pool->pool_no);
  6239. }
  6240. else
  6241. if (have_longpoll)
  6242. applog(LOG_NOTICE, "New block detected on network before longpoll");
  6243. else
  6244. applog(LOG_NOTICE, "New block detected on network");
  6245. }
  6246. restart_threads();
  6247. }
  6248. else
  6249. {
  6250. bool restart = false;
  6251. if (unlikely(pool->block_id != block_id))
  6252. {
  6253. bool was_active = pool->block_id != 0;
  6254. pool->block_id = block_id;
  6255. pool_update_work_restart_time(pool);
  6256. if (!work->longpoll)
  6257. update_last_work(work);
  6258. if (was_active)
  6259. {
  6260. // Pool actively changed block
  6261. if (pool == current_pool())
  6262. restart = true;
  6263. if (block_id == blkchain->currentblk->block_id)
  6264. {
  6265. // Caught up, only announce if this pool is the one in use
  6266. if (restart)
  6267. applog(LOG_NOTICE, "%s %d caught up to new block",
  6268. work->longpoll ? "Longpoll from pool" : "Pool",
  6269. pool->pool_no);
  6270. }
  6271. else
  6272. {
  6273. // Switched to a block we know, but not the latest... why?
  6274. // This might detect pools trying to double-spend or 51%,
  6275. // but let's not make any accusations until it's had time
  6276. // in the real world.
  6277. char hexstr[65];
  6278. blkhashstr(hexstr, prevblkhash);
  6279. applog(LOG_WARNING, "%s %d is issuing work for an old block: %s",
  6280. work->longpoll ? "Longpoll from pool" : "Pool",
  6281. pool->pool_no,
  6282. hexstr);
  6283. }
  6284. }
  6285. }
  6286. if (work->longpoll)
  6287. {
  6288. struct pool * const cp = current_pool();
  6289. ++pool->work_restart_id;
  6290. if (work->tr && work->tr == pool->swork.tr)
  6291. pool->swork.work_restart_id = pool->work_restart_id;
  6292. update_last_work(work);
  6293. pool_update_work_restart_time(pool);
  6294. applog(
  6295. ((!opt_quiet_work_updates) && pool_actively_in_use(pool, cp) ? LOG_NOTICE : LOG_DEBUG),
  6296. "Longpoll from pool %d requested work update",
  6297. pool->pool_no);
  6298. if ((!restart) && pool == cp)
  6299. restart = true;
  6300. }
  6301. if (restart)
  6302. restart_threads();
  6303. }
  6304. work->longpoll = false;
  6305. out_free:
  6306. return ret;
  6307. }
  6308. static int tv_sort(struct work *worka, struct work *workb)
  6309. {
  6310. return worka->tv_staged.tv_sec - workb->tv_staged.tv_sec;
  6311. }
  6312. static bool work_rollable(struct work *work)
  6313. {
  6314. return (!work->clone && work->rolltime);
  6315. }
  6316. static bool hash_push(struct work *work)
  6317. {
  6318. bool rc = true;
  6319. mutex_lock(stgd_lock);
  6320. if (work_rollable(work))
  6321. staged_rollable++;
  6322. if (likely(!getq->frozen)) {
  6323. HASH_ADD_INT(staged_work, id, work);
  6324. HASH_SORT(staged_work, tv_sort);
  6325. } else
  6326. rc = false;
  6327. pthread_cond_broadcast(&getq->cond);
  6328. mutex_unlock(stgd_lock);
  6329. return rc;
  6330. }
  6331. static void stage_work(struct work *work)
  6332. {
  6333. applog(LOG_DEBUG, "Pushing work %d from pool %d to hash queue",
  6334. work->id, work->pool->pool_no);
  6335. work->work_restart_id = work->pool->work_restart_id;
  6336. work->pool->last_work_time = time(NULL);
  6337. cgtime(&work->pool->tv_last_work_time);
  6338. test_work_current(work);
  6339. work->pool->works++;
  6340. hash_push(work);
  6341. }
  6342. #ifdef HAVE_CURSES
  6343. int curses_int(const char *query)
  6344. {
  6345. int ret;
  6346. char *cvar;
  6347. cvar = curses_input(query);
  6348. if (unlikely(!cvar))
  6349. return -1;
  6350. ret = atoi(cvar);
  6351. free(cvar);
  6352. return ret;
  6353. }
  6354. #endif
  6355. #ifdef HAVE_CURSES
  6356. static bool input_pool(bool live);
  6357. #endif
  6358. #ifdef HAVE_CURSES
  6359. static void display_pool_summary(struct pool *pool)
  6360. {
  6361. double efficiency = 0.0;
  6362. char xfer[ALLOC_H2B_NOUNIT+ALLOC_H2B_SPACED+4+1], bw[ALLOC_H2B_NOUNIT+ALLOC_H2B_SPACED+6+1];
  6363. int pool_secs;
  6364. if (curses_active_locked()) {
  6365. wlog("Pool: %s Goal: %s\n", pool->rpc_url, pool->goal->name);
  6366. if (pool->solved)
  6367. wlog("SOLVED %d BLOCK%s!\n", pool->solved, pool->solved > 1 ? "S" : "");
  6368. if (!pool->has_stratum)
  6369. wlog("%s own long-poll support\n", pool->lp_url ? "Has" : "Does not have");
  6370. wlog(" Queued work requests: %d\n", pool->getwork_requested);
  6371. wlog(" Share submissions: %d\n", pool->accepted + pool->rejected);
  6372. wlog(" Accepted shares: %d\n", pool->accepted);
  6373. wlog(" Rejected shares: %d + %d stale (%.2f%%)\n",
  6374. pool->rejected, pool->stale_shares,
  6375. (float)(pool->rejected + pool->stale_shares) / (float)(pool->rejected + pool->stale_shares + pool->accepted)
  6376. );
  6377. wlog(" Accepted difficulty shares: %1.f\n", pool->diff_accepted);
  6378. wlog(" Rejected difficulty shares: %1.f\n", pool->diff_rejected);
  6379. pool_secs = timer_elapsed(&pool->cgminer_stats.start_tv, NULL);
  6380. wlog(" Network transfer: %s (%s)\n",
  6381. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  6382. (float)pool->cgminer_pool_stats.net_bytes_received,
  6383. (float)pool->cgminer_pool_stats.net_bytes_sent),
  6384. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  6385. (float)(pool->cgminer_pool_stats.net_bytes_received / pool_secs),
  6386. (float)(pool->cgminer_pool_stats.net_bytes_sent / pool_secs)));
  6387. uint64_t pool_bytes_xfer = pool->cgminer_pool_stats.net_bytes_received + pool->cgminer_pool_stats.net_bytes_sent;
  6388. efficiency = pool_bytes_xfer ? pool->diff_accepted * 2048. / pool_bytes_xfer : 0.0;
  6389. wlog(" Efficiency (accepted * difficulty / 2 KB): %.2f\n", efficiency);
  6390. wlog(" Items worked on: %d\n", pool->works);
  6391. wlog(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  6392. wlog(" Unable to get work from server occasions: %d\n", pool->getfail_occasions);
  6393. wlog(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  6394. unlock_curses();
  6395. }
  6396. }
  6397. #endif
  6398. /* We can't remove the memory used for this struct pool because there may
  6399. * still be work referencing it. We just remove it from the pools list */
  6400. void remove_pool(struct pool *pool)
  6401. {
  6402. int i, last_pool = total_pools - 1;
  6403. struct pool *other;
  6404. disable_pool(pool, POOL_DISABLED);
  6405. /* Boost priority of any lower prio than this one */
  6406. for (i = 0; i < total_pools; i++) {
  6407. other = pools[i];
  6408. if (other->prio > pool->prio)
  6409. other->prio--;
  6410. }
  6411. if (pool->pool_no < last_pool) {
  6412. /* Swap the last pool for this one */
  6413. (pools[last_pool])->pool_no = pool->pool_no;
  6414. pools[pool->pool_no] = pools[last_pool];
  6415. }
  6416. /* Give it an invalid number */
  6417. pool->pool_no = total_pools;
  6418. pool->removed = true;
  6419. pool->has_stratum = false;
  6420. total_pools--;
  6421. }
  6422. /* add a mutex if this needs to be thread safe in the future */
  6423. static struct JE {
  6424. char *buf;
  6425. struct JE *next;
  6426. } *jedata = NULL;
  6427. static void json_escape_free()
  6428. {
  6429. struct JE *jeptr = jedata;
  6430. struct JE *jenext;
  6431. jedata = NULL;
  6432. while (jeptr) {
  6433. jenext = jeptr->next;
  6434. free(jeptr->buf);
  6435. free(jeptr);
  6436. jeptr = jenext;
  6437. }
  6438. }
  6439. static
  6440. char *json_escape(const char *str)
  6441. {
  6442. struct JE *jeptr;
  6443. char *buf, *ptr;
  6444. /* 2x is the max, may as well just allocate that */
  6445. ptr = buf = malloc(strlen(str) * 2 + 1);
  6446. jeptr = malloc(sizeof(*jeptr));
  6447. jeptr->buf = buf;
  6448. jeptr->next = jedata;
  6449. jedata = jeptr;
  6450. while (*str) {
  6451. if (*str == '\\' || *str == '"')
  6452. *(ptr++) = '\\';
  6453. *(ptr++) = *(str++);
  6454. }
  6455. *ptr = '\0';
  6456. return buf;
  6457. }
  6458. static
  6459. void _write_config_string_elist(FILE *fcfg, const char *configname, struct string_elist * const elist)
  6460. {
  6461. if (!elist)
  6462. return;
  6463. static struct string_elist *entry;
  6464. fprintf(fcfg, ",\n\"%s\" : [", configname);
  6465. bool first = true;
  6466. DL_FOREACH(elist, entry)
  6467. {
  6468. const char * const s = entry->string;
  6469. fprintf(fcfg, "%s\n\t\"%s\"", first ? "" : ",", json_escape(s));
  6470. first = false;
  6471. }
  6472. fprintf(fcfg, "\n]");
  6473. }
  6474. void write_config(FILE *fcfg)
  6475. {
  6476. int i;
  6477. /* Write pool values */
  6478. fputs("{\n\"pools\" : [", fcfg);
  6479. for(i = 0; i < total_pools; i++) {
  6480. struct pool *pool = pools[i];
  6481. if (pool->failover_only)
  6482. // Don't write failover-only (automatically added) pools to the config file for now
  6483. continue;
  6484. if (pool->quota != 1) {
  6485. fprintf(fcfg, "%s\n\t{\n\t\t\"quota\" : \"%d;%s\",", i > 0 ? "," : "",
  6486. pool->quota,
  6487. json_escape(pool->rpc_url));
  6488. } else {
  6489. fprintf(fcfg, "%s\n\t{\n\t\t\"url\" : \"%s\",", i > 0 ? "," : "",
  6490. json_escape(pool->rpc_url));
  6491. }
  6492. if (pool->rpc_proxy)
  6493. fprintf(fcfg, "\n\t\t\"pool-proxy\" : \"%s\",", json_escape(pool->rpc_proxy));
  6494. fprintf(fcfg, "\n\t\t\"user\" : \"%s\",", json_escape(pool->rpc_user));
  6495. fprintf(fcfg, "\n\t\t\"pass\" : \"%s\",", json_escape(pool->rpc_pass));
  6496. fprintf(fcfg, "\n\t\t\"pool-priority\" : \"%d\"", pool->prio);
  6497. if (pool->force_rollntime)
  6498. fprintf(fcfg, ",\n\t\t\"force-rollntime\" : %d", pool->force_rollntime);
  6499. fprintf(fcfg, "\n\t}");
  6500. }
  6501. fputs("\n]\n", fcfg);
  6502. #ifdef HAVE_OPENCL
  6503. write_config_opencl(fcfg);
  6504. #endif
  6505. #ifdef WANT_CPUMINE
  6506. fprintf(fcfg, ",\n\"algo\" : \"%s\"", algo_names[opt_algo]);
  6507. #endif
  6508. /* Simple bool and int options */
  6509. struct opt_table *opt;
  6510. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  6511. char *p, *name = strdup(opt->names);
  6512. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  6513. if (p[1] != '-')
  6514. continue;
  6515. if (opt->type & OPT_NOARG &&
  6516. ((void *)opt->cb == (void *)opt_set_bool || (void *)opt->cb == (void *)opt_set_invbool) &&
  6517. (*(bool *)opt->u.arg == ((void *)opt->cb == (void *)opt_set_bool)))
  6518. fprintf(fcfg, ",\n\"%s\" : true", p+2);
  6519. if (opt->type & OPT_HASARG &&
  6520. ((void *)opt->cb_arg == (void *)set_int_0_to_9999 ||
  6521. (void *)opt->cb_arg == (void *)set_int_1_to_65535 ||
  6522. (void *)opt->cb_arg == (void *)set_int_0_to_10 ||
  6523. (void *)opt->cb_arg == (void *)set_int_1_to_10) &&
  6524. opt->desc != opt_hidden &&
  6525. 0 <= *(int *)opt->u.arg)
  6526. fprintf(fcfg, ",\n\"%s\" : \"%d\"", p+2, *(int *)opt->u.arg);
  6527. }
  6528. }
  6529. /* Special case options */
  6530. if (request_target_str)
  6531. {
  6532. if (request_pdiff == (long)request_pdiff)
  6533. fprintf(fcfg, ",\n\"request-diff\" : %ld", (long)request_pdiff);
  6534. else
  6535. fprintf(fcfg, ",\n\"request-diff\" : %f", request_pdiff);
  6536. }
  6537. fprintf(fcfg, ",\n\"shares\" : %g", opt_shares);
  6538. if (pool_strategy == POOL_BALANCE)
  6539. fputs(",\n\"balance\" : true", fcfg);
  6540. if (pool_strategy == POOL_LOADBALANCE)
  6541. fputs(",\n\"load-balance\" : true", fcfg);
  6542. if (pool_strategy == POOL_ROUNDROBIN)
  6543. fputs(",\n\"round-robin\" : true", fcfg);
  6544. if (pool_strategy == POOL_ROTATE)
  6545. fprintf(fcfg, ",\n\"rotate\" : \"%d\"", opt_rotate_period);
  6546. #if defined(unix) || defined(__APPLE__)
  6547. if (opt_stderr_cmd && *opt_stderr_cmd)
  6548. fprintf(fcfg, ",\n\"monitor\" : \"%s\"", json_escape(opt_stderr_cmd));
  6549. #endif // defined(unix)
  6550. if (opt_kernel_path && *opt_kernel_path) {
  6551. char *kpath = strdup(opt_kernel_path);
  6552. if (kpath[strlen(kpath)-1] == '/')
  6553. kpath[strlen(kpath)-1] = 0;
  6554. fprintf(fcfg, ",\n\"kernel-path\" : \"%s\"", json_escape(kpath));
  6555. free(kpath);
  6556. }
  6557. if (schedstart.enable)
  6558. fprintf(fcfg, ",\n\"sched-time\" : \"%d:%d\"", schedstart.tm.tm_hour, schedstart.tm.tm_min);
  6559. if (schedstop.enable)
  6560. fprintf(fcfg, ",\n\"stop-time\" : \"%d:%d\"", schedstop.tm.tm_hour, schedstop.tm.tm_min);
  6561. if (opt_socks_proxy && *opt_socks_proxy)
  6562. fprintf(fcfg, ",\n\"socks-proxy\" : \"%s\"", json_escape(opt_socks_proxy));
  6563. _write_config_string_elist(fcfg, "scan", scan_devices);
  6564. #ifdef USE_LIBMICROHTTPD
  6565. if (httpsrv_port != -1)
  6566. fprintf(fcfg, ",\n\"http-port\" : %d", httpsrv_port);
  6567. #endif
  6568. #ifdef USE_LIBEVENT
  6569. if (stratumsrv_port != -1)
  6570. fprintf(fcfg, ",\n\"stratum-port\" : %d", stratumsrv_port);
  6571. #endif
  6572. _write_config_string_elist(fcfg, "device", opt_devices_enabled_list);
  6573. _write_config_string_elist(fcfg, "set-device", opt_set_device_list);
  6574. if (opt_api_allow)
  6575. fprintf(fcfg, ",\n\"api-allow\" : \"%s\"", json_escape(opt_api_allow));
  6576. if (strcmp(opt_api_mcast_addr, API_MCAST_ADDR) != 0)
  6577. fprintf(fcfg, ",\n\"api-mcast-addr\" : \"%s\"", json_escape(opt_api_mcast_addr));
  6578. if (strcmp(opt_api_mcast_code, API_MCAST_CODE) != 0)
  6579. fprintf(fcfg, ",\n\"api-mcast-code\" : \"%s\"", json_escape(opt_api_mcast_code));
  6580. if (*opt_api_mcast_des)
  6581. fprintf(fcfg, ",\n\"api-mcast-des\" : \"%s\"", json_escape(opt_api_mcast_des));
  6582. if (strcmp(opt_api_description, PACKAGE_STRING) != 0)
  6583. fprintf(fcfg, ",\n\"api-description\" : \"%s\"", json_escape(opt_api_description));
  6584. if (opt_api_groups)
  6585. fprintf(fcfg, ",\n\"api-groups\" : \"%s\"", json_escape(opt_api_groups));
  6586. fputs("\n}\n", fcfg);
  6587. json_escape_free();
  6588. }
  6589. void zero_bestshare(void)
  6590. {
  6591. int i;
  6592. best_diff = 0;
  6593. suffix_string(best_diff, best_share, sizeof(best_share), 0);
  6594. for (i = 0; i < total_pools; i++) {
  6595. struct pool *pool = pools[i];
  6596. pool->best_diff = 0;
  6597. }
  6598. }
  6599. void zero_stats(void)
  6600. {
  6601. int i;
  6602. applog(LOG_DEBUG, "Zeroing stats");
  6603. cgtime(&total_tv_start);
  6604. miner_started = total_tv_start;
  6605. total_rolling = 0;
  6606. total_mhashes_done = 0;
  6607. total_getworks = 0;
  6608. total_accepted = 0;
  6609. total_rejected = 0;
  6610. hw_errors = 0;
  6611. total_stale = 0;
  6612. total_discarded = 0;
  6613. total_bytes_rcvd = total_bytes_sent = 0;
  6614. new_blocks = 0;
  6615. local_work = 0;
  6616. total_go = 0;
  6617. total_ro = 0;
  6618. total_secs = 1.0;
  6619. total_diff1 = 0;
  6620. total_bad_diff1 = 0;
  6621. found_blocks = 0;
  6622. total_diff_accepted = 0;
  6623. total_diff_rejected = 0;
  6624. total_diff_stale = 0;
  6625. #ifdef HAVE_CURSES
  6626. awidth = rwidth = swidth = hwwidth = 1;
  6627. #endif
  6628. struct mining_goal_info *goal, *tmpgoal;
  6629. HASH_ITER(hh, mining_goals, goal, tmpgoal)
  6630. {
  6631. goal->diff_accepted = 0;
  6632. }
  6633. for (i = 0; i < total_pools; i++) {
  6634. struct pool *pool = pools[i];
  6635. pool->getwork_requested = 0;
  6636. pool->accepted = 0;
  6637. pool->rejected = 0;
  6638. pool->solved = 0;
  6639. pool->getwork_requested = 0;
  6640. pool->stale_shares = 0;
  6641. pool->discarded_work = 0;
  6642. pool->getfail_occasions = 0;
  6643. pool->remotefail_occasions = 0;
  6644. pool->last_share_time = 0;
  6645. pool->works = 0;
  6646. pool->diff1 = 0;
  6647. pool->diff_accepted = 0;
  6648. pool->diff_rejected = 0;
  6649. pool->diff_stale = 0;
  6650. pool->last_share_diff = 0;
  6651. pool->cgminer_stats.start_tv = total_tv_start;
  6652. pool->cgminer_stats.getwork_calls = 0;
  6653. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6654. pool->cgminer_stats.getwork_wait_max.tv_sec = 0;
  6655. pool->cgminer_stats.getwork_wait_max.tv_usec = 0;
  6656. pool->cgminer_pool_stats.getwork_calls = 0;
  6657. pool->cgminer_pool_stats.getwork_attempts = 0;
  6658. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6659. pool->cgminer_pool_stats.getwork_wait_max.tv_sec = 0;
  6660. pool->cgminer_pool_stats.getwork_wait_max.tv_usec = 0;
  6661. pool->cgminer_pool_stats.min_diff = 0;
  6662. pool->cgminer_pool_stats.max_diff = 0;
  6663. pool->cgminer_pool_stats.min_diff_count = 0;
  6664. pool->cgminer_pool_stats.max_diff_count = 0;
  6665. pool->cgminer_pool_stats.times_sent = 0;
  6666. pool->cgminer_pool_stats.bytes_sent = 0;
  6667. pool->cgminer_pool_stats.net_bytes_sent = 0;
  6668. pool->cgminer_pool_stats.times_received = 0;
  6669. pool->cgminer_pool_stats.bytes_received = 0;
  6670. pool->cgminer_pool_stats.net_bytes_received = 0;
  6671. }
  6672. zero_bestshare();
  6673. for (i = 0; i < total_devices; ++i) {
  6674. struct cgpu_info *cgpu = get_devices(i);
  6675. mutex_lock(&hash_lock);
  6676. cgpu->total_mhashes = 0;
  6677. cgpu->accepted = 0;
  6678. cgpu->rejected = 0;
  6679. cgpu->stale = 0;
  6680. cgpu->hw_errors = 0;
  6681. cgpu->utility = 0.0;
  6682. cgpu->utility_diff1 = 0;
  6683. cgpu->last_share_pool_time = 0;
  6684. cgpu->bad_diff1 = 0;
  6685. cgpu->diff1 = 0;
  6686. cgpu->diff_accepted = 0;
  6687. cgpu->diff_rejected = 0;
  6688. cgpu->diff_stale = 0;
  6689. cgpu->last_share_diff = 0;
  6690. cgpu->thread_fail_init_count = 0;
  6691. cgpu->thread_zero_hash_count = 0;
  6692. cgpu->thread_fail_queue_count = 0;
  6693. cgpu->dev_sick_idle_60_count = 0;
  6694. cgpu->dev_dead_idle_600_count = 0;
  6695. cgpu->dev_nostart_count = 0;
  6696. cgpu->dev_over_heat_count = 0;
  6697. cgpu->dev_thermal_cutoff_count = 0;
  6698. cgpu->dev_comms_error_count = 0;
  6699. cgpu->dev_throttle_count = 0;
  6700. cgpu->cgminer_stats.start_tv = total_tv_start;
  6701. cgpu->cgminer_stats.getwork_calls = 0;
  6702. cgpu->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6703. cgpu->cgminer_stats.getwork_wait_max.tv_sec = 0;
  6704. cgpu->cgminer_stats.getwork_wait_max.tv_usec = 0;
  6705. mutex_unlock(&hash_lock);
  6706. if (cgpu->drv->zero_stats)
  6707. cgpu->drv->zero_stats(cgpu);
  6708. }
  6709. }
  6710. #ifdef HAVE_CURSES
  6711. static
  6712. void loginput_mode(const int size)
  6713. {
  6714. clear_logwin();
  6715. loginput_size = size;
  6716. check_winsizes();
  6717. }
  6718. static void display_pools(void)
  6719. {
  6720. struct pool *pool;
  6721. int selected, i, j;
  6722. char input;
  6723. loginput_mode(7 + total_pools);
  6724. immedok(logwin, true);
  6725. updated:
  6726. for (j = 0; j < total_pools; j++) {
  6727. for (i = 0; i < total_pools; i++) {
  6728. pool = pools[i];
  6729. if (pool->prio != j)
  6730. continue;
  6731. if (pool == current_pool())
  6732. wattron(logwin, A_BOLD);
  6733. if (pool->enabled != POOL_ENABLED || pool->failover_only)
  6734. wattron(logwin, A_DIM);
  6735. wlogprint("%d: ", pool->prio);
  6736. switch (pool->enabled) {
  6737. case POOL_ENABLED:
  6738. if (pool->failover_only)
  6739. wlogprint("Failover ");
  6740. else
  6741. wlogprint("Enabled ");
  6742. break;
  6743. case POOL_DISABLED:
  6744. wlogprint("Disabled ");
  6745. break;
  6746. case POOL_REJECTING:
  6747. wlogprint("Rejectin ");
  6748. break;
  6749. case POOL_MISBEHAVING:
  6750. wlogprint("Misbehav ");
  6751. break;
  6752. }
  6753. _wlogprint(pool_proto_str(pool));
  6754. wlogprint(" Quota %d Pool %d: %s User:%s\n",
  6755. pool->quota,
  6756. pool->pool_no,
  6757. pool->rpc_url, pool->rpc_user);
  6758. wattroff(logwin, A_BOLD | A_DIM);
  6759. break; //for (i = 0; i < total_pools; i++)
  6760. }
  6761. }
  6762. retry:
  6763. wlogprint("\nCurrent pool management strategy: %s\n",
  6764. strategies[pool_strategy].s);
  6765. if (pool_strategy == POOL_ROTATE)
  6766. wlogprint("Set to rotate every %d minutes\n", opt_rotate_period);
  6767. wlogprint("[F]ailover only %s\n", opt_fail_only ? "enabled" : "disabled");
  6768. wlogprint("Pool [A]dd [R]emove [D]isable [E]nable [P]rioritize [Q]uota change\n");
  6769. wlogprint("[C]hange management strategy [S]witch pool [I]nformation\n");
  6770. wlogprint("Or press any other key to continue\n");
  6771. logwin_update();
  6772. input = getch();
  6773. if (!strncasecmp(&input, "a", 1)) {
  6774. if (opt_benchmark)
  6775. {
  6776. wlogprint("Cannot add pools in benchmark mode");
  6777. goto retry;
  6778. }
  6779. input_pool(true);
  6780. goto updated;
  6781. } else if (!strncasecmp(&input, "r", 1)) {
  6782. if (total_pools <= 1) {
  6783. wlogprint("Cannot remove last pool");
  6784. goto retry;
  6785. }
  6786. selected = curses_int("Select pool number");
  6787. if (selected < 0 || selected >= total_pools) {
  6788. wlogprint("Invalid selection\n");
  6789. goto retry;
  6790. }
  6791. pool = pools[selected];
  6792. if (pool == current_pool())
  6793. switch_pools(NULL);
  6794. if (pool == current_pool()) {
  6795. wlogprint("Unable to remove pool due to activity\n");
  6796. goto retry;
  6797. }
  6798. remove_pool(pool);
  6799. goto updated;
  6800. } else if (!strncasecmp(&input, "s", 1)) {
  6801. selected = curses_int("Select pool number");
  6802. if (selected < 0 || selected >= total_pools) {
  6803. wlogprint("Invalid selection\n");
  6804. goto retry;
  6805. }
  6806. pool = pools[selected];
  6807. pool->failover_only = false;
  6808. switch_pools(pool);
  6809. goto updated;
  6810. } else if (!strncasecmp(&input, "d", 1)) {
  6811. if (enabled_pools <= 1) {
  6812. wlogprint("Cannot disable last pool");
  6813. goto retry;
  6814. }
  6815. selected = curses_int("Select pool number");
  6816. if (selected < 0 || selected >= total_pools) {
  6817. wlogprint("Invalid selection\n");
  6818. goto retry;
  6819. }
  6820. pool = pools[selected];
  6821. disable_pool(pool, POOL_DISABLED);
  6822. goto updated;
  6823. } else if (!strncasecmp(&input, "e", 1)) {
  6824. selected = curses_int("Select pool number");
  6825. if (selected < 0 || selected >= total_pools) {
  6826. wlogprint("Invalid selection\n");
  6827. goto retry;
  6828. }
  6829. pool = pools[selected];
  6830. pool->failover_only = false;
  6831. enable_pool(pool);
  6832. goto updated;
  6833. } else if (!strncasecmp(&input, "c", 1)) {
  6834. for (i = 0; i <= TOP_STRATEGY; i++)
  6835. wlogprint("%d: %s\n", i, strategies[i].s);
  6836. selected = curses_int("Select strategy number type");
  6837. if (selected < 0 || selected > TOP_STRATEGY) {
  6838. wlogprint("Invalid selection\n");
  6839. goto retry;
  6840. }
  6841. if (selected == POOL_ROTATE) {
  6842. opt_rotate_period = curses_int("Select interval in minutes");
  6843. if (opt_rotate_period < 0 || opt_rotate_period > 9999) {
  6844. opt_rotate_period = 0;
  6845. wlogprint("Invalid selection\n");
  6846. goto retry;
  6847. }
  6848. }
  6849. mutex_lock(&lp_lock);
  6850. pool_strategy = selected;
  6851. pthread_cond_broadcast(&lp_cond);
  6852. mutex_unlock(&lp_lock);
  6853. switch_pools(NULL);
  6854. goto updated;
  6855. } else if (!strncasecmp(&input, "i", 1)) {
  6856. selected = curses_int("Select pool number");
  6857. if (selected < 0 || selected >= total_pools) {
  6858. wlogprint("Invalid selection\n");
  6859. goto retry;
  6860. }
  6861. pool = pools[selected];
  6862. display_pool_summary(pool);
  6863. goto retry;
  6864. } else if (!strncasecmp(&input, "q", 1)) {
  6865. selected = curses_int("Select pool number");
  6866. if (selected < 0 || selected >= total_pools) {
  6867. wlogprint("Invalid selection\n");
  6868. goto retry;
  6869. }
  6870. pool = pools[selected];
  6871. selected = curses_int("Set quota");
  6872. if (selected < 0) {
  6873. wlogprint("Invalid negative quota\n");
  6874. goto retry;
  6875. }
  6876. pool->quota = selected;
  6877. adjust_quota_gcd();
  6878. goto updated;
  6879. } else if (!strncasecmp(&input, "f", 1)) {
  6880. opt_fail_only ^= true;
  6881. goto updated;
  6882. } else if (!strncasecmp(&input, "p", 1)) {
  6883. char *prilist = curses_input("Enter new pool priority (comma separated list)");
  6884. if (!prilist)
  6885. {
  6886. wlogprint("Not changing priorities\n");
  6887. goto retry;
  6888. }
  6889. int res = prioritize_pools(prilist, &i);
  6890. free(prilist);
  6891. switch (res) {
  6892. case MSG_NOPOOL:
  6893. wlogprint("No pools\n");
  6894. goto retry;
  6895. case MSG_MISPID:
  6896. wlogprint("Missing pool id parameter\n");
  6897. goto retry;
  6898. case MSG_INVPID:
  6899. wlogprint("Invalid pool id %d - range is 0 - %d\n", i, total_pools - 1);
  6900. goto retry;
  6901. case MSG_DUPPID:
  6902. wlogprint("Duplicate pool specified %d\n", i);
  6903. goto retry;
  6904. case MSG_POOLPRIO:
  6905. default:
  6906. goto updated;
  6907. }
  6908. }
  6909. immedok(logwin, false);
  6910. loginput_mode(0);
  6911. }
  6912. static const char *summary_detail_level_str(void)
  6913. {
  6914. if (opt_compact)
  6915. return "compact";
  6916. if (opt_show_procs)
  6917. return "processors";
  6918. return "devices";
  6919. }
  6920. static void display_options(void)
  6921. {
  6922. int selected;
  6923. char input;
  6924. immedok(logwin, true);
  6925. loginput_mode(12);
  6926. retry:
  6927. clear_logwin();
  6928. wlogprint("[N]ormal [C]lear [S]ilent mode (disable all output)\n");
  6929. wlogprint("[D]ebug:%s\n[P]er-device:%s\n[Q]uiet:%s\n[V]erbose:%s\n"
  6930. "[R]PC debug:%s\n[W]orkTime details:%s\nsu[M]mary detail level:%s\n"
  6931. "[L]og interval:%d\nS[T]atistical counts: %s\n[Z]ero statistics\n",
  6932. opt_debug_console ? "on" : "off",
  6933. want_per_device_stats? "on" : "off",
  6934. opt_quiet ? "on" : "off",
  6935. opt_log_output ? "on" : "off",
  6936. opt_protocol ? "on" : "off",
  6937. opt_worktime ? "on" : "off",
  6938. summary_detail_level_str(),
  6939. opt_log_interval,
  6940. opt_weighed_stats ? "weighed" : "absolute");
  6941. wlogprint("Select an option or any other key to return\n");
  6942. logwin_update();
  6943. input = getch();
  6944. if (!strncasecmp(&input, "q", 1)) {
  6945. opt_quiet ^= true;
  6946. wlogprint("Quiet mode %s\n", opt_quiet ? "enabled" : "disabled");
  6947. goto retry;
  6948. } else if (!strncasecmp(&input, "v", 1)) {
  6949. opt_log_output ^= true;
  6950. if (opt_log_output)
  6951. opt_quiet = false;
  6952. wlogprint("Verbose mode %s\n", opt_log_output ? "enabled" : "disabled");
  6953. goto retry;
  6954. } else if (!strncasecmp(&input, "n", 1)) {
  6955. opt_log_output = false;
  6956. opt_debug_console = false;
  6957. opt_quiet = false;
  6958. opt_protocol = false;
  6959. opt_compact = false;
  6960. opt_show_procs = false;
  6961. devsummaryYOffset = 0;
  6962. want_per_device_stats = false;
  6963. wlogprint("Output mode reset to normal\n");
  6964. switch_logsize();
  6965. goto retry;
  6966. } else if (!strncasecmp(&input, "d", 1)) {
  6967. opt_debug = true;
  6968. opt_debug_console ^= true;
  6969. opt_log_output = opt_debug_console;
  6970. if (opt_debug_console)
  6971. opt_quiet = false;
  6972. wlogprint("Debug mode %s\n", opt_debug_console ? "enabled" : "disabled");
  6973. goto retry;
  6974. } else if (!strncasecmp(&input, "m", 1)) {
  6975. if (opt_compact)
  6976. opt_compact = false;
  6977. else
  6978. if (!opt_show_procs)
  6979. opt_show_procs = true;
  6980. else
  6981. {
  6982. opt_compact = true;
  6983. opt_show_procs = false;
  6984. devsummaryYOffset = 0;
  6985. }
  6986. wlogprint("su[M]mary detail level changed to: %s\n", summary_detail_level_str());
  6987. switch_logsize();
  6988. goto retry;
  6989. } else if (!strncasecmp(&input, "p", 1)) {
  6990. want_per_device_stats ^= true;
  6991. opt_log_output = want_per_device_stats;
  6992. wlogprint("Per-device stats %s\n", want_per_device_stats ? "enabled" : "disabled");
  6993. goto retry;
  6994. } else if (!strncasecmp(&input, "r", 1)) {
  6995. opt_protocol ^= true;
  6996. if (opt_protocol)
  6997. opt_quiet = false;
  6998. wlogprint("RPC protocol debugging %s\n", opt_protocol ? "enabled" : "disabled");
  6999. goto retry;
  7000. } else if (!strncasecmp(&input, "c", 1))
  7001. clear_logwin();
  7002. else if (!strncasecmp(&input, "l", 1)) {
  7003. selected = curses_int("Interval in seconds");
  7004. if (selected < 0 || selected > 9999) {
  7005. wlogprint("Invalid selection\n");
  7006. goto retry;
  7007. }
  7008. opt_log_interval = selected;
  7009. wlogprint("Log interval set to %d seconds\n", opt_log_interval);
  7010. goto retry;
  7011. } else if (!strncasecmp(&input, "s", 1)) {
  7012. opt_realquiet = true;
  7013. } else if (!strncasecmp(&input, "w", 1)) {
  7014. opt_worktime ^= true;
  7015. wlogprint("WorkTime details %s\n", opt_worktime ? "enabled" : "disabled");
  7016. goto retry;
  7017. } else if (!strncasecmp(&input, "t", 1)) {
  7018. opt_weighed_stats ^= true;
  7019. wlogprint("Now displaying %s statistics\n", opt_weighed_stats ? "weighed" : "absolute");
  7020. goto retry;
  7021. } else if (!strncasecmp(&input, "z", 1)) {
  7022. zero_stats();
  7023. goto retry;
  7024. }
  7025. immedok(logwin, false);
  7026. loginput_mode(0);
  7027. }
  7028. #endif
  7029. void default_save_file(char *filename)
  7030. {
  7031. #if defined(unix) || defined(__APPLE__)
  7032. if (getenv("HOME") && *getenv("HOME")) {
  7033. strcpy(filename, getenv("HOME"));
  7034. strcat(filename, "/");
  7035. }
  7036. else
  7037. strcpy(filename, "");
  7038. strcat(filename, ".bfgminer/");
  7039. mkdir(filename, 0777);
  7040. #else
  7041. strcpy(filename, "");
  7042. #endif
  7043. strcat(filename, def_conf);
  7044. }
  7045. #ifdef HAVE_CURSES
  7046. static void set_options(void)
  7047. {
  7048. int selected;
  7049. char input;
  7050. immedok(logwin, true);
  7051. loginput_mode(8);
  7052. retry:
  7053. wlogprint("\n[L]ongpoll: %s\n", want_longpoll ? "On" : "Off");
  7054. wlogprint("[Q]ueue: %d\n[S]cantime: %d\n[E]xpiry: %d\n[R]etries: %d\n"
  7055. "[W]rite config file\n[B]FGMiner restart\n",
  7056. opt_queue, opt_scantime, opt_expiry, opt_retries);
  7057. wlogprint("Select an option or any other key to return\n");
  7058. logwin_update();
  7059. input = getch();
  7060. if (!strncasecmp(&input, "q", 1)) {
  7061. selected = curses_int("Extra work items to queue");
  7062. if (selected < 0 || selected > 9999) {
  7063. wlogprint("Invalid selection\n");
  7064. goto retry;
  7065. }
  7066. opt_queue = selected;
  7067. goto retry;
  7068. } else if (!strncasecmp(&input, "l", 1)) {
  7069. if (want_longpoll)
  7070. stop_longpoll();
  7071. else
  7072. start_longpoll();
  7073. applog(LOG_WARNING, "Longpoll %s", want_longpoll ? "enabled" : "disabled");
  7074. goto retry;
  7075. } else if (!strncasecmp(&input, "s", 1)) {
  7076. selected = curses_int("Set scantime in seconds");
  7077. if (selected < 0 || selected > 9999) {
  7078. wlogprint("Invalid selection\n");
  7079. goto retry;
  7080. }
  7081. opt_scantime = selected;
  7082. goto retry;
  7083. } else if (!strncasecmp(&input, "e", 1)) {
  7084. selected = curses_int("Set expiry time in seconds");
  7085. if (selected < 0 || selected > 9999) {
  7086. wlogprint("Invalid selection\n");
  7087. goto retry;
  7088. }
  7089. opt_expiry = selected;
  7090. goto retry;
  7091. } else if (!strncasecmp(&input, "r", 1)) {
  7092. selected = curses_int("Retries before failing (-1 infinite)");
  7093. if (selected < -1 || selected > 9999) {
  7094. wlogprint("Invalid selection\n");
  7095. goto retry;
  7096. }
  7097. opt_retries = selected;
  7098. goto retry;
  7099. } else if (!strncasecmp(&input, "w", 1)) {
  7100. FILE *fcfg;
  7101. char *str, filename[PATH_MAX], prompt[PATH_MAX + 50];
  7102. default_save_file(filename);
  7103. snprintf(prompt, sizeof(prompt), "Config filename to write (Enter for default) [%s]", filename);
  7104. str = curses_input(prompt);
  7105. if (str) {
  7106. struct stat statbuf;
  7107. strcpy(filename, str);
  7108. free(str);
  7109. if (!stat(filename, &statbuf)) {
  7110. wlogprint("File exists, overwrite?\n");
  7111. input = getch();
  7112. if (strncasecmp(&input, "y", 1))
  7113. goto retry;
  7114. }
  7115. }
  7116. fcfg = fopen(filename, "w");
  7117. if (!fcfg) {
  7118. wlogprint("Cannot open or create file\n");
  7119. goto retry;
  7120. }
  7121. write_config(fcfg);
  7122. fclose(fcfg);
  7123. goto retry;
  7124. } else if (!strncasecmp(&input, "b", 1)) {
  7125. wlogprint("Are you sure?\n");
  7126. input = getch();
  7127. if (!strncasecmp(&input, "y", 1))
  7128. app_restart();
  7129. else
  7130. clear_logwin();
  7131. } else
  7132. clear_logwin();
  7133. loginput_mode(0);
  7134. immedok(logwin, false);
  7135. }
  7136. int scan_serial(const char *);
  7137. static
  7138. void _managetui_msg(const char *repr, const char **msg)
  7139. {
  7140. if (*msg)
  7141. {
  7142. applog(LOG_DEBUG, "ManageTUI: %"PRIpreprv": %s", repr, *msg);
  7143. wattron(logwin, A_BOLD);
  7144. wlogprint("%s", *msg);
  7145. wattroff(logwin, A_BOLD);
  7146. *msg = NULL;
  7147. }
  7148. logwin_update();
  7149. }
  7150. void manage_device(void)
  7151. {
  7152. char logline[256];
  7153. const char *msg = NULL;
  7154. struct cgpu_info *cgpu;
  7155. const struct device_drv *drv;
  7156. selecting_device = true;
  7157. immedok(logwin, true);
  7158. loginput_mode(12);
  7159. devchange:
  7160. if (unlikely(!total_devices))
  7161. {
  7162. clear_logwin();
  7163. wlogprint("(no devices)\n");
  7164. wlogprint("[Plus] Add device(s) [Enter] Close device manager\n");
  7165. _managetui_msg("(none)", &msg);
  7166. int input = getch();
  7167. switch (input)
  7168. {
  7169. case '+': case '=': // add new device
  7170. goto addnew;
  7171. default:
  7172. goto out;
  7173. }
  7174. }
  7175. cgpu = devices[selected_device];
  7176. drv = cgpu->drv;
  7177. refresh_devstatus();
  7178. refresh:
  7179. clear_logwin();
  7180. wlogprint("Select processor to manage using up/down arrow keys\n");
  7181. get_statline3(logline, sizeof(logline), cgpu, true, true);
  7182. wattron(logwin, A_BOLD);
  7183. wlogprint("%s", logline);
  7184. wattroff(logwin, A_BOLD);
  7185. wlogprint("\n");
  7186. if (cgpu->dev_manufacturer)
  7187. wlogprint(" %s from %s\n", (cgpu->dev_product ?: "Device"), cgpu->dev_manufacturer);
  7188. else
  7189. if (cgpu->dev_product)
  7190. wlogprint(" %s\n", cgpu->dev_product);
  7191. if (cgpu->dev_serial)
  7192. wlogprint("Serial: %s\n", cgpu->dev_serial);
  7193. if (cgpu->kname)
  7194. wlogprint("Kernel: %s\n", cgpu->kname);
  7195. if (drv->proc_wlogprint_status && likely(cgpu->status != LIFE_INIT))
  7196. drv->proc_wlogprint_status(cgpu);
  7197. wlogprint("\n");
  7198. // TODO: Last share at TIMESTAMP on pool N
  7199. // TODO: Custom device info/commands
  7200. if (cgpu->deven != DEV_ENABLED)
  7201. wlogprint("[E]nable ");
  7202. if (cgpu->deven != DEV_DISABLED)
  7203. wlogprint("[D]isable ");
  7204. if (drv->identify_device)
  7205. wlogprint("[I]dentify ");
  7206. if (drv->proc_tui_wlogprint_choices && likely(cgpu->status != LIFE_INIT))
  7207. drv->proc_tui_wlogprint_choices(cgpu);
  7208. wlogprint("\n");
  7209. wlogprint("[Slash] Find processor [Plus] Add device(s) [Enter] Close device manager\n");
  7210. _managetui_msg(cgpu->proc_repr, &msg);
  7211. while (true)
  7212. {
  7213. int input = getch();
  7214. applog(LOG_DEBUG, "ManageTUI: %"PRIpreprv": (choice %d)", cgpu->proc_repr, input);
  7215. switch (input) {
  7216. case 'd': case 'D':
  7217. if (cgpu->deven == DEV_DISABLED)
  7218. msg = "Processor already disabled\n";
  7219. else
  7220. {
  7221. cgpu->deven = DEV_DISABLED;
  7222. msg = "Processor being disabled\n";
  7223. }
  7224. goto refresh;
  7225. case 'e': case 'E':
  7226. if (cgpu->deven == DEV_ENABLED)
  7227. msg = "Processor already enabled\n";
  7228. else
  7229. {
  7230. proc_enable(cgpu);
  7231. msg = "Processor being enabled\n";
  7232. }
  7233. goto refresh;
  7234. case 'i': case 'I':
  7235. if (drv->identify_device && drv->identify_device(cgpu))
  7236. msg = "Identify command sent\n";
  7237. else
  7238. goto key_default;
  7239. goto refresh;
  7240. case KEY_DOWN:
  7241. if (selected_device >= total_devices - 1)
  7242. break;
  7243. ++selected_device;
  7244. goto devchange;
  7245. case KEY_UP:
  7246. if (selected_device <= 0)
  7247. break;
  7248. --selected_device;
  7249. goto devchange;
  7250. case KEY_NPAGE:
  7251. {
  7252. if (selected_device >= total_devices - 1)
  7253. break;
  7254. struct cgpu_info *mdev = devices[selected_device]->device;
  7255. do {
  7256. ++selected_device;
  7257. } while (devices[selected_device]->device == mdev && selected_device < total_devices - 1);
  7258. goto devchange;
  7259. }
  7260. case KEY_PPAGE:
  7261. {
  7262. if (selected_device <= 0)
  7263. break;
  7264. struct cgpu_info *mdev = devices[selected_device]->device;
  7265. do {
  7266. --selected_device;
  7267. } while (devices[selected_device]->device == mdev && selected_device > 0);
  7268. goto devchange;
  7269. }
  7270. case '/': case '?': // find device
  7271. {
  7272. static char *pattern = NULL;
  7273. char *newpattern = curses_input("Enter pattern");
  7274. if (newpattern)
  7275. {
  7276. free(pattern);
  7277. pattern = newpattern;
  7278. }
  7279. else
  7280. if (!pattern)
  7281. pattern = calloc(1, 1);
  7282. int match = cgpu_search(pattern, selected_device + 1);
  7283. if (match == -1)
  7284. {
  7285. msg = "Couldn't find device\n";
  7286. goto refresh;
  7287. }
  7288. selected_device = match;
  7289. goto devchange;
  7290. }
  7291. case '+': case '=': // add new device
  7292. {
  7293. addnew:
  7294. clear_logwin();
  7295. _wlogprint(
  7296. "Enter \"auto\", \"all\", or a serial port to probe for mining devices.\n"
  7297. "Prefix by a driver name and colon to only probe a specific driver.\n"
  7298. "For example: erupter:"
  7299. #ifdef WIN32
  7300. "\\\\.\\COM40"
  7301. #elif defined(__APPLE__)
  7302. "/dev/cu.SLAB_USBtoUART"
  7303. #else
  7304. "/dev/ttyUSB39"
  7305. #endif
  7306. "\n"
  7307. );
  7308. char *scanser = curses_input("Enter target");
  7309. if (scan_serial(scanser))
  7310. {
  7311. selected_device = total_devices - 1;
  7312. msg = "Device scan succeeded\n";
  7313. }
  7314. else
  7315. msg = "No new devices found\n";
  7316. goto devchange;
  7317. }
  7318. case 'Q': case 'q':
  7319. case KEY_BREAK: case KEY_BACKSPACE: case KEY_CANCEL: case KEY_CLOSE: case KEY_EXIT:
  7320. case '\x1b': // ESC
  7321. case KEY_ENTER:
  7322. case '\r': // Ctrl-M on Windows, with nonl
  7323. #ifdef PADENTER
  7324. case PADENTER: // pdcurses, used by Enter key on Windows with nonl
  7325. #endif
  7326. case '\n':
  7327. goto out;
  7328. default:
  7329. ;
  7330. key_default:
  7331. if (drv->proc_tui_handle_choice && likely(drv_ready(cgpu)))
  7332. {
  7333. msg = drv->proc_tui_handle_choice(cgpu, input);
  7334. if (msg)
  7335. goto refresh;
  7336. }
  7337. }
  7338. }
  7339. out:
  7340. selecting_device = false;
  7341. loginput_mode(0);
  7342. immedok(logwin, false);
  7343. }
  7344. void show_help(void)
  7345. {
  7346. loginput_mode(11);
  7347. // NOTE: wlogprint is a macro with a buffer limit
  7348. _wlogprint(
  7349. "LU: oldest explicit work update currently being used for new work\n"
  7350. "ST: work in queue | F: network fails | NB: new blocks detected\n"
  7351. "AS: shares being submitted | BW: bandwidth (up/down)\n"
  7352. "E: # shares * diff per 2kB bw | I: expected income | BS: best share ever found\n"
  7353. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7354. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7355. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7356. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_BTEE
  7357. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7358. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7359. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_BTEE U8_HLINE U8_HLINE U8_HLINE
  7360. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7361. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7362. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7363. "\n"
  7364. "devices/processors hashing (only for totals line), hottest temperature\n"
  7365. );
  7366. wlogprint(
  7367. "hashrates: %ds decaying / all-time average / all-time average (effective)\n"
  7368. , opt_log_interval);
  7369. _wlogprint(
  7370. "A: accepted shares | R: rejected+discarded(% of total)\n"
  7371. "HW: hardware errors / % nonces invalid\n"
  7372. "\n"
  7373. "Press any key to clear"
  7374. );
  7375. logwin_update();
  7376. getch();
  7377. loginput_mode(0);
  7378. }
  7379. static void *input_thread(void __maybe_unused *userdata)
  7380. {
  7381. RenameThread("input");
  7382. if (!curses_active)
  7383. return NULL;
  7384. while (1) {
  7385. int input;
  7386. input = getch();
  7387. switch (input) {
  7388. case 'h': case 'H': case '?':
  7389. case KEY_F(1):
  7390. show_help();
  7391. break;
  7392. case 'q': case 'Q':
  7393. kill_work();
  7394. return NULL;
  7395. case 'd': case 'D':
  7396. display_options();
  7397. break;
  7398. case 'm': case 'M':
  7399. manage_device();
  7400. break;
  7401. case 'p': case 'P':
  7402. display_pools();
  7403. break;
  7404. case 's': case 'S':
  7405. set_options();
  7406. break;
  7407. #ifdef HAVE_CURSES
  7408. case KEY_DOWN:
  7409. {
  7410. const int visible_lines = logcursor - devcursor;
  7411. const int invisible_lines = total_lines - visible_lines;
  7412. if (devsummaryYOffset <= -invisible_lines)
  7413. break;
  7414. devsummaryYOffset -= 2;
  7415. }
  7416. case KEY_UP:
  7417. if (devsummaryYOffset == 0)
  7418. break;
  7419. ++devsummaryYOffset;
  7420. refresh_devstatus();
  7421. break;
  7422. case KEY_NPAGE:
  7423. {
  7424. const int visible_lines = logcursor - devcursor;
  7425. const int invisible_lines = total_lines - visible_lines;
  7426. if (devsummaryYOffset - visible_lines <= -invisible_lines)
  7427. devsummaryYOffset = -invisible_lines;
  7428. else
  7429. devsummaryYOffset -= visible_lines;
  7430. refresh_devstatus();
  7431. break;
  7432. }
  7433. case KEY_PPAGE:
  7434. {
  7435. const int visible_lines = logcursor - devcursor;
  7436. if (devsummaryYOffset + visible_lines >= 0)
  7437. devsummaryYOffset = 0;
  7438. else
  7439. devsummaryYOffset += visible_lines;
  7440. refresh_devstatus();
  7441. break;
  7442. }
  7443. #endif
  7444. }
  7445. if (opt_realquiet) {
  7446. disable_curses();
  7447. break;
  7448. }
  7449. }
  7450. return NULL;
  7451. }
  7452. #endif
  7453. static void *api_thread(void *userdata)
  7454. {
  7455. struct thr_info *mythr = userdata;
  7456. pthread_detach(pthread_self());
  7457. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  7458. RenameThread("rpc");
  7459. api(api_thr_id);
  7460. mythr->has_pth = false;
  7461. return NULL;
  7462. }
  7463. void thread_reportin(struct thr_info *thr)
  7464. {
  7465. cgtime(&thr->last);
  7466. thr->cgpu->status = LIFE_WELL;
  7467. thr->getwork = 0;
  7468. thr->cgpu->device_last_well = time(NULL);
  7469. }
  7470. void thread_reportout(struct thr_info *thr)
  7471. {
  7472. thr->getwork = time(NULL);
  7473. }
  7474. static void hashmeter(int thr_id, struct timeval *diff,
  7475. uint64_t hashes_done)
  7476. {
  7477. char logstatusline[256];
  7478. struct timeval temp_tv_end, total_diff;
  7479. double secs;
  7480. double local_secs;
  7481. static double local_mhashes_done = 0;
  7482. double local_mhashes = (double)hashes_done / 1000000.0;
  7483. bool showlog = false;
  7484. char cHr[ALLOC_H2B_NOUNIT+1], aHr[ALLOC_H2B_NOUNIT+1], uHr[ALLOC_H2B_SPACED+3+1];
  7485. char rejpcbuf[6];
  7486. char bnbuf[6];
  7487. struct thr_info *thr;
  7488. /* Update the last time this thread reported in */
  7489. if (thr_id >= 0) {
  7490. thr = get_thread(thr_id);
  7491. cgtime(&(thr->last));
  7492. thr->cgpu->device_last_well = time(NULL);
  7493. }
  7494. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  7495. /* So we can call hashmeter from a non worker thread */
  7496. if (thr_id >= 0) {
  7497. struct cgpu_info *cgpu = thr->cgpu;
  7498. int threadobj = cgpu->threads ?: 1;
  7499. double thread_rolling = 0.0;
  7500. int i;
  7501. applog(LOG_DEBUG, "[thread %d: %"PRIu64" hashes, %.1f khash/sec]",
  7502. thr_id, hashes_done, hashes_done / 1000 / secs);
  7503. /* Rolling average for each thread and each device */
  7504. decay_time(&thr->rolling, local_mhashes / secs, secs);
  7505. for (i = 0; i < threadobj; i++)
  7506. thread_rolling += cgpu->thr[i]->rolling;
  7507. mutex_lock(&hash_lock);
  7508. decay_time(&cgpu->rolling, thread_rolling, secs);
  7509. cgpu->total_mhashes += local_mhashes;
  7510. mutex_unlock(&hash_lock);
  7511. // If needed, output detailed, per-device stats
  7512. if (want_per_device_stats) {
  7513. struct timeval now;
  7514. struct timeval elapsed;
  7515. struct timeval *last_msg_tv = opt_show_procs ? &thr->cgpu->last_message_tv : &thr->cgpu->device->last_message_tv;
  7516. cgtime(&now);
  7517. timersub(&now, last_msg_tv, &elapsed);
  7518. if (opt_log_interval <= elapsed.tv_sec) {
  7519. struct cgpu_info *cgpu = thr->cgpu;
  7520. char logline[255];
  7521. *last_msg_tv = now;
  7522. get_statline(logline, sizeof(logline), cgpu);
  7523. if (!curses_active) {
  7524. printf("\n%s\r", logline);
  7525. fflush(stdout);
  7526. } else
  7527. applog(LOG_INFO, "%s", logline);
  7528. }
  7529. }
  7530. }
  7531. /* Totals are updated by all threads so can race without locking */
  7532. mutex_lock(&hash_lock);
  7533. cgtime(&temp_tv_end);
  7534. timersub(&temp_tv_end, &total_tv_start, &total_diff);
  7535. total_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  7536. timersub(&temp_tv_end, &total_tv_end, &total_diff);
  7537. total_mhashes_done += local_mhashes;
  7538. local_mhashes_done += local_mhashes;
  7539. /* Only update with opt_log_interval */
  7540. if (total_diff.tv_sec < opt_log_interval)
  7541. goto out_unlock;
  7542. showlog = true;
  7543. cgtime(&total_tv_end);
  7544. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  7545. decay_time(&total_rolling, local_mhashes_done / local_secs, local_secs);
  7546. global_hashrate = ((unsigned long long)lround(total_rolling)) * 1000000;
  7547. double wtotal = (total_diff_accepted + total_diff_rejected + total_diff_stale);
  7548. multi_format_unit_array2(
  7549. ((char*[]){cHr, aHr, uHr}),
  7550. ((size_t[]){sizeof(cHr), sizeof(aHr), sizeof(uHr)}),
  7551. true, "h/s", H2B_SHORT,
  7552. 3,
  7553. 1e6*total_rolling,
  7554. 1e6*total_mhashes_done / total_secs,
  7555. utility_to_hashrate(total_diff1 * (wtotal ? (total_diff_accepted / wtotal) : 1) * 60 / total_secs));
  7556. int ui_accepted, ui_rejected, ui_stale;
  7557. if (opt_weighed_stats)
  7558. {
  7559. ui_accepted = total_diff_accepted;
  7560. ui_rejected = total_diff_rejected;
  7561. ui_stale = total_diff_stale;
  7562. }
  7563. else
  7564. {
  7565. ui_accepted = total_accepted;
  7566. ui_rejected = total_rejected;
  7567. ui_stale = total_stale;
  7568. }
  7569. #ifdef HAVE_CURSES
  7570. if (curses_active_locked()) {
  7571. float temp = 0;
  7572. struct cgpu_info *proc, *last_working_dev = NULL;
  7573. int i, working_devs = 0, working_procs = 0;
  7574. int divx;
  7575. bool bad = false;
  7576. // Find the highest temperature of all processors
  7577. for (i = 0; i < total_devices; ++i)
  7578. {
  7579. proc = get_devices(i);
  7580. if (proc->temp > temp)
  7581. temp = proc->temp;
  7582. if (unlikely(proc->deven == DEV_DISABLED))
  7583. ; // Just need to block it off from both conditions
  7584. else
  7585. if (likely(proc->status == LIFE_WELL && proc->deven == DEV_ENABLED))
  7586. {
  7587. if (proc->rolling > .1)
  7588. {
  7589. ++working_procs;
  7590. if (proc->device != last_working_dev)
  7591. {
  7592. ++working_devs;
  7593. last_working_dev = proc->device;
  7594. }
  7595. }
  7596. }
  7597. else
  7598. bad = true;
  7599. }
  7600. if (working_devs == working_procs)
  7601. snprintf(statusline, sizeof(statusline), "%s%d ", bad ? U8_BAD_START : "", working_devs);
  7602. else
  7603. snprintf(statusline, sizeof(statusline), "%s%d/%d ", bad ? U8_BAD_START : "", working_devs, working_procs);
  7604. divx = 7;
  7605. if (opt_show_procs && !opt_compact)
  7606. divx += max_lpdigits;
  7607. if (bad)
  7608. {
  7609. divx += sizeof(U8_BAD_START)-1;
  7610. strcpy(&statusline[divx], U8_BAD_END);
  7611. divx += sizeof(U8_BAD_END)-1;
  7612. }
  7613. temperature_column(&statusline[divx], sizeof(statusline)-divx, true, &temp);
  7614. format_statline(statusline, sizeof(statusline),
  7615. cHr, aHr,
  7616. uHr,
  7617. ui_accepted,
  7618. ui_rejected,
  7619. ui_stale,
  7620. total_diff_rejected + total_diff_stale, total_diff_accepted,
  7621. hw_errors,
  7622. total_bad_diff1, total_bad_diff1 + total_diff1);
  7623. unlock_curses();
  7624. }
  7625. #endif
  7626. // Add a space
  7627. memmove(&uHr[6], &uHr[5], strlen(&uHr[5]) + 1);
  7628. uHr[5] = ' ';
  7629. percentf4(rejpcbuf, sizeof(rejpcbuf), total_diff_rejected + total_diff_stale, total_diff_accepted);
  7630. percentf4(bnbuf, sizeof(bnbuf), total_bad_diff1, total_diff1);
  7631. snprintf(logstatusline, sizeof(logstatusline),
  7632. "%s%ds:%s avg:%s u:%s | A:%d R:%d+%d(%s) HW:%d/%s",
  7633. want_per_device_stats ? "ALL " : "",
  7634. opt_log_interval,
  7635. cHr, aHr,
  7636. uHr,
  7637. ui_accepted,
  7638. ui_rejected,
  7639. ui_stale,
  7640. rejpcbuf,
  7641. hw_errors,
  7642. bnbuf
  7643. );
  7644. local_mhashes_done = 0;
  7645. out_unlock:
  7646. mutex_unlock(&hash_lock);
  7647. if (showlog) {
  7648. if (!curses_active) {
  7649. if (want_per_device_stats)
  7650. printf("\n%s\r", logstatusline);
  7651. else
  7652. {
  7653. const int logstatusline_len = strlen(logstatusline);
  7654. int padding;
  7655. if (last_logstatusline_len > logstatusline_len)
  7656. padding = (last_logstatusline_len - logstatusline_len);
  7657. else
  7658. {
  7659. padding = 0;
  7660. if (last_logstatusline_len == -1)
  7661. puts("");
  7662. }
  7663. printf("%s%*s\r", logstatusline, padding, "");
  7664. last_logstatusline_len = logstatusline_len;
  7665. }
  7666. fflush(stdout);
  7667. } else
  7668. applog(LOG_INFO, "%s", logstatusline);
  7669. }
  7670. }
  7671. void hashmeter2(struct thr_info *thr)
  7672. {
  7673. struct timeval tv_now, tv_elapsed;
  7674. timerclear(&thr->tv_hashes_done);
  7675. cgtime(&tv_now);
  7676. timersub(&tv_now, &thr->tv_lastupdate, &tv_elapsed);
  7677. /* Update the hashmeter at most 5 times per second */
  7678. if ((thr->hashes_done && (tv_elapsed.tv_sec > 0 || tv_elapsed.tv_usec > 200000)) ||
  7679. tv_elapsed.tv_sec >= opt_log_interval) {
  7680. hashmeter(thr->id, &tv_elapsed, thr->hashes_done);
  7681. thr->hashes_done = 0;
  7682. thr->tv_lastupdate = tv_now;
  7683. }
  7684. }
  7685. static void stratum_share_result(json_t *val, json_t *res_val, json_t *err_val,
  7686. struct stratum_share *sshare)
  7687. {
  7688. struct work *work = sshare->work;
  7689. share_result(val, res_val, err_val, work, false, "");
  7690. }
  7691. /* Parses stratum json responses and tries to find the id that the request
  7692. * matched to and treat it accordingly. */
  7693. bool parse_stratum_response(struct pool *pool, char *s)
  7694. {
  7695. json_t *val = NULL, *err_val, *res_val, *id_val;
  7696. struct stratum_share *sshare;
  7697. json_error_t err;
  7698. bool ret = false;
  7699. int id;
  7700. val = JSON_LOADS(s, &err);
  7701. if (!val) {
  7702. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  7703. goto out;
  7704. }
  7705. res_val = json_object_get(val, "result");
  7706. err_val = json_object_get(val, "error");
  7707. id_val = json_object_get(val, "id");
  7708. if (json_is_null(id_val) || !id_val) {
  7709. char *ss;
  7710. if (err_val)
  7711. ss = json_dumps(err_val, JSON_INDENT(3));
  7712. else
  7713. ss = strdup("(unknown reason)");
  7714. applog(LOG_INFO, "JSON-RPC non method decode failed: %s", ss);
  7715. free(ss);
  7716. goto out;
  7717. }
  7718. if (!json_is_integer(id_val)) {
  7719. if (json_is_string(id_val)
  7720. && !strncmp(json_string_value(id_val), "txlist", 6))
  7721. {
  7722. const bool is_array = json_is_array(res_val);
  7723. applog(LOG_DEBUG, "Received %s for pool %u job %s",
  7724. is_array ? "transaction list" : "no-transaction-list response",
  7725. pool->pool_no, &json_string_value(id_val)[6]);
  7726. if (!is_array)
  7727. {
  7728. // No need to wait for a timeout
  7729. timer_unset(&pool->swork.tv_transparency);
  7730. pool_set_opaque(pool, true);
  7731. goto fishy;
  7732. }
  7733. if (strcmp(json_string_value(id_val) + 6, pool->swork.job_id))
  7734. // We only care about a transaction list for the current job id
  7735. goto fishy;
  7736. // Check that the transactions actually hash to the merkle links
  7737. {
  7738. unsigned maxtx = 1 << pool->swork.merkles;
  7739. unsigned mintx = maxtx >> 1;
  7740. --maxtx;
  7741. unsigned acttx = (unsigned)json_array_size(res_val);
  7742. if (acttx < mintx || acttx > maxtx) {
  7743. applog(LOG_WARNING, "Pool %u is sending mismatched block contents to us (%u is not %u-%u)",
  7744. pool->pool_no, acttx, mintx, maxtx);
  7745. goto fishy;
  7746. }
  7747. // TODO: Check hashes match actual merkle links
  7748. }
  7749. pool_set_opaque(pool, false);
  7750. timer_unset(&pool->swork.tv_transparency);
  7751. fishy:
  7752. ret = true;
  7753. }
  7754. goto out;
  7755. }
  7756. id = json_integer_value(id_val);
  7757. mutex_lock(&sshare_lock);
  7758. HASH_FIND_INT(stratum_shares, &id, sshare);
  7759. if (sshare)
  7760. HASH_DEL(stratum_shares, sshare);
  7761. mutex_unlock(&sshare_lock);
  7762. if (!sshare) {
  7763. double pool_diff;
  7764. /* Since the share is untracked, we can only guess at what the
  7765. * work difficulty is based on the current pool diff. */
  7766. cg_rlock(&pool->data_lock);
  7767. pool_diff = target_diff(pool->swork.target);
  7768. cg_runlock(&pool->data_lock);
  7769. if (json_is_true(res_val)) {
  7770. struct mining_goal_info * const goal = pool->goal;
  7771. applog(LOG_NOTICE, "Accepted untracked stratum share from pool %d", pool->pool_no);
  7772. /* We don't know what device this came from so we can't
  7773. * attribute the work to the relevant cgpu */
  7774. mutex_lock(&stats_lock);
  7775. total_accepted++;
  7776. pool->accepted++;
  7777. total_diff_accepted += pool_diff;
  7778. pool->diff_accepted += pool_diff;
  7779. goal->diff_accepted += pool_diff;
  7780. mutex_unlock(&stats_lock);
  7781. } else {
  7782. applog(LOG_NOTICE, "Rejected untracked stratum share from pool %d", pool->pool_no);
  7783. mutex_lock(&stats_lock);
  7784. total_rejected++;
  7785. pool->rejected++;
  7786. total_diff_rejected += pool_diff;
  7787. pool->diff_rejected += pool_diff;
  7788. mutex_unlock(&stats_lock);
  7789. }
  7790. goto out;
  7791. }
  7792. else {
  7793. mutex_lock(&submitting_lock);
  7794. --total_submitting;
  7795. mutex_unlock(&submitting_lock);
  7796. }
  7797. stratum_share_result(val, res_val, err_val, sshare);
  7798. free_work(sshare->work);
  7799. free(sshare);
  7800. ret = true;
  7801. out:
  7802. if (val)
  7803. json_decref(val);
  7804. return ret;
  7805. }
  7806. static void shutdown_stratum(struct pool *pool)
  7807. {
  7808. // Shut down Stratum as if we never had it
  7809. pool->stratum_active = false;
  7810. pool->stratum_init = false;
  7811. pool->has_stratum = false;
  7812. shutdown(pool->sock, SHUT_RDWR);
  7813. free(pool->stratum_url);
  7814. if (pool->sockaddr_url == pool->stratum_url)
  7815. pool->sockaddr_url = NULL;
  7816. pool->stratum_url = NULL;
  7817. }
  7818. void clear_stratum_shares(struct pool *pool)
  7819. {
  7820. int my_mining_threads = mining_threads; // Cached outside of locking
  7821. struct stratum_share *sshare, *tmpshare;
  7822. struct work *work;
  7823. struct cgpu_info *cgpu;
  7824. double diff_cleared = 0;
  7825. double thr_diff_cleared[my_mining_threads];
  7826. int cleared = 0;
  7827. int thr_cleared[my_mining_threads];
  7828. // NOTE: This is per-thread rather than per-device to avoid getting devices lock in stratum_shares loop
  7829. for (int i = 0; i < my_mining_threads; ++i)
  7830. {
  7831. thr_diff_cleared[i] = 0;
  7832. thr_cleared[i] = 0;
  7833. }
  7834. mutex_lock(&sshare_lock);
  7835. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  7836. work = sshare->work;
  7837. if (sshare->work->pool == pool && work->thr_id < my_mining_threads) {
  7838. HASH_DEL(stratum_shares, sshare);
  7839. sharelog("disconnect", work);
  7840. diff_cleared += sshare->work->work_difficulty;
  7841. thr_diff_cleared[work->thr_id] += work->work_difficulty;
  7842. ++thr_cleared[work->thr_id];
  7843. free_work(sshare->work);
  7844. free(sshare);
  7845. cleared++;
  7846. }
  7847. }
  7848. mutex_unlock(&sshare_lock);
  7849. if (cleared) {
  7850. applog(LOG_WARNING, "Lost %d shares due to stratum disconnect on pool %d", cleared, pool->pool_no);
  7851. mutex_lock(&stats_lock);
  7852. pool->stale_shares += cleared;
  7853. total_stale += cleared;
  7854. pool->diff_stale += diff_cleared;
  7855. total_diff_stale += diff_cleared;
  7856. for (int i = 0; i < my_mining_threads; ++i)
  7857. if (thr_cleared[i])
  7858. {
  7859. cgpu = get_thr_cgpu(i);
  7860. cgpu->diff_stale += thr_diff_cleared[i];
  7861. cgpu->stale += thr_cleared[i];
  7862. }
  7863. mutex_unlock(&stats_lock);
  7864. mutex_lock(&submitting_lock);
  7865. total_submitting -= cleared;
  7866. mutex_unlock(&submitting_lock);
  7867. }
  7868. }
  7869. static void resubmit_stratum_shares(struct pool *pool)
  7870. {
  7871. struct stratum_share *sshare, *tmpshare;
  7872. struct work *work;
  7873. unsigned resubmitted = 0;
  7874. mutex_lock(&sshare_lock);
  7875. mutex_lock(&submitting_lock);
  7876. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  7877. if (sshare->work->pool != pool)
  7878. continue;
  7879. HASH_DEL(stratum_shares, sshare);
  7880. work = sshare->work;
  7881. DL_APPEND(submit_waiting, work);
  7882. free(sshare);
  7883. ++resubmitted;
  7884. }
  7885. mutex_unlock(&submitting_lock);
  7886. mutex_unlock(&sshare_lock);
  7887. if (resubmitted) {
  7888. notifier_wake(submit_waiting_notifier);
  7889. applog(LOG_DEBUG, "Resubmitting %u shares due to stratum disconnect on pool %u", resubmitted, pool->pool_no);
  7890. }
  7891. }
  7892. static void clear_pool_work(struct pool *pool)
  7893. {
  7894. struct work *work, *tmp;
  7895. int cleared = 0;
  7896. mutex_lock(stgd_lock);
  7897. HASH_ITER(hh, staged_work, work, tmp) {
  7898. if (work->pool == pool) {
  7899. HASH_DEL(staged_work, work);
  7900. free_work(work);
  7901. cleared++;
  7902. staged_full = false;
  7903. }
  7904. }
  7905. mutex_unlock(stgd_lock);
  7906. }
  7907. static int cp_prio(void)
  7908. {
  7909. int prio;
  7910. cg_rlock(&control_lock);
  7911. prio = currentpool->prio;
  7912. cg_runlock(&control_lock);
  7913. return prio;
  7914. }
  7915. /* We only need to maintain a secondary pool connection when we need the
  7916. * capacity to get work from the backup pools while still on the primary */
  7917. static bool cnx_needed(struct pool *pool)
  7918. {
  7919. struct pool *cp;
  7920. // We want to keep a connection open for rejecting or misbehaving pools, to detect when/if they change their tune
  7921. if (pool->enabled == POOL_DISABLED)
  7922. return false;
  7923. /* Idle stratum pool needs something to kick it alive again */
  7924. if (pool->has_stratum && pool->idle)
  7925. return true;
  7926. /* Getwork pools without opt_fail_only need backup pools up to be able
  7927. * to leak shares */
  7928. cp = current_pool();
  7929. if (pool_actively_desired(pool, cp))
  7930. return true;
  7931. if (!pool_localgen(cp) && (!opt_fail_only || !cp->hdr_path))
  7932. return true;
  7933. /* Keep the connection open to allow any stray shares to be submitted
  7934. * on switching pools for 2 minutes. */
  7935. if (timer_elapsed(&pool->tv_last_work_time, NULL) < 120)
  7936. return true;
  7937. /* If the pool has only just come to life and is higher priority than
  7938. * the current pool keep the connection open so we can fail back to
  7939. * it. */
  7940. if (pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  7941. return true;
  7942. if (pool_unworkable(cp))
  7943. return true;
  7944. /* We've run out of work, bring anything back to life. */
  7945. if (no_work)
  7946. return true;
  7947. // If the current pool lacks its own block change detection, see if we are needed for that
  7948. if (pool_active_lp_pool(cp) == pool)
  7949. return true;
  7950. return false;
  7951. }
  7952. static void wait_lpcurrent(struct pool *pool);
  7953. static void pool_resus(struct pool *pool);
  7954. static void stratum_resumed(struct pool *pool)
  7955. {
  7956. if (!pool->stratum_notify)
  7957. return;
  7958. if (pool_tclear(pool, &pool->idle)) {
  7959. applog(LOG_INFO, "Stratum connection to pool %d resumed", pool->pool_no);
  7960. pool_resus(pool);
  7961. }
  7962. }
  7963. static bool supports_resume(struct pool *pool)
  7964. {
  7965. bool ret;
  7966. cg_rlock(&pool->data_lock);
  7967. ret = (pool->sessionid != NULL);
  7968. cg_runlock(&pool->data_lock);
  7969. return ret;
  7970. }
  7971. static bool pools_active;
  7972. /* One stratum thread per pool that has stratum waits on the socket checking
  7973. * for new messages and for the integrity of the socket connection. We reset
  7974. * the connection based on the integrity of the receive side only as the send
  7975. * side will eventually expire data it fails to send. */
  7976. static void *stratum_thread(void *userdata)
  7977. {
  7978. struct pool *pool = (struct pool *)userdata;
  7979. pthread_detach(pthread_self());
  7980. char threadname[20];
  7981. snprintf(threadname, 20, "stratum%u", pool->pool_no);
  7982. RenameThread(threadname);
  7983. srand(time(NULL) + (intptr_t)userdata);
  7984. while (42) {
  7985. struct timeval timeout;
  7986. int sel_ret;
  7987. fd_set rd;
  7988. char *s;
  7989. int sock;
  7990. if (unlikely(!pool->has_stratum))
  7991. break;
  7992. /* Check to see whether we need to maintain this connection
  7993. * indefinitely or just bring it up when we switch to this
  7994. * pool */
  7995. while (true)
  7996. {
  7997. sock = pool->sock;
  7998. if (sock == INVSOCK)
  7999. applog(LOG_DEBUG, "Pool %u: Invalid socket, suspending",
  8000. pool->pool_no);
  8001. else
  8002. if (!sock_full(pool) && !cnx_needed(pool) && pools_active)
  8003. applog(LOG_DEBUG, "Pool %u: Connection not needed, suspending",
  8004. pool->pool_no);
  8005. else
  8006. break;
  8007. suspend_stratum(pool);
  8008. clear_stratum_shares(pool);
  8009. clear_pool_work(pool);
  8010. wait_lpcurrent(pool);
  8011. if (!restart_stratum(pool)) {
  8012. pool_died(pool);
  8013. while (!restart_stratum(pool)) {
  8014. if (pool->removed)
  8015. goto out;
  8016. cgsleep_ms(30000);
  8017. }
  8018. }
  8019. }
  8020. FD_ZERO(&rd);
  8021. FD_SET(sock, &rd);
  8022. timeout.tv_sec = 120;
  8023. timeout.tv_usec = 0;
  8024. /* If we fail to receive any notify messages for 2 minutes we
  8025. * assume the connection has been dropped and treat this pool
  8026. * as dead */
  8027. if (!sock_full(pool) && (sel_ret = select(sock + 1, &rd, NULL, NULL, &timeout)) < 1) {
  8028. applog(LOG_DEBUG, "Stratum select failed on pool %d with value %d", pool->pool_no, sel_ret);
  8029. s = NULL;
  8030. } else
  8031. s = recv_line(pool);
  8032. if (!s) {
  8033. if (!pool->has_stratum)
  8034. break;
  8035. applog(LOG_NOTICE, "Stratum connection to pool %d interrupted", pool->pool_no);
  8036. pool->getfail_occasions++;
  8037. total_go++;
  8038. mutex_lock(&pool->stratum_lock);
  8039. pool->stratum_active = pool->stratum_notify = false;
  8040. pool->sock = INVSOCK;
  8041. mutex_unlock(&pool->stratum_lock);
  8042. /* If the socket to our stratum pool disconnects, all
  8043. * submissions need to be discarded or resent. */
  8044. if (!supports_resume(pool))
  8045. clear_stratum_shares(pool);
  8046. else
  8047. resubmit_stratum_shares(pool);
  8048. clear_pool_work(pool);
  8049. if (pool == current_pool())
  8050. restart_threads();
  8051. if (restart_stratum(pool))
  8052. continue;
  8053. shutdown_stratum(pool);
  8054. pool_died(pool);
  8055. break;
  8056. }
  8057. /* Check this pool hasn't died while being a backup pool and
  8058. * has not had its idle flag cleared */
  8059. stratum_resumed(pool);
  8060. if (!parse_method(pool, s) && !parse_stratum_response(pool, s))
  8061. applog(LOG_INFO, "Unknown stratum msg: %s", s);
  8062. free(s);
  8063. if (pool->swork.clean) {
  8064. struct work *work = make_work();
  8065. /* Generate a single work item to update the current
  8066. * block database */
  8067. pool->swork.clean = false;
  8068. gen_stratum_work(pool, work);
  8069. /* Try to extract block height from coinbase scriptSig */
  8070. uint8_t *bin_height = &bytes_buf(&pool->swork.coinbase)[4 /*version*/ + 1 /*txin count*/ + 36 /*prevout*/ + 1 /*scriptSig len*/ + 1 /*push opcode*/];
  8071. unsigned char cb_height_sz;
  8072. cb_height_sz = bin_height[-1];
  8073. if (cb_height_sz == 3) {
  8074. // FIXME: The block number will overflow this by AD 2173
  8075. struct mining_goal_info * const goal = pool->goal;
  8076. const void * const prevblkhash = &work->data[4];
  8077. uint32_t height = 0;
  8078. memcpy(&height, bin_height, 3);
  8079. height = le32toh(height);
  8080. have_block_height(goal, prevblkhash, height);
  8081. }
  8082. pool->swork.work_restart_id =
  8083. ++pool->work_restart_id;
  8084. pool_update_work_restart_time(pool);
  8085. if (test_work_current(work)) {
  8086. /* Only accept a work update if this stratum
  8087. * connection is from the current pool */
  8088. struct pool * const cp = current_pool();
  8089. if (pool == cp)
  8090. restart_threads();
  8091. applog(
  8092. ((!opt_quiet_work_updates) && pool_actively_in_use(pool, cp) ? LOG_NOTICE : LOG_DEBUG),
  8093. "Stratum from pool %d requested work update", pool->pool_no);
  8094. } else
  8095. applog(LOG_NOTICE, "Stratum from pool %d detected new block", pool->pool_no);
  8096. free_work(work);
  8097. }
  8098. if (timer_passed(&pool->swork.tv_transparency, NULL)) {
  8099. // More than 4 timmills past since requested transactions
  8100. timer_unset(&pool->swork.tv_transparency);
  8101. pool_set_opaque(pool, true);
  8102. }
  8103. }
  8104. out:
  8105. return NULL;
  8106. }
  8107. static void init_stratum_thread(struct pool *pool)
  8108. {
  8109. have_longpoll = true;
  8110. if (unlikely(pthread_create(&pool->stratum_thread, NULL, stratum_thread, (void *)pool)))
  8111. quit(1, "Failed to create stratum thread");
  8112. }
  8113. static void *longpoll_thread(void *userdata);
  8114. static bool stratum_works(struct pool *pool)
  8115. {
  8116. applog(LOG_INFO, "Testing pool %d stratum %s", pool->pool_no, pool->stratum_url);
  8117. if (!extract_sockaddr(pool->stratum_url, &pool->sockaddr_url, &pool->stratum_port))
  8118. return false;
  8119. if (pool->stratum_active)
  8120. return true;
  8121. if (!initiate_stratum(pool))
  8122. return false;
  8123. return true;
  8124. }
  8125. static
  8126. bool pool_recently_got_work(struct pool * const pool, const struct timeval * const tvp_now)
  8127. {
  8128. return (timer_isset(&pool->tv_last_work_time) && timer_elapsed(&pool->tv_last_work_time, tvp_now) < 60);
  8129. }
  8130. static bool pool_active(struct pool *pool, bool pinging)
  8131. {
  8132. struct timeval tv_now, tv_getwork, tv_getwork_reply;
  8133. bool ret = false;
  8134. json_t *val;
  8135. CURL *curl = NULL;
  8136. int rolltime;
  8137. char *rpc_req;
  8138. struct work *work;
  8139. enum pool_protocol proto;
  8140. if (pool->stratum_init)
  8141. {
  8142. if (pool->stratum_active)
  8143. return true;
  8144. }
  8145. else
  8146. if (!pool->idle)
  8147. {
  8148. timer_set_now(&tv_now);
  8149. if (pool_recently_got_work(pool, &tv_now))
  8150. return true;
  8151. }
  8152. mutex_lock(&pool->pool_test_lock);
  8153. if (pool->stratum_init)
  8154. {
  8155. ret = pool->stratum_active;
  8156. goto out;
  8157. }
  8158. timer_set_now(&tv_now);
  8159. if (pool->idle)
  8160. {
  8161. if (timer_elapsed(&pool->tv_idle, &tv_now) < 30)
  8162. goto out;
  8163. }
  8164. else
  8165. if (pool_recently_got_work(pool, &tv_now))
  8166. {
  8167. ret = true;
  8168. goto out;
  8169. }
  8170. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  8171. /* This is the central point we activate stratum when we can */
  8172. curl = curl_easy_init();
  8173. if (unlikely(!curl)) {
  8174. applog(LOG_ERR, "CURL initialisation failed");
  8175. goto out;
  8176. }
  8177. if (!(want_gbt || want_getwork))
  8178. goto nohttp;
  8179. work = make_work();
  8180. /* Probe for GBT support on first pass */
  8181. proto = want_gbt ? PLP_GETBLOCKTEMPLATE : PLP_GETWORK;
  8182. tryagain:
  8183. rpc_req = prepare_rpc_req_probe(work, proto, NULL);
  8184. work->pool = pool;
  8185. if (!rpc_req)
  8186. goto out;
  8187. pool->probed = false;
  8188. cgtime(&tv_getwork);
  8189. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  8190. true, false, &rolltime, pool, false);
  8191. cgtime(&tv_getwork_reply);
  8192. free(rpc_req);
  8193. /* Detect if a http getwork pool has an X-Stratum header at startup,
  8194. * and if so, switch to that in preference to getwork if it works */
  8195. if (pool->stratum_url && want_stratum && pool_may_redirect_to(pool, pool->stratum_url) && (pool->has_stratum || stratum_works(pool))) {
  8196. if (!pool->has_stratum) {
  8197. applog(LOG_NOTICE, "Switching pool %d %s to %s", pool->pool_no, pool->rpc_url, pool->stratum_url);
  8198. if (!pool->rpc_url)
  8199. pool_set_uri(pool, strdup(pool->stratum_url));
  8200. pool->has_stratum = true;
  8201. }
  8202. free_work(work);
  8203. if (val)
  8204. json_decref(val);
  8205. retry_stratum:
  8206. ;
  8207. /* We create the stratum thread for each pool just after
  8208. * successful authorisation. Once the init flag has been set
  8209. * we never unset it and the stratum thread is responsible for
  8210. * setting/unsetting the active flag */
  8211. bool init = pool_tset(pool, &pool->stratum_init);
  8212. if (!init) {
  8213. ret = initiate_stratum(pool) && auth_stratum(pool);
  8214. if (ret)
  8215. {
  8216. detect_algo = 2;
  8217. init_stratum_thread(pool);
  8218. }
  8219. else
  8220. {
  8221. pool_tclear(pool, &pool->stratum_init);
  8222. pool->tv_idle = tv_getwork_reply;
  8223. }
  8224. goto out;
  8225. }
  8226. ret = pool->stratum_active;
  8227. goto out;
  8228. }
  8229. else if (pool->has_stratum)
  8230. shutdown_stratum(pool);
  8231. if (val) {
  8232. bool rc;
  8233. json_t *res;
  8234. res = json_object_get(val, "result");
  8235. if ((!json_is_object(res)) || (proto == PLP_GETBLOCKTEMPLATE && !json_object_get(res, "bits")))
  8236. goto badwork;
  8237. work->rolltime = rolltime;
  8238. rc = work_decode(pool, work, val);
  8239. if (rc) {
  8240. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  8241. pool->pool_no, pool->rpc_url);
  8242. work->pool = pool;
  8243. copy_time(&work->tv_getwork, &tv_getwork);
  8244. copy_time(&work->tv_getwork_reply, &tv_getwork_reply);
  8245. work->getwork_mode = GETWORK_MODE_TESTPOOL;
  8246. calc_diff(work, 0);
  8247. update_last_work(work);
  8248. applog(LOG_DEBUG, "Pushing pooltest work to base pool");
  8249. stage_work(work);
  8250. total_getworks++;
  8251. pool->getwork_requested++;
  8252. ret = true;
  8253. pool->tv_idle = tv_getwork_reply;
  8254. } else {
  8255. badwork:
  8256. json_decref(val);
  8257. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher work from pool %u %s",
  8258. pool->pool_no, pool->rpc_url);
  8259. pool->proto = proto = pool_protocol_fallback(proto);
  8260. if (PLP_NONE != proto)
  8261. goto tryagain;
  8262. pool->tv_idle = tv_getwork_reply;
  8263. free_work(work);
  8264. goto out;
  8265. }
  8266. json_decref(val);
  8267. if (proto != pool->proto) {
  8268. pool->proto = proto;
  8269. applog(LOG_INFO, "Selected %s protocol for pool %u", pool_protocol_name(proto), pool->pool_no);
  8270. }
  8271. if (pool->lp_url)
  8272. goto out;
  8273. /* Decipher the longpoll URL, if any, and store it in ->lp_url */
  8274. const struct blktmpl_longpoll_req *lp;
  8275. if (work->tr && (lp = blktmpl_get_longpoll(work->tr->tmpl))) {
  8276. // NOTE: work_decode takes care of lp id
  8277. pool->lp_url = lp->uri ? absolute_uri(lp->uri, pool->rpc_url) : pool->rpc_url;
  8278. if (!pool->lp_url)
  8279. {
  8280. ret = false;
  8281. goto out;
  8282. }
  8283. pool->lp_proto = PLP_GETBLOCKTEMPLATE;
  8284. }
  8285. else
  8286. if (pool->hdr_path && want_getwork) {
  8287. pool->lp_url = absolute_uri(pool->hdr_path, pool->rpc_url);
  8288. if (!pool->lp_url)
  8289. {
  8290. ret = false;
  8291. goto out;
  8292. }
  8293. pool->lp_proto = PLP_GETWORK;
  8294. } else
  8295. pool->lp_url = NULL;
  8296. if (want_longpoll && !pool->lp_started) {
  8297. pool->lp_started = true;
  8298. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  8299. quit(1, "Failed to create pool longpoll thread");
  8300. }
  8301. } else if (PLP_NONE != (proto = pool_protocol_fallback(proto))) {
  8302. pool->proto = proto;
  8303. goto tryagain;
  8304. } else {
  8305. pool->tv_idle = tv_getwork_reply;
  8306. free_work(work);
  8307. nohttp:
  8308. /* If we failed to parse a getwork, this could be a stratum
  8309. * url without the prefix stratum+tcp:// so let's check it */
  8310. if (extract_sockaddr(pool->rpc_url, &pool->sockaddr_url, &pool->stratum_port) && initiate_stratum(pool)) {
  8311. pool->has_stratum = true;
  8312. goto retry_stratum;
  8313. }
  8314. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  8315. pool->pool_no, pool->rpc_url);
  8316. if (!pinging)
  8317. applog(LOG_WARNING, "Pool %u slow/down or URL or credentials invalid", pool->pool_no);
  8318. }
  8319. out:
  8320. if (curl)
  8321. curl_easy_cleanup(curl);
  8322. mutex_unlock(&pool->pool_test_lock);
  8323. return ret;
  8324. }
  8325. static void pool_resus(struct pool *pool)
  8326. {
  8327. if (pool->enabled == POOL_ENABLED && pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  8328. applog(LOG_WARNING, "Pool %d %s alive, testing stability", pool->pool_no, pool->rpc_url);
  8329. else
  8330. applog(LOG_INFO, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  8331. }
  8332. static
  8333. void *cmd_idle_thread(void * const __maybe_unused userp)
  8334. {
  8335. pthread_detach(pthread_self());
  8336. RenameThread("cmd-idle");
  8337. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  8338. sleep(opt_log_interval);
  8339. pthread_testcancel();
  8340. run_cmd(cmd_idle);
  8341. return NULL;
  8342. }
  8343. static struct work *hash_pop(void)
  8344. {
  8345. struct work *work = NULL, *tmp;
  8346. int hc;
  8347. bool did_cmd_idle = false;
  8348. pthread_t cmd_idle_thr;
  8349. retry:
  8350. mutex_lock(stgd_lock);
  8351. while (!HASH_COUNT(staged_work))
  8352. {
  8353. if (unlikely(staged_full))
  8354. {
  8355. if (likely(opt_queue < 10 + mining_threads))
  8356. {
  8357. ++opt_queue;
  8358. applog(LOG_WARNING, "Staged work underrun; increasing queue minimum to %d", opt_queue);
  8359. }
  8360. else
  8361. applog(LOG_WARNING, "Staged work underrun; not automatically increasing above %d", opt_queue);
  8362. staged_full = false; // Let it fill up before triggering an underrun again
  8363. no_work = true;
  8364. }
  8365. pthread_cond_signal(&gws_cond);
  8366. if (cmd_idle && !did_cmd_idle)
  8367. {
  8368. if (likely(!pthread_create(&cmd_idle_thr, NULL, cmd_idle_thread, NULL)))
  8369. did_cmd_idle = true;
  8370. }
  8371. pthread_cond_wait(&getq->cond, stgd_lock);
  8372. }
  8373. if (did_cmd_idle)
  8374. pthread_cancel(cmd_idle_thr);
  8375. no_work = false;
  8376. hc = HASH_COUNT(staged_work);
  8377. /* Find clone work if possible, to allow masters to be reused */
  8378. if (hc > staged_rollable) {
  8379. HASH_ITER(hh, staged_work, work, tmp) {
  8380. if (!work_rollable(work))
  8381. break;
  8382. }
  8383. } else
  8384. work = staged_work;
  8385. if (can_roll(work) && should_roll(work))
  8386. {
  8387. // Instead of consuming it, force it to be cloned and grab the clone
  8388. mutex_unlock(stgd_lock);
  8389. clone_available();
  8390. goto retry;
  8391. }
  8392. HASH_DEL(staged_work, work);
  8393. if (work_rollable(work))
  8394. staged_rollable--;
  8395. /* Signal the getwork scheduler to look for more work */
  8396. pthread_cond_signal(&gws_cond);
  8397. /* Signal hash_pop again in case there are mutliple hash_pop waiters */
  8398. pthread_cond_signal(&getq->cond);
  8399. mutex_unlock(stgd_lock);
  8400. work->pool->last_work_time = time(NULL);
  8401. cgtime(&work->pool->tv_last_work_time);
  8402. return work;
  8403. }
  8404. /* Clones work by rolling it if possible, and returning a clone instead of the
  8405. * original work item which gets staged again to possibly be rolled again in
  8406. * the future */
  8407. static struct work *clone_work(struct work *work)
  8408. {
  8409. int mrs = mining_threads + opt_queue - total_staged();
  8410. struct work *work_clone;
  8411. bool cloned;
  8412. if (mrs < 1)
  8413. return work;
  8414. cloned = false;
  8415. work_clone = make_clone(work);
  8416. while (mrs-- > 0 && can_roll(work) && should_roll(work)) {
  8417. applog(LOG_DEBUG, "Pushing rolled converted work to stage thread");
  8418. stage_work(work_clone);
  8419. roll_work(work);
  8420. work_clone = make_clone(work);
  8421. /* Roll it again to prevent duplicates should this be used
  8422. * directly later on */
  8423. roll_work(work);
  8424. cloned = true;
  8425. }
  8426. if (cloned) {
  8427. stage_work(work);
  8428. return work_clone;
  8429. }
  8430. free_work(work_clone);
  8431. return work;
  8432. }
  8433. void gen_hash(unsigned char *data, unsigned char *hash, int len)
  8434. {
  8435. unsigned char hash1[32];
  8436. sha256(data, len, hash1);
  8437. sha256(hash1, 32, hash);
  8438. }
  8439. /* PDiff 1 is a 256 bit unsigned integer of
  8440. * 0x00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff
  8441. * so we use a big endian 32 bit unsigned integer positioned at the Nth byte to
  8442. * cover a huge range of difficulty targets, though not all 256 bits' worth */
  8443. static void pdiff_target_leadzero(void * const target_p, double diff)
  8444. {
  8445. uint8_t *target = target_p;
  8446. diff *= 0x100000000;
  8447. int skip = log2(diff) / 8;
  8448. if (skip)
  8449. {
  8450. if (skip > 0x1c)
  8451. skip = 0x1c;
  8452. diff /= pow(0x100, skip);
  8453. memset(target, 0, skip);
  8454. }
  8455. uint32_t n = 0xffffffff;
  8456. n = (double)n / diff;
  8457. n = htobe32(n);
  8458. memcpy(&target[skip], &n, sizeof(n));
  8459. memset(&target[skip + sizeof(n)], 0xff, 32 - (skip + sizeof(n)));
  8460. }
  8461. void set_target_to_pdiff(void * const dest_target, const double pdiff)
  8462. {
  8463. unsigned char rtarget[32];
  8464. pdiff_target_leadzero(rtarget, pdiff);
  8465. swab256(dest_target, rtarget);
  8466. if (opt_debug) {
  8467. char htarget[65];
  8468. bin2hex(htarget, rtarget, 32);
  8469. applog(LOG_DEBUG, "Generated target %s", htarget);
  8470. }
  8471. }
  8472. void set_target_to_bdiff(void * const dest_target, const double bdiff)
  8473. {
  8474. set_target_to_pdiff(dest_target, bdiff_to_pdiff(bdiff));
  8475. }
  8476. void _test_target(void * const funcp, const char * const funcname, const bool little_endian, const void * const expectp, const double diff)
  8477. {
  8478. uint8_t bufr[32], buf[32], expectr[32], expect[32];
  8479. int off;
  8480. void (*func)(void *, double) = funcp;
  8481. func(little_endian ? bufr : buf, diff);
  8482. if (little_endian)
  8483. swab256(buf, bufr);
  8484. swap32tobe(expect, expectp, 256/32);
  8485. // Fuzzy comparison: the first 32 bits set must match, and the actual target must be >= the expected
  8486. for (off = 0; off < 28 && !buf[off]; ++off)
  8487. {}
  8488. if (memcmp(&buf[off], &expect[off], 4))
  8489. {
  8490. testfail: ;
  8491. ++unittest_failures;
  8492. char hexbuf[65], expectbuf[65];
  8493. bin2hex(hexbuf, buf, 32);
  8494. bin2hex(expectbuf, expect, 32);
  8495. applogr(, LOG_WARNING, "%s test failed: diff %g got %s (expected %s)",
  8496. funcname, diff, hexbuf, expectbuf);
  8497. }
  8498. if (!little_endian)
  8499. swab256(bufr, buf);
  8500. swab256(expectr, expect);
  8501. if (!hash_target_check(expectr, bufr))
  8502. goto testfail;
  8503. }
  8504. #define TEST_TARGET(func, le, expect, diff) \
  8505. _test_target(func, #func, le, expect, diff)
  8506. void test_target()
  8507. {
  8508. uint32_t expect[8] = {0};
  8509. // bdiff 1 should be exactly 00000000ffff0000000006f29cfd29510a6caee84634e86a57257cf03152537f due to floating-point imprecision (pdiff1 / 1.0000152590218966)
  8510. expect[0] = 0x0000ffff;
  8511. TEST_TARGET(set_target_to_bdiff, true, expect, 1./0x10000);
  8512. expect[0] = 0;
  8513. expect[1] = 0xffff0000;
  8514. TEST_TARGET(set_target_to_bdiff, true, expect, 1);
  8515. expect[1] >>= 1;
  8516. TEST_TARGET(set_target_to_bdiff, true, expect, 2);
  8517. expect[1] >>= 3;
  8518. TEST_TARGET(set_target_to_bdiff, true, expect, 0x10);
  8519. expect[1] >>= 4;
  8520. TEST_TARGET(set_target_to_bdiff, true, expect, 0x100);
  8521. memset(&expect[1], '\xff', 28);
  8522. expect[0] = 0x0000ffff;
  8523. TEST_TARGET(set_target_to_pdiff, true, expect, 1./0x10000);
  8524. expect[0] = 0;
  8525. TEST_TARGET(set_target_to_pdiff, true, expect, 1);
  8526. expect[1] >>= 1;
  8527. TEST_TARGET(set_target_to_pdiff, true, expect, 2);
  8528. expect[1] >>= 3;
  8529. TEST_TARGET(set_target_to_pdiff, true, expect, 0x10);
  8530. expect[1] >>= 4;
  8531. TEST_TARGET(set_target_to_pdiff, true, expect, 0x100);
  8532. }
  8533. void stratum_work_cpy(struct stratum_work * const dst, const struct stratum_work * const src)
  8534. {
  8535. *dst = *src;
  8536. if (dst->tr)
  8537. tmpl_incref(dst->tr);
  8538. dst->nonce1 = maybe_strdup(src->nonce1);
  8539. dst->job_id = maybe_strdup(src->job_id);
  8540. bytes_cpy(&dst->coinbase, &src->coinbase);
  8541. bytes_cpy(&dst->merkle_bin, &src->merkle_bin);
  8542. }
  8543. void stratum_work_clean(struct stratum_work * const swork)
  8544. {
  8545. if (swork->tr)
  8546. tmpl_decref(swork->tr);
  8547. free(swork->nonce1);
  8548. free(swork->job_id);
  8549. bytes_free(&swork->coinbase);
  8550. bytes_free(&swork->merkle_bin);
  8551. }
  8552. bool pool_has_usable_swork(const struct pool * const pool)
  8553. {
  8554. if (opt_benchmark)
  8555. return true;
  8556. if (pool->swork.tr)
  8557. {
  8558. // GBT
  8559. struct timeval tv_now;
  8560. timer_set_now(&tv_now);
  8561. return blkmk_time_left(pool->swork.tr->tmpl, tv_now.tv_sec);
  8562. }
  8563. return pool->stratum_notify;
  8564. }
  8565. /* Generates stratum based work based on the most recent notify information
  8566. * from the pool. This will keep generating work while a pool is down so we use
  8567. * other means to detect when the pool has died in stratum_thread */
  8568. static void gen_stratum_work(struct pool *pool, struct work *work)
  8569. {
  8570. clean_work(work);
  8571. cg_wlock(&pool->data_lock);
  8572. pool->swork.data_lock_p = &pool->data_lock;
  8573. const int n2size = pool->swork.n2size;
  8574. bytes_resize(&work->nonce2, n2size);
  8575. if (pool->nonce2sz < n2size)
  8576. memset(&bytes_buf(&work->nonce2)[pool->nonce2sz], 0, n2size - pool->nonce2sz);
  8577. memcpy(bytes_buf(&work->nonce2),
  8578. #ifdef WORDS_BIGENDIAN
  8579. // NOTE: On big endian, the most significant bits are stored at the end, so skip the LSBs
  8580. &((char*)&pool->nonce2)[pool->nonce2off],
  8581. #else
  8582. &pool->nonce2,
  8583. #endif
  8584. pool->nonce2sz);
  8585. pool->nonce2++;
  8586. work->pool = pool;
  8587. work->work_restart_id = pool->swork.work_restart_id;
  8588. gen_stratum_work2(work, &pool->swork);
  8589. cgtime(&work->tv_staged);
  8590. }
  8591. void gen_stratum_work2(struct work *work, struct stratum_work *swork)
  8592. {
  8593. unsigned char *coinbase, merkle_root[32], merkle_sha[64];
  8594. uint8_t *merkle_bin;
  8595. uint32_t *data32, *swap32;
  8596. int i;
  8597. /* Generate coinbase */
  8598. coinbase = bytes_buf(&swork->coinbase);
  8599. memcpy(&coinbase[swork->nonce2_offset], bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  8600. /* Downgrade to a read lock to read off the variables */
  8601. if (swork->data_lock_p)
  8602. cg_dwlock(swork->data_lock_p);
  8603. /* Generate merkle root */
  8604. gen_hash(coinbase, merkle_root, bytes_len(&swork->coinbase));
  8605. memcpy(merkle_sha, merkle_root, 32);
  8606. merkle_bin = bytes_buf(&swork->merkle_bin);
  8607. for (i = 0; i < swork->merkles; ++i, merkle_bin += 32) {
  8608. memcpy(merkle_sha + 32, merkle_bin, 32);
  8609. gen_hash(merkle_sha, merkle_root, 64);
  8610. memcpy(merkle_sha, merkle_root, 32);
  8611. }
  8612. data32 = (uint32_t *)merkle_sha;
  8613. swap32 = (uint32_t *)merkle_root;
  8614. flip32(swap32, data32);
  8615. memcpy(&work->data[0], swork->header1, 36);
  8616. memcpy(&work->data[36], merkle_root, 32);
  8617. *((uint32_t*)&work->data[68]) = htobe32(swork->ntime + timer_elapsed(&swork->tv_received, NULL));
  8618. memcpy(&work->data[72], swork->diffbits, 4);
  8619. memset(&work->data[76], 0, 4); // nonce
  8620. memcpy(&work->data[80], workpadding_bin, 48);
  8621. work->ntime_roll_limits = swork->ntime_roll_limits;
  8622. /* Copy parameters required for share submission */
  8623. memcpy(work->target, swork->target, sizeof(work->target));
  8624. work->job_id = maybe_strdup(swork->job_id);
  8625. work->nonce1 = maybe_strdup(swork->nonce1);
  8626. if (swork->data_lock_p)
  8627. cg_runlock(swork->data_lock_p);
  8628. if (opt_debug)
  8629. {
  8630. char header[161];
  8631. char nonce2hex[(bytes_len(&work->nonce2) * 2) + 1];
  8632. bin2hex(header, work->data, 80);
  8633. bin2hex(nonce2hex, bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  8634. applog(LOG_DEBUG, "Generated stratum header %s", header);
  8635. applog(LOG_DEBUG, "Work job_id %s nonce2 %s", work->job_id, nonce2hex);
  8636. }
  8637. calc_midstate(work);
  8638. local_work++;
  8639. work->stratum = true;
  8640. work->blk.nonce = 0;
  8641. work->id = total_work++;
  8642. work->longpoll = false;
  8643. work->getwork_mode = GETWORK_MODE_STRATUM;
  8644. calc_diff(work, 0);
  8645. }
  8646. void request_work(struct thr_info *thr)
  8647. {
  8648. struct cgpu_info *cgpu = thr->cgpu;
  8649. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  8650. /* Tell the watchdog thread this thread is waiting on getwork and
  8651. * should not be restarted */
  8652. thread_reportout(thr);
  8653. // HACK: Since get_work still blocks, reportout all processors dependent on this thread
  8654. for (struct cgpu_info *proc = thr->cgpu->next_proc; proc; proc = proc->next_proc)
  8655. {
  8656. if (proc->threads)
  8657. break;
  8658. thread_reportout(proc->thr[0]);
  8659. }
  8660. cgtime(&dev_stats->_get_start);
  8661. }
  8662. // FIXME: Make this non-blocking (and remove HACK above)
  8663. struct work *get_work(struct thr_info *thr)
  8664. {
  8665. const int thr_id = thr->id;
  8666. struct cgpu_info *cgpu = thr->cgpu;
  8667. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  8668. struct cgminer_stats *pool_stats;
  8669. struct timeval tv_get;
  8670. struct work *work = NULL;
  8671. applog(LOG_DEBUG, "%"PRIpreprv": Popping work from get queue to get work", cgpu->proc_repr);
  8672. while (!work) {
  8673. work = hash_pop();
  8674. if (stale_work(work, false)) {
  8675. staged_full = false; // It wasn't really full, since it was stale :(
  8676. discard_work(work);
  8677. work = NULL;
  8678. wake_gws();
  8679. }
  8680. }
  8681. last_getwork = time(NULL);
  8682. applog(LOG_DEBUG, "%"PRIpreprv": Got work %d from get queue to get work for thread %d",
  8683. cgpu->proc_repr, work->id, thr_id);
  8684. work->thr_id = thr_id;
  8685. thread_reportin(thr);
  8686. // HACK: Since get_work still blocks, reportin all processors dependent on this thread
  8687. for (struct cgpu_info *proc = thr->cgpu->next_proc; proc; proc = proc->next_proc)
  8688. {
  8689. if (proc->threads)
  8690. break;
  8691. thread_reportin(proc->thr[0]);
  8692. }
  8693. work->mined = true;
  8694. work->blk.nonce = 0;
  8695. cgtime(&tv_get);
  8696. timersub(&tv_get, &dev_stats->_get_start, &tv_get);
  8697. timeradd(&tv_get, &dev_stats->getwork_wait, &dev_stats->getwork_wait);
  8698. if (timercmp(&tv_get, &dev_stats->getwork_wait_max, >))
  8699. dev_stats->getwork_wait_max = tv_get;
  8700. if (timercmp(&tv_get, &dev_stats->getwork_wait_min, <))
  8701. dev_stats->getwork_wait_min = tv_get;
  8702. ++dev_stats->getwork_calls;
  8703. pool_stats = &(work->pool->cgminer_stats);
  8704. timeradd(&tv_get, &pool_stats->getwork_wait, &pool_stats->getwork_wait);
  8705. if (timercmp(&tv_get, &pool_stats->getwork_wait_max, >))
  8706. pool_stats->getwork_wait_max = tv_get;
  8707. if (timercmp(&tv_get, &pool_stats->getwork_wait_min, <))
  8708. pool_stats->getwork_wait_min = tv_get;
  8709. ++pool_stats->getwork_calls;
  8710. if (work->work_difficulty < 1)
  8711. {
  8712. if (unlikely(work->work_difficulty < cgpu->min_nonce_diff))
  8713. {
  8714. if (cgpu->min_nonce_diff - work->work_difficulty > 1./0x10000000)
  8715. applog(LOG_WARNING, "%"PRIpreprv": Using work with lower difficulty than device supports",
  8716. cgpu->proc_repr);
  8717. work->nonce_diff = cgpu->min_nonce_diff;
  8718. }
  8719. else
  8720. work->nonce_diff = work->work_difficulty;
  8721. }
  8722. else
  8723. work->nonce_diff = 1;
  8724. return work;
  8725. }
  8726. struct dupe_hash_elem {
  8727. uint8_t hash[0x20];
  8728. struct timeval tv_prune;
  8729. UT_hash_handle hh;
  8730. };
  8731. static
  8732. void _submit_work_async(struct work *work)
  8733. {
  8734. applog(LOG_DEBUG, "Pushing submit work to work thread");
  8735. if (opt_benchmark)
  8736. {
  8737. json_t * const jn = json_null(), *result = NULL;
  8738. work_check_for_block(work);
  8739. {
  8740. static struct dupe_hash_elem *dupe_hashes;
  8741. struct dupe_hash_elem *dhe, *dhetmp;
  8742. HASH_FIND(hh, dupe_hashes, &work->hash, sizeof(dhe->hash), dhe);
  8743. if (dhe)
  8744. result = json_string("duplicate");
  8745. else
  8746. {
  8747. struct timeval tv_now;
  8748. timer_set_now(&tv_now);
  8749. // Prune old entries
  8750. HASH_ITER(hh, dupe_hashes, dhe, dhetmp)
  8751. {
  8752. if (!timer_passed(&dhe->tv_prune, &tv_now))
  8753. break;
  8754. HASH_DEL(dupe_hashes, dhe);
  8755. free(dhe);
  8756. }
  8757. dhe = malloc(sizeof(*dhe));
  8758. memcpy(dhe->hash, work->hash, sizeof(dhe->hash));
  8759. timer_set_delay(&dhe->tv_prune, &tv_now, 337500000);
  8760. HASH_ADD(hh, dupe_hashes, hash, sizeof(dhe->hash), dhe);
  8761. }
  8762. }
  8763. if (result)
  8764. {}
  8765. else
  8766. if (stale_work(work, true))
  8767. {
  8768. char stalemsg[0x10];
  8769. snprintf(stalemsg, sizeof(stalemsg), "stale %us", benchmark_update_interval * (work->pool->work_restart_id - work->work_restart_id));
  8770. result = json_string(stalemsg);
  8771. }
  8772. else
  8773. result = json_incref(jn);
  8774. share_result(jn, result, jn, work, false, "");
  8775. free_work(work);
  8776. json_decref(result);
  8777. json_decref(jn);
  8778. return;
  8779. }
  8780. mutex_lock(&submitting_lock);
  8781. ++total_submitting;
  8782. DL_APPEND(submit_waiting, work);
  8783. mutex_unlock(&submitting_lock);
  8784. notifier_wake(submit_waiting_notifier);
  8785. }
  8786. /* Submit a copy of the tested, statistic recorded work item asynchronously */
  8787. static void submit_work_async2(struct work *work, struct timeval *tv_work_found)
  8788. {
  8789. if (tv_work_found)
  8790. copy_time(&work->tv_work_found, tv_work_found);
  8791. _submit_work_async(work);
  8792. }
  8793. void inc_hw_errors3(struct thr_info *thr, const struct work *work, const uint32_t *bad_nonce_p, float nonce_diff)
  8794. {
  8795. struct cgpu_info * const cgpu = thr->cgpu;
  8796. if (bad_nonce_p)
  8797. {
  8798. if (bad_nonce_p == UNKNOWN_NONCE)
  8799. applog(LOG_DEBUG, "%"PRIpreprv": invalid nonce - HW error",
  8800. cgpu->proc_repr);
  8801. else
  8802. applog(LOG_DEBUG, "%"PRIpreprv": invalid nonce (%08lx) - HW error",
  8803. cgpu->proc_repr, (unsigned long)be32toh(*bad_nonce_p));
  8804. }
  8805. mutex_lock(&stats_lock);
  8806. hw_errors++;
  8807. ++cgpu->hw_errors;
  8808. if (bad_nonce_p)
  8809. {
  8810. total_bad_diff1 += nonce_diff;
  8811. cgpu->bad_diff1 += nonce_diff;
  8812. }
  8813. mutex_unlock(&stats_lock);
  8814. if (thr->cgpu->drv->hw_error)
  8815. thr->cgpu->drv->hw_error(thr);
  8816. }
  8817. void work_hash(struct work * const work)
  8818. {
  8819. #ifdef USE_SCRYPT
  8820. if (opt_scrypt)
  8821. scrypt_hash_data(work->hash, work->data);
  8822. else
  8823. #endif
  8824. hash_data(work->hash, work->data);
  8825. }
  8826. static
  8827. bool test_hash(const void * const phash, const float diff)
  8828. {
  8829. const uint32_t * const hash = phash;
  8830. if (diff >= 1.)
  8831. // FIXME: > 1 should check more
  8832. return !hash[7];
  8833. const uint32_t Htarg = (uint32_t)ceil((1. / diff) - 1);
  8834. const uint32_t tmp_hash7 = le32toh(hash[7]);
  8835. applog(LOG_DEBUG, "htarget %08lx hash %08lx",
  8836. (long unsigned int)Htarg,
  8837. (long unsigned int)tmp_hash7);
  8838. return (tmp_hash7 <= Htarg);
  8839. }
  8840. enum test_nonce2_result _test_nonce2(struct work *work, uint32_t nonce, bool checktarget)
  8841. {
  8842. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  8843. *work_nonce = htole32(nonce);
  8844. work_hash(work);
  8845. if (!test_hash(work->hash, work->nonce_diff))
  8846. return TNR_BAD;
  8847. if (checktarget && !hash_target_check_v(work->hash, work->target))
  8848. {
  8849. bool high_hash = true;
  8850. struct pool * const pool = work->pool;
  8851. if (pool->stratum_active)
  8852. {
  8853. // 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
  8854. if (memcmp(pool->next_target, work->target, sizeof(work->target)))
  8855. {
  8856. applog(LOG_DEBUG, "Stratum pool %u target has changed since work job issued, checking that too",
  8857. pool->pool_no);
  8858. if (hash_target_check_v(work->hash, pool->next_target))
  8859. high_hash = false;
  8860. }
  8861. }
  8862. if (high_hash)
  8863. return TNR_HIGH;
  8864. }
  8865. return TNR_GOOD;
  8866. }
  8867. /* Returns true if nonce for work was a valid share */
  8868. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  8869. {
  8870. return submit_noffset_nonce(thr, work, nonce, 0);
  8871. }
  8872. /* Allows drivers to submit work items where the driver has changed the ntime
  8873. * value by noffset. Must be only used with a work protocol that does not ntime
  8874. * roll itself intrinsically to generate work (eg stratum). We do not touch
  8875. * the original work struct, but the copy of it only. */
  8876. bool submit_noffset_nonce(struct thr_info *thr, struct work *work_in, uint32_t nonce,
  8877. int noffset)
  8878. {
  8879. struct work *work = make_work();
  8880. _copy_work(work, work_in, noffset);
  8881. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  8882. struct timeval tv_work_found;
  8883. enum test_nonce2_result res;
  8884. bool ret = true;
  8885. thread_reportout(thr);
  8886. cgtime(&tv_work_found);
  8887. *work_nonce = htole32(nonce);
  8888. work->thr_id = thr->id;
  8889. /* Do one last check before attempting to submit the work */
  8890. /* Side effect: sets work->data and work->hash for us */
  8891. res = test_nonce2(work, nonce);
  8892. if (unlikely(res == TNR_BAD))
  8893. {
  8894. inc_hw_errors(thr, work, nonce);
  8895. ret = false;
  8896. goto out;
  8897. }
  8898. mutex_lock(&stats_lock);
  8899. total_diff1 += work->nonce_diff;
  8900. thr ->cgpu->diff1 += work->nonce_diff;
  8901. work->pool->diff1 += work->nonce_diff;
  8902. thr->cgpu->last_device_valid_work = time(NULL);
  8903. mutex_unlock(&stats_lock);
  8904. if (noncelog_file)
  8905. noncelog(work);
  8906. if (res == TNR_HIGH)
  8907. {
  8908. // Share above target, normal
  8909. /* Check the diff of the share, even if it didn't reach the
  8910. * target, just to set the best share value if it's higher. */
  8911. share_diff(work);
  8912. goto out;
  8913. }
  8914. submit_work_async2(work, &tv_work_found);
  8915. work = NULL; // Taken by submit_work_async2
  8916. out:
  8917. if (work)
  8918. free_work(work);
  8919. thread_reportin(thr);
  8920. return ret;
  8921. }
  8922. // return true of we should stop working on this piece of work
  8923. // returning false means we will keep scanning for a nonce
  8924. // assumptions: work->blk.nonce is the number of nonces completed in the work
  8925. // see minerloop_scanhash comments for more details & usage
  8926. bool abandon_work(struct work *work, struct timeval *wdiff, uint64_t max_hashes)
  8927. {
  8928. if (work->blk.nonce == 0xffffffff || // known we are scanning a full nonce range
  8929. wdiff->tv_sec > opt_scantime || // scan-time has elapsed (user specified, default 60s)
  8930. work->blk.nonce >= 0xfffffffe - max_hashes || // are there enough nonces left in the work
  8931. max_hashes >= 0xfffffffe || // assume we are scanning a full nonce range
  8932. stale_work(work, false)) // work is stale
  8933. return true;
  8934. return false;
  8935. }
  8936. void __thr_being_msg(int prio, struct thr_info *thr, const char *being)
  8937. {
  8938. struct cgpu_info *proc = thr->cgpu;
  8939. if (proc->threads > 1)
  8940. applog(prio, "%"PRIpreprv" (thread %d) %s", proc->proc_repr, thr->id, being);
  8941. else
  8942. applog(prio, "%"PRIpreprv" %s", proc->proc_repr, being);
  8943. }
  8944. // Called by asynchronous minerloops, when they find their processor should be disabled
  8945. void mt_disable_start(struct thr_info *mythr)
  8946. {
  8947. struct cgpu_info *cgpu = mythr->cgpu;
  8948. struct device_drv *drv = cgpu->drv;
  8949. if (drv->thread_disable)
  8950. drv->thread_disable(mythr);
  8951. hashmeter2(mythr);
  8952. __thr_being_msg(LOG_WARNING, mythr, "being disabled");
  8953. mythr->rolling = mythr->cgpu->rolling = 0;
  8954. thread_reportout(mythr);
  8955. mythr->_mt_disable_called = true;
  8956. }
  8957. /* Put a new unqueued work item in cgpu->unqueued_work under cgpu->qlock till
  8958. * the driver tells us it's full so that it may extract the work item using
  8959. * the get_queued() function which adds it to the hashtable on
  8960. * cgpu->queued_work. */
  8961. static void fill_queue(struct thr_info *mythr, struct cgpu_info *cgpu, struct device_drv *drv, const int thr_id)
  8962. {
  8963. thread_reportout(mythr);
  8964. do {
  8965. bool need_work;
  8966. /* Do this lockless just to know if we need more unqueued work. */
  8967. need_work = (!cgpu->unqueued_work);
  8968. /* get_work is a blocking function so do it outside of lock
  8969. * to prevent deadlocks with other locks. */
  8970. if (need_work) {
  8971. struct work *work = get_work(mythr);
  8972. wr_lock(&cgpu->qlock);
  8973. /* Check we haven't grabbed work somehow between
  8974. * checking and picking up the lock. */
  8975. if (likely(!cgpu->unqueued_work))
  8976. cgpu->unqueued_work = work;
  8977. else
  8978. need_work = false;
  8979. wr_unlock(&cgpu->qlock);
  8980. if (unlikely(!need_work))
  8981. discard_work(work);
  8982. }
  8983. /* The queue_full function should be used by the driver to
  8984. * actually place work items on the physical device if it
  8985. * does have a queue. */
  8986. } while (drv->queue_full && !drv->queue_full(cgpu));
  8987. }
  8988. /* Add a work item to a cgpu's queued hashlist */
  8989. void __add_queued(struct cgpu_info *cgpu, struct work *work)
  8990. {
  8991. cgpu->queued_count++;
  8992. HASH_ADD_INT(cgpu->queued_work, id, work);
  8993. }
  8994. /* This function is for retrieving one work item from the unqueued pointer and
  8995. * adding it to the hashtable of queued work. Code using this function must be
  8996. * able to handle NULL as a return which implies there is no work available. */
  8997. struct work *get_queued(struct cgpu_info *cgpu)
  8998. {
  8999. struct work *work = NULL;
  9000. wr_lock(&cgpu->qlock);
  9001. if (cgpu->unqueued_work) {
  9002. work = cgpu->unqueued_work;
  9003. if (unlikely(stale_work(work, false))) {
  9004. discard_work(work);
  9005. work = NULL;
  9006. wake_gws();
  9007. } else
  9008. __add_queued(cgpu, work);
  9009. cgpu->unqueued_work = NULL;
  9010. }
  9011. wr_unlock(&cgpu->qlock);
  9012. return work;
  9013. }
  9014. void add_queued(struct cgpu_info *cgpu, struct work *work)
  9015. {
  9016. wr_lock(&cgpu->qlock);
  9017. __add_queued(cgpu, work);
  9018. wr_unlock(&cgpu->qlock);
  9019. }
  9020. /* Get fresh work and add it to cgpu's queued hashlist */
  9021. struct work *get_queue_work(struct thr_info *thr, struct cgpu_info *cgpu, int thr_id)
  9022. {
  9023. struct work *work = get_work(thr);
  9024. add_queued(cgpu, work);
  9025. return work;
  9026. }
  9027. /* This function is for finding an already queued work item in the
  9028. * given que hashtable. Code using this function must be able
  9029. * to handle NULL as a return which implies there is no matching work.
  9030. * The calling function must lock access to the que if it is required.
  9031. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  9032. struct work *__find_work_bymidstate(struct work *que, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  9033. {
  9034. struct work *work, *tmp, *ret = NULL;
  9035. HASH_ITER(hh, que, work, tmp) {
  9036. if (memcmp(work->midstate, midstate, midstatelen) == 0 &&
  9037. memcmp(work->data + offset, data, datalen) == 0) {
  9038. ret = work;
  9039. break;
  9040. }
  9041. }
  9042. return ret;
  9043. }
  9044. /* This function is for finding an already queued work item in the
  9045. * device's queued_work hashtable. Code using this function must be able
  9046. * to handle NULL as a return which implies there is no matching work.
  9047. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  9048. struct work *find_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  9049. {
  9050. struct work *ret;
  9051. rd_lock(&cgpu->qlock);
  9052. ret = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  9053. rd_unlock(&cgpu->qlock);
  9054. return ret;
  9055. }
  9056. struct work *clone_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  9057. {
  9058. struct work *work, *ret = NULL;
  9059. rd_lock(&cgpu->qlock);
  9060. work = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  9061. if (work)
  9062. ret = copy_work(work);
  9063. rd_unlock(&cgpu->qlock);
  9064. return ret;
  9065. }
  9066. void __work_completed(struct cgpu_info *cgpu, struct work *work)
  9067. {
  9068. cgpu->queued_count--;
  9069. HASH_DEL(cgpu->queued_work, work);
  9070. }
  9071. /* This iterates over a queued hashlist finding work started more than secs
  9072. * seconds ago and discards the work as completed. The driver must set the
  9073. * work->tv_work_start value appropriately. Returns the number of items aged. */
  9074. int age_queued_work(struct cgpu_info *cgpu, double secs)
  9075. {
  9076. struct work *work, *tmp;
  9077. struct timeval tv_now;
  9078. int aged = 0;
  9079. cgtime(&tv_now);
  9080. wr_lock(&cgpu->qlock);
  9081. HASH_ITER(hh, cgpu->queued_work, work, tmp) {
  9082. if (tdiff(&tv_now, &work->tv_work_start) > secs) {
  9083. __work_completed(cgpu, work);
  9084. aged++;
  9085. }
  9086. }
  9087. wr_unlock(&cgpu->qlock);
  9088. return aged;
  9089. }
  9090. /* This function should be used by queued device drivers when they're sure
  9091. * the work struct is no longer in use. */
  9092. void work_completed(struct cgpu_info *cgpu, struct work *work)
  9093. {
  9094. wr_lock(&cgpu->qlock);
  9095. __work_completed(cgpu, work);
  9096. wr_unlock(&cgpu->qlock);
  9097. free_work(work);
  9098. }
  9099. /* Combines find_queued_work_bymidstate and work_completed in one function
  9100. * withOUT destroying the work so the driver must free it. */
  9101. struct work *take_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  9102. {
  9103. struct work *work;
  9104. wr_lock(&cgpu->qlock);
  9105. work = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  9106. if (work)
  9107. __work_completed(cgpu, work);
  9108. wr_unlock(&cgpu->qlock);
  9109. return work;
  9110. }
  9111. void flush_queue(struct cgpu_info *cgpu)
  9112. {
  9113. struct work *work = NULL;
  9114. wr_lock(&cgpu->qlock);
  9115. work = cgpu->unqueued_work;
  9116. cgpu->unqueued_work = NULL;
  9117. wr_unlock(&cgpu->qlock);
  9118. if (work) {
  9119. free_work(work);
  9120. applog(LOG_DEBUG, "Discarded queued work item");
  9121. }
  9122. }
  9123. /* This version of hash work is for devices that are fast enough to always
  9124. * perform a full nonce range and need a queue to maintain the device busy.
  9125. * Work creation and destruction is not done from within this function
  9126. * directly. */
  9127. void hash_queued_work(struct thr_info *mythr)
  9128. {
  9129. const long cycle = opt_log_interval / 5 ? : 1;
  9130. struct timeval tv_start = {0, 0}, tv_end;
  9131. struct cgpu_info *cgpu = mythr->cgpu;
  9132. struct device_drv *drv = cgpu->drv;
  9133. const int thr_id = mythr->id;
  9134. int64_t hashes_done = 0;
  9135. if (unlikely(cgpu->deven != DEV_ENABLED))
  9136. mt_disable(mythr);
  9137. while (likely(!cgpu->shutdown)) {
  9138. struct timeval diff;
  9139. int64_t hashes;
  9140. fill_queue(mythr, cgpu, drv, thr_id);
  9141. thread_reportin(mythr);
  9142. hashes = drv->scanwork(mythr);
  9143. /* Reset the bool here in case the driver looks for it
  9144. * synchronously in the scanwork loop. */
  9145. mythr->work_restart = false;
  9146. if (unlikely(hashes == -1 )) {
  9147. applog(LOG_ERR, "%s %d failure, disabling!", drv->name, cgpu->device_id);
  9148. cgpu->deven = DEV_DISABLED;
  9149. dev_error(cgpu, REASON_THREAD_ZERO_HASH);
  9150. mt_disable(mythr);
  9151. }
  9152. hashes_done += hashes;
  9153. cgtime(&tv_end);
  9154. timersub(&tv_end, &tv_start, &diff);
  9155. if (diff.tv_sec >= cycle) {
  9156. hashmeter(thr_id, &diff, hashes_done);
  9157. hashes_done = 0;
  9158. copy_time(&tv_start, &tv_end);
  9159. }
  9160. if (unlikely(mythr->pause || cgpu->deven != DEV_ENABLED))
  9161. mt_disable(mythr);
  9162. if (unlikely(mythr->work_restart)) {
  9163. flush_queue(cgpu);
  9164. if (drv->flush_work)
  9165. drv->flush_work(cgpu);
  9166. }
  9167. }
  9168. // cgpu->deven = DEV_DISABLED; set in miner_thread
  9169. }
  9170. // Called by minerloop, when it is re-enabling a processor
  9171. void mt_disable_finish(struct thr_info *mythr)
  9172. {
  9173. struct device_drv *drv = mythr->cgpu->drv;
  9174. thread_reportin(mythr);
  9175. __thr_being_msg(LOG_WARNING, mythr, "being re-enabled");
  9176. if (drv->thread_enable)
  9177. drv->thread_enable(mythr);
  9178. mythr->_mt_disable_called = false;
  9179. }
  9180. // Called by synchronous minerloops, when they find their processor should be disabled
  9181. // Calls mt_disable_start, waits until it's re-enabled, then calls mt_disable_finish
  9182. void mt_disable(struct thr_info *mythr)
  9183. {
  9184. const struct cgpu_info * const cgpu = mythr->cgpu;
  9185. mt_disable_start(mythr);
  9186. applog(LOG_DEBUG, "Waiting for wakeup notification in miner thread");
  9187. do {
  9188. notifier_read(mythr->notifier);
  9189. } while (mythr->pause || cgpu->deven != DEV_ENABLED);
  9190. mt_disable_finish(mythr);
  9191. }
  9192. enum {
  9193. STAT_SLEEP_INTERVAL = 1,
  9194. STAT_CTR_INTERVAL = 10000000,
  9195. FAILURE_INTERVAL = 30,
  9196. };
  9197. /* Stage another work item from the work returned in a longpoll */
  9198. 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)
  9199. {
  9200. bool rc;
  9201. work->rolltime = rolltime;
  9202. rc = work_decode(pool, work, val);
  9203. if (unlikely(!rc)) {
  9204. applog(LOG_ERR, "Could not convert longpoll data to work");
  9205. free_work(work);
  9206. return;
  9207. }
  9208. total_getworks++;
  9209. pool->getwork_requested++;
  9210. work->pool = pool;
  9211. copy_time(&work->tv_getwork, tv_lp);
  9212. copy_time(&work->tv_getwork_reply, tv_lp_reply);
  9213. calc_diff(work, 0);
  9214. if (pool->enabled == POOL_REJECTING)
  9215. work->mandatory = true;
  9216. work->longpoll = true;
  9217. work->getwork_mode = GETWORK_MODE_LP;
  9218. update_last_work(work);
  9219. /* We'll be checking this work item twice, but we already know it's
  9220. * from a new block so explicitly force the new block detection now
  9221. * rather than waiting for it to hit the stage thread. This also
  9222. * allows testwork to know whether LP discovered the block or not. */
  9223. test_work_current(work);
  9224. /* Don't use backup LPs as work if we have failover-only enabled. Use
  9225. * the longpoll work from a pool that has been rejecting shares as a
  9226. * way to detect when the pool has recovered.
  9227. */
  9228. if (pool != current_pool() && opt_fail_only && pool->enabled != POOL_REJECTING) {
  9229. free_work(work);
  9230. return;
  9231. }
  9232. work = clone_work(work);
  9233. applog(LOG_DEBUG, "Pushing converted work to stage thread");
  9234. stage_work(work);
  9235. applog(LOG_DEBUG, "Converted longpoll data to work");
  9236. }
  9237. /* If we want longpoll, enable it for the chosen default pool, or, if
  9238. * the pool does not support longpoll, find the first one that does
  9239. * and use its longpoll support */
  9240. static
  9241. struct pool *_select_longpoll_pool(struct pool *cp, bool(*func)(struct pool *))
  9242. {
  9243. int i;
  9244. if (func(cp))
  9245. return cp;
  9246. for (i = 0; i < total_pools; i++) {
  9247. struct pool *pool = pools[i];
  9248. if (func(pool))
  9249. return pool;
  9250. }
  9251. return NULL;
  9252. }
  9253. /* This will make the longpoll thread wait till it's the current pool, or it
  9254. * has been flagged as rejecting, before attempting to open any connections.
  9255. */
  9256. static void wait_lpcurrent(struct pool *pool)
  9257. {
  9258. mutex_lock(&lp_lock);
  9259. while (!cnx_needed(pool))
  9260. {
  9261. pool->lp_active = false;
  9262. pthread_cond_wait(&lp_cond, &lp_lock);
  9263. }
  9264. mutex_unlock(&lp_lock);
  9265. }
  9266. static curl_socket_t save_curl_socket(void *vpool, __maybe_unused curlsocktype purpose, struct curl_sockaddr *addr) {
  9267. struct pool *pool = vpool;
  9268. curl_socket_t sock = bfg_socket(addr->family, addr->socktype, addr->protocol);
  9269. pool->lp_socket = sock;
  9270. return sock;
  9271. }
  9272. static void *longpoll_thread(void *userdata)
  9273. {
  9274. struct pool *cp = (struct pool *)userdata;
  9275. /* This *pool is the source of the actual longpoll, not the pool we've
  9276. * tied it to */
  9277. struct timeval start, reply, end;
  9278. struct pool *pool = NULL;
  9279. char threadname[20];
  9280. CURL *curl = NULL;
  9281. int failures = 0;
  9282. char *lp_url;
  9283. int rolltime;
  9284. #ifndef HAVE_PTHREAD_CANCEL
  9285. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  9286. #endif
  9287. snprintf(threadname, 20, "longpoll%u", cp->pool_no);
  9288. RenameThread(threadname);
  9289. curl = curl_easy_init();
  9290. if (unlikely(!curl)) {
  9291. applog(LOG_ERR, "CURL initialisation failed");
  9292. return NULL;
  9293. }
  9294. retry_pool:
  9295. pool = select_longpoll_pool(cp);
  9296. if (!pool) {
  9297. applog(LOG_WARNING, "No suitable long-poll found for %s", cp->rpc_url);
  9298. while (!pool) {
  9299. cgsleep_ms(60000);
  9300. pool = select_longpoll_pool(cp);
  9301. }
  9302. }
  9303. if (pool->has_stratum) {
  9304. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  9305. cp->rpc_url, pool->rpc_url);
  9306. goto out;
  9307. }
  9308. /* Any longpoll from any pool is enough for this to be true */
  9309. have_longpoll = true;
  9310. wait_lpcurrent(cp);
  9311. {
  9312. lp_url = pool->lp_url;
  9313. if (cp == pool)
  9314. applog(LOG_WARNING, "Long-polling activated for %s (%s)", lp_url, pool_protocol_name(pool->lp_proto));
  9315. else
  9316. applog(LOG_WARNING, "Long-polling activated for %s via %s (%s)", cp->rpc_url, lp_url, pool_protocol_name(pool->lp_proto));
  9317. }
  9318. while (42) {
  9319. json_t *val, *soval;
  9320. struct work *work = make_work();
  9321. char *lpreq;
  9322. lpreq = prepare_rpc_req(work, pool->lp_proto, pool->lp_id);
  9323. work->pool = pool;
  9324. if (!lpreq)
  9325. {
  9326. free_work(work);
  9327. goto lpfail;
  9328. }
  9329. wait_lpcurrent(cp);
  9330. cgtime(&start);
  9331. /* Longpoll connections can be persistent for a very long time
  9332. * and any number of issues could have come up in the meantime
  9333. * so always establish a fresh connection instead of relying on
  9334. * a persistent one. */
  9335. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  9336. curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, save_curl_socket);
  9337. curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, pool);
  9338. val = json_rpc_call(curl, lp_url, pool->rpc_userpass,
  9339. lpreq, false, true, &rolltime, pool, false);
  9340. pool->lp_socket = CURL_SOCKET_BAD;
  9341. cgtime(&reply);
  9342. free(lpreq);
  9343. if (likely(val)) {
  9344. soval = json_object_get(json_object_get(val, "result"), "submitold");
  9345. if (soval)
  9346. pool->submit_old = json_is_true(soval);
  9347. else
  9348. pool->submit_old = false;
  9349. convert_to_work(val, rolltime, pool, work, &start, &reply);
  9350. failures = 0;
  9351. json_decref(val);
  9352. } else {
  9353. /* Some pools regularly drop the longpoll request so
  9354. * only see this as longpoll failure if it happens
  9355. * immediately and just restart it the rest of the
  9356. * time. */
  9357. cgtime(&end);
  9358. free_work(work);
  9359. if (end.tv_sec - start.tv_sec <= 30)
  9360. {
  9361. if (failures == 1)
  9362. applog(LOG_WARNING, "longpoll failed for %s, retrying every 30s", lp_url);
  9363. lpfail:
  9364. cgsleep_ms(30000);
  9365. }
  9366. }
  9367. if (pool != cp) {
  9368. pool = select_longpoll_pool(cp);
  9369. if (pool->has_stratum) {
  9370. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  9371. cp->rpc_url, pool->rpc_url);
  9372. break;
  9373. }
  9374. if (unlikely(!pool))
  9375. goto retry_pool;
  9376. }
  9377. if (unlikely(pool->removed))
  9378. break;
  9379. }
  9380. out:
  9381. pool->lp_active = false;
  9382. curl_easy_cleanup(curl);
  9383. return NULL;
  9384. }
  9385. static void stop_longpoll(void)
  9386. {
  9387. int i;
  9388. want_longpoll = false;
  9389. for (i = 0; i < total_pools; ++i)
  9390. {
  9391. struct pool *pool = pools[i];
  9392. if (unlikely(!pool->lp_started))
  9393. continue;
  9394. pool->lp_started = false;
  9395. pthread_cancel(pool->longpoll_thread);
  9396. }
  9397. have_longpoll = false;
  9398. }
  9399. static void start_longpoll(void)
  9400. {
  9401. int i;
  9402. want_longpoll = true;
  9403. for (i = 0; i < total_pools; ++i)
  9404. {
  9405. struct pool *pool = pools[i];
  9406. if (unlikely(pool->removed || pool->lp_started || !pool->lp_url))
  9407. continue;
  9408. pool->lp_started = true;
  9409. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  9410. quit(1, "Failed to create pool longpoll thread");
  9411. }
  9412. }
  9413. void reinit_device(struct cgpu_info *cgpu)
  9414. {
  9415. if (cgpu->drv->reinit_device)
  9416. cgpu->drv->reinit_device(cgpu);
  9417. }
  9418. static struct timeval rotate_tv;
  9419. /* We reap curls if they are unused for over a minute */
  9420. static void reap_curl(struct pool *pool)
  9421. {
  9422. struct curl_ent *ent, *iter;
  9423. struct timeval now;
  9424. int reaped = 0;
  9425. cgtime(&now);
  9426. mutex_lock(&pool->pool_lock);
  9427. LL_FOREACH_SAFE(pool->curllist, ent, iter) {
  9428. if (pool->curls < 2)
  9429. break;
  9430. if (now.tv_sec - ent->tv.tv_sec > 300) {
  9431. reaped++;
  9432. pool->curls--;
  9433. LL_DELETE(pool->curllist, ent);
  9434. curl_easy_cleanup(ent->curl);
  9435. free(ent);
  9436. }
  9437. }
  9438. mutex_unlock(&pool->pool_lock);
  9439. if (reaped)
  9440. applog(LOG_DEBUG, "Reaped %d curl%s from pool %d", reaped, reaped > 1 ? "s" : "", pool->pool_no);
  9441. }
  9442. static void *watchpool_thread(void __maybe_unused *userdata)
  9443. {
  9444. int intervals = 0;
  9445. #ifndef HAVE_PTHREAD_CANCEL
  9446. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  9447. #endif
  9448. RenameThread("watchpool");
  9449. while (42) {
  9450. struct timeval now;
  9451. int i;
  9452. if (++intervals > 20)
  9453. intervals = 0;
  9454. cgtime(&now);
  9455. for (i = 0; i < total_pools; i++) {
  9456. struct pool *pool = pools[i];
  9457. if (!opt_benchmark)
  9458. reap_curl(pool);
  9459. /* Get a rolling utility per pool over 10 mins */
  9460. if (intervals > 19) {
  9461. int shares = pool->diff1 - pool->last_shares;
  9462. pool->last_shares = pool->diff1;
  9463. pool->utility = (pool->utility + (double)shares * 0.63) / 1.63;
  9464. pool->shares = pool->utility;
  9465. }
  9466. if (pool->enabled == POOL_DISABLED)
  9467. continue;
  9468. /* Don't start testing any pools if the test threads
  9469. * from startup are still doing their first attempt. */
  9470. if (unlikely(pool->testing)) {
  9471. pthread_join(pool->test_thread, NULL);
  9472. }
  9473. /* Test pool is idle once every minute */
  9474. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 30) {
  9475. if (pool_active(pool, true) && pool_tclear(pool, &pool->idle))
  9476. pool_resus(pool);
  9477. }
  9478. /* Only switch pools if the failback pool has been
  9479. * alive for more than 5 minutes (default) to prevent
  9480. * intermittently failing pools from being used. */
  9481. 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)
  9482. {
  9483. if (opt_fail_switch_delay % 60)
  9484. applog(LOG_WARNING, "Pool %d %s stable for %d second%s",
  9485. pool->pool_no, pool->rpc_url,
  9486. opt_fail_switch_delay,
  9487. (opt_fail_switch_delay == 1 ? "" : "s"));
  9488. else
  9489. applog(LOG_WARNING, "Pool %d %s stable for %d minute%s",
  9490. pool->pool_no, pool->rpc_url,
  9491. opt_fail_switch_delay / 60,
  9492. (opt_fail_switch_delay == 60 ? "" : "s"));
  9493. switch_pools(NULL);
  9494. }
  9495. }
  9496. if (current_pool()->idle)
  9497. switch_pools(NULL);
  9498. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  9499. cgtime(&rotate_tv);
  9500. switch_pools(NULL);
  9501. }
  9502. cgsleep_ms(30000);
  9503. }
  9504. return NULL;
  9505. }
  9506. void mt_enable(struct thr_info *thr)
  9507. {
  9508. applog(LOG_DEBUG, "Waking up thread %d", thr->id);
  9509. notifier_wake(thr->notifier);
  9510. }
  9511. void proc_enable(struct cgpu_info *cgpu)
  9512. {
  9513. int j;
  9514. cgpu->deven = DEV_ENABLED;
  9515. for (j = cgpu->threads ?: 1; j--; )
  9516. mt_enable(cgpu->thr[j]);
  9517. }
  9518. #define device_recovered(cgpu) proc_enable(cgpu)
  9519. void cgpu_set_defaults(struct cgpu_info * const cgpu)
  9520. {
  9521. struct string_elist *setstr_elist;
  9522. const char *p, *p2;
  9523. char replybuf[0x2000];
  9524. size_t L;
  9525. DL_FOREACH(opt_set_device_list, setstr_elist)
  9526. {
  9527. const char * const setstr = setstr_elist->string;
  9528. p = strchr(setstr, ':');
  9529. if (!p)
  9530. p = setstr;
  9531. {
  9532. L = p - setstr;
  9533. char pattern[L + 1];
  9534. if (L)
  9535. memcpy(pattern, setstr, L);
  9536. pattern[L] = '\0';
  9537. if (!cgpu_match(pattern, cgpu))
  9538. continue;
  9539. }
  9540. applog(LOG_DEBUG, "%"PRIpreprv": %s: Matched with set default: %s",
  9541. cgpu->proc_repr, __func__, setstr);
  9542. if (p[0] == ':')
  9543. ++p;
  9544. p2 = strchr(p, '=');
  9545. if (!p2)
  9546. {
  9547. L = strlen(p);
  9548. p2 = "";
  9549. }
  9550. else
  9551. {
  9552. L = p2 - p;
  9553. ++p2;
  9554. }
  9555. char opt[L + 1];
  9556. if (L)
  9557. memcpy(opt, p, L);
  9558. opt[L] = '\0';
  9559. L = strlen(p2);
  9560. char setval[L + 1];
  9561. if (L)
  9562. memcpy(setval, p2, L);
  9563. setval[L] = '\0';
  9564. enum bfg_set_device_replytype success;
  9565. p = proc_set_device(cgpu, opt, setval, replybuf, &success);
  9566. switch (success)
  9567. {
  9568. case SDR_OK:
  9569. applog(LOG_DEBUG, "%"PRIpreprv": Applied rule %s%s%s",
  9570. cgpu->proc_repr, setstr,
  9571. p ? ": " : "", p ?: "");
  9572. break;
  9573. case SDR_ERR:
  9574. case SDR_HELP:
  9575. case SDR_UNKNOWN:
  9576. applog(LOG_DEBUG, "%"PRIpreprv": Applying rule %s: %s",
  9577. cgpu->proc_repr, setstr, p);
  9578. break;
  9579. case SDR_AUTO:
  9580. case SDR_NOSUPP:
  9581. applog(LOG_DEBUG, "%"PRIpreprv": set_device is not implemented (trying to apply rule: %s)",
  9582. cgpu->proc_repr, setstr);
  9583. }
  9584. }
  9585. cgpu->already_set_defaults = true;
  9586. }
  9587. 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)
  9588. {
  9589. struct device_drv dummy_drv = *drv;
  9590. struct cgpu_info dummy_cgpu = {
  9591. .drv = &dummy_drv,
  9592. .device = &dummy_cgpu,
  9593. .device_id = -1,
  9594. .proc_id = -1,
  9595. .device_data = userp,
  9596. .device_path = devpath,
  9597. .dev_serial = serial,
  9598. };
  9599. strcpy(dummy_cgpu.proc_repr, drv->name);
  9600. switch (mode)
  9601. {
  9602. case 0:
  9603. dummy_drv.set_device = datap;
  9604. break;
  9605. case 1:
  9606. dummy_drv.set_device = NULL;
  9607. dummy_cgpu.set_device_funcs = datap;
  9608. break;
  9609. }
  9610. cgpu_set_defaults(&dummy_cgpu);
  9611. }
  9612. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  9613. * the screen at regular intervals, and restarts threads if they appear to have
  9614. * died. */
  9615. #define WATCHDOG_SICK_TIME 60
  9616. #define WATCHDOG_DEAD_TIME 600
  9617. #define WATCHDOG_SICK_COUNT (WATCHDOG_SICK_TIME/WATCHDOG_INTERVAL)
  9618. #define WATCHDOG_DEAD_COUNT (WATCHDOG_DEAD_TIME/WATCHDOG_INTERVAL)
  9619. static void *watchdog_thread(void __maybe_unused *userdata)
  9620. {
  9621. const unsigned int interval = WATCHDOG_INTERVAL;
  9622. struct timeval zero_tv;
  9623. #ifndef HAVE_PTHREAD_CANCEL
  9624. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  9625. #endif
  9626. RenameThread("watchdog");
  9627. memset(&zero_tv, 0, sizeof(struct timeval));
  9628. cgtime(&rotate_tv);
  9629. while (1) {
  9630. int i;
  9631. struct timeval now;
  9632. sleep(interval);
  9633. discard_stale();
  9634. hashmeter(-1, &zero_tv, 0);
  9635. #ifdef HAVE_CURSES
  9636. const int ts = total_staged();
  9637. if (curses_active_locked()) {
  9638. change_logwinsize();
  9639. curses_print_status(ts);
  9640. _refresh_devstatus(true);
  9641. touchwin(logwin);
  9642. wrefresh(logwin);
  9643. unlock_curses();
  9644. }
  9645. #endif
  9646. cgtime(&now);
  9647. if (!sched_paused && !should_run()) {
  9648. applog(LOG_WARNING, "Pausing execution as per stop time %02d:%02d scheduled",
  9649. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  9650. if (!schedstart.enable) {
  9651. quit(0, "Terminating execution as planned");
  9652. break;
  9653. }
  9654. applog(LOG_WARNING, "Will restart execution as scheduled at %02d:%02d",
  9655. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  9656. sched_paused = true;
  9657. rd_lock(&mining_thr_lock);
  9658. for (i = 0; i < mining_threads; i++)
  9659. mining_thr[i]->pause = true;
  9660. rd_unlock(&mining_thr_lock);
  9661. } else if (sched_paused && should_run()) {
  9662. applog(LOG_WARNING, "Restarting execution as per start time %02d:%02d scheduled",
  9663. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  9664. if (schedstop.enable)
  9665. applog(LOG_WARNING, "Will pause execution as scheduled at %02d:%02d",
  9666. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  9667. sched_paused = false;
  9668. for (i = 0; i < mining_threads; i++) {
  9669. struct thr_info *thr;
  9670. thr = get_thread(i);
  9671. thr->pause = false;
  9672. }
  9673. for (i = 0; i < total_devices; ++i)
  9674. {
  9675. struct cgpu_info *cgpu = get_devices(i);
  9676. /* Don't touch disabled devices */
  9677. if (cgpu->deven == DEV_DISABLED)
  9678. continue;
  9679. proc_enable(cgpu);
  9680. }
  9681. }
  9682. for (i = 0; i < total_devices; ++i) {
  9683. struct cgpu_info *cgpu = get_devices(i);
  9684. if (!cgpu->disable_watchdog)
  9685. bfg_watchdog(cgpu, &now);
  9686. }
  9687. }
  9688. return NULL;
  9689. }
  9690. void bfg_watchdog(struct cgpu_info * const cgpu, struct timeval * const tvp_now)
  9691. {
  9692. struct thr_info *thr = cgpu->thr[0];
  9693. enum dev_enable *denable;
  9694. char *dev_str = cgpu->proc_repr;
  9695. if (likely(drv_ready(cgpu)))
  9696. {
  9697. if (unlikely(!cgpu->already_set_defaults))
  9698. cgpu_set_defaults(cgpu);
  9699. if (cgpu->drv->get_stats)
  9700. cgpu->drv->get_stats(cgpu);
  9701. }
  9702. denable = &cgpu->deven;
  9703. if (cgpu->drv->watchdog)
  9704. cgpu->drv->watchdog(cgpu, tvp_now);
  9705. /* Thread is disabled */
  9706. if (*denable == DEV_DISABLED)
  9707. return;
  9708. else
  9709. if (*denable == DEV_RECOVER_ERR) {
  9710. if (opt_restart && timer_elapsed(&cgpu->tv_device_last_not_well, NULL) > cgpu->reinit_backoff) {
  9711. applog(LOG_NOTICE, "Attempting to reinitialize %s",
  9712. dev_str);
  9713. if (cgpu->reinit_backoff < 300)
  9714. cgpu->reinit_backoff *= 2;
  9715. device_recovered(cgpu);
  9716. }
  9717. return;
  9718. }
  9719. else
  9720. if (*denable == DEV_RECOVER) {
  9721. if (opt_restart && cgpu->temp < cgpu->targettemp) {
  9722. applog(LOG_NOTICE, "%s recovered to temperature below target, re-enabling",
  9723. dev_str);
  9724. device_recovered(cgpu);
  9725. }
  9726. dev_error_update(cgpu, REASON_DEV_THERMAL_CUTOFF);
  9727. return;
  9728. }
  9729. else
  9730. if (cgpu->temp > cgpu->cutofftemp)
  9731. {
  9732. applog(LOG_WARNING, "%s hit thermal cutoff limit at %dC, disabling!",
  9733. dev_str, (int)cgpu->temp);
  9734. *denable = DEV_RECOVER;
  9735. dev_error(cgpu, REASON_DEV_THERMAL_CUTOFF);
  9736. run_cmd(cmd_idle);
  9737. }
  9738. if (thr->getwork) {
  9739. if (cgpu->status == LIFE_WELL && thr->getwork < tvp_now->tv_sec - opt_log_interval) {
  9740. int thrid;
  9741. bool cgpu_idle = true;
  9742. thr->rolling = 0;
  9743. for (thrid = 0; thrid < cgpu->threads; ++thrid)
  9744. if (!cgpu->thr[thrid]->getwork)
  9745. cgpu_idle = false;
  9746. if (cgpu_idle) {
  9747. cgpu->rolling = 0;
  9748. cgpu->status = LIFE_WAIT;
  9749. }
  9750. }
  9751. return;
  9752. }
  9753. else if (cgpu->status == LIFE_WAIT)
  9754. cgpu->status = LIFE_WELL;
  9755. #ifdef WANT_CPUMINE
  9756. if (!strcmp(cgpu->drv->dname, "cpu"))
  9757. return;
  9758. #endif
  9759. if (cgpu->status != LIFE_WELL && (tvp_now->tv_sec - thr->last.tv_sec < WATCHDOG_SICK_TIME)) {
  9760. if (likely(cgpu->status != LIFE_INIT && cgpu->status != LIFE_INIT2))
  9761. applog(LOG_ERR, "%s: Recovered, declaring WELL!", dev_str);
  9762. cgpu->status = LIFE_WELL;
  9763. cgpu->device_last_well = time(NULL);
  9764. } else if (cgpu->status == LIFE_WELL && (tvp_now->tv_sec - thr->last.tv_sec > WATCHDOG_SICK_TIME)) {
  9765. thr->rolling = cgpu->rolling = 0;
  9766. cgpu->status = LIFE_SICK;
  9767. applog(LOG_ERR, "%s: Idle for more than 60 seconds, declaring SICK!", dev_str);
  9768. cgtime(&thr->sick);
  9769. dev_error(cgpu, REASON_DEV_SICK_IDLE_60);
  9770. run_cmd(cmd_sick);
  9771. if (opt_restart && cgpu->drv->reinit_device) {
  9772. applog(LOG_ERR, "%s: Attempting to restart", dev_str);
  9773. reinit_device(cgpu);
  9774. }
  9775. } else if (cgpu->status == LIFE_SICK && (tvp_now->tv_sec - thr->last.tv_sec > WATCHDOG_DEAD_TIME)) {
  9776. cgpu->status = LIFE_DEAD;
  9777. applog(LOG_ERR, "%s: Not responded for more than 10 minutes, declaring DEAD!", dev_str);
  9778. cgtime(&thr->sick);
  9779. dev_error(cgpu, REASON_DEV_DEAD_IDLE_600);
  9780. run_cmd(cmd_dead);
  9781. } else if (tvp_now->tv_sec - thr->sick.tv_sec > 60 &&
  9782. (cgpu->status == LIFE_SICK || cgpu->status == LIFE_DEAD)) {
  9783. /* Attempt to restart a GPU that's sick or dead once every minute */
  9784. cgtime(&thr->sick);
  9785. if (opt_restart)
  9786. reinit_device(cgpu);
  9787. }
  9788. }
  9789. static void log_print_status(struct cgpu_info *cgpu)
  9790. {
  9791. char logline[255];
  9792. get_statline(logline, sizeof(logline), cgpu);
  9793. applog(LOG_WARNING, "%s", logline);
  9794. }
  9795. void print_summary(void)
  9796. {
  9797. struct timeval diff;
  9798. int hours, mins, secs, i;
  9799. double utility, efficiency = 0.0;
  9800. char xfer[(ALLOC_H2B_SPACED*2)+4+1], bw[(ALLOC_H2B_SPACED*2)+6+1];
  9801. int pool_secs;
  9802. timersub(&total_tv_end, &total_tv_start, &diff);
  9803. hours = diff.tv_sec / 3600;
  9804. mins = (diff.tv_sec % 3600) / 60;
  9805. secs = diff.tv_sec % 60;
  9806. utility = total_accepted / total_secs * 60;
  9807. efficiency = total_bytes_xfer ? total_diff_accepted * 2048. / total_bytes_xfer : 0.0;
  9808. applog(LOG_WARNING, "\nSummary of runtime statistics:\n");
  9809. applog(LOG_WARNING, "Started at %s", datestamp);
  9810. if (total_pools == 1)
  9811. applog(LOG_WARNING, "Pool: %s", pools[0]->rpc_url);
  9812. #ifdef WANT_CPUMINE
  9813. if (opt_n_threads > 0)
  9814. applog(LOG_WARNING, "CPU hasher algorithm used: %s", algo_names[opt_algo]);
  9815. #endif
  9816. applog(LOG_WARNING, "Runtime: %d hrs : %d mins : %d secs", hours, mins, secs);
  9817. applog(LOG_WARNING, "Average hashrate: %.1f Megahash/s", total_mhashes_done / total_secs);
  9818. applog(LOG_WARNING, "Solved blocks: %d", found_blocks);
  9819. applog(LOG_WARNING, "Best share difficulty: %s", best_share);
  9820. applog(LOG_WARNING, "Share submissions: %d", total_accepted + total_rejected);
  9821. applog(LOG_WARNING, "Accepted shares: %d", total_accepted);
  9822. applog(LOG_WARNING, "Rejected shares: %d + %d stale (%.2f%%)",
  9823. total_rejected, total_stale,
  9824. (float)(total_rejected + total_stale) / (float)(total_rejected + total_stale + total_accepted)
  9825. );
  9826. applog(LOG_WARNING, "Accepted difficulty shares: %1.f", total_diff_accepted);
  9827. applog(LOG_WARNING, "Rejected difficulty shares: %1.f", total_diff_rejected);
  9828. applog(LOG_WARNING, "Hardware errors: %d", hw_errors);
  9829. applog(LOG_WARNING, "Network transfer: %s (%s)",
  9830. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  9831. (float)total_bytes_rcvd,
  9832. (float)total_bytes_sent),
  9833. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  9834. (float)(total_bytes_rcvd / total_secs),
  9835. (float)(total_bytes_sent / total_secs)));
  9836. applog(LOG_WARNING, "Efficiency (accepted shares * difficulty / 2 KB): %.2f", efficiency);
  9837. applog(LOG_WARNING, "Utility (accepted shares / min): %.2f/min\n", utility);
  9838. applog(LOG_WARNING, "Unable to get work from server occasions: %d", total_go);
  9839. applog(LOG_WARNING, "Work items generated locally: %d", local_work);
  9840. applog(LOG_WARNING, "Submitting work remotely delay occasions: %d", total_ro);
  9841. applog(LOG_WARNING, "New blocks detected on network: %d\n", new_blocks);
  9842. if (total_pools > 1) {
  9843. for (i = 0; i < total_pools; i++) {
  9844. struct pool *pool = pools[i];
  9845. applog(LOG_WARNING, "Pool: %s", pool->rpc_url);
  9846. if (pool->solved)
  9847. applog(LOG_WARNING, "SOLVED %d BLOCK%s!", pool->solved, pool->solved > 1 ? "S" : "");
  9848. applog(LOG_WARNING, " Share submissions: %d", pool->accepted + pool->rejected);
  9849. applog(LOG_WARNING, " Accepted shares: %d", pool->accepted);
  9850. applog(LOG_WARNING, " Rejected shares: %d + %d stale (%.2f%%)",
  9851. pool->rejected, pool->stale_shares,
  9852. (float)(pool->rejected + pool->stale_shares) / (float)(pool->rejected + pool->stale_shares + pool->accepted)
  9853. );
  9854. applog(LOG_WARNING, " Accepted difficulty shares: %1.f", pool->diff_accepted);
  9855. applog(LOG_WARNING, " Rejected difficulty shares: %1.f", pool->diff_rejected);
  9856. pool_secs = timer_elapsed(&pool->cgminer_stats.start_tv, NULL);
  9857. applog(LOG_WARNING, " Network transfer: %s (%s)",
  9858. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  9859. (float)pool->cgminer_pool_stats.net_bytes_received,
  9860. (float)pool->cgminer_pool_stats.net_bytes_sent),
  9861. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  9862. (float)(pool->cgminer_pool_stats.net_bytes_received / pool_secs),
  9863. (float)(pool->cgminer_pool_stats.net_bytes_sent / pool_secs)));
  9864. uint64_t pool_bytes_xfer = pool->cgminer_pool_stats.net_bytes_received + pool->cgminer_pool_stats.net_bytes_sent;
  9865. efficiency = pool_bytes_xfer ? pool->diff_accepted * 2048. / pool_bytes_xfer : 0.0;
  9866. applog(LOG_WARNING, " Efficiency (accepted * difficulty / 2 KB): %.2f", efficiency);
  9867. applog(LOG_WARNING, " Items worked on: %d", pool->works);
  9868. applog(LOG_WARNING, " Unable to get work from server occasions: %d", pool->getfail_occasions);
  9869. applog(LOG_WARNING, " Submitting work remotely delay occasions: %d\n", pool->remotefail_occasions);
  9870. }
  9871. }
  9872. if (opt_quit_summary != BQS_NONE)
  9873. {
  9874. if (opt_quit_summary == BQS_DEFAULT)
  9875. {
  9876. if (total_devices < 25)
  9877. opt_quit_summary = BQS_PROCS;
  9878. else
  9879. opt_quit_summary = BQS_DEVS;
  9880. }
  9881. if (opt_quit_summary == BQS_DETAILED)
  9882. include_serial_in_statline = true;
  9883. applog(LOG_WARNING, "Summary of per device statistics:\n");
  9884. for (i = 0; i < total_devices; ++i) {
  9885. struct cgpu_info *cgpu = get_devices(i);
  9886. if (!cgpu->proc_id)
  9887. {
  9888. // Device summary line
  9889. opt_show_procs = false;
  9890. log_print_status(cgpu);
  9891. opt_show_procs = true;
  9892. }
  9893. if ((opt_quit_summary == BQS_PROCS || opt_quit_summary == BQS_DETAILED) && cgpu->procs > 1)
  9894. log_print_status(cgpu);
  9895. }
  9896. }
  9897. if (opt_shares) {
  9898. applog(LOG_WARNING, "Mined %g accepted shares of %g requested\n", total_diff_accepted, opt_shares);
  9899. if (opt_shares > total_diff_accepted)
  9900. applog(LOG_WARNING, "WARNING - Mined only %g shares of %g requested.", total_diff_accepted, opt_shares);
  9901. }
  9902. applog(LOG_WARNING, " ");
  9903. fflush(stderr);
  9904. fflush(stdout);
  9905. }
  9906. void _bfg_clean_up(bool restarting)
  9907. {
  9908. #ifdef HAVE_OPENCL
  9909. clear_adl(nDevs);
  9910. #endif
  9911. #ifdef HAVE_LIBUSB
  9912. if (likely(have_libusb))
  9913. libusb_exit(NULL);
  9914. #endif
  9915. cgtime(&total_tv_end);
  9916. #ifdef WIN32
  9917. timeEndPeriod(1);
  9918. #endif
  9919. if (!restarting) {
  9920. /* Attempting to disable curses or print a summary during a
  9921. * restart can lead to a deadlock. */
  9922. #ifdef HAVE_CURSES
  9923. disable_curses();
  9924. #endif
  9925. if (!opt_realquiet && successful_connect)
  9926. print_summary();
  9927. }
  9928. if (opt_n_threads > 0)
  9929. free(cpus);
  9930. curl_global_cleanup();
  9931. #ifdef WIN32
  9932. WSACleanup();
  9933. #endif
  9934. }
  9935. void _quit(int status)
  9936. {
  9937. if (status) {
  9938. const char *ev = getenv("__BFGMINER_SEGFAULT_ERRQUIT");
  9939. if (unlikely(ev && ev[0] && ev[0] != '0')) {
  9940. int *p = NULL;
  9941. // NOTE debugger can bypass with: p = &p
  9942. *p = status; // Segfault, hopefully dumping core
  9943. }
  9944. }
  9945. #if defined(unix) || defined(__APPLE__)
  9946. if (forkpid > 0) {
  9947. kill(forkpid, SIGTERM);
  9948. forkpid = 0;
  9949. }
  9950. #endif
  9951. exit(status);
  9952. }
  9953. #ifdef HAVE_CURSES
  9954. char *curses_input(const char *query)
  9955. {
  9956. char *input;
  9957. echo();
  9958. input = malloc(255);
  9959. if (!input)
  9960. quit(1, "Failed to malloc input");
  9961. leaveok(logwin, false);
  9962. wlogprint("%s:\n", query);
  9963. wgetnstr(logwin, input, 255);
  9964. if (!strlen(input))
  9965. {
  9966. free(input);
  9967. input = NULL;
  9968. }
  9969. leaveok(logwin, true);
  9970. noecho();
  9971. return input;
  9972. }
  9973. #endif
  9974. static void *test_pool_thread(void *arg)
  9975. {
  9976. struct pool *pool = (struct pool *)arg;
  9977. if (pool_active(pool, false)) {
  9978. pool_tset(pool, &pool->lagging);
  9979. pool_tclear(pool, &pool->idle);
  9980. bool first_pool = false;
  9981. cg_wlock(&control_lock);
  9982. if (!pools_active) {
  9983. currentpool = pool;
  9984. if (pool->pool_no != 0)
  9985. first_pool = true;
  9986. pools_active = true;
  9987. }
  9988. cg_wunlock(&control_lock);
  9989. if (unlikely(first_pool))
  9990. applog(LOG_NOTICE, "Switching to pool %d %s - first alive pool", pool->pool_no, pool->rpc_url);
  9991. else
  9992. applog(LOG_NOTICE, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  9993. switch_pools(NULL);
  9994. } else
  9995. pool_died(pool);
  9996. pool->testing = false;
  9997. return NULL;
  9998. }
  9999. /* Always returns true that the pool details were added unless we are not
  10000. * live, implying this is the only pool being added, so if no pools are
  10001. * active it returns false. */
  10002. bool add_pool_details(struct pool *pool, bool live, char *url, char *user, char *pass)
  10003. {
  10004. size_t siz;
  10005. pool_set_uri(pool, url);
  10006. pool->rpc_user = user;
  10007. pool->rpc_pass = pass;
  10008. siz = strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2;
  10009. pool->rpc_userpass = malloc(siz);
  10010. if (!pool->rpc_userpass)
  10011. quit(1, "Failed to malloc userpass");
  10012. snprintf(pool->rpc_userpass, siz, "%s:%s", pool->rpc_user, pool->rpc_pass);
  10013. pool->testing = true;
  10014. pool->idle = true;
  10015. enable_pool(pool);
  10016. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  10017. if (!live) {
  10018. pthread_join(pool->test_thread, NULL);
  10019. return pools_active;
  10020. }
  10021. return true;
  10022. }
  10023. #ifdef HAVE_CURSES
  10024. static bool input_pool(bool live)
  10025. {
  10026. char *url = NULL, *user = NULL, *pass = NULL;
  10027. struct pool *pool;
  10028. bool ret = false;
  10029. immedok(logwin, true);
  10030. wlogprint("Input server details.\n");
  10031. url = curses_input("URL");
  10032. if (!url)
  10033. goto out;
  10034. user = curses_input("Username");
  10035. if (!user)
  10036. goto out;
  10037. pass = curses_input("Password");
  10038. if (!pass)
  10039. pass = calloc(1, 1);
  10040. pool = add_pool();
  10041. if (!detect_stratum(pool, url) && strncmp(url, "http://", 7) &&
  10042. strncmp(url, "https://", 8)) {
  10043. char *httpinput;
  10044. httpinput = malloc(256);
  10045. if (!httpinput)
  10046. quit(1, "Failed to malloc httpinput");
  10047. strcpy(httpinput, "http://");
  10048. strncat(httpinput, url, 248);
  10049. free(url);
  10050. url = httpinput;
  10051. }
  10052. ret = add_pool_details(pool, live, url, user, pass);
  10053. out:
  10054. immedok(logwin, false);
  10055. if (!ret) {
  10056. if (url)
  10057. free(url);
  10058. if (user)
  10059. free(user);
  10060. if (pass)
  10061. free(pass);
  10062. }
  10063. return ret;
  10064. }
  10065. #endif
  10066. #if BLKMAKER_VERSION > 1
  10067. static
  10068. bool _add_local_gbt(const char * const filepath, void *userp)
  10069. {
  10070. const bool * const live_p = userp;
  10071. struct pool *pool;
  10072. char buf[0x100];
  10073. char *rpcuser = NULL, *rpcpass = NULL, *rpcconnect = NULL;
  10074. int rpcport = 0, rpcssl = -101;
  10075. FILE * const F = fopen(filepath, "r");
  10076. if (!F)
  10077. applogr(false, LOG_WARNING, "%s: Failed to open %s for reading", "add_local_gbt", filepath);
  10078. while (fgets(buf, sizeof(buf), F))
  10079. {
  10080. if (!strncasecmp(buf, "rpcuser=", 8))
  10081. rpcuser = trimmed_strdup(&buf[8]);
  10082. else
  10083. if (!strncasecmp(buf, "rpcpassword=", 12))
  10084. rpcpass = trimmed_strdup(&buf[12]);
  10085. else
  10086. if (!strncasecmp(buf, "rpcport=", 8))
  10087. rpcport = atoi(&buf[8]);
  10088. else
  10089. if (!strncasecmp(buf, "rpcssl=", 7))
  10090. rpcssl = atoi(&buf[7]);
  10091. else
  10092. if (!strncasecmp(buf, "rpcconnect=", 11))
  10093. rpcconnect = trimmed_strdup(&buf[11]);
  10094. else
  10095. continue;
  10096. if (rpcuser && rpcpass && rpcport && rpcssl != -101 && rpcconnect)
  10097. break;
  10098. }
  10099. fclose(F);
  10100. if (!rpcpass)
  10101. {
  10102. applog(LOG_DEBUG, "%s: Did not find rpcpassword in %s", "add_local_gbt", filepath);
  10103. err:
  10104. free(rpcuser);
  10105. free(rpcpass);
  10106. goto out;
  10107. }
  10108. if (!rpcport)
  10109. rpcport = 8332;
  10110. if (rpcssl == -101)
  10111. rpcssl = 0;
  10112. const bool have_cbaddr = bytes_len(&opt_coinbase_script);
  10113. const int uri_sz = 0x30;
  10114. char * const uri = malloc(uri_sz);
  10115. snprintf(uri, uri_sz, "http%s://%s:%d/%s#allblocks", rpcssl ? "s" : "", rpcconnect ?: "localhost", rpcport, have_cbaddr ? "" : "#getcbaddr");
  10116. char hfuri[0x40];
  10117. if (rpcconnect)
  10118. snprintf(hfuri, sizeof(hfuri), "%s:%d", rpcconnect, rpcport);
  10119. else
  10120. snprintf(hfuri, sizeof(hfuri), "port %d", rpcport);
  10121. applog(LOG_DEBUG, "Local bitcoin RPC server on %s found in %s", hfuri, filepath);
  10122. for (int i = 0; i < total_pools; ++i)
  10123. {
  10124. struct pool *pool = pools[i];
  10125. if (!(strcmp(pool->rpc_url, uri) || strcmp(pool->rpc_pass, rpcpass)))
  10126. {
  10127. applog(LOG_DEBUG, "Server on %s is already configured, not adding as failover", hfuri);
  10128. free(uri);
  10129. goto err;
  10130. }
  10131. }
  10132. pool = add_pool();
  10133. if (!pool)
  10134. {
  10135. applog(LOG_ERR, "%s: Error adding pool for bitcoin configured in %s", "add_local_gbt", filepath);
  10136. goto err;
  10137. }
  10138. if (!rpcuser)
  10139. rpcuser = "";
  10140. pool->quota = 0;
  10141. adjust_quota_gcd();
  10142. pool->failover_only = true;
  10143. add_pool_details(pool, *live_p, uri, rpcuser, rpcpass);
  10144. applog(LOG_NOTICE, "Added local bitcoin RPC server on %s as pool %d", hfuri, pool->pool_no);
  10145. out:
  10146. return false;
  10147. }
  10148. static
  10149. void add_local_gbt(bool live)
  10150. {
  10151. appdata_file_call("Bitcoin", "bitcoin.conf", _add_local_gbt, &live);
  10152. }
  10153. #endif
  10154. #if defined(unix) || defined(__APPLE__)
  10155. static void fork_monitor()
  10156. {
  10157. // Make a pipe: [readFD, writeFD]
  10158. int pfd[2];
  10159. int r = pipe(pfd);
  10160. if (r < 0) {
  10161. perror("pipe - failed to create pipe for --monitor");
  10162. exit(1);
  10163. }
  10164. // Make stderr write end of pipe
  10165. fflush(stderr);
  10166. r = dup2(pfd[1], 2);
  10167. if (r < 0) {
  10168. perror("dup2 - failed to alias stderr to write end of pipe for --monitor");
  10169. exit(1);
  10170. }
  10171. r = close(pfd[1]);
  10172. if (r < 0) {
  10173. perror("close - failed to close write end of pipe for --monitor");
  10174. exit(1);
  10175. }
  10176. // Don't allow a dying monitor to kill the main process
  10177. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  10178. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  10179. if (SIG_ERR == sr0 || SIG_ERR == sr1) {
  10180. perror("signal - failed to edit signal mask for --monitor");
  10181. exit(1);
  10182. }
  10183. // Fork a child process
  10184. forkpid = fork();
  10185. if (forkpid < 0) {
  10186. perror("fork - failed to fork child process for --monitor");
  10187. exit(1);
  10188. }
  10189. // Child: launch monitor command
  10190. if (0 == forkpid) {
  10191. // Make stdin read end of pipe
  10192. r = dup2(pfd[0], 0);
  10193. if (r < 0) {
  10194. perror("dup2 - in child, failed to alias read end of pipe to stdin for --monitor");
  10195. exit(1);
  10196. }
  10197. close(pfd[0]);
  10198. if (r < 0) {
  10199. perror("close - in child, failed to close read end of pipe for --monitor");
  10200. exit(1);
  10201. }
  10202. // Launch user specified command
  10203. execl("/bin/bash", "/bin/bash", "-c", opt_stderr_cmd, (char*)NULL);
  10204. perror("execl - in child failed to exec user specified command for --monitor");
  10205. exit(1);
  10206. }
  10207. // Parent: clean up unused fds and bail
  10208. r = close(pfd[0]);
  10209. if (r < 0) {
  10210. perror("close - failed to close read end of pipe for --monitor");
  10211. exit(1);
  10212. }
  10213. }
  10214. #endif // defined(unix)
  10215. #ifdef HAVE_CURSES
  10216. #ifdef USE_UNICODE
  10217. static
  10218. wchar_t select_unicode_char(const wchar_t *opt)
  10219. {
  10220. for ( ; *opt; ++opt)
  10221. if (iswprint(*opt))
  10222. return *opt;
  10223. return '?';
  10224. }
  10225. #endif
  10226. void enable_curses(void) {
  10227. int x;
  10228. __maybe_unused int y;
  10229. lock_curses();
  10230. if (curses_active) {
  10231. unlock_curses();
  10232. return;
  10233. }
  10234. #ifdef USE_UNICODE
  10235. if (use_unicode)
  10236. {
  10237. setlocale(LC_CTYPE, "");
  10238. if (iswprint(0xb0))
  10239. have_unicode_degrees = true;
  10240. unicode_micro = select_unicode_char(L"\xb5\u03bcu");
  10241. }
  10242. #endif
  10243. mainwin = initscr();
  10244. start_color();
  10245. #if defined(PDCURSES) || defined(NCURSES_VERSION)
  10246. if (ERR != use_default_colors())
  10247. default_bgcolor = -1;
  10248. #endif
  10249. if (has_colors() && ERR != init_pair(1, COLOR_WHITE, COLOR_BLUE))
  10250. {
  10251. menu_attr = COLOR_PAIR(1);
  10252. if (ERR != init_pair(2, COLOR_RED, default_bgcolor))
  10253. attr_bad |= COLOR_PAIR(2);
  10254. }
  10255. keypad(mainwin, true);
  10256. getmaxyx(mainwin, y, x);
  10257. statuswin = newwin(logstart, x, 0, 0);
  10258. leaveok(statuswin, true);
  10259. // For whatever reason, PDCurses crashes if the logwin is initialized to height y-logcursor
  10260. // We resize the window later anyway, so just start it off at 1 :)
  10261. logwin = newwin(1, 0, logcursor, 0);
  10262. idlok(logwin, true);
  10263. scrollok(logwin, true);
  10264. leaveok(logwin, true);
  10265. cbreak();
  10266. noecho();
  10267. nonl();
  10268. curses_active = true;
  10269. statusy = logstart;
  10270. unlock_curses();
  10271. }
  10272. #endif
  10273. /* TODO: fix need a dummy CPU device_drv even if no support for CPU mining */
  10274. #ifndef WANT_CPUMINE
  10275. struct device_drv cpu_drv;
  10276. struct device_drv cpu_drv = {
  10277. .name = "CPU",
  10278. };
  10279. #endif
  10280. static int cgminer_id_count = 0;
  10281. static int device_line_id_count;
  10282. void register_device(struct cgpu_info *cgpu)
  10283. {
  10284. cgpu->deven = DEV_ENABLED;
  10285. wr_lock(&devices_lock);
  10286. devices[cgpu->cgminer_id = cgminer_id_count++] = cgpu;
  10287. wr_unlock(&devices_lock);
  10288. if (!cgpu->proc_id)
  10289. cgpu->device_line_id = device_line_id_count++;
  10290. int thr_objs = cgpu->threads ?: 1;
  10291. mining_threads += thr_objs;
  10292. base_queue += thr_objs + cgpu->extra_work_queue;
  10293. #ifdef HAVE_CURSES
  10294. adj_width(mining_threads, &dev_width);
  10295. #endif
  10296. rwlock_init(&cgpu->qlock);
  10297. cgpu->queued_work = NULL;
  10298. }
  10299. struct _cgpu_devid_counter {
  10300. char name[4];
  10301. int lastid;
  10302. UT_hash_handle hh;
  10303. };
  10304. void renumber_cgpu(struct cgpu_info *cgpu)
  10305. {
  10306. static struct _cgpu_devid_counter *devids = NULL;
  10307. struct _cgpu_devid_counter *d;
  10308. HASH_FIND_STR(devids, cgpu->drv->name, d);
  10309. if (d)
  10310. cgpu->device_id = ++d->lastid;
  10311. else {
  10312. d = malloc(sizeof(*d));
  10313. memcpy(d->name, cgpu->drv->name, sizeof(d->name));
  10314. cgpu->device_id = d->lastid = 0;
  10315. HASH_ADD_STR(devids, name, d);
  10316. }
  10317. // Build repr strings
  10318. sprintf(cgpu->dev_repr, "%s%2u", cgpu->drv->name, cgpu->device_id % 100);
  10319. sprintf(cgpu->dev_repr_ns, "%s%u", cgpu->drv->name, cgpu->device_id % 100);
  10320. strcpy(cgpu->proc_repr, cgpu->dev_repr);
  10321. sprintf(cgpu->proc_repr_ns, "%s%u", cgpu->drv->name, cgpu->device_id);
  10322. const int lpcount = cgpu->procs;
  10323. if (lpcount > 1)
  10324. {
  10325. int ns;
  10326. struct cgpu_info *slave;
  10327. int lpdigits = 1;
  10328. for (int i = lpcount; i > 26 && lpdigits < 3; i /= 26)
  10329. ++lpdigits;
  10330. if (lpdigits > max_lpdigits)
  10331. max_lpdigits = lpdigits;
  10332. memset(&cgpu->proc_repr[5], 'a', lpdigits);
  10333. cgpu->proc_repr[5 + lpdigits] = '\0';
  10334. ns = strlen(cgpu->proc_repr_ns);
  10335. strcpy(&cgpu->proc_repr_ns[ns], &cgpu->proc_repr[5]);
  10336. slave = cgpu;
  10337. for (int i = 1; i < lpcount; ++i)
  10338. {
  10339. slave = slave->next_proc;
  10340. strcpy(slave->proc_repr, cgpu->proc_repr);
  10341. strcpy(slave->proc_repr_ns, cgpu->proc_repr_ns);
  10342. for (int x = i, y = lpdigits; --y, x; x /= 26)
  10343. {
  10344. slave->proc_repr_ns[ns + y] =
  10345. slave->proc_repr[5 + y] += (x % 26);
  10346. }
  10347. }
  10348. }
  10349. }
  10350. static bool my_blkmaker_sha256_callback(void *digest, const void *buffer, size_t length)
  10351. {
  10352. sha256(buffer, length, digest);
  10353. return true;
  10354. }
  10355. static
  10356. int drv_algo_check(const struct device_drv * const drv)
  10357. {
  10358. const int algomatch = opt_scrypt ? POW_SCRYPT : POW_SHA256D;
  10359. const supported_algos_t algos = drv->supported_algos ?: POW_SHA256D;
  10360. return (algos & algomatch);
  10361. }
  10362. #ifndef HAVE_PTHREAD_CANCEL
  10363. extern void setup_pthread_cancel_workaround();
  10364. extern struct sigaction pcwm_orig_term_handler;
  10365. #endif
  10366. bool bfg_need_detect_rescan;
  10367. extern void probe_device(struct lowlevel_device_info *);
  10368. static void schedule_rescan(const struct timeval *);
  10369. static
  10370. void drv_detect_all()
  10371. {
  10372. bool rescanning = false;
  10373. rescan:
  10374. bfg_need_detect_rescan = false;
  10375. #ifdef HAVE_BFG_LOWLEVEL
  10376. struct lowlevel_device_info * const infolist = lowlevel_scan(), *info, *infotmp;
  10377. LL_FOREACH_SAFE(infolist, info, infotmp)
  10378. probe_device(info);
  10379. LL_FOREACH_SAFE(infolist, info, infotmp)
  10380. pthread_join(info->probe_pth, NULL);
  10381. #endif
  10382. struct driver_registration *reg, *tmp;
  10383. BFG_FOREACH_DRIVER_BY_PRIORITY(reg, tmp)
  10384. {
  10385. const struct device_drv * const drv = reg->drv;
  10386. if (!(drv_algo_check(drv) && drv->drv_detect))
  10387. continue;
  10388. drv->drv_detect();
  10389. }
  10390. #ifdef HAVE_BFG_LOWLEVEL
  10391. lowlevel_scan_free();
  10392. #endif
  10393. if (bfg_need_detect_rescan)
  10394. {
  10395. if (rescanning)
  10396. {
  10397. applog(LOG_DEBUG, "Device rescan requested a second time, delaying");
  10398. struct timeval tv_when;
  10399. timer_set_delay_from_now(&tv_when, rescan_delay_ms * 1000);
  10400. schedule_rescan(&tv_when);
  10401. }
  10402. else
  10403. {
  10404. rescanning = true;
  10405. applog(LOG_DEBUG, "Device rescan requested");
  10406. goto rescan;
  10407. }
  10408. }
  10409. }
  10410. static
  10411. void allocate_cgpu(struct cgpu_info *cgpu, unsigned int *kp)
  10412. {
  10413. struct thr_info *thr;
  10414. int j;
  10415. struct device_drv *api = cgpu->drv;
  10416. cgpu->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  10417. int threadobj = cgpu->threads;
  10418. if (!threadobj)
  10419. // Create a fake thread object to handle hashmeter etc
  10420. threadobj = 1;
  10421. cgpu->thr = calloc(threadobj + 1, sizeof(*cgpu->thr));
  10422. cgpu->thr[threadobj] = NULL;
  10423. cgpu->status = LIFE_INIT;
  10424. if (opt_devices_enabled_list)
  10425. {
  10426. struct string_elist *enablestr_elist;
  10427. cgpu->deven = DEV_DISABLED;
  10428. DL_FOREACH(opt_devices_enabled_list, enablestr_elist)
  10429. {
  10430. const char * const enablestr = enablestr_elist->string;
  10431. if (cgpu_match(enablestr, cgpu))
  10432. {
  10433. cgpu->deven = DEV_ENABLED;
  10434. break;
  10435. }
  10436. }
  10437. }
  10438. cgpu->max_hashes = 0;
  10439. BFGINIT(cgpu->min_nonce_diff, 1);
  10440. BFGINIT(cgpu->cutofftemp, opt_cutofftemp);
  10441. BFGINIT(cgpu->targettemp, cgpu->cutofftemp - 6);
  10442. // Setup thread structs before starting any of the threads, in case they try to interact
  10443. for (j = 0; j < threadobj; ++j, ++*kp) {
  10444. thr = get_thread(*kp);
  10445. thr->id = *kp;
  10446. thr->cgpu = cgpu;
  10447. thr->device_thread = j;
  10448. thr->work_restart_notifier[1] = INVSOCK;
  10449. thr->mutex_request[1] = INVSOCK;
  10450. thr->_job_transition_in_progress = true;
  10451. timerclear(&thr->tv_morework);
  10452. thr->scanhash_working = true;
  10453. thr->hashes_done = 0;
  10454. timerclear(&thr->tv_hashes_done);
  10455. cgtime(&thr->tv_lastupdate);
  10456. thr->tv_poll.tv_sec = -1;
  10457. thr->_max_nonce = api->can_limit_work ? api->can_limit_work(thr) : 0xffffffff;
  10458. cgpu->thr[j] = thr;
  10459. }
  10460. if (!cgpu->device->threads)
  10461. notifier_init_invalid(cgpu->thr[0]->notifier);
  10462. else
  10463. if (!cgpu->threads)
  10464. memcpy(&cgpu->thr[0]->notifier, &cgpu->device->thr[0]->notifier, sizeof(cgpu->thr[0]->notifier));
  10465. else
  10466. for (j = 0; j < cgpu->threads; ++j)
  10467. {
  10468. thr = cgpu->thr[j];
  10469. notifier_init(thr->notifier);
  10470. }
  10471. }
  10472. static
  10473. void start_cgpu(struct cgpu_info *cgpu)
  10474. {
  10475. struct thr_info *thr;
  10476. int j;
  10477. for (j = 0; j < cgpu->threads; ++j) {
  10478. thr = cgpu->thr[j];
  10479. /* Enable threads for devices set not to mine but disable
  10480. * their queue in case we wish to enable them later */
  10481. if (cgpu->drv->thread_prepare && !cgpu->drv->thread_prepare(thr))
  10482. continue;
  10483. thread_reportout(thr);
  10484. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  10485. quit(1, "thread %d create failed", thr->id);
  10486. notifier_wake(thr->notifier);
  10487. }
  10488. if (cgpu->deven == DEV_ENABLED)
  10489. proc_enable(cgpu);
  10490. }
  10491. static
  10492. void _scan_serial(void *p)
  10493. {
  10494. const char *s = p;
  10495. struct string_elist *iter, *tmp;
  10496. struct string_elist *orig_scan_devices = scan_devices;
  10497. if (s)
  10498. {
  10499. // Make temporary scan_devices list
  10500. scan_devices = NULL;
  10501. string_elist_add("noauto", &scan_devices);
  10502. add_serial(s);
  10503. }
  10504. drv_detect_all();
  10505. if (s)
  10506. {
  10507. DL_FOREACH_SAFE(scan_devices, iter, tmp)
  10508. {
  10509. string_elist_del(&scan_devices, iter);
  10510. }
  10511. scan_devices = orig_scan_devices;
  10512. }
  10513. }
  10514. #ifdef HAVE_BFG_LOWLEVEL
  10515. static
  10516. bool _probe_device_match(const struct lowlevel_device_info * const info, const char * const ser)
  10517. {
  10518. if (!(false
  10519. || (info->serial && !strcasecmp(ser, info->serial))
  10520. || (info->path && !strcasecmp(ser, info->path ))
  10521. || (info->devid && !strcasecmp(ser, info->devid ))
  10522. ))
  10523. {
  10524. char *devid = devpath_to_devid(ser);
  10525. if (!devid)
  10526. return false;
  10527. const bool different = strcmp(info->devid, devid);
  10528. free(devid);
  10529. if (different)
  10530. return false;
  10531. }
  10532. return true;
  10533. }
  10534. static
  10535. const struct device_drv *_probe_device_find_drv(const char * const _dname, const size_t dnamelen)
  10536. {
  10537. struct driver_registration *dreg;
  10538. char dname[dnamelen];
  10539. int i;
  10540. for (i = 0; i < dnamelen; ++i)
  10541. dname[i] = tolower(_dname[i]);
  10542. BFG_FIND_DRV_BY_DNAME(dreg, dname, dnamelen);
  10543. if (!dreg)
  10544. {
  10545. for (i = 0; i < dnamelen; ++i)
  10546. dname[i] = toupper(_dname[i]);
  10547. BFG_FIND_DRV_BY_NAME(dreg, dname, dnamelen);
  10548. if (!dreg)
  10549. return NULL;
  10550. }
  10551. if (!drv_algo_check(dreg->drv))
  10552. return NULL;
  10553. return dreg->drv;
  10554. }
  10555. static
  10556. bool _probe_device_do_probe(const struct device_drv * const drv, const struct lowlevel_device_info * const info, bool * const request_rescan_p)
  10557. {
  10558. bfg_probe_result_flags = 0;
  10559. if (drv->lowl_probe(info))
  10560. {
  10561. if (!(bfg_probe_result_flags & BPR_CONTINUE_PROBES))
  10562. return true;
  10563. }
  10564. else
  10565. if (request_rescan_p && opt_hotplug && !(bfg_probe_result_flags & BPR_DONT_RESCAN))
  10566. *request_rescan_p = true;
  10567. return false;
  10568. }
  10569. bool dummy_check_never_true = false;
  10570. static
  10571. void *probe_device_thread(void *p)
  10572. {
  10573. struct lowlevel_device_info * const infolist = p;
  10574. struct lowlevel_device_info *info = infolist;
  10575. bool request_rescan = false;
  10576. {
  10577. char threadname[5 + strlen(info->devid) + 1];
  10578. sprintf(threadname, "probe_%s", info->devid);
  10579. RenameThread(threadname);
  10580. }
  10581. // If already in use, ignore
  10582. if (bfg_claim_any(NULL, NULL, info->devid))
  10583. applogr(NULL, LOG_DEBUG, "%s: \"%s\" already in use",
  10584. __func__, info->product);
  10585. // if lowlevel device matches specific user assignment, probe requested driver(s)
  10586. struct string_elist *sd_iter, *sd_tmp;
  10587. struct driver_registration *dreg, *dreg_tmp;
  10588. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  10589. {
  10590. const char * const dname = sd_iter->string;
  10591. const char * const colon = strpbrk(dname, ":@");
  10592. if (!(colon && colon != dname))
  10593. continue;
  10594. const char * const ser = &colon[1];
  10595. LL_FOREACH2(infolist, info, same_devid_next)
  10596. {
  10597. if (!_probe_device_match(info, ser))
  10598. continue;
  10599. const size_t dnamelen = (colon - dname);
  10600. const struct device_drv * const drv = _probe_device_find_drv(dname, dnamelen);
  10601. if (!(drv && drv->lowl_probe && drv_algo_check(drv)))
  10602. continue;
  10603. if (_probe_device_do_probe(drv, info, &request_rescan))
  10604. return NULL;
  10605. }
  10606. }
  10607. // probe driver(s) with auto enabled and matching VID/PID/Product/etc of device
  10608. BFG_FOREACH_DRIVER_BY_PRIORITY(dreg, dreg_tmp)
  10609. {
  10610. const struct device_drv * const drv = dreg->drv;
  10611. if (!drv_algo_check(drv))
  10612. continue;
  10613. // Check for "noauto" flag
  10614. // NOTE: driver-specific configuration overrides general
  10615. bool doauto = true;
  10616. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  10617. {
  10618. const char * const dname = sd_iter->string;
  10619. // NOTE: Only checking flags here, NOT path/serial, so @ is unacceptable
  10620. const char *colon = strchr(dname, ':');
  10621. if (!colon)
  10622. colon = &dname[-1];
  10623. if (strcasecmp("noauto", &colon[1]) && strcasecmp("auto", &colon[1]))
  10624. continue;
  10625. const ssize_t dnamelen = (colon - dname);
  10626. if (dnamelen >= 0 && _probe_device_find_drv(dname, dnamelen) != drv)
  10627. continue;
  10628. doauto = (tolower(colon[1]) == 'a');
  10629. if (dnamelen != -1)
  10630. break;
  10631. }
  10632. if (doauto && drv->lowl_match)
  10633. {
  10634. LL_FOREACH2(infolist, info, same_devid_next)
  10635. {
  10636. /*
  10637. The below call to applog is absolutely necessary
  10638. Starting with commit 76d0cc183b1c9ddcc0ef34d2e43bc696ef9de92e installing BFGMiner on
  10639. Mac OS X using Homebrew results in a binary that segfaults on startup
  10640. There are two unresolved issues:
  10641. 1) The BFGMiner authors cannot find a way to install BFGMiner with Homebrew that results
  10642. in debug symbols being available to help troubleshoot the issue
  10643. 2) The issue disappears when unrelated code changes are made, such as adding the following
  10644. call to applog with infolist and / or p
  10645. We would encourage revisiting this in the future to come up with a more concrete solution
  10646. Reproducing should only require commenting / removing the following line and installing
  10647. BFGMiner using "brew install bfgminer --HEAD"
  10648. */
  10649. if (dummy_check_never_true)
  10650. applog(LOG_DEBUG, "lowl_match: %p(%s) %p %p %p", drv, drv->dname, info, infolist, p);
  10651. if (!drv->lowl_match(info))
  10652. continue;
  10653. if (_probe_device_do_probe(drv, info, &request_rescan))
  10654. return NULL;
  10655. }
  10656. }
  10657. }
  10658. // probe driver(s) with 'all' enabled
  10659. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  10660. {
  10661. const char * const dname = sd_iter->string;
  10662. // NOTE: Only checking flags here, NOT path/serial, so @ is unacceptable
  10663. const char * const colon = strchr(dname, ':');
  10664. if (!colon)
  10665. {
  10666. LL_FOREACH2(infolist, info, same_devid_next)
  10667. {
  10668. if (
  10669. #ifdef NEED_BFG_LOWL_VCOM
  10670. (info->lowl == &lowl_vcom && !strcasecmp(dname, "all")) ||
  10671. #endif
  10672. _probe_device_match(info, (dname[0] == '@') ? &dname[1] : dname))
  10673. {
  10674. bool dont_rescan = false;
  10675. BFG_FOREACH_DRIVER_BY_PRIORITY(dreg, dreg_tmp)
  10676. {
  10677. const struct device_drv * const drv = dreg->drv;
  10678. if (!drv_algo_check(drv))
  10679. continue;
  10680. if (drv->lowl_probe_by_name_only)
  10681. continue;
  10682. if (!drv->lowl_probe)
  10683. continue;
  10684. if (_probe_device_do_probe(drv, info, NULL))
  10685. return NULL;
  10686. if (bfg_probe_result_flags & BPR_DONT_RESCAN)
  10687. dont_rescan = true;
  10688. }
  10689. if (opt_hotplug && !dont_rescan)
  10690. request_rescan = true;
  10691. break;
  10692. }
  10693. }
  10694. continue;
  10695. }
  10696. if (strcasecmp(&colon[1], "all"))
  10697. continue;
  10698. const size_t dnamelen = (colon - dname);
  10699. const struct device_drv * const drv = _probe_device_find_drv(dname, dnamelen);
  10700. if (!(drv && drv->lowl_probe && drv_algo_check(drv)))
  10701. continue;
  10702. LL_FOREACH2(infolist, info, same_devid_next)
  10703. {
  10704. if (info->lowl->exclude_from_all)
  10705. continue;
  10706. if (_probe_device_do_probe(drv, info, NULL))
  10707. return NULL;
  10708. }
  10709. }
  10710. // Only actually request a rescan if we never found any cgpu
  10711. if (request_rescan)
  10712. bfg_need_detect_rescan = true;
  10713. return NULL;
  10714. }
  10715. void probe_device(struct lowlevel_device_info * const info)
  10716. {
  10717. pthread_create(&info->probe_pth, NULL, probe_device_thread, info);
  10718. }
  10719. #endif
  10720. int create_new_cgpus(void (*addfunc)(void*), void *arg)
  10721. {
  10722. static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  10723. int devcount, i, mining_threads_new = 0;
  10724. unsigned int k;
  10725. struct cgpu_info *cgpu;
  10726. struct thr_info *thr;
  10727. void *p;
  10728. mutex_lock(&mutex);
  10729. devcount = total_devices;
  10730. addfunc(arg);
  10731. if (!total_devices_new)
  10732. goto out;
  10733. wr_lock(&devices_lock);
  10734. p = realloc(devices, sizeof(struct cgpu_info *) * (total_devices + total_devices_new + 1));
  10735. if (unlikely(!p))
  10736. {
  10737. wr_unlock(&devices_lock);
  10738. applog(LOG_ERR, "scan_serial: realloc failed trying to grow devices array");
  10739. goto out;
  10740. }
  10741. devices = p;
  10742. wr_unlock(&devices_lock);
  10743. for (i = 0; i < total_devices_new; ++i)
  10744. {
  10745. cgpu = devices_new[i];
  10746. mining_threads_new += cgpu->threads ?: 1;
  10747. }
  10748. wr_lock(&mining_thr_lock);
  10749. mining_threads_new += mining_threads;
  10750. p = realloc(mining_thr, sizeof(struct thr_info *) * mining_threads_new);
  10751. if (unlikely(!p))
  10752. {
  10753. wr_unlock(&mining_thr_lock);
  10754. applog(LOG_ERR, "scan_serial: realloc failed trying to grow mining_thr");
  10755. goto out;
  10756. }
  10757. mining_thr = p;
  10758. wr_unlock(&mining_thr_lock);
  10759. for (i = mining_threads; i < mining_threads_new; ++i) {
  10760. mining_thr[i] = calloc(1, sizeof(*thr));
  10761. if (!mining_thr[i])
  10762. {
  10763. applog(LOG_ERR, "scan_serial: Failed to calloc mining_thr[%d]", i);
  10764. for ( ; --i >= mining_threads; )
  10765. free(mining_thr[i]);
  10766. goto out;
  10767. }
  10768. }
  10769. k = mining_threads;
  10770. for (i = 0; i < total_devices_new; ++i)
  10771. {
  10772. cgpu = devices_new[i];
  10773. allocate_cgpu(cgpu, &k);
  10774. }
  10775. for (i = 0; i < total_devices_new; ++i)
  10776. {
  10777. cgpu = devices_new[i];
  10778. start_cgpu(cgpu);
  10779. register_device(cgpu);
  10780. ++total_devices;
  10781. }
  10782. #ifdef HAVE_CURSES
  10783. switch_logsize();
  10784. #endif
  10785. out:
  10786. total_devices_new = 0;
  10787. devcount = total_devices - devcount;
  10788. mutex_unlock(&mutex);
  10789. return devcount;
  10790. }
  10791. int scan_serial(const char *s)
  10792. {
  10793. return create_new_cgpus(_scan_serial, (void*)s);
  10794. }
  10795. static pthread_mutex_t rescan_mutex = PTHREAD_MUTEX_INITIALIZER;
  10796. static bool rescan_active;
  10797. static struct timeval tv_rescan;
  10798. static notifier_t rescan_notifier;
  10799. static
  10800. void *rescan_thread(__maybe_unused void *p)
  10801. {
  10802. pthread_detach(pthread_self());
  10803. RenameThread("rescan");
  10804. struct timeval tv_timeout, tv_now;
  10805. fd_set rfds;
  10806. while (true)
  10807. {
  10808. mutex_lock(&rescan_mutex);
  10809. tv_timeout = tv_rescan;
  10810. if (!timer_isset(&tv_timeout))
  10811. {
  10812. rescan_active = false;
  10813. mutex_unlock(&rescan_mutex);
  10814. break;
  10815. }
  10816. mutex_unlock(&rescan_mutex);
  10817. FD_ZERO(&rfds);
  10818. FD_SET(rescan_notifier[0], &rfds);
  10819. const int maxfd = rescan_notifier[0];
  10820. timer_set_now(&tv_now);
  10821. if (select(maxfd+1, &rfds, NULL, NULL, select_timeout(&tv_timeout, &tv_now)) > 0)
  10822. notifier_read(rescan_notifier);
  10823. mutex_lock(&rescan_mutex);
  10824. if (timer_passed(&tv_rescan, NULL))
  10825. {
  10826. timer_unset(&tv_rescan);
  10827. mutex_unlock(&rescan_mutex);
  10828. applog(LOG_DEBUG, "Rescan timer expired, triggering");
  10829. scan_serial(NULL);
  10830. }
  10831. else
  10832. mutex_unlock(&rescan_mutex);
  10833. }
  10834. return NULL;
  10835. }
  10836. static
  10837. void _schedule_rescan(const struct timeval * const tvp_when)
  10838. {
  10839. if (rescan_active)
  10840. {
  10841. if (timercmp(tvp_when, &tv_rescan, <))
  10842. applog(LOG_DEBUG, "schedule_rescan: New schedule is before current, waiting it out");
  10843. else
  10844. {
  10845. applog(LOG_DEBUG, "schedule_rescan: New schedule is after current, delaying rescan");
  10846. tv_rescan = *tvp_when;
  10847. }
  10848. return;
  10849. }
  10850. applog(LOG_DEBUG, "schedule_rescan: Scheduling rescan (no rescans currently pending)");
  10851. tv_rescan = *tvp_when;
  10852. rescan_active = true;
  10853. static pthread_t pth;
  10854. if (unlikely(pthread_create(&pth, NULL, rescan_thread, NULL)))
  10855. applog(LOG_ERR, "Failed to start rescan thread");
  10856. }
  10857. static
  10858. void schedule_rescan(const struct timeval * const tvp_when)
  10859. {
  10860. mutex_lock(&rescan_mutex);
  10861. _schedule_rescan(tvp_when);
  10862. mutex_unlock(&rescan_mutex);
  10863. }
  10864. #ifdef HAVE_BFG_HOTPLUG
  10865. static
  10866. void hotplug_trigger()
  10867. {
  10868. applog(LOG_DEBUG, "%s: Scheduling rescan immediately", __func__);
  10869. struct timeval tv_now;
  10870. timer_set_now(&tv_now);
  10871. schedule_rescan(&tv_now);
  10872. }
  10873. #endif
  10874. #if defined(HAVE_LIBUDEV) && defined(HAVE_SYS_EPOLL_H)
  10875. static
  10876. void *hotplug_thread(__maybe_unused void *p)
  10877. {
  10878. pthread_detach(pthread_self());
  10879. RenameThread("hotplug");
  10880. struct udev * const udev = udev_new();
  10881. if (unlikely(!udev))
  10882. applogfailr(NULL, LOG_ERR, "udev_new");
  10883. struct udev_monitor * const mon = udev_monitor_new_from_netlink(udev, "udev");
  10884. if (unlikely(!mon))
  10885. applogfailr(NULL, LOG_ERR, "udev_monitor_new_from_netlink");
  10886. if (unlikely(udev_monitor_enable_receiving(mon)))
  10887. applogfailr(NULL, LOG_ERR, "udev_monitor_enable_receiving");
  10888. const int epfd = epoll_create(1);
  10889. if (unlikely(epfd == -1))
  10890. applogfailr(NULL, LOG_ERR, "epoll_create");
  10891. {
  10892. const int fd = udev_monitor_get_fd(mon);
  10893. struct epoll_event ev = {
  10894. .events = EPOLLIN | EPOLLPRI,
  10895. .data.fd = fd,
  10896. };
  10897. if (epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev))
  10898. applogfailr(NULL, LOG_ERR, "epoll_ctl");
  10899. }
  10900. struct epoll_event ev;
  10901. int rv;
  10902. bool pending = false;
  10903. while (true)
  10904. {
  10905. rv = epoll_wait(epfd, &ev, 1, pending ? hotplug_delay_ms : -1);
  10906. if (rv == -1)
  10907. {
  10908. if (errno == EAGAIN || errno == EINTR)
  10909. continue;
  10910. break;
  10911. }
  10912. if (!rv)
  10913. {
  10914. hotplug_trigger();
  10915. pending = false;
  10916. continue;
  10917. }
  10918. struct udev_device * const device = udev_monitor_receive_device(mon);
  10919. if (!device)
  10920. continue;
  10921. const char * const action = udev_device_get_action(device);
  10922. applog(LOG_DEBUG, "%s: Received %s event", __func__, action);
  10923. if (!strcmp(action, "add"))
  10924. pending = true;
  10925. udev_device_unref(device);
  10926. }
  10927. applogfailr(NULL, LOG_ERR, "epoll_wait");
  10928. }
  10929. #elif defined(WIN32)
  10930. static UINT_PTR _hotplug_wintimer_id;
  10931. VOID CALLBACK hotplug_win_timer(HWND hwnd, UINT msg, UINT_PTR idEvent, DWORD dwTime)
  10932. {
  10933. KillTimer(NULL, _hotplug_wintimer_id);
  10934. _hotplug_wintimer_id = 0;
  10935. hotplug_trigger();
  10936. }
  10937. LRESULT CALLBACK hotplug_win_callback(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
  10938. {
  10939. if (msg == WM_DEVICECHANGE && wParam == DBT_DEVNODES_CHANGED)
  10940. {
  10941. applog(LOG_DEBUG, "%s: Received DBT_DEVNODES_CHANGED event", __func__);
  10942. _hotplug_wintimer_id = SetTimer(NULL, _hotplug_wintimer_id, hotplug_delay_ms, hotplug_win_timer);
  10943. }
  10944. return DefWindowProc(hwnd, msg, wParam, lParam);
  10945. }
  10946. static
  10947. void *hotplug_thread(__maybe_unused void *p)
  10948. {
  10949. pthread_detach(pthread_self());
  10950. WNDCLASS DummyWinCls = {
  10951. .lpszClassName = "BFGDummyWinCls",
  10952. .lpfnWndProc = hotplug_win_callback,
  10953. };
  10954. ATOM a = RegisterClass(&DummyWinCls);
  10955. if (unlikely(!a))
  10956. applogfailinfor(NULL, LOG_ERR, "RegisterClass", "%d", (int)GetLastError());
  10957. HWND hwnd = CreateWindow((void*)(intptr_t)a, NULL, WS_OVERLAPPED, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, NULL, NULL);
  10958. if (unlikely(!hwnd))
  10959. applogfailinfor(NULL, LOG_ERR, "CreateWindow", "%d", (int)GetLastError());
  10960. MSG msg;
  10961. while (GetMessage(&msg, NULL, 0, 0))
  10962. {
  10963. TranslateMessage(&msg);
  10964. DispatchMessage(&msg);
  10965. }
  10966. quit(0, "WM_QUIT received");
  10967. return NULL;
  10968. }
  10969. #endif
  10970. #ifdef HAVE_BFG_HOTPLUG
  10971. static
  10972. void hotplug_start()
  10973. {
  10974. pthread_t pth;
  10975. if (unlikely(pthread_create(&pth, NULL, hotplug_thread, NULL)))
  10976. applog(LOG_ERR, "Failed to start hotplug thread");
  10977. }
  10978. #endif
  10979. static void probe_pools(void)
  10980. {
  10981. int i;
  10982. for (i = 0; i < total_pools; i++) {
  10983. struct pool *pool = pools[i];
  10984. pool->testing = true;
  10985. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  10986. }
  10987. }
  10988. static void raise_fd_limits(void)
  10989. {
  10990. #ifdef HAVE_SETRLIMIT
  10991. struct rlimit fdlimit;
  10992. rlim_t old_soft_limit;
  10993. char frombuf[0x10] = "unlimited";
  10994. char hardbuf[0x10] = "unlimited";
  10995. if (getrlimit(RLIMIT_NOFILE, &fdlimit))
  10996. applogr(, LOG_DEBUG, "setrlimit: Failed to getrlimit(RLIMIT_NOFILE)");
  10997. old_soft_limit = fdlimit.rlim_cur;
  10998. if (fdlimit.rlim_max > FD_SETSIZE || fdlimit.rlim_max == RLIM_INFINITY)
  10999. fdlimit.rlim_cur = FD_SETSIZE;
  11000. else
  11001. fdlimit.rlim_cur = fdlimit.rlim_max;
  11002. if (fdlimit.rlim_max != RLIM_INFINITY)
  11003. snprintf(hardbuf, sizeof(hardbuf), "%lu", (unsigned long)fdlimit.rlim_max);
  11004. if (old_soft_limit != RLIM_INFINITY)
  11005. snprintf(frombuf, sizeof(frombuf), "%lu", (unsigned long)old_soft_limit);
  11006. if (fdlimit.rlim_cur == old_soft_limit)
  11007. applogr(, LOG_DEBUG, "setrlimit: Soft fd limit not being changed from %lu (FD_SETSIZE=%lu; hard limit=%s)",
  11008. (unsigned long)old_soft_limit, (unsigned long)FD_SETSIZE, hardbuf);
  11009. if (setrlimit(RLIMIT_NOFILE, &fdlimit))
  11010. applogr(, LOG_DEBUG, "setrlimit: Failed to change soft fd limit from %s to %lu (FD_SETSIZE=%lu; hard limit=%s)",
  11011. frombuf, (unsigned long)fdlimit.rlim_cur, (unsigned long)FD_SETSIZE, hardbuf);
  11012. applog(LOG_DEBUG, "setrlimit: Changed soft fd limit from %s to %lu (FD_SETSIZE=%lu; hard limit=%s)",
  11013. frombuf, (unsigned long)fdlimit.rlim_cur, (unsigned long)FD_SETSIZE, hardbuf);
  11014. #else
  11015. applog(LOG_DEBUG, "setrlimit: Not supported by platform");
  11016. #endif
  11017. }
  11018. static
  11019. void bfg_atexit(void)
  11020. {
  11021. puts("");
  11022. }
  11023. extern void bfg_init_threadlocal();
  11024. extern void stratumsrv_start();
  11025. extern void test_aan_pll(void);
  11026. int main(int argc, char *argv[])
  11027. {
  11028. struct sigaction handler;
  11029. struct thr_info *thr;
  11030. unsigned int k;
  11031. int i;
  11032. int rearrange_pools = 0;
  11033. char *s;
  11034. #ifdef WIN32
  11035. LoadLibrary("backtrace.dll");
  11036. #endif
  11037. atexit(bfg_atexit);
  11038. b58_sha256_impl = my_blkmaker_sha256_callback;
  11039. blkmk_sha256_impl = my_blkmaker_sha256_callback;
  11040. bfg_init_threadlocal();
  11041. #ifndef HAVE_PTHREAD_CANCEL
  11042. setup_pthread_cancel_workaround();
  11043. #endif
  11044. bfg_init_checksums();
  11045. #ifdef WIN32
  11046. {
  11047. WSADATA wsa;
  11048. i = WSAStartup(MAKEWORD(2, 2), &wsa);
  11049. if (i)
  11050. quit(1, "Failed to initialise Winsock: %s", bfg_strerror(i, BST_SOCKET));
  11051. }
  11052. #endif
  11053. /* This dangerous functions tramples random dynamically allocated
  11054. * variables so do it before anything at all */
  11055. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  11056. quit(1, "Failed to curl_global_init");
  11057. initial_args = malloc(sizeof(char *) * (argc + 1));
  11058. for (i = 0; i < argc; i++)
  11059. initial_args[i] = strdup(argv[i]);
  11060. initial_args[argc] = NULL;
  11061. mutex_init(&hash_lock);
  11062. mutex_init(&console_lock);
  11063. cglock_init(&control_lock);
  11064. mutex_init(&stats_lock);
  11065. mutex_init(&sharelog_lock);
  11066. cglock_init(&ch_lock);
  11067. mutex_init(&sshare_lock);
  11068. rwlock_init(&blk_lock);
  11069. rwlock_init(&netacc_lock);
  11070. rwlock_init(&mining_thr_lock);
  11071. rwlock_init(&devices_lock);
  11072. mutex_init(&lp_lock);
  11073. if (unlikely(pthread_cond_init(&lp_cond, bfg_condattr)))
  11074. quit(1, "Failed to pthread_cond_init lp_cond");
  11075. if (unlikely(pthread_cond_init(&gws_cond, bfg_condattr)))
  11076. quit(1, "Failed to pthread_cond_init gws_cond");
  11077. notifier_init(submit_waiting_notifier);
  11078. timer_unset(&tv_rescan);
  11079. notifier_init(rescan_notifier);
  11080. /* Create a unique get work queue */
  11081. getq = tq_new();
  11082. if (!getq)
  11083. quit(1, "Failed to create getq");
  11084. /* We use the getq mutex as the staged lock */
  11085. stgd_lock = &getq->mutex;
  11086. snprintf(packagename, sizeof(packagename), "%s %s", PACKAGE, VERSION);
  11087. #ifdef WANT_CPUMINE
  11088. init_max_name_len();
  11089. #endif
  11090. handler.sa_handler = &sighandler;
  11091. handler.sa_flags = 0;
  11092. sigemptyset(&handler.sa_mask);
  11093. #ifdef HAVE_PTHREAD_CANCEL
  11094. sigaction(SIGTERM, &handler, &termhandler);
  11095. #else
  11096. // Need to let pthread_cancel emulation handle SIGTERM first
  11097. termhandler = pcwm_orig_term_handler;
  11098. pcwm_orig_term_handler = handler;
  11099. #endif
  11100. sigaction(SIGINT, &handler, &inthandler);
  11101. #ifndef WIN32
  11102. signal(SIGPIPE, SIG_IGN);
  11103. #else
  11104. timeBeginPeriod(1);
  11105. #endif
  11106. opt_kernel_path = CGMINER_PREFIX;
  11107. cgminer_path = alloca(PATH_MAX);
  11108. s = strdup(argv[0]);
  11109. strcpy(cgminer_path, dirname(s));
  11110. free(s);
  11111. strcat(cgminer_path, "/");
  11112. #if defined(WANT_CPUMINE) && defined(WIN32)
  11113. {
  11114. char buf[32];
  11115. int gev = GetEnvironmentVariable("BFGMINER_BENCH_ALGO", buf, sizeof(buf));
  11116. if (gev > 0 && gev < sizeof(buf))
  11117. {
  11118. setup_benchmark_pool();
  11119. double rate = bench_algo_stage3(atoi(buf));
  11120. // Write result to shared memory for parent
  11121. char unique_name[64];
  11122. if (GetEnvironmentVariable("BFGMINER_SHARED_MEM", unique_name, 32))
  11123. {
  11124. HANDLE map_handle = CreateFileMapping(
  11125. INVALID_HANDLE_VALUE, // use paging file
  11126. NULL, // default security attributes
  11127. PAGE_READWRITE, // read/write access
  11128. 0, // size: high 32-bits
  11129. 4096, // size: low 32-bits
  11130. unique_name // name of map object
  11131. );
  11132. if (NULL != map_handle) {
  11133. void *shared_mem = MapViewOfFile(
  11134. map_handle, // object to map view of
  11135. FILE_MAP_WRITE, // read/write access
  11136. 0, // high offset: map from
  11137. 0, // low offset: beginning
  11138. 0 // default: map entire file
  11139. );
  11140. if (NULL != shared_mem)
  11141. CopyMemory(shared_mem, &rate, sizeof(rate));
  11142. (void)UnmapViewOfFile(shared_mem);
  11143. }
  11144. (void)CloseHandle(map_handle);
  11145. }
  11146. exit(0);
  11147. }
  11148. }
  11149. #endif
  11150. #ifdef HAVE_CURSES
  11151. devcursor = 8;
  11152. logstart = devcursor;
  11153. logcursor = logstart;
  11154. #endif
  11155. mutex_init(&submitting_lock);
  11156. #ifdef HAVE_OPENCL
  11157. opencl_early_init();
  11158. #endif
  11159. schedstart.tm.tm_sec = 1;
  11160. schedstop .tm.tm_sec = 1;
  11161. opt_register_table(opt_early_table, NULL);
  11162. opt_register_table(opt_config_table, NULL);
  11163. opt_register_table(opt_cmdline_table, NULL);
  11164. opt_early_parse(argc, argv, applog_and_exit);
  11165. if (!config_loaded)
  11166. {
  11167. load_default_config();
  11168. rearrange_pools = total_pools;
  11169. }
  11170. opt_free_table();
  11171. /* parse command line */
  11172. opt_register_table(opt_config_table,
  11173. "Options for both config file and command line");
  11174. opt_register_table(opt_cmdline_table,
  11175. "Options for command line only");
  11176. opt_parse(&argc, argv, applog_and_exit);
  11177. if (argc != 1)
  11178. quit(1, "Unexpected extra commandline arguments");
  11179. if (rearrange_pools && rearrange_pools < total_pools)
  11180. {
  11181. // Prioritise commandline pools before default-config pools
  11182. for (i = 0; i < rearrange_pools; ++i)
  11183. pools[i]->prio += rearrange_pools;
  11184. for ( ; i < total_pools; ++i)
  11185. pools[i]->prio -= rearrange_pools;
  11186. }
  11187. #ifndef HAVE_PTHREAD_CANCEL
  11188. // Can't do this any earlier, or config isn't loaded
  11189. applog(LOG_DEBUG, "pthread_cancel workaround in use");
  11190. #endif
  11191. #ifdef HAVE_PWD_H
  11192. struct passwd *user_info = NULL;
  11193. if (opt_setuid != NULL) {
  11194. if ((user_info = getpwnam(opt_setuid)) == NULL) {
  11195. quit(1, "Unable to find setuid user information");
  11196. }
  11197. }
  11198. #endif
  11199. #ifdef HAVE_CHROOT
  11200. if (chroot_dir != NULL) {
  11201. #ifdef HAVE_PWD_H
  11202. if (user_info == NULL && getuid() == 0) {
  11203. applog(LOG_WARNING, "Running as root inside chroot");
  11204. }
  11205. #endif
  11206. if (chroot(chroot_dir) != 0) {
  11207. quit(1, "Unable to chroot");
  11208. }
  11209. if (chdir("/"))
  11210. quit(1, "Unable to chdir to chroot");
  11211. }
  11212. #endif
  11213. #ifdef HAVE_PWD_H
  11214. if (user_info != NULL) {
  11215. if (setgid((*user_info).pw_gid) != 0)
  11216. quit(1, "Unable to setgid");
  11217. if (setuid((*user_info).pw_uid) != 0)
  11218. quit(1, "Unable to setuid");
  11219. }
  11220. #endif
  11221. raise_fd_limits();
  11222. if (opt_benchmark) {
  11223. while (total_pools)
  11224. remove_pool(pools[0]);
  11225. setup_benchmark_pool();
  11226. }
  11227. if (opt_unittest) {
  11228. test_cgpu_match();
  11229. test_intrange();
  11230. test_decimal_width();
  11231. test_domain_funcs();
  11232. #ifdef USE_SCRYPT
  11233. test_scrypt();
  11234. #endif
  11235. test_target();
  11236. test_uri_get_param();
  11237. utf8_test();
  11238. #ifdef USE_JINGTIAN
  11239. test_aan_pll();
  11240. #endif
  11241. if (unittest_failures)
  11242. quit(1, "Unit tests failed");
  11243. }
  11244. #ifdef HAVE_CURSES
  11245. if (opt_realquiet || opt_display_devs)
  11246. use_curses = false;
  11247. setlocale(LC_ALL, "C");
  11248. if (use_curses)
  11249. enable_curses();
  11250. #endif
  11251. #ifdef HAVE_LIBUSB
  11252. int err = libusb_init(NULL);
  11253. if (err)
  11254. applog(LOG_WARNING, "libusb_init() failed err %d", err);
  11255. else
  11256. have_libusb = true;
  11257. #endif
  11258. applog(LOG_WARNING, "Started %s", packagename);
  11259. {
  11260. struct bfg_loaded_configfile *configfile;
  11261. LL_FOREACH(bfg_loaded_configfiles, configfile)
  11262. {
  11263. char * const cnfbuf = configfile->filename;
  11264. int fileconf_load = configfile->fileconf_load;
  11265. applog(LOG_NOTICE, "Loaded configuration file %s", cnfbuf);
  11266. switch (fileconf_load) {
  11267. case 0:
  11268. applog(LOG_WARNING, "Fatal JSON error in configuration file.");
  11269. applog(LOG_WARNING, "Configuration file could not be used.");
  11270. break;
  11271. case -1:
  11272. applog(LOG_WARNING, "Error in configuration file, partially loaded.");
  11273. if (use_curses)
  11274. applog(LOG_WARNING, "Start BFGMiner with -T to see what failed to load.");
  11275. break;
  11276. default:
  11277. break;
  11278. }
  11279. }
  11280. }
  11281. i = strlen(opt_kernel_path) + 2;
  11282. char __kernel_path[i];
  11283. snprintf(__kernel_path, i, "%s/", opt_kernel_path);
  11284. opt_kernel_path = __kernel_path;
  11285. if (want_per_device_stats)
  11286. opt_log_output = true;
  11287. #ifdef WANT_CPUMINE
  11288. #ifdef USE_SCRYPT
  11289. if (opt_scrypt)
  11290. set_scrypt_algo(&opt_algo);
  11291. #endif
  11292. #endif
  11293. bfg_devapi_init();
  11294. drv_detect_all();
  11295. total_devices = total_devices_new;
  11296. devices = devices_new;
  11297. total_devices_new = 0;
  11298. devices_new = NULL;
  11299. if (opt_display_devs) {
  11300. int devcount = 0;
  11301. applog(LOG_ERR, "Devices detected:");
  11302. for (i = 0; i < total_devices; ++i) {
  11303. struct cgpu_info *cgpu = devices[i];
  11304. char buf[0x100];
  11305. if (cgpu->device != cgpu)
  11306. continue;
  11307. if (cgpu->name)
  11308. snprintf(buf, sizeof(buf), " %s", cgpu->name);
  11309. else
  11310. if (cgpu->dev_manufacturer)
  11311. snprintf(buf, sizeof(buf), " %s by %s", (cgpu->dev_product ?: "Device"), cgpu->dev_manufacturer);
  11312. else
  11313. if (cgpu->dev_product)
  11314. snprintf(buf, sizeof(buf), " %s", cgpu->dev_product);
  11315. else
  11316. strcpy(buf, " Device");
  11317. tailsprintf(buf, sizeof(buf), " (driver=%s; procs=%d", cgpu->drv->dname, cgpu->procs);
  11318. if (cgpu->dev_serial)
  11319. tailsprintf(buf, sizeof(buf), "; serial=%s", cgpu->dev_serial);
  11320. if (cgpu->device_path)
  11321. tailsprintf(buf, sizeof(buf), "; path=%s", cgpu->device_path);
  11322. tailsprintf(buf, sizeof(buf), ")");
  11323. _applog(LOG_NOTICE, buf);
  11324. ++devcount;
  11325. }
  11326. quit(0, "%d devices listed", devcount);
  11327. }
  11328. mining_threads = 0;
  11329. for (i = 0; i < total_devices; ++i)
  11330. register_device(devices[i]);
  11331. if (!total_devices) {
  11332. applog(LOG_WARNING, "No devices detected!");
  11333. if (use_curses)
  11334. applog(LOG_WARNING, "Waiting for devices; press 'M+' to add, or 'Q' to quit");
  11335. else
  11336. applog(LOG_WARNING, "Waiting for devices");
  11337. }
  11338. #ifdef HAVE_CURSES
  11339. switch_logsize();
  11340. #endif
  11341. #if BLKMAKER_VERSION > 1
  11342. if (opt_load_bitcoin_conf && !(opt_scrypt || opt_benchmark))
  11343. add_local_gbt(total_pools);
  11344. #endif
  11345. if (!total_pools) {
  11346. applog(LOG_WARNING, "Need to specify at least one pool server.");
  11347. #ifdef HAVE_CURSES
  11348. if (!use_curses || !input_pool(false))
  11349. #endif
  11350. quit(1, "Pool setup failed");
  11351. }
  11352. for (i = 0; i < total_pools; i++) {
  11353. struct pool *pool = pools[i];
  11354. size_t siz;
  11355. if (!pool->rpc_url)
  11356. quit(1, "No URI supplied for pool %u", i);
  11357. if (!pool->rpc_userpass) {
  11358. if (!pool->rpc_user || !pool->rpc_pass)
  11359. quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  11360. siz = strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2;
  11361. pool->rpc_userpass = malloc(siz);
  11362. if (!pool->rpc_userpass)
  11363. quit(1, "Failed to malloc userpass");
  11364. snprintf(pool->rpc_userpass, siz, "%s:%s", pool->rpc_user, pool->rpc_pass);
  11365. }
  11366. }
  11367. /* Set the currentpool to pool with priority 0 */
  11368. validate_pool_priorities();
  11369. for (i = 0; i < total_pools; i++) {
  11370. struct pool *pool = pools[i];
  11371. if (!pool->prio)
  11372. currentpool = pool;
  11373. }
  11374. #ifdef HAVE_SYSLOG_H
  11375. if (use_syslog)
  11376. openlog(PACKAGE, LOG_PID, LOG_USER);
  11377. #endif
  11378. #if defined(unix) || defined(__APPLE__)
  11379. if (opt_stderr_cmd)
  11380. fork_monitor();
  11381. #endif // defined(unix)
  11382. mining_thr = calloc(mining_threads, sizeof(thr));
  11383. if (!mining_thr)
  11384. quit(1, "Failed to calloc mining_thr");
  11385. for (i = 0; i < mining_threads; i++) {
  11386. mining_thr[i] = calloc(1, sizeof(*thr));
  11387. if (!mining_thr[i])
  11388. quit(1, "Failed to calloc mining_thr[%d]", i);
  11389. }
  11390. total_control_threads = 6;
  11391. control_thr = calloc(total_control_threads, sizeof(*thr));
  11392. if (!control_thr)
  11393. quit(1, "Failed to calloc control_thr");
  11394. if (opt_benchmark)
  11395. goto begin_bench;
  11396. applog(LOG_NOTICE, "Probing for an alive pool");
  11397. do {
  11398. bool still_testing;
  11399. int i;
  11400. /* Look for at least one active pool before starting */
  11401. probe_pools();
  11402. do {
  11403. sleep(1);
  11404. if (pools_active)
  11405. break;
  11406. still_testing = false;
  11407. for (int i = 0; i < total_pools; ++i)
  11408. if (pools[i]->testing)
  11409. still_testing = true;
  11410. } while (still_testing);
  11411. if (!pools_active) {
  11412. applog(LOG_ERR, "No servers were found that could be used to get work from.");
  11413. applog(LOG_ERR, "Please check the details from the list below of the servers you have input");
  11414. applog(LOG_ERR, "Most likely you have input the wrong URL, forgotten to add a port, or have not set up workers");
  11415. for (i = 0; i < total_pools; i++) {
  11416. struct pool *pool;
  11417. pool = pools[i];
  11418. applog(LOG_WARNING, "Pool: %d URL: %s User: %s Password: %s",
  11419. i, pool->rpc_url, pool->rpc_user, pool->rpc_pass);
  11420. }
  11421. #ifdef HAVE_CURSES
  11422. if (use_curses) {
  11423. halfdelay(150);
  11424. applog(LOG_ERR, "Press any key to exit, or BFGMiner will try again in 15s.");
  11425. if (getch() != ERR)
  11426. quit(0, "No servers could be used! Exiting.");
  11427. cbreak();
  11428. } else
  11429. #endif
  11430. quit(0, "No servers could be used! Exiting.");
  11431. }
  11432. } while (!pools_active);
  11433. #ifdef USE_SCRYPT
  11434. if (detect_algo == 1 && !opt_scrypt) {
  11435. applog(LOG_NOTICE, "Detected scrypt algorithm");
  11436. opt_scrypt = true;
  11437. }
  11438. #endif
  11439. detect_algo = 0;
  11440. begin_bench:
  11441. total_mhashes_done = 0;
  11442. for (i = 0; i < total_devices; i++) {
  11443. struct cgpu_info *cgpu = devices[i];
  11444. cgpu->rolling = cgpu->total_mhashes = 0;
  11445. }
  11446. cgtime(&total_tv_start);
  11447. cgtime(&total_tv_end);
  11448. miner_started = total_tv_start;
  11449. time_t miner_start_ts = time(NULL);
  11450. if (schedstart.tm.tm_sec)
  11451. localtime_r(&miner_start_ts, &schedstart.tm);
  11452. if (schedstop.tm.tm_sec)
  11453. localtime_r(&miner_start_ts, &schedstop .tm);
  11454. get_datestamp(datestamp, sizeof(datestamp), miner_start_ts);
  11455. // Initialise processors and threads
  11456. k = 0;
  11457. for (i = 0; i < total_devices; ++i) {
  11458. struct cgpu_info *cgpu = devices[i];
  11459. allocate_cgpu(cgpu, &k);
  11460. }
  11461. // Start threads
  11462. for (i = 0; i < total_devices; ++i) {
  11463. struct cgpu_info *cgpu = devices[i];
  11464. start_cgpu(cgpu);
  11465. }
  11466. #ifdef HAVE_OPENCL
  11467. for (i = 0; i < nDevs; i++)
  11468. pause_dynamic_threads(i);
  11469. #endif
  11470. #ifdef WANT_CPUMINE
  11471. if (opt_n_threads > 0)
  11472. applog(LOG_INFO, "%d cpu miner threads started, using '%s' algorithm.",
  11473. opt_n_threads, algo_names[opt_algo]);
  11474. #endif
  11475. cgtime(&total_tv_start);
  11476. cgtime(&total_tv_end);
  11477. if (!opt_benchmark)
  11478. {
  11479. pthread_t submit_thread;
  11480. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, NULL)))
  11481. quit(1, "submit_work thread create failed");
  11482. }
  11483. watchpool_thr_id = 1;
  11484. thr = &control_thr[watchpool_thr_id];
  11485. /* start watchpool thread */
  11486. if (thr_info_create(thr, NULL, watchpool_thread, NULL))
  11487. quit(1, "watchpool thread create failed");
  11488. pthread_detach(thr->pth);
  11489. watchdog_thr_id = 2;
  11490. thr = &control_thr[watchdog_thr_id];
  11491. /* start watchdog thread */
  11492. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  11493. quit(1, "watchdog thread create failed");
  11494. pthread_detach(thr->pth);
  11495. #ifdef HAVE_OPENCL
  11496. /* Create reinit gpu thread */
  11497. gpur_thr_id = 3;
  11498. thr = &control_thr[gpur_thr_id];
  11499. thr->q = tq_new();
  11500. if (!thr->q)
  11501. quit(1, "tq_new failed for gpur_thr_id");
  11502. if (thr_info_create(thr, NULL, reinit_gpu, thr))
  11503. quit(1, "reinit_gpu thread create failed");
  11504. #endif
  11505. /* Create API socket thread */
  11506. api_thr_id = 4;
  11507. thr = &control_thr[api_thr_id];
  11508. if (thr_info_create(thr, NULL, api_thread, thr))
  11509. quit(1, "API thread create failed");
  11510. #ifdef USE_LIBMICROHTTPD
  11511. if (httpsrv_port != -1)
  11512. httpsrv_start(httpsrv_port);
  11513. #endif
  11514. #ifdef USE_LIBEVENT
  11515. if (stratumsrv_port != -1)
  11516. stratumsrv_start();
  11517. #endif
  11518. #ifdef HAVE_BFG_HOTPLUG
  11519. if (opt_hotplug)
  11520. hotplug_start();
  11521. #endif
  11522. #ifdef HAVE_CURSES
  11523. /* Create curses input thread for keyboard input. Create this last so
  11524. * that we know all threads are created since this can call kill_work
  11525. * to try and shut down ll previous threads. */
  11526. input_thr_id = 5;
  11527. thr = &control_thr[input_thr_id];
  11528. if (thr_info_create(thr, NULL, input_thread, thr))
  11529. quit(1, "input thread create failed");
  11530. pthread_detach(thr->pth);
  11531. #endif
  11532. /* Just to be sure */
  11533. if (total_control_threads != 6)
  11534. quit(1, "incorrect total_control_threads (%d) should be 7", total_control_threads);
  11535. /* Once everything is set up, main() becomes the getwork scheduler */
  11536. while (42) {
  11537. int ts, max_staged = opt_queue;
  11538. struct pool *pool, *cp;
  11539. bool lagging = false;
  11540. struct curl_ent *ce;
  11541. struct work *work;
  11542. cp = current_pool();
  11543. // Generally, each processor needs a new work, and all at once during work restarts
  11544. max_staged += base_queue;
  11545. mutex_lock(stgd_lock);
  11546. ts = __total_staged();
  11547. if (!pool_localgen(cp) && !ts && !opt_fail_only)
  11548. lagging = true;
  11549. /* Wait until hash_pop tells us we need to create more work */
  11550. if (ts > max_staged) {
  11551. staged_full = true;
  11552. pthread_cond_wait(&gws_cond, stgd_lock);
  11553. ts = __total_staged();
  11554. }
  11555. mutex_unlock(stgd_lock);
  11556. if (ts > max_staged)
  11557. continue;
  11558. work = make_work();
  11559. if (lagging && !pool_tset(cp, &cp->lagging)) {
  11560. applog(LOG_WARNING, "Pool %d not providing work fast enough", cp->pool_no);
  11561. cp->getfail_occasions++;
  11562. total_go++;
  11563. }
  11564. pool = select_pool(lagging);
  11565. retry:
  11566. if (pool->has_stratum) {
  11567. while (!pool->stratum_active || !pool->stratum_notify) {
  11568. struct pool *altpool = select_pool(true);
  11569. if (altpool == pool && pool->has_stratum)
  11570. cgsleep_ms(5000);
  11571. pool = altpool;
  11572. goto retry;
  11573. }
  11574. gen_stratum_work(pool, work);
  11575. applog(LOG_DEBUG, "Generated stratum work");
  11576. stage_work(work);
  11577. continue;
  11578. }
  11579. if (pool->last_work_copy) {
  11580. mutex_lock(&pool->last_work_lock);
  11581. struct work *last_work = pool->last_work_copy;
  11582. if (!last_work)
  11583. {}
  11584. else
  11585. if (can_roll(last_work) && should_roll(last_work)) {
  11586. struct timeval tv_now;
  11587. cgtime(&tv_now);
  11588. free_work(work);
  11589. work = make_clone(pool->last_work_copy);
  11590. mutex_unlock(&pool->last_work_lock);
  11591. roll_work(work);
  11592. 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));
  11593. stage_work(work);
  11594. continue;
  11595. } else if (last_work->tr && pool->proto == PLP_GETBLOCKTEMPLATE && blkmk_work_left(last_work->tr->tmpl) > (unsigned long)mining_threads) {
  11596. // Don't free last_work_copy, since it is used to detect upstream provides plenty of work per template
  11597. } else {
  11598. free_work(last_work);
  11599. pool->last_work_copy = NULL;
  11600. }
  11601. mutex_unlock(&pool->last_work_lock);
  11602. }
  11603. if (clone_available()) {
  11604. applog(LOG_DEBUG, "Cloned getwork work");
  11605. free_work(work);
  11606. continue;
  11607. }
  11608. if (opt_benchmark) {
  11609. get_benchmark_work(work, opt_benchmark_intense);
  11610. applog(LOG_DEBUG, "Generated benchmark work");
  11611. stage_work(work);
  11612. continue;
  11613. }
  11614. work->pool = pool;
  11615. ce = pop_curl_entry3(pool, 2);
  11616. /* obtain new work from bitcoin via JSON-RPC */
  11617. if (!get_upstream_work(work, ce->curl)) {
  11618. struct pool *next_pool;
  11619. /* Make sure the pool just hasn't stopped serving
  11620. * requests but is up as we'll keep hammering it */
  11621. push_curl_entry(ce, pool);
  11622. ++pool->seq_getfails;
  11623. pool_died(pool);
  11624. next_pool = select_pool(!opt_fail_only);
  11625. if (pool == next_pool) {
  11626. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, retrying in 5s", pool->pool_no);
  11627. cgsleep_ms(5000);
  11628. } else {
  11629. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, failover activated", pool->pool_no);
  11630. pool = next_pool;
  11631. }
  11632. goto retry;
  11633. }
  11634. if (ts >= max_staged)
  11635. pool_tclear(pool, &pool->lagging);
  11636. if (pool_tclear(pool, &pool->idle))
  11637. pool_resus(pool);
  11638. applog(LOG_DEBUG, "Generated getwork work");
  11639. stage_work(work);
  11640. push_curl_entry(ce, pool);
  11641. }
  11642. return 0;
  11643. }