miner.c 358 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858
  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 uint32_t coinbase_script_block_id;
  119. static uint32_t template_nonce;
  120. #endif
  121. #if BLKMAKER_VERSION > 0
  122. char *opt_coinbase_sig;
  123. #endif
  124. static enum bfg_quit_summary opt_quit_summary = BQS_DEFAULT;
  125. static bool include_serial_in_statline;
  126. char *request_target_str;
  127. float request_pdiff = 1.0;
  128. double request_bdiff;
  129. static bool want_stratum = true;
  130. int opt_skip_checks;
  131. bool want_per_device_stats;
  132. bool use_syslog;
  133. bool opt_quiet_work_updates = true;
  134. bool opt_quiet;
  135. bool opt_realquiet;
  136. int loginput_size;
  137. bool opt_compact;
  138. bool opt_show_procs;
  139. const int opt_cutofftemp = 95;
  140. int opt_hysteresis = 3;
  141. static int opt_retries = -1;
  142. int opt_fail_pause = 5;
  143. int opt_log_interval = 20;
  144. int opt_queue = 1;
  145. int opt_scantime = 60;
  146. int opt_expiry = 120;
  147. int opt_expiry_lp = 3600;
  148. unsigned long long global_hashrate;
  149. static bool opt_unittest = false;
  150. unsigned unittest_failures;
  151. unsigned long global_quota_gcd = 1;
  152. time_t last_getwork;
  153. #ifdef USE_OPENCL
  154. int opt_dynamic_interval = 7;
  155. int nDevs;
  156. int opt_g_threads = -1;
  157. #endif
  158. #ifdef USE_SCRYPT
  159. static char detect_algo = 1;
  160. #else
  161. static char detect_algo;
  162. #endif
  163. bool opt_restart = true;
  164. #ifdef USE_LIBMICROHTTPD
  165. #include "httpsrv.h"
  166. int httpsrv_port = -1;
  167. #endif
  168. #ifdef USE_LIBEVENT
  169. int stratumsrv_port = -1;
  170. #endif
  171. const
  172. int rescan_delay_ms = 1000;
  173. #ifdef HAVE_BFG_HOTPLUG
  174. bool opt_hotplug = 1;
  175. const
  176. int hotplug_delay_ms = 100;
  177. #else
  178. const bool opt_hotplug;
  179. #endif
  180. struct string_elist *scan_devices;
  181. static struct string_elist *opt_set_device_list;
  182. bool opt_force_dev_init;
  183. static struct string_elist *opt_devices_enabled_list;
  184. static bool opt_display_devs;
  185. int total_devices;
  186. struct cgpu_info **devices;
  187. int total_devices_new;
  188. struct cgpu_info **devices_new;
  189. bool have_opencl;
  190. int opt_n_threads = -1;
  191. int mining_threads;
  192. int base_queue;
  193. int num_processors;
  194. #ifdef HAVE_CURSES
  195. bool use_curses = true;
  196. #else
  197. bool use_curses;
  198. #endif
  199. int last_logstatusline_len;
  200. #ifdef HAVE_LIBUSB
  201. bool have_libusb;
  202. #endif
  203. static bool opt_submit_stale = true;
  204. static float opt_shares;
  205. static int opt_submit_threads = 0x40;
  206. bool opt_fail_only;
  207. int opt_fail_switch_delay = 300;
  208. bool opt_autofan;
  209. bool opt_autoengine;
  210. bool opt_noadl;
  211. char *opt_api_allow = NULL;
  212. char *opt_api_groups;
  213. char *opt_api_description = PACKAGE_STRING;
  214. int opt_api_port = 4028;
  215. bool opt_api_listen;
  216. bool opt_api_mcast;
  217. char *opt_api_mcast_addr = API_MCAST_ADDR;
  218. char *opt_api_mcast_code = API_MCAST_CODE;
  219. char *opt_api_mcast_des = "";
  220. int opt_api_mcast_port = 4028;
  221. bool opt_api_network;
  222. bool opt_delaynet;
  223. bool opt_disable_pool;
  224. bool opt_disable_client_reconnect = false;
  225. static bool no_work;
  226. bool opt_worktime;
  227. bool opt_weighed_stats;
  228. char *opt_kernel_path;
  229. char *cgminer_path;
  230. #if defined(USE_BITFORCE)
  231. bool opt_bfl_noncerange;
  232. #endif
  233. #define QUIET (opt_quiet || opt_realquiet)
  234. struct thr_info *control_thr;
  235. struct thr_info **mining_thr;
  236. static int watchpool_thr_id;
  237. static int watchdog_thr_id;
  238. #ifdef HAVE_CURSES
  239. static int input_thr_id;
  240. #endif
  241. int gpur_thr_id;
  242. static int api_thr_id;
  243. static int total_control_threads;
  244. pthread_mutex_t hash_lock;
  245. static pthread_mutex_t *stgd_lock;
  246. pthread_mutex_t console_lock;
  247. cglock_t ch_lock;
  248. static pthread_rwlock_t blk_lock;
  249. static pthread_mutex_t sshare_lock;
  250. pthread_rwlock_t netacc_lock;
  251. pthread_rwlock_t mining_thr_lock;
  252. pthread_rwlock_t devices_lock;
  253. static pthread_mutex_t lp_lock;
  254. static pthread_cond_t lp_cond;
  255. pthread_cond_t gws_cond;
  256. bool shutting_down;
  257. double total_rolling;
  258. double total_mhashes_done;
  259. static struct timeval total_tv_start, total_tv_end;
  260. static struct timeval miner_started;
  261. cglock_t control_lock;
  262. pthread_mutex_t stats_lock;
  263. static pthread_mutex_t submitting_lock;
  264. static int total_submitting;
  265. static struct work *submit_waiting;
  266. notifier_t submit_waiting_notifier;
  267. int hw_errors;
  268. int total_accepted, total_rejected;
  269. int total_getworks, total_stale, total_discarded;
  270. uint64_t total_bytes_rcvd, total_bytes_sent;
  271. double total_diff1, total_bad_diff1;
  272. double total_diff_accepted, total_diff_rejected, total_diff_stale;
  273. static int staged_rollable, staged_spare;
  274. unsigned int new_blocks;
  275. unsigned int found_blocks;
  276. unsigned int local_work;
  277. unsigned int total_go, total_ro;
  278. struct pool **pools;
  279. static struct pool *currentpool = NULL;
  280. int total_pools, enabled_pools;
  281. enum pool_strategy pool_strategy = POOL_FAILOVER;
  282. int opt_rotate_period;
  283. static int total_urls, total_users, total_passes;
  284. static
  285. #ifndef HAVE_CURSES
  286. const
  287. #endif
  288. bool curses_active;
  289. #ifdef HAVE_CURSES
  290. #if !(defined(PDCURSES) || defined(NCURSES_VERSION))
  291. const
  292. #endif
  293. short default_bgcolor = COLOR_BLACK;
  294. static int attr_title = A_BOLD;
  295. #endif
  296. static
  297. #if defined(HAVE_CURSES) && defined(USE_UNICODE)
  298. bool use_unicode;
  299. static
  300. bool have_unicode_degrees;
  301. static
  302. wchar_t unicode_micro = 'u';
  303. #else
  304. const bool use_unicode;
  305. static
  306. const bool have_unicode_degrees;
  307. #ifdef HAVE_CURSES
  308. static
  309. const char unicode_micro = 'u';
  310. #endif
  311. #endif
  312. #ifdef HAVE_CURSES
  313. #define U8_BAD_START "\xef\x80\x81"
  314. #define U8_BAD_END "\xef\x80\x80"
  315. #define AS_BAD(x) U8_BAD_START x U8_BAD_END
  316. /* logstart is where the log window should start */
  317. static int devcursor, logstart, logcursor;
  318. bool selecting_device;
  319. unsigned selected_device;
  320. #endif
  321. static int max_lpdigits;
  322. // current_hash was replaced with goal->current_goal_detail
  323. // current_block_id was replaced with blkchain->currentblk->block_id
  324. static char datestamp[40];
  325. static char best_share[ALLOC_H2B_SHORTV] = "0";
  326. double best_diff = 0;
  327. struct mining_algorithm *mining_algorithms;
  328. struct mining_goal_info *mining_goals;
  329. int active_goals = 1;
  330. int swork_id;
  331. /* For creating a hash database of stratum shares submitted that have not had
  332. * a response yet */
  333. struct stratum_share {
  334. UT_hash_handle hh;
  335. bool block;
  336. struct work *work;
  337. int id;
  338. };
  339. static struct stratum_share *stratum_shares = NULL;
  340. char *opt_socks_proxy = NULL;
  341. static const char def_conf[] = "bfgminer.conf";
  342. static bool config_loaded;
  343. static int include_count;
  344. #define JSON_INCLUDE_CONF "include"
  345. #define JSON_LOAD_ERROR "JSON decode of file '%s' failed\n %s"
  346. #define JSON_LOAD_ERROR_LEN strlen(JSON_LOAD_ERROR)
  347. #define JSON_MAX_DEPTH 10
  348. #define JSON_MAX_DEPTH_ERR "Too many levels of JSON includes (limit 10) or a loop"
  349. char *cmd_idle, *cmd_sick, *cmd_dead;
  350. #if defined(unix) || defined(__APPLE__)
  351. static char *opt_stderr_cmd = NULL;
  352. static int forkpid;
  353. #endif // defined(unix)
  354. #ifdef HAVE_CHROOT
  355. char *chroot_dir;
  356. #endif
  357. #ifdef HAVE_PWD_H
  358. char *opt_setuid;
  359. #endif
  360. struct sigaction termhandler, inthandler;
  361. struct thread_q *getq;
  362. static int total_work;
  363. static bool staged_full;
  364. struct work *staged_work = NULL;
  365. struct schedtime {
  366. bool enable;
  367. struct tm tm;
  368. };
  369. struct schedtime schedstart;
  370. struct schedtime schedstop;
  371. bool sched_paused;
  372. static bool time_before(struct tm *tm1, struct tm *tm2)
  373. {
  374. if (tm1->tm_hour < tm2->tm_hour)
  375. return true;
  376. if (tm1->tm_hour == tm2->tm_hour && tm1->tm_min < tm2->tm_min)
  377. return true;
  378. return false;
  379. }
  380. static bool should_run(void)
  381. {
  382. struct tm tm;
  383. time_t tt;
  384. bool within_range;
  385. if (!schedstart.enable && !schedstop.enable)
  386. return true;
  387. tt = time(NULL);
  388. localtime_r(&tt, &tm);
  389. // NOTE: This is delicately balanced so that should_run is always false if schedstart==schedstop
  390. if (time_before(&schedstop.tm, &schedstart.tm))
  391. within_range = (time_before(&tm, &schedstop.tm) || !time_before(&tm, &schedstart.tm));
  392. else
  393. within_range = (time_before(&tm, &schedstop.tm) && !time_before(&tm, &schedstart.tm));
  394. if (within_range && !schedstop.enable)
  395. /* This is a once off event with no stop time set */
  396. schedstart.enable = false;
  397. return within_range;
  398. }
  399. void get_datestamp(char *f, size_t fsiz, time_t tt)
  400. {
  401. struct tm _tm;
  402. struct tm *tm = &_tm;
  403. if (tt == INVALID_TIMESTAMP)
  404. tt = time(NULL);
  405. localtime_r(&tt, tm);
  406. snprintf(f, fsiz, "[%d-%02d-%02d %02d:%02d:%02d]",
  407. tm->tm_year + 1900,
  408. tm->tm_mon + 1,
  409. tm->tm_mday,
  410. tm->tm_hour,
  411. tm->tm_min,
  412. tm->tm_sec);
  413. }
  414. static
  415. void get_timestamp(char *f, size_t fsiz, time_t tt)
  416. {
  417. struct tm _tm;
  418. struct tm *tm = &_tm;
  419. localtime_r(&tt, tm);
  420. snprintf(f, fsiz, "[%02d:%02d:%02d]",
  421. tm->tm_hour,
  422. tm->tm_min,
  423. tm->tm_sec);
  424. }
  425. static void applog_and_exit(const char *fmt, ...) FORMAT_SYNTAX_CHECK(printf, 1, 2);
  426. static char exit_buf[512];
  427. static void applog_and_exit(const char *fmt, ...)
  428. {
  429. va_list ap;
  430. va_start(ap, fmt);
  431. vsnprintf(exit_buf, sizeof(exit_buf), fmt, ap);
  432. va_end(ap);
  433. _applog(LOG_ERR, exit_buf);
  434. exit(1);
  435. }
  436. static
  437. float drv_min_nonce_diff(const struct device_drv * const drv, struct cgpu_info * const proc, const struct mining_algorithm * const malgo)
  438. {
  439. if (drv->drv_min_nonce_diff)
  440. return drv->drv_min_nonce_diff(proc, malgo);
  441. #ifdef USE_SHA256D
  442. return (malgo->algo == POW_SHA256D) ? 1. : -1.;
  443. #else
  444. return -1.;
  445. #endif
  446. }
  447. char *devpath_to_devid(const char *devpath)
  448. {
  449. #ifndef WIN32
  450. if (devpath[0] != '/')
  451. return NULL;
  452. struct stat my_stat;
  453. if (stat(devpath, &my_stat))
  454. return NULL;
  455. char *devs = malloc(6 + (sizeof(dev_t) * 2) + 1);
  456. memcpy(devs, "dev_t:", 6);
  457. bin2hex(&devs[6], &my_stat.st_rdev, sizeof(dev_t));
  458. #else
  459. if (!strncmp(devpath, "\\\\.\\", 4))
  460. devpath += 4;
  461. if (strncasecmp(devpath, "COM", 3) || !devpath[3])
  462. return NULL;
  463. devpath += 3;
  464. char *p;
  465. strtol(devpath, &p, 10);
  466. if (p[0])
  467. return NULL;
  468. const int sz = (p - devpath);
  469. char *devs = malloc(4 + sz + 1);
  470. sprintf(devs, "com:%s", devpath);
  471. #endif
  472. return devs;
  473. }
  474. static
  475. bool devpaths_match(const char * const ap, const char * const bp)
  476. {
  477. char * const a = devpath_to_devid(ap);
  478. if (!a)
  479. return false;
  480. char * const b = devpath_to_devid(bp);
  481. bool rv = false;
  482. if (b)
  483. {
  484. rv = !strcmp(a, b);
  485. free(b);
  486. }
  487. free(a);
  488. return rv;
  489. }
  490. static
  491. int proc_letter_to_number(const char *s, const char ** const rem)
  492. {
  493. int n = 0, c;
  494. for ( ; s[0]; ++s)
  495. {
  496. if (unlikely(n > INT_MAX / 26))
  497. break;
  498. c = tolower(s[0]) - 'a';
  499. if (unlikely(c < 0 || c > 25))
  500. break;
  501. if (unlikely(INT_MAX - c < n))
  502. break;
  503. n = (n * 26) + c;
  504. }
  505. *rem = s;
  506. return n;
  507. }
  508. static
  509. bool cgpu_match(const char * const pattern, const struct cgpu_info * const cgpu)
  510. {
  511. // all - matches anything
  512. // d0 - matches all processors of device 0
  513. // d0-3 - matches all processors of device 0, 1, 2, or 3
  514. // d0a - matches first processor of device 0
  515. // 0 - matches processor 0
  516. // 0-4 - matches processors 0, 1, 2, 3, or 4
  517. // ___ - matches all processors on all devices using driver/name ___
  518. // ___0 - matches all processors of 0th device using driver/name ___
  519. // ___0a - matches first processor of 0th device using driver/name ___
  520. // @* - matches device with serial or path *
  521. // @*@a - matches first processor of device with serial or path *
  522. // ___@* - matches device with serial or path * using driver/name ___
  523. if (!strcasecmp(pattern, "all"))
  524. return true;
  525. const struct device_drv * const drv = cgpu->drv;
  526. const char *p = pattern, *p2;
  527. size_t L;
  528. int n, i, c = -1;
  529. int n2;
  530. int proc_first = -1, proc_last = -1;
  531. struct cgpu_info *device;
  532. if (!(strncasecmp(drv->dname, p, (L = strlen(drv->dname)))
  533. && strncasecmp(drv-> name, p, (L = strlen(drv-> name)))))
  534. // dname or name
  535. p = &pattern[L];
  536. else
  537. if (p[0] == 'd' && (isdigit(p[1]) || p[1] == '-'))
  538. // d#
  539. ++p;
  540. else
  541. if (isdigit(p[0]) || p[0] == '@' || p[0] == '-')
  542. // # or @
  543. {}
  544. else
  545. return false;
  546. L = p - pattern;
  547. while (isspace(p[0]))
  548. ++p;
  549. if (p[0] == '@')
  550. {
  551. // Serial/path
  552. const char * const ser = &p[1];
  553. for (p = ser; p[0] != '@' && p[0] != '\0'; ++p)
  554. {}
  555. p2 = (p[0] == '@') ? &p[1] : p;
  556. const size_t serlen = (p - ser);
  557. p = "";
  558. n = n2 = 0;
  559. const char * const devpath = cgpu->device_path ?: "";
  560. const char * const devser = cgpu->dev_serial ?: "";
  561. if ((!strncmp(devpath, ser, serlen)) && devpath[serlen] == '\0')
  562. {} // Match
  563. else
  564. if ((!strncmp(devser, ser, serlen)) && devser[serlen] == '\0')
  565. {} // Match
  566. else
  567. {
  568. char devpath2[serlen + 1];
  569. memcpy(devpath2, ser, serlen);
  570. devpath2[serlen] = '\0';
  571. if (!devpaths_match(devpath, ser))
  572. return false;
  573. }
  574. }
  575. else
  576. {
  577. if (isdigit(p[0]))
  578. n = strtol(p, (void*)&p2, 0);
  579. else
  580. {
  581. n = 0;
  582. p2 = p;
  583. }
  584. if (p2[0] == '-')
  585. {
  586. ++p2;
  587. if (p2[0] && isdigit(p2[0]))
  588. n2 = strtol(p2, (void*)&p2, 0);
  589. else
  590. n2 = INT_MAX;
  591. }
  592. else
  593. n2 = n;
  594. if (p == pattern)
  595. {
  596. if (!p[0])
  597. return true;
  598. if (p2 && p2[0])
  599. goto invsyntax;
  600. for (i = n; i <= n2; ++i)
  601. {
  602. if (i >= total_devices)
  603. break;
  604. if (cgpu == devices[i])
  605. return true;
  606. }
  607. return false;
  608. }
  609. }
  610. if (p2[0])
  611. {
  612. proc_first = proc_letter_to_number(&p2[0], &p2);
  613. if (p2[0] == '-')
  614. {
  615. ++p2;
  616. if (p2[0])
  617. proc_last = proc_letter_to_number(p2, &p2);
  618. else
  619. proc_last = INT_MAX;
  620. }
  621. else
  622. proc_last = proc_first;
  623. if (p2[0])
  624. goto invsyntax;
  625. }
  626. if (L > 1 || tolower(pattern[0]) != 'd' || !p[0])
  627. {
  628. if ((L == 3 && !strncasecmp(pattern, drv->name, 3)) ||
  629. (!L) ||
  630. (L == strlen(drv->dname) && !strncasecmp(pattern, drv->dname, L)))
  631. {} // Matched name or dname
  632. else
  633. return false;
  634. if (p[0] && (cgpu->device_id < n || cgpu->device_id > n2))
  635. return false;
  636. if (proc_first != -1 && (cgpu->proc_id < proc_first || cgpu->proc_id > proc_last))
  637. return false;
  638. return true;
  639. }
  640. // d#
  641. c = -1;
  642. for (i = 0; ; ++i)
  643. {
  644. if (i == total_devices)
  645. return false;
  646. if (devices[i]->device != devices[i])
  647. continue;
  648. ++c;
  649. if (c < n)
  650. continue;
  651. if (c > n2)
  652. break;
  653. for (device = devices[i]; device; device = device->next_proc)
  654. {
  655. if (proc_first != -1 && (device->proc_id < proc_first || device->proc_id > proc_last))
  656. continue;
  657. if (device == cgpu)
  658. return true;
  659. }
  660. }
  661. return false;
  662. invsyntax:
  663. applog(LOG_WARNING, "%s: Invalid syntax: %s", __func__, pattern);
  664. return false;
  665. }
  666. #define TEST_CGPU_MATCH(pattern) \
  667. if (!cgpu_match(pattern, &cgpu)) \
  668. { \
  669. ++unittest_failures; \
  670. applog(LOG_ERR, "%s: Pattern \"%s\" should have matched!", __func__, pattern); \
  671. } \
  672. // END TEST_CGPU_MATCH
  673. #define TEST_CGPU_NOMATCH(pattern) \
  674. if (cgpu_match(pattern, &cgpu)) \
  675. { \
  676. ++unittest_failures; \
  677. applog(LOG_ERR, "%s: Pattern \"%s\" should NOT have matched!", __func__, pattern); \
  678. } \
  679. // END TEST_CGPU_MATCH
  680. static __maybe_unused
  681. void test_cgpu_match()
  682. {
  683. struct device_drv drv = {
  684. .dname = "test",
  685. .name = "TST",
  686. };
  687. struct cgpu_info cgpu = {
  688. .drv = &drv,
  689. .device = &cgpu,
  690. .device_id = 1,
  691. .proc_id = 1,
  692. .proc_repr = "TST 1b",
  693. }, cgpu0a = {
  694. .drv = &drv,
  695. .device = &cgpu0a,
  696. .device_id = 0,
  697. .proc_id = 0,
  698. .proc_repr = "TST 0a",
  699. }, cgpu1a = {
  700. .drv = &drv,
  701. .device = &cgpu0a,
  702. .device_id = 1,
  703. .proc_id = 0,
  704. .proc_repr = "TST 1a",
  705. };
  706. struct cgpu_info *devices_list[3] = {&cgpu0a, &cgpu1a, &cgpu,};
  707. devices = devices_list;
  708. total_devices = 3;
  709. TEST_CGPU_MATCH("all")
  710. TEST_CGPU_MATCH("d1")
  711. TEST_CGPU_NOMATCH("d2")
  712. TEST_CGPU_MATCH("d0-5")
  713. TEST_CGPU_NOMATCH("d0-0")
  714. TEST_CGPU_NOMATCH("d2-5")
  715. TEST_CGPU_MATCH("d-1")
  716. TEST_CGPU_MATCH("d1-")
  717. TEST_CGPU_NOMATCH("d-0")
  718. TEST_CGPU_NOMATCH("d2-")
  719. TEST_CGPU_MATCH("2")
  720. TEST_CGPU_NOMATCH("3")
  721. TEST_CGPU_MATCH("1-2")
  722. TEST_CGPU_MATCH("2-3")
  723. TEST_CGPU_NOMATCH("1-1")
  724. TEST_CGPU_NOMATCH("3-4")
  725. TEST_CGPU_MATCH("TST")
  726. TEST_CGPU_MATCH("test")
  727. TEST_CGPU_MATCH("tst")
  728. TEST_CGPU_MATCH("TEST")
  729. TEST_CGPU_NOMATCH("TSF")
  730. TEST_CGPU_NOMATCH("TS")
  731. TEST_CGPU_NOMATCH("TSTF")
  732. TEST_CGPU_MATCH("TST1")
  733. TEST_CGPU_MATCH("test1")
  734. TEST_CGPU_MATCH("TST0-1")
  735. TEST_CGPU_MATCH("TST 1")
  736. TEST_CGPU_MATCH("TST 1-2")
  737. TEST_CGPU_MATCH("TEST 1-2")
  738. TEST_CGPU_NOMATCH("TST2")
  739. TEST_CGPU_NOMATCH("TST2-3")
  740. TEST_CGPU_NOMATCH("TST0-0")
  741. TEST_CGPU_MATCH("TST1b")
  742. TEST_CGPU_MATCH("tst1b")
  743. TEST_CGPU_NOMATCH("TST1c")
  744. TEST_CGPU_NOMATCH("TST1bb")
  745. TEST_CGPU_MATCH("TST0-1b")
  746. TEST_CGPU_NOMATCH("TST0-1c")
  747. TEST_CGPU_MATCH("TST1a-d")
  748. TEST_CGPU_NOMATCH("TST1a-a")
  749. TEST_CGPU_NOMATCH("TST1-a")
  750. TEST_CGPU_NOMATCH("TST1c-z")
  751. TEST_CGPU_NOMATCH("TST1c-")
  752. TEST_CGPU_MATCH("@")
  753. TEST_CGPU_NOMATCH("@abc")
  754. TEST_CGPU_MATCH("@@b")
  755. TEST_CGPU_NOMATCH("@@c")
  756. TEST_CGPU_MATCH("TST@")
  757. TEST_CGPU_NOMATCH("TST@abc")
  758. TEST_CGPU_MATCH("TST@@b")
  759. TEST_CGPU_NOMATCH("TST@@c")
  760. TEST_CGPU_MATCH("TST@@b-f")
  761. TEST_CGPU_NOMATCH("TST@@c-f")
  762. TEST_CGPU_NOMATCH("TST@@-a")
  763. cgpu.device_path = "/dev/test";
  764. cgpu.dev_serial = "testy";
  765. TEST_CGPU_MATCH("TST@/dev/test")
  766. TEST_CGPU_MATCH("TST@testy")
  767. TEST_CGPU_NOMATCH("TST@")
  768. TEST_CGPU_NOMATCH("TST@/dev/test5@b")
  769. TEST_CGPU_NOMATCH("TST@testy3@b")
  770. TEST_CGPU_MATCH("TST@/dev/test@b")
  771. TEST_CGPU_MATCH("TST@testy@b")
  772. TEST_CGPU_NOMATCH("TST@/dev/test@c")
  773. TEST_CGPU_NOMATCH("TST@testy@c")
  774. cgpu.device_path = "usb:000:999";
  775. TEST_CGPU_MATCH("TST@usb:000:999")
  776. drv.dname = "test7";
  777. TEST_CGPU_MATCH("test7")
  778. TEST_CGPU_MATCH("TEST7")
  779. TEST_CGPU_NOMATCH("test&")
  780. TEST_CGPU_MATCH("test7 1-2")
  781. TEST_CGPU_MATCH("test7@testy@b")
  782. }
  783. static
  784. int cgpu_search(const char * const pattern, const int first)
  785. {
  786. int i;
  787. struct cgpu_info *cgpu;
  788. #define CHECK_CGPU_SEARCH do{ \
  789. cgpu = get_devices(i); \
  790. if (cgpu_match(pattern, cgpu)) \
  791. return i; \
  792. }while(0)
  793. for (i = first; i < total_devices; ++i)
  794. CHECK_CGPU_SEARCH;
  795. for (i = 0; i < first; ++i)
  796. CHECK_CGPU_SEARCH;
  797. #undef CHECK_CGPU_SEARCH
  798. return -1;
  799. }
  800. static pthread_mutex_t sharelog_lock;
  801. static FILE *sharelog_file = NULL;
  802. struct thr_info *get_thread(int thr_id)
  803. {
  804. struct thr_info *thr;
  805. rd_lock(&mining_thr_lock);
  806. thr = mining_thr[thr_id];
  807. rd_unlock(&mining_thr_lock);
  808. return thr;
  809. }
  810. static struct cgpu_info *get_thr_cgpu(int thr_id)
  811. {
  812. struct thr_info *thr = get_thread(thr_id);
  813. return thr->cgpu;
  814. }
  815. struct cgpu_info *get_devices(int id)
  816. {
  817. struct cgpu_info *cgpu;
  818. rd_lock(&devices_lock);
  819. cgpu = devices[id];
  820. rd_unlock(&devices_lock);
  821. return cgpu;
  822. }
  823. static pthread_mutex_t noncelog_lock = PTHREAD_MUTEX_INITIALIZER;
  824. static FILE *noncelog_file = NULL;
  825. static
  826. void noncelog(const struct work * const work)
  827. {
  828. const int thr_id = work->thr_id;
  829. const struct cgpu_info *proc = get_thr_cgpu(thr_id);
  830. char buf[0x200], hash[65], data[161], midstate[65];
  831. int rv;
  832. size_t ret;
  833. bin2hex(hash, work->hash, 32);
  834. bin2hex(data, work->data, 80);
  835. bin2hex(midstate, work->midstate, 32);
  836. // timestamp,proc,hash,data,midstate
  837. rv = snprintf(buf, sizeof(buf), "%lu,%s,%s,%s,%s\n",
  838. (unsigned long)time(NULL), proc->proc_repr_ns,
  839. hash, data, midstate);
  840. if (unlikely(rv < 1))
  841. {
  842. applog(LOG_ERR, "noncelog printf error");
  843. return;
  844. }
  845. mutex_lock(&noncelog_lock);
  846. ret = fwrite(buf, rv, 1, noncelog_file);
  847. fflush(noncelog_file);
  848. mutex_unlock(&noncelog_lock);
  849. if (ret != 1)
  850. applog(LOG_ERR, "noncelog fwrite error");
  851. }
  852. static void sharelog(const char*disposition, const struct work*work)
  853. {
  854. char target[(sizeof(work->target) * 2) + 1];
  855. char hash[(sizeof(work->hash) * 2) + 1];
  856. char data[(sizeof(work->data) * 2) + 1];
  857. struct cgpu_info *cgpu;
  858. unsigned long int t;
  859. struct pool *pool;
  860. int thr_id, rv;
  861. char s[1024];
  862. size_t ret;
  863. if (!sharelog_file)
  864. return;
  865. thr_id = work->thr_id;
  866. cgpu = get_thr_cgpu(thr_id);
  867. pool = work->pool;
  868. t = work->ts_getwork + timer_elapsed(&work->tv_getwork, &work->tv_work_found);
  869. bin2hex(target, work->target, sizeof(work->target));
  870. bin2hex(hash, work->hash, sizeof(work->hash));
  871. bin2hex(data, work->data, sizeof(work->data));
  872. // timestamp,disposition,target,pool,dev,thr,sharehash,sharedata
  873. 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);
  874. if (rv >= (int)(sizeof(s)))
  875. s[sizeof(s) - 1] = '\0';
  876. else if (rv < 0) {
  877. applog(LOG_ERR, "sharelog printf error");
  878. return;
  879. }
  880. mutex_lock(&sharelog_lock);
  881. ret = fwrite(s, rv, 1, sharelog_file);
  882. fflush(sharelog_file);
  883. mutex_unlock(&sharelog_lock);
  884. if (ret != 1)
  885. applog(LOG_ERR, "sharelog fwrite error");
  886. }
  887. #ifdef HAVE_CURSES
  888. static void switch_logsize(void);
  889. #endif
  890. static void hotplug_trigger();
  891. void goal_set_malgo(struct mining_goal_info * const goal, struct mining_algorithm * const malgo)
  892. {
  893. if (goal->malgo == malgo)
  894. return;
  895. if (goal->malgo)
  896. --goal->malgo->goal_refs;
  897. if (malgo->goal_refs++)
  898. // First time using a new mining algorithm may means we need to add mining hardware to support it
  899. // api_thr_id is used as an ugly hack to determine if mining has started - if not, we do NOT want to try to hotplug anything (let the initial detect handle it)
  900. if (opt_hotplug && api_thr_id)
  901. hotplug_trigger();
  902. goal->malgo = malgo;
  903. }
  904. struct mining_algorithm *mining_algorithm_by_alias(const char * const alias)
  905. {
  906. struct mining_algorithm *malgo;
  907. LL_FOREACH(mining_algorithms, malgo)
  908. {
  909. if (match_strtok(malgo->aliases, "|", alias))
  910. return malgo;
  911. }
  912. return NULL;
  913. }
  914. #if defined(USE_SHA256D) && defined(USE_OPENCL)
  915. static
  916. float opencl_oclthreads_to_intensity_sha256d(const unsigned long oclthreads)
  917. {
  918. return log2f(oclthreads) - 15.;
  919. }
  920. static
  921. unsigned long opencl_intensity_to_oclthreads_sha256d(float intensity)
  922. {
  923. return powf(2, intensity + 15);
  924. }
  925. #endif
  926. #ifdef USE_SHA256D
  927. static struct mining_algorithm malgo_sha256d = {
  928. .name = "SHA256d",
  929. .aliases = "SHA256d|SHA256|SHA2",
  930. .algo = POW_SHA256D,
  931. .ui_skip_hash_bytes = 4,
  932. .worktime_skip_prevblk_u32 = 1,
  933. .reasonable_low_nonce_diff = 1.,
  934. .hash_data_f = hash_data,
  935. #ifdef USE_OPENCL
  936. .opencl_nodefault = true,
  937. .opencl_oclthreads_to_intensity = opencl_oclthreads_to_intensity_sha256d,
  938. .opencl_intensity_to_oclthreads = opencl_intensity_to_oclthreads_sha256d,
  939. .opencl_min_oclthreads = 0x20, // intensity -10
  940. .opencl_max_oclthreads = 0x20000000, // intensity 14
  941. #endif
  942. };
  943. #endif
  944. #ifdef USE_SCRYPT
  945. #ifdef USE_OPENCL
  946. static
  947. float opencl_oclthreads_to_intensity_scrypt(const unsigned long oclthreads)
  948. {
  949. return log2(oclthreads);
  950. }
  951. static
  952. unsigned long opencl_intensity_to_oclthreads_scrypt(float intensity)
  953. {
  954. return pow(2, intensity);
  955. }
  956. #endif
  957. static struct mining_algorithm malgo_scrypt = {
  958. .name = "scrypt",
  959. .aliases = "scrypt",
  960. .algo = POW_SCRYPT,
  961. .ui_skip_hash_bytes = 2,
  962. .reasonable_low_nonce_diff = 1./0x10000,
  963. .hash_data_f = scrypt_hash_data,
  964. #ifdef USE_OPENCL
  965. .opencl_oclthreads_to_intensity = opencl_oclthreads_to_intensity_scrypt,
  966. .opencl_intensity_to_oclthreads = opencl_intensity_to_oclthreads_scrypt,
  967. .opencl_min_oclthreads = 0x100, // intensity 8
  968. .opencl_max_oclthreads = 0x20000000, // intensity 31
  969. #endif
  970. };
  971. static
  972. const char *set_malgo_scrypt()
  973. {
  974. goal_set_malgo(get_mining_goal("default"), &malgo_scrypt);
  975. return NULL;
  976. }
  977. #endif
  978. static
  979. __attribute__((constructor))
  980. void init_mining_goals(struct mining_goal_info * const goal, const struct mining_algorithm * const malgo)
  981. {
  982. #ifdef USE_SHA256D
  983. LL_APPEND(mining_algorithms, (&malgo_sha256d));
  984. #endif
  985. #ifdef USE_SCRYPT
  986. LL_APPEND(mining_algorithms, (&malgo_scrypt));
  987. #endif
  988. }
  989. static
  990. int mining_goals_name_cmp(const struct mining_goal_info * const a, const struct mining_goal_info * const b)
  991. {
  992. // default always goes first
  993. if (a->is_default)
  994. return -1;
  995. if (b->is_default)
  996. return 1;
  997. return strcmp(a->name, b->name);
  998. }
  999. static
  1000. void blkchain_init_block(struct blockchain_info * const blkchain)
  1001. {
  1002. struct block_info * const dummy_block = calloc(sizeof(*dummy_block), 1);
  1003. memset(dummy_block->prevblkhash, 0, 0x20);
  1004. HASH_ADD(hh, blkchain->blocks, prevblkhash, sizeof(dummy_block->prevblkhash), dummy_block);
  1005. blkchain->currentblk = dummy_block;
  1006. }
  1007. struct mining_goal_info *get_mining_goal(const char * const name)
  1008. {
  1009. static unsigned next_goal_id;
  1010. struct mining_goal_info *goal;
  1011. HASH_FIND_STR(mining_goals, name, goal);
  1012. if (!goal)
  1013. {
  1014. struct blockchain_info * const blkchain = malloc(sizeof(*blkchain) + sizeof(*goal));
  1015. goal = (void*)(&blkchain[1]);
  1016. *blkchain = (struct blockchain_info){
  1017. .currentblk = NULL,
  1018. };
  1019. blkchain_init_block(blkchain);
  1020. *goal = (struct mining_goal_info){
  1021. .id = next_goal_id++,
  1022. .name = strdup(name),
  1023. .is_default = !strcmp(name, "default"),
  1024. .blkchain = blkchain,
  1025. .current_diff = 0xFFFFFFFFFFFFFFFFULL,
  1026. };
  1027. #ifdef HAVE_SHA256D
  1028. goal_set_malgo(goal, &malgo_sha256d);
  1029. #else
  1030. // NOTE: Basically random default
  1031. goal_set_malgo(goal, mining_algorithms);
  1032. #endif
  1033. HASH_ADD_STR(mining_goals, name, goal);
  1034. HASH_SORT(mining_goals, mining_goals_name_cmp);
  1035. #ifdef HAVE_CURSES
  1036. devcursor = 7 + active_goals;
  1037. switch_logsize();
  1038. #endif
  1039. }
  1040. return goal;
  1041. }
  1042. void mining_goal_reset(struct mining_goal_info * const goal)
  1043. {
  1044. struct blockchain_info * const blkchain = goal->blkchain;
  1045. struct block_info *blkinfo, *tmpblkinfo;
  1046. HASH_ITER(hh, blkchain->blocks, blkinfo, tmpblkinfo)
  1047. {
  1048. HASH_DEL(blkchain->blocks, blkinfo);
  1049. free(blkinfo);
  1050. }
  1051. blkchain_init_block(blkchain);
  1052. }
  1053. static char *getwork_req = "{\"method\": \"getwork\", \"params\": [], \"id\":0}\n";
  1054. /* Adjust all the pools' quota to the greatest common denominator after a pool
  1055. * has been added or the quotas changed. */
  1056. void adjust_quota_gcd(void)
  1057. {
  1058. unsigned long gcd, lowest_quota = ~0UL, quota;
  1059. struct pool *pool;
  1060. int i;
  1061. for (i = 0; i < total_pools; i++) {
  1062. pool = pools[i];
  1063. quota = pool->quota;
  1064. if (!quota)
  1065. continue;
  1066. if (quota < lowest_quota)
  1067. lowest_quota = quota;
  1068. }
  1069. if (likely(lowest_quota < ~0UL)) {
  1070. gcd = lowest_quota;
  1071. for (i = 0; i < total_pools; i++) {
  1072. pool = pools[i];
  1073. quota = pool->quota;
  1074. if (!quota)
  1075. continue;
  1076. while (quota % gcd)
  1077. gcd--;
  1078. }
  1079. } else
  1080. gcd = 1;
  1081. for (i = 0; i < total_pools; i++) {
  1082. pool = pools[i];
  1083. pool->quota_used *= global_quota_gcd;
  1084. pool->quota_used /= gcd;
  1085. pool->quota_gcd = pool->quota / gcd;
  1086. }
  1087. global_quota_gcd = gcd;
  1088. applog(LOG_DEBUG, "Global quota greatest common denominator set to %lu", gcd);
  1089. }
  1090. /* Return value is ignored if not called from add_pool_details */
  1091. struct pool *add_pool2(struct mining_goal_info * const goal)
  1092. {
  1093. struct pool *pool;
  1094. pool = calloc(sizeof(struct pool), 1);
  1095. if (!pool)
  1096. quit(1, "Failed to malloc pool in add_pool");
  1097. pool->pool_no = pool->prio = total_pools;
  1098. mutex_init(&pool->last_work_lock);
  1099. mutex_init(&pool->pool_lock);
  1100. mutex_init(&pool->pool_test_lock);
  1101. if (unlikely(pthread_cond_init(&pool->cr_cond, bfg_condattr)))
  1102. quit(1, "Failed to pthread_cond_init in add_pool");
  1103. cglock_init(&pool->data_lock);
  1104. mutex_init(&pool->stratum_lock);
  1105. timer_unset(&pool->swork.tv_transparency);
  1106. pool->swork.pool = pool;
  1107. pool->goal = goal;
  1108. pool->idle = true;
  1109. /* Make sure the pool doesn't think we've been idle since time 0 */
  1110. pool->tv_idle.tv_sec = ~0UL;
  1111. cgtime(&pool->cgminer_stats.start_tv);
  1112. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  1113. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  1114. pool->rpc_proxy = NULL;
  1115. pool->quota = 1;
  1116. pool->sock = INVSOCK;
  1117. pool->lp_socket = CURL_SOCKET_BAD;
  1118. pools = realloc(pools, sizeof(struct pool *) * (total_pools + 2));
  1119. pools[total_pools++] = pool;
  1120. if (opt_benchmark)
  1121. {
  1122. // Immediately remove it
  1123. remove_pool(pool);
  1124. return pool;
  1125. }
  1126. adjust_quota_gcd();
  1127. if (!currentpool)
  1128. currentpool = pool;
  1129. enable_pool(pool);
  1130. return pool;
  1131. }
  1132. static
  1133. void pool_set_uri(struct pool * const pool, char * const uri)
  1134. {
  1135. pool->rpc_url = uri;
  1136. }
  1137. /* Pool variant of test and set */
  1138. static bool pool_tset(struct pool *pool, bool *var)
  1139. {
  1140. bool ret;
  1141. mutex_lock(&pool->pool_lock);
  1142. ret = *var;
  1143. *var = true;
  1144. mutex_unlock(&pool->pool_lock);
  1145. return ret;
  1146. }
  1147. bool pool_tclear(struct pool *pool, bool *var)
  1148. {
  1149. bool ret;
  1150. mutex_lock(&pool->pool_lock);
  1151. ret = *var;
  1152. *var = false;
  1153. mutex_unlock(&pool->pool_lock);
  1154. return ret;
  1155. }
  1156. struct pool *current_pool(void)
  1157. {
  1158. struct pool *pool;
  1159. cg_rlock(&control_lock);
  1160. pool = currentpool;
  1161. cg_runlock(&control_lock);
  1162. return pool;
  1163. }
  1164. #if defined(USE_CPUMINING) && !defined(USE_SHA256D)
  1165. static
  1166. char *arg_ignored(const char * const arg)
  1167. {
  1168. return NULL;
  1169. }
  1170. #endif
  1171. static
  1172. char *set_bool_ignore_arg(const char * const arg, bool * const b)
  1173. {
  1174. return opt_set_bool(b);
  1175. }
  1176. char *set_int_range(const char *arg, int *i, int min, int max)
  1177. {
  1178. char *err = opt_set_intval(arg, i);
  1179. if (err)
  1180. return err;
  1181. if (*i < min || *i > max)
  1182. return "Value out of range";
  1183. return NULL;
  1184. }
  1185. static char *set_int_0_to_9999(const char *arg, int *i)
  1186. {
  1187. return set_int_range(arg, i, 0, 9999);
  1188. }
  1189. static char *set_int_1_to_65535(const char *arg, int *i)
  1190. {
  1191. return set_int_range(arg, i, 1, 65535);
  1192. }
  1193. static char *set_int_0_to_10(const char *arg, int *i)
  1194. {
  1195. return set_int_range(arg, i, 0, 10);
  1196. }
  1197. static char *set_int_1_to_10(const char *arg, int *i)
  1198. {
  1199. return set_int_range(arg, i, 1, 10);
  1200. }
  1201. char *set_strdup(const char *arg, char **p)
  1202. {
  1203. *p = strdup((char *)arg);
  1204. return NULL;
  1205. }
  1206. #if BLKMAKER_VERSION > 1
  1207. static
  1208. char *set_b58addr(const char * const arg, bytes_t * const b)
  1209. {
  1210. size_t scriptsz = blkmk_address_to_script(NULL, 0, arg);
  1211. if (!scriptsz)
  1212. return "Invalid address";
  1213. char *script = malloc(scriptsz);
  1214. if (blkmk_address_to_script(script, scriptsz, arg) != scriptsz) {
  1215. free(script);
  1216. return "Failed to convert address to script";
  1217. }
  1218. bytes_assimilate_raw(b, script, scriptsz, scriptsz);
  1219. return NULL;
  1220. }
  1221. static char *set_generate_addr2(struct mining_goal_info *, const char *);
  1222. static
  1223. char *set_generate_addr(char *arg)
  1224. {
  1225. char * const colon = strchr(arg, ':');
  1226. struct mining_goal_info *goal;
  1227. if (colon)
  1228. {
  1229. colon[0] = '\0';
  1230. goal = get_mining_goal(arg);
  1231. arg = &colon[1];
  1232. }
  1233. else
  1234. goal = get_mining_goal("default");
  1235. return set_generate_addr2(goal, arg);
  1236. }
  1237. static
  1238. char *set_generate_addr2(struct mining_goal_info * const goal, const char * const arg)
  1239. {
  1240. bytes_t newscript = BYTES_INIT;
  1241. char *estr = set_b58addr(arg, &newscript);
  1242. if (estr)
  1243. {
  1244. bytes_free(&newscript);
  1245. return estr;
  1246. }
  1247. if (!goal->generation_script)
  1248. {
  1249. goal->generation_script = malloc(sizeof(*goal->generation_script));
  1250. bytes_init(goal->generation_script);
  1251. }
  1252. bytes_assimilate(goal->generation_script, &newscript);
  1253. bytes_free(&newscript);
  1254. return NULL;
  1255. }
  1256. #endif
  1257. static
  1258. char *set_quit_summary(const char * const arg)
  1259. {
  1260. if (!(strcasecmp(arg, "none") && strcasecmp(arg, "no")))
  1261. opt_quit_summary = BQS_NONE;
  1262. else
  1263. if (!(strcasecmp(arg, "devs") && strcasecmp(arg, "devices")))
  1264. opt_quit_summary = BQS_DEVS;
  1265. else
  1266. if (!(strcasecmp(arg, "procs") && strcasecmp(arg, "processors") && strcasecmp(arg, "chips") && strcasecmp(arg, "cores")))
  1267. opt_quit_summary = BQS_PROCS;
  1268. else
  1269. if (!(strcasecmp(arg, "detailed") && strcasecmp(arg, "detail") && strcasecmp(arg, "all")))
  1270. opt_quit_summary = BQS_DETAILED;
  1271. else
  1272. return "Quit summary must be one of none/devs/procs/detailed";
  1273. return NULL;
  1274. }
  1275. static void pdiff_target_leadzero(void *, double);
  1276. char *set_request_diff(const char *arg, float *p)
  1277. {
  1278. unsigned char target[32];
  1279. char *e = opt_set_floatval(arg, p);
  1280. if (e)
  1281. return e;
  1282. request_bdiff = (double)*p * 0.9999847412109375;
  1283. pdiff_target_leadzero(target, *p);
  1284. request_target_str = malloc(65);
  1285. bin2hex(request_target_str, target, 32);
  1286. return NULL;
  1287. }
  1288. #ifdef NEED_BFG_LOWL_VCOM
  1289. extern struct lowlevel_device_info *_vcom_devinfo_findorcreate(struct lowlevel_device_info **, const char *);
  1290. #ifdef WIN32
  1291. void _vcom_devinfo_scan_querydosdevice(struct lowlevel_device_info ** const devinfo_list)
  1292. {
  1293. char dev[PATH_MAX];
  1294. char *devp = dev;
  1295. size_t bufLen = 0x100;
  1296. tryagain: ;
  1297. char buf[bufLen];
  1298. if (!QueryDosDevice(NULL, buf, bufLen)) {
  1299. if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
  1300. bufLen *= 2;
  1301. applog(LOG_DEBUG, "QueryDosDevice returned insufficent buffer error; enlarging to %lx", (unsigned long)bufLen);
  1302. goto tryagain;
  1303. }
  1304. applogr(, LOG_WARNING, "Error occurred trying to enumerate COM ports with QueryDosDevice");
  1305. }
  1306. size_t tLen;
  1307. memcpy(devp, "\\\\.\\", 4);
  1308. devp = &devp[4];
  1309. for (char *t = buf; *t; t += tLen) {
  1310. tLen = strlen(t) + 1;
  1311. if (strncmp("COM", t, 3))
  1312. continue;
  1313. memcpy(devp, t, tLen);
  1314. // NOTE: We depend on _vcom_devinfo_findorcreate to further check that there's a number (and only a number) on the end
  1315. _vcom_devinfo_findorcreate(devinfo_list, dev);
  1316. }
  1317. }
  1318. #else
  1319. void _vcom_devinfo_scan_lsdev(struct lowlevel_device_info ** const devinfo_list)
  1320. {
  1321. char dev[PATH_MAX];
  1322. char *devp = dev;
  1323. DIR *D;
  1324. struct dirent *de;
  1325. const char devdir[] = "/dev";
  1326. const size_t devdirlen = sizeof(devdir) - 1;
  1327. char *devpath = devp;
  1328. char *devfile = devpath + devdirlen + 1;
  1329. D = opendir(devdir);
  1330. if (!D)
  1331. applogr(, LOG_DEBUG, "No /dev directory to look for VCOM devices in");
  1332. memcpy(devpath, devdir, devdirlen);
  1333. devpath[devdirlen] = '/';
  1334. while ( (de = readdir(D)) ) {
  1335. if (!strncmp(de->d_name, "cu.", 3)
  1336. //don't probe Bluetooth devices - causes bus errors and segfaults
  1337. && strncmp(de->d_name, "cu.Bluetooth", 12))
  1338. goto trydev;
  1339. if (strncmp(de->d_name, "tty", 3))
  1340. continue;
  1341. if (strncmp(&de->d_name[3], "USB", 3) && strncmp(&de->d_name[3], "ACM", 3))
  1342. continue;
  1343. trydev:
  1344. strcpy(devfile, de->d_name);
  1345. _vcom_devinfo_findorcreate(devinfo_list, dev);
  1346. }
  1347. closedir(D);
  1348. }
  1349. #endif
  1350. #endif
  1351. static char *add_serial(const char *arg)
  1352. {
  1353. string_elist_add(arg, &scan_devices);
  1354. return NULL;
  1355. }
  1356. static
  1357. char *opt_string_elist_add(const char *arg, struct string_elist **elist)
  1358. {
  1359. string_elist_add(arg, elist);
  1360. return NULL;
  1361. }
  1362. bool get_intrange(const char *arg, int *val1, int *val2)
  1363. {
  1364. // NOTE: This could be done with sscanf, but its %n is broken in strange ways on Windows
  1365. char *p, *p2;
  1366. *val1 = strtol(arg, &p, 0);
  1367. if (arg == p)
  1368. // Zero-length ending number, invalid
  1369. return false;
  1370. while (true)
  1371. {
  1372. if (!p[0])
  1373. {
  1374. *val2 = *val1;
  1375. return true;
  1376. }
  1377. if (p[0] == '-')
  1378. break;
  1379. if (!isspace(p[0]))
  1380. // Garbage, invalid
  1381. return false;
  1382. ++p;
  1383. }
  1384. p2 = &p[1];
  1385. *val2 = strtol(p2, &p, 0);
  1386. if (p2 == p)
  1387. // Zero-length ending number, invalid
  1388. return false;
  1389. while (true)
  1390. {
  1391. if (!p[0])
  1392. return true;
  1393. if (!isspace(p[0]))
  1394. // Garbage, invalid
  1395. return false;
  1396. ++p;
  1397. }
  1398. }
  1399. static
  1400. void _test_intrange(const char *s, const int v[2])
  1401. {
  1402. int a[2];
  1403. if (!get_intrange(s, &a[0], &a[1]))
  1404. {
  1405. ++unittest_failures;
  1406. applog(LOG_ERR, "Test \"%s\" failed: returned false", s);
  1407. }
  1408. for (int i = 0; i < 2; ++i)
  1409. if (unlikely(a[i] != v[i]))
  1410. {
  1411. ++unittest_failures;
  1412. applog(LOG_ERR, "Test \"%s\" failed: value %d should be %d but got %d", s, i, v[i], a[i]);
  1413. }
  1414. }
  1415. #define _test_intrange(s, ...) _test_intrange(s, (int[]){ __VA_ARGS__ })
  1416. static
  1417. void _test_intrange_fail(const char *s)
  1418. {
  1419. int a[2];
  1420. if (get_intrange(s, &a[0], &a[1]))
  1421. {
  1422. ++unittest_failures;
  1423. applog(LOG_ERR, "Test !\"%s\" failed: returned true with %d and %d", s, a[0], a[1]);
  1424. }
  1425. }
  1426. static
  1427. void test_intrange()
  1428. {
  1429. _test_intrange("-1--2", -1, -2);
  1430. _test_intrange("-1-2", -1, 2);
  1431. _test_intrange("1--2", 1, -2);
  1432. _test_intrange("1-2", 1, 2);
  1433. _test_intrange("111-222", 111, 222);
  1434. _test_intrange(" 11 - 22 ", 11, 22);
  1435. _test_intrange("+11-+22", 11, 22);
  1436. _test_intrange("-1", -1, -1);
  1437. _test_intrange_fail("all");
  1438. _test_intrange_fail("1-");
  1439. _test_intrange_fail("");
  1440. _test_intrange_fail("1-54x");
  1441. }
  1442. static char *set_devices(char *arg)
  1443. {
  1444. if (*arg) {
  1445. if (*arg == '?') {
  1446. opt_display_devs = true;
  1447. return NULL;
  1448. }
  1449. } else
  1450. return "Invalid device parameters";
  1451. string_elist_add(arg, &opt_devices_enabled_list);
  1452. return NULL;
  1453. }
  1454. static char *set_balance(enum pool_strategy *strategy)
  1455. {
  1456. *strategy = POOL_BALANCE;
  1457. return NULL;
  1458. }
  1459. static char *set_loadbalance(enum pool_strategy *strategy)
  1460. {
  1461. *strategy = POOL_LOADBALANCE;
  1462. return NULL;
  1463. }
  1464. static char *set_rotate(const char *arg, int *i)
  1465. {
  1466. pool_strategy = POOL_ROTATE;
  1467. return set_int_range(arg, i, 0, 9999);
  1468. }
  1469. static char *set_rr(enum pool_strategy *strategy)
  1470. {
  1471. *strategy = POOL_ROUNDROBIN;
  1472. return NULL;
  1473. }
  1474. static
  1475. char *set_benchmark_intense()
  1476. {
  1477. opt_benchmark = true;
  1478. opt_benchmark_intense = true;
  1479. return NULL;
  1480. }
  1481. /* Detect that url is for a stratum protocol either via the presence of
  1482. * stratum+tcp or by detecting a stratum server response */
  1483. bool detect_stratum(struct pool *pool, char *url)
  1484. {
  1485. if (!extract_sockaddr(url, &pool->sockaddr_url, &pool->stratum_port))
  1486. return false;
  1487. if (!strncasecmp(url, "stratum+tcp://", 14)) {
  1488. pool_set_uri(pool, strdup(url));
  1489. pool->has_stratum = true;
  1490. pool->stratum_url = pool->sockaddr_url;
  1491. return true;
  1492. }
  1493. return false;
  1494. }
  1495. static struct pool *add_url(void)
  1496. {
  1497. total_urls++;
  1498. if (total_urls > total_pools)
  1499. add_pool();
  1500. return pools[total_urls - 1];
  1501. }
  1502. static void setup_url(struct pool *pool, char *arg)
  1503. {
  1504. if (detect_stratum(pool, arg))
  1505. return;
  1506. opt_set_charp(arg, &pool->rpc_url);
  1507. if (strncmp(arg, "http://", 7) &&
  1508. strncmp(arg, "https://", 8)) {
  1509. const size_t L = strlen(arg);
  1510. char *httpinput;
  1511. httpinput = malloc(8 + L);
  1512. if (!httpinput)
  1513. quit(1, "Failed to malloc httpinput");
  1514. sprintf(httpinput, "http://%s", arg);
  1515. pool_set_uri(pool, httpinput);
  1516. }
  1517. }
  1518. static char *set_url(char *arg)
  1519. {
  1520. struct pool *pool = add_url();
  1521. setup_url(pool, arg);
  1522. return NULL;
  1523. }
  1524. static char *set_quota(char *arg)
  1525. {
  1526. char *semicolon = strchr(arg, ';'), *url;
  1527. int len, qlen, quota;
  1528. struct pool *pool;
  1529. if (!semicolon)
  1530. return "No semicolon separated quota;URL pair found";
  1531. len = strlen(arg);
  1532. *semicolon = '\0';
  1533. qlen = strlen(arg);
  1534. if (!qlen)
  1535. return "No parameter for quota found";
  1536. len -= qlen + 1;
  1537. if (len < 1)
  1538. return "No parameter for URL found";
  1539. quota = atoi(arg);
  1540. if (quota < 0)
  1541. return "Invalid negative parameter for quota set";
  1542. url = arg + qlen + 1;
  1543. pool = add_url();
  1544. setup_url(pool, url);
  1545. pool->quota = quota;
  1546. applog(LOG_INFO, "Setting pool %d to quota %d", pool->pool_no, pool->quota);
  1547. adjust_quota_gcd();
  1548. return NULL;
  1549. }
  1550. static char *set_user(const char *arg)
  1551. {
  1552. struct pool *pool;
  1553. total_users++;
  1554. if (total_users > total_pools)
  1555. add_pool();
  1556. pool = pools[total_users - 1];
  1557. opt_set_charp(arg, &pool->rpc_user);
  1558. return NULL;
  1559. }
  1560. static char *set_pass(const char *arg)
  1561. {
  1562. struct pool *pool;
  1563. total_passes++;
  1564. if (total_passes > total_pools)
  1565. add_pool();
  1566. pool = pools[total_passes - 1];
  1567. opt_set_charp(arg, &pool->rpc_pass);
  1568. return NULL;
  1569. }
  1570. static char *set_userpass(const char *arg)
  1571. {
  1572. struct pool *pool;
  1573. char *updup;
  1574. if (total_users != total_passes)
  1575. return "User + pass options must be balanced before userpass";
  1576. ++total_users;
  1577. ++total_passes;
  1578. if (total_users > total_pools)
  1579. add_pool();
  1580. pool = pools[total_users - 1];
  1581. updup = strdup(arg);
  1582. opt_set_charp(arg, &pool->rpc_userpass);
  1583. pool->rpc_user = updup;
  1584. pool->rpc_pass = strchr(updup, ':');
  1585. if (pool->rpc_pass)
  1586. pool->rpc_pass++[0] = '\0';
  1587. else
  1588. pool->rpc_pass = &updup[strlen(updup)];
  1589. return NULL;
  1590. }
  1591. static char *set_cbcaddr(char *arg)
  1592. {
  1593. struct pool *pool;
  1594. char *p, *addr;
  1595. bytes_t target_script = BYTES_INIT;
  1596. if (!total_pools)
  1597. return "Define pool first, then the --coinbase-check-addr list";
  1598. pool = pools[total_pools - 1];
  1599. /* NOTE: 'x' is a new prefix which leads both mainnet and testnet address, we would
  1600. * need support it later, but now leave the code just so.
  1601. *
  1602. * Regarding details of address prefix 'x', check the below URL:
  1603. * https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#Serialization_format
  1604. */
  1605. pool->cb_param.testnet = (arg[0] != '1' && arg[0] != '3' && arg[0] != 'x');
  1606. for (; (addr = strtok_r(arg, ",", &p)); arg = NULL)
  1607. {
  1608. struct bytes_hashtbl *ah;
  1609. if (set_b58addr(addr, &target_script))
  1610. /* No bother to free memory since we are going to exit anyway */
  1611. return "Invalid address in --coinbase-check-address list";
  1612. HASH_FIND(hh, pool->cb_param.scripts, bytes_buf(&target_script), bytes_len(&target_script), ah);
  1613. if (!ah)
  1614. {
  1615. /* Note: for the below allocated memory we have good way to release its memory
  1616. * since we can't be sure there are no reference to the pool struct when remove_pool()
  1617. * get called.
  1618. *
  1619. * We just hope the remove_pool() would not be called many many times during
  1620. * the whole running life of this program.
  1621. */
  1622. ah = malloc(sizeof(*ah));
  1623. bytes_init(&ah->b);
  1624. bytes_assimilate(&ah->b, &target_script);
  1625. HASH_ADD(hh, pool->cb_param.scripts, b.buf, bytes_len(&ah->b), ah);
  1626. }
  1627. }
  1628. bytes_free(&target_script);
  1629. return NULL;
  1630. }
  1631. static char *set_cbctotal(const char *arg)
  1632. {
  1633. struct pool *pool;
  1634. if (!total_pools)
  1635. return "Define pool first, then the --coinbase-check-total argument";
  1636. pool = pools[total_pools - 1];
  1637. pool->cb_param.total = atoll(arg);
  1638. if (pool->cb_param.total < 0)
  1639. return "The total payout amount in coinbase should be greater than 0";
  1640. return NULL;
  1641. }
  1642. static char *set_cbcperc(const char *arg)
  1643. {
  1644. struct pool *pool;
  1645. if (!total_pools)
  1646. return "Define pool first, then the --coinbase-check-percent argument";
  1647. pool = pools[total_pools - 1];
  1648. if (!pool->cb_param.scripts)
  1649. return "Define --coinbase-check-addr list first, then the --coinbase-check-total argument";
  1650. pool->cb_param.perc = atof(arg) / 100;
  1651. if (pool->cb_param.perc < 0.0 || pool->cb_param.perc > 1.0)
  1652. return "The percentage should be between 0 and 100";
  1653. return NULL;
  1654. }
  1655. static
  1656. const char *goal_set(struct mining_goal_info * const goal, const char * const optname, const char * const newvalue, bytes_t * const replybuf, enum bfg_set_device_replytype * const out_success)
  1657. {
  1658. *out_success = SDR_ERR;
  1659. if (!(strcasecmp(optname, "malgo") && strcasecmp(optname, "algo")))
  1660. {
  1661. if (!newvalue)
  1662. return "Goal option 'malgo' requires a value (eg, SHA256d)";
  1663. struct mining_algorithm * const new_malgo = mining_algorithm_by_alias(newvalue);
  1664. if (!new_malgo)
  1665. return "Unrecognised mining algorithm";
  1666. goal_set_malgo(goal, new_malgo);
  1667. goto success;
  1668. }
  1669. #if BLKMAKER_VERSION > 1
  1670. if (match_strtok("generate-to|generate-to-addr|generate-to-address|genaddress|genaddr|gen-address|gen-addr|generate-address|generate-addr|coinbase-addr|coinbase-address|coinbase-payout|cbaddress|cbaddr|cb-address|cb-addr|payout", "|", optname))
  1671. {
  1672. if (!newvalue)
  1673. return "Missing value for 'generate-to' goal option";
  1674. const char * const emsg = set_generate_addr2(goal, newvalue);
  1675. if (emsg)
  1676. return emsg;
  1677. goto success;
  1678. }
  1679. #endif
  1680. *out_success = SDR_UNKNOWN;
  1681. return "Unknown goal option";
  1682. success:
  1683. *out_success = SDR_OK;
  1684. return NULL;
  1685. }
  1686. // May leak replybuf if returning an error
  1687. static
  1688. const char *set_goal_params(struct mining_goal_info * const goal, char *arg)
  1689. {
  1690. bytes_t replybuf = BYTES_INIT;
  1691. for (char *param, *nextptr; (param = strtok_r(arg, ",", &nextptr)); arg = NULL)
  1692. {
  1693. char *val = strchr(param, '=');
  1694. if (val)
  1695. val++[0] = '\0';
  1696. enum bfg_set_device_replytype success;
  1697. const char * const emsg = goal_set(goal, param, val, &replybuf, &success);
  1698. if (success != SDR_OK)
  1699. return emsg ?: "Error setting goal param";
  1700. }
  1701. bytes_free(&replybuf);
  1702. return NULL;
  1703. }
  1704. static
  1705. const char *set_pool_goal(const char * const arg)
  1706. {
  1707. struct pool *pool;
  1708. if (!total_pools)
  1709. return "Usage of --pool-goal before pools are defined does not make sense";
  1710. pool = pools[total_pools - 1];
  1711. char *param = strchr(arg, ':');
  1712. if (param)
  1713. param++[0] = '\0';
  1714. pool->goal = get_mining_goal(arg);
  1715. if (param)
  1716. return set_goal_params(pool->goal, param);
  1717. return NULL;
  1718. }
  1719. static char *set_pool_priority(const char *arg)
  1720. {
  1721. struct pool *pool;
  1722. if (!total_pools)
  1723. return "Usage of --pool-priority before pools are defined does not make sense";
  1724. pool = pools[total_pools - 1];
  1725. opt_set_intval(arg, &pool->prio);
  1726. return NULL;
  1727. }
  1728. static char *set_pool_proxy(const char *arg)
  1729. {
  1730. struct pool *pool;
  1731. if (!total_pools)
  1732. return "Usage of --pool-proxy before pools are defined does not make sense";
  1733. if (!our_curl_supports_proxy_uris())
  1734. return "Your installed cURL library does not support proxy URIs. At least version 7.21.7 is required.";
  1735. pool = pools[total_pools - 1];
  1736. opt_set_charp(arg, &pool->rpc_proxy);
  1737. return NULL;
  1738. }
  1739. static char *set_pool_force_rollntime(const char *arg)
  1740. {
  1741. struct pool *pool;
  1742. if (!total_pools)
  1743. return "Usage of --force-rollntime before pools are defined does not make sense";
  1744. pool = pools[total_pools - 1];
  1745. opt_set_intval(arg, &pool->force_rollntime);
  1746. return NULL;
  1747. }
  1748. static char *enable_debug(bool *flag)
  1749. {
  1750. *flag = true;
  1751. opt_debug_console = true;
  1752. /* Turn on verbose output, too. */
  1753. opt_log_output = true;
  1754. return NULL;
  1755. }
  1756. static char *set_schedtime(const char *arg, struct schedtime *st)
  1757. {
  1758. if (sscanf(arg, "%d:%d", &st->tm.tm_hour, &st->tm.tm_min) != 2)
  1759. {
  1760. if (strcasecmp(arg, "now"))
  1761. return "Invalid time set, should be HH:MM";
  1762. } else
  1763. schedstop.tm.tm_sec = 0;
  1764. if (st->tm.tm_hour > 23 || st->tm.tm_min > 59 || st->tm.tm_hour < 0 || st->tm.tm_min < 0)
  1765. return "Invalid time set.";
  1766. st->enable = true;
  1767. return NULL;
  1768. }
  1769. static
  1770. char *set_log_file(char *arg)
  1771. {
  1772. char *r = "";
  1773. long int i = strtol(arg, &r, 10);
  1774. int fd, stderr_fd = fileno(stderr);
  1775. if ((!*r) && i >= 0 && i <= INT_MAX)
  1776. fd = i;
  1777. else
  1778. if (!strcmp(arg, "-"))
  1779. {
  1780. fd = fileno(stdout);
  1781. if (unlikely(fd == -1))
  1782. return "Standard output missing for log-file";
  1783. }
  1784. else
  1785. {
  1786. fd = open(arg, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR);
  1787. if (unlikely(fd == -1))
  1788. return "Failed to open log-file";
  1789. }
  1790. close(stderr_fd);
  1791. if (unlikely(-1 == dup2(fd, stderr_fd)))
  1792. return "Failed to dup2 for log-file";
  1793. close(fd);
  1794. return NULL;
  1795. }
  1796. static
  1797. char *_bfgopt_set_file(const char *arg, FILE **F, const char *mode, const char *purpose)
  1798. {
  1799. char *r = "";
  1800. long int i = strtol(arg, &r, 10);
  1801. static char *err = NULL;
  1802. const size_t errbufsz = 0x100;
  1803. free(err);
  1804. err = NULL;
  1805. if ((!*r) && i >= 0 && i <= INT_MAX) {
  1806. *F = fdopen((int)i, mode);
  1807. if (!*F)
  1808. {
  1809. err = malloc(errbufsz);
  1810. snprintf(err, errbufsz, "Failed to open fd %d for %s",
  1811. (int)i, purpose);
  1812. return err;
  1813. }
  1814. } else if (!strcmp(arg, "-")) {
  1815. *F = (mode[0] == 'a') ? stdout : stdin;
  1816. if (!*F)
  1817. {
  1818. err = malloc(errbufsz);
  1819. snprintf(err, errbufsz, "Standard %sput missing for %s",
  1820. (mode[0] == 'a') ? "out" : "in", purpose);
  1821. return err;
  1822. }
  1823. } else {
  1824. *F = fopen(arg, mode);
  1825. if (!*F)
  1826. {
  1827. err = malloc(errbufsz);
  1828. snprintf(err, errbufsz, "Failed to open %s for %s",
  1829. arg, purpose);
  1830. return err;
  1831. }
  1832. }
  1833. return NULL;
  1834. }
  1835. static char *set_noncelog(char *arg)
  1836. {
  1837. return _bfgopt_set_file(arg, &noncelog_file, "a", "nonce log");
  1838. }
  1839. static char *set_sharelog(char *arg)
  1840. {
  1841. return _bfgopt_set_file(arg, &sharelog_file, "a", "share log");
  1842. }
  1843. static
  1844. void _add_set_device_option(const char * const func, const char * const buf)
  1845. {
  1846. applog(LOG_DEBUG, "%s: Using --set-device %s", func, buf);
  1847. string_elist_add(buf, &opt_set_device_list);
  1848. }
  1849. #define add_set_device_option(...) do{ \
  1850. char _tmp1718[0x100]; \
  1851. snprintf(_tmp1718, sizeof(_tmp1718), __VA_ARGS__); \
  1852. _add_set_device_option(__func__, _tmp1718); \
  1853. }while(0)
  1854. char *set_temp_cutoff(char *arg)
  1855. {
  1856. if (strchr(arg, ','))
  1857. return "temp-cutoff no longer supports comma-delimited syntax, use --set-device for better control";
  1858. applog(LOG_WARNING, "temp-cutoff is deprecated! Use --set-device for better control");
  1859. add_set_device_option("all:temp-cutoff=%s", arg);
  1860. return NULL;
  1861. }
  1862. char *set_temp_target(char *arg)
  1863. {
  1864. if (strchr(arg, ','))
  1865. return "temp-target no longer supports comma-delimited syntax, use --set-device for better control";
  1866. applog(LOG_WARNING, "temp-target is deprecated! Use --set-device for better control");
  1867. add_set_device_option("all:temp-target=%s", arg);
  1868. return NULL;
  1869. }
  1870. #ifdef USE_OPENCL
  1871. static
  1872. char *set_no_opencl_binaries(__maybe_unused void * const dummy)
  1873. {
  1874. applog(LOG_WARNING, "The --no-opencl-binaries option is deprecated! Use --set-device OCL:binary=no");
  1875. add_set_device_option("OCL:binary=no");
  1876. return NULL;
  1877. }
  1878. #endif
  1879. static
  1880. char *disable_pool_redirect(__maybe_unused void * const dummy)
  1881. {
  1882. opt_disable_client_reconnect = true;
  1883. want_stratum = false;
  1884. return NULL;
  1885. }
  1886. static char *set_api_allow(const char *arg)
  1887. {
  1888. opt_set_charp(arg, &opt_api_allow);
  1889. return NULL;
  1890. }
  1891. static char *set_api_groups(const char *arg)
  1892. {
  1893. opt_set_charp(arg, &opt_api_groups);
  1894. return NULL;
  1895. }
  1896. static char *set_api_description(const char *arg)
  1897. {
  1898. opt_set_charp(arg, &opt_api_description);
  1899. return NULL;
  1900. }
  1901. static char *set_api_mcast_des(const char *arg)
  1902. {
  1903. opt_set_charp(arg, &opt_api_mcast_des);
  1904. return NULL;
  1905. }
  1906. #ifdef USE_ICARUS
  1907. extern const struct bfg_set_device_definition icarus_set_device_funcs[];
  1908. static char *set_icarus_options(const char *arg)
  1909. {
  1910. if (strchr(arg, ','))
  1911. return "icarus-options no longer supports comma-delimited syntax, see README.FPGA for better control";
  1912. applog(LOG_WARNING, "icarus-options is deprecated! See README.FPGA for better control");
  1913. char *opts = strdup(arg), *argdup;
  1914. argdup = opts;
  1915. const struct bfg_set_device_definition *sdf = icarus_set_device_funcs;
  1916. const char *drivers[] = {"antminer", "cairnsmore", "erupter", "icarus"};
  1917. char *saveptr, *opt;
  1918. for (int i = 0; i < 4; ++i, ++sdf)
  1919. {
  1920. opt = strtok_r(opts, ":", &saveptr);
  1921. opts = NULL;
  1922. if (!opt)
  1923. break;
  1924. if (!opt[0])
  1925. continue;
  1926. for (int j = 0; j < 4; ++j)
  1927. add_set_device_option("%s:%s=%s", drivers[j], sdf->optname, opt);
  1928. }
  1929. free(argdup);
  1930. return NULL;
  1931. }
  1932. static char *set_icarus_timing(const char *arg)
  1933. {
  1934. if (strchr(arg, ','))
  1935. return "icarus-timing no longer supports comma-delimited syntax, see README.FPGA for better control";
  1936. applog(LOG_WARNING, "icarus-timing is deprecated! See README.FPGA for better control");
  1937. const char *drivers[] = {"antminer", "cairnsmore", "erupter", "icarus"};
  1938. for (int j = 0; j < 4; ++j)
  1939. add_set_device_option("%s:timing=%s", drivers[j], arg);
  1940. return NULL;
  1941. }
  1942. #endif
  1943. #ifdef USE_AVALON
  1944. extern const struct bfg_set_device_definition avalon_set_device_funcs[];
  1945. static char *set_avalon_options(const char *arg)
  1946. {
  1947. if (strchr(arg, ','))
  1948. return "avalon-options no longer supports comma-delimited syntax, see README.FPGA for better control";
  1949. applog(LOG_WARNING, "avalon-options is deprecated! See README.FPGA for better control");
  1950. char *opts = strdup(arg), *argdup;
  1951. argdup = opts;
  1952. const struct bfg_set_device_definition *sdf = avalon_set_device_funcs;
  1953. char *saveptr, *opt;
  1954. for (int i = 0; i < 5; ++i, ++sdf)
  1955. {
  1956. opt = strtok_r(opts, ":", &saveptr);
  1957. opts = NULL;
  1958. if (!opt)
  1959. break;
  1960. if (!opt[0])
  1961. continue;
  1962. add_set_device_option("avalon:%s=%s", sdf->optname, opt);
  1963. }
  1964. free(argdup);
  1965. return NULL;
  1966. }
  1967. #endif
  1968. #ifdef USE_KLONDIKE
  1969. static char *set_klondike_options(const char *arg)
  1970. {
  1971. int hashclock;
  1972. double temptarget;
  1973. switch (sscanf(arg, "%d:%lf", &hashclock, &temptarget))
  1974. {
  1975. default:
  1976. return "Unrecognised --klondike-options";
  1977. case 2:
  1978. add_set_device_option("klondike:temp-target=%lf", temptarget);
  1979. // fallthru
  1980. case 1:
  1981. add_set_device_option("klondike:clock=%d", hashclock);
  1982. }
  1983. applog(LOG_WARNING, "klondike-options is deprecated! Use --set-device for better control");
  1984. return NULL;
  1985. }
  1986. #endif
  1987. __maybe_unused
  1988. static char *set_null(const char __maybe_unused *arg)
  1989. {
  1990. return NULL;
  1991. }
  1992. /* These options are available from config file or commandline */
  1993. static struct opt_table opt_config_table[] = {
  1994. #ifdef USE_CPUMINING
  1995. #ifdef USE_SHA256D
  1996. OPT_WITH_ARG("--algo",
  1997. set_algo, show_algo, &opt_algo,
  1998. "Specify sha256 implementation for CPU mining:\n"
  1999. "\tfastauto*\tQuick benchmark at startup to pick a working algorithm\n"
  2000. "\tauto\t\tBenchmark at startup and pick fastest algorithm"
  2001. "\n\tc\t\tLinux kernel sha256, implemented in C"
  2002. #ifdef WANT_SSE2_4WAY
  2003. "\n\t4way\t\ttcatm's 4-way SSE2 implementation"
  2004. #endif
  2005. #ifdef WANT_VIA_PADLOCK
  2006. "\n\tvia\t\tVIA padlock implementation"
  2007. #endif
  2008. "\n\tcryptopp\tCrypto++ C/C++ implementation"
  2009. #ifdef WANT_CRYPTOPP_ASM32
  2010. "\n\tcryptopp_asm32\tCrypto++ 32-bit assembler implementation"
  2011. #endif
  2012. #ifdef WANT_X8632_SSE2
  2013. "\n\tsse2_32\t\tSSE2 32 bit implementation for i386 machines"
  2014. #endif
  2015. #ifdef WANT_X8664_SSE2
  2016. "\n\tsse2_64\t\tSSE2 64 bit implementation for x86_64 machines"
  2017. #endif
  2018. #ifdef WANT_X8664_SSE4
  2019. "\n\tsse4_64\t\tSSE4.1 64 bit implementation for x86_64 machines"
  2020. #endif
  2021. #ifdef WANT_ALTIVEC_4WAY
  2022. "\n\taltivec_4way\tAltivec implementation for PowerPC G4 and G5 machines"
  2023. #endif
  2024. ),
  2025. OPT_WITH_ARG("-a",
  2026. set_algo, show_algo, &opt_algo,
  2027. opt_hidden),
  2028. #else
  2029. // NOTE: Silently ignoring option, since it is plausable a non-SHA256d miner was using it just to skip benchmarking
  2030. OPT_WITH_ARG("--algo|-a", arg_ignored, NULL, NULL, opt_hidden),
  2031. #endif /* USE_SHA256D */
  2032. #endif /* USE_CPUMINING */
  2033. OPT_WITH_ARG("--api-allow",
  2034. set_api_allow, NULL, NULL,
  2035. "Allow API access only to the given list of [G:]IP[/Prefix] addresses[/subnets]"),
  2036. OPT_WITH_ARG("--api-description",
  2037. set_api_description, NULL, NULL,
  2038. "Description placed in the API status header, default: BFGMiner version"),
  2039. OPT_WITH_ARG("--api-groups",
  2040. set_api_groups, NULL, NULL,
  2041. "API one letter groups G:cmd:cmd[,P:cmd:*...] defining the cmds a groups can use"),
  2042. OPT_WITHOUT_ARG("--api-listen",
  2043. opt_set_bool, &opt_api_listen,
  2044. "Enable API, default: disabled"),
  2045. OPT_WITHOUT_ARG("--api-mcast",
  2046. opt_set_bool, &opt_api_mcast,
  2047. "Enable API Multicast listener, default: disabled"),
  2048. OPT_WITH_ARG("--api-mcast-addr",
  2049. opt_set_charp, opt_show_charp, &opt_api_mcast_addr,
  2050. "API Multicast listen address"),
  2051. OPT_WITH_ARG("--api-mcast-code",
  2052. opt_set_charp, opt_show_charp, &opt_api_mcast_code,
  2053. "Code expected in the API Multicast message, don't use '-'"),
  2054. OPT_WITH_ARG("--api-mcast-des",
  2055. set_api_mcast_des, NULL, NULL,
  2056. "Description appended to the API Multicast reply, default: ''"),
  2057. OPT_WITH_ARG("--api-mcast-port",
  2058. set_int_1_to_65535, opt_show_intval, &opt_api_mcast_port,
  2059. "API Multicast listen port"),
  2060. OPT_WITHOUT_ARG("--api-network",
  2061. opt_set_bool, &opt_api_network,
  2062. "Allow API (if enabled) to listen on/for any address, default: only 127.0.0.1"),
  2063. OPT_WITH_ARG("--api-port",
  2064. set_int_1_to_65535, opt_show_intval, &opt_api_port,
  2065. "Port number of miner API"),
  2066. #ifdef HAVE_ADL
  2067. OPT_WITHOUT_ARG("--auto-fan",
  2068. opt_set_bool, &opt_autofan,
  2069. opt_hidden),
  2070. OPT_WITHOUT_ARG("--auto-gpu",
  2071. opt_set_bool, &opt_autoengine,
  2072. opt_hidden),
  2073. #endif
  2074. OPT_WITHOUT_ARG("--balance",
  2075. set_balance, &pool_strategy,
  2076. "Change multipool strategy from failover to even share balance"),
  2077. OPT_WITHOUT_ARG("--benchmark",
  2078. opt_set_bool, &opt_benchmark,
  2079. "Run BFGMiner in benchmark mode - produces no shares"),
  2080. OPT_WITHOUT_ARG("--benchmark-intense",
  2081. set_benchmark_intense, &opt_benchmark_intense,
  2082. "Run BFGMiner in intensive benchmark mode - produces no shares"),
  2083. #if defined(USE_BITFORCE)
  2084. OPT_WITHOUT_ARG("--bfl-range",
  2085. opt_set_bool, &opt_bfl_noncerange,
  2086. "Use nonce range on bitforce devices if supported"),
  2087. #endif
  2088. #ifdef HAVE_CHROOT
  2089. OPT_WITH_ARG("--chroot-dir",
  2090. opt_set_charp, NULL, &chroot_dir,
  2091. "Chroot to a directory right after startup"),
  2092. #endif
  2093. OPT_WITH_ARG("--cmd-idle",
  2094. opt_set_charp, NULL, &cmd_idle,
  2095. "Execute a command when a device is allowed to be idle (rest or wait)"),
  2096. OPT_WITH_ARG("--cmd-sick",
  2097. opt_set_charp, NULL, &cmd_sick,
  2098. "Execute a command when a device is declared sick"),
  2099. OPT_WITH_ARG("--cmd-dead",
  2100. opt_set_charp, NULL, &cmd_dead,
  2101. "Execute a command when a device is declared dead"),
  2102. #if BLKMAKER_VERSION > 0
  2103. OPT_WITH_ARG("--coinbase-sig",
  2104. set_strdup, NULL, &opt_coinbase_sig,
  2105. "Set coinbase signature when possible"),
  2106. OPT_WITH_ARG("--coinbase|--cbsig|--cb-sig|--cb|--prayer",
  2107. set_strdup, NULL, &opt_coinbase_sig,
  2108. opt_hidden),
  2109. #endif
  2110. #ifdef HAVE_CURSES
  2111. OPT_WITHOUT_ARG("--compact",
  2112. opt_set_bool, &opt_compact,
  2113. "Use compact display without per device statistics"),
  2114. #endif
  2115. #ifdef USE_CPUMINING
  2116. OPT_WITH_ARG("--cpu-threads",
  2117. force_nthreads_int, opt_show_intval, &opt_n_threads,
  2118. "Number of miner CPU threads"),
  2119. OPT_WITH_ARG("-t",
  2120. force_nthreads_int, opt_show_intval, &opt_n_threads,
  2121. opt_hidden),
  2122. #endif
  2123. OPT_WITHOUT_ARG("--debug|-D",
  2124. enable_debug, &opt_debug,
  2125. "Enable debug output"),
  2126. OPT_WITHOUT_ARG("--debuglog",
  2127. opt_set_bool, &opt_debug,
  2128. "Enable debug logging"),
  2129. OPT_WITHOUT_ARG("--device-protocol-dump",
  2130. opt_set_bool, &opt_dev_protocol,
  2131. "Verbose dump of device protocol-level activities"),
  2132. OPT_WITH_ARG("--device|-d",
  2133. set_devices, NULL, NULL,
  2134. "Enable only devices matching pattern (default: all)"),
  2135. OPT_WITHOUT_ARG("--disable-rejecting",
  2136. opt_set_bool, &opt_disable_pool,
  2137. "Automatically disable pools that continually reject shares"),
  2138. #ifdef USE_LIBMICROHTTPD
  2139. OPT_WITH_ARG("--http-port",
  2140. opt_set_intval, opt_show_intval, &httpsrv_port,
  2141. "Port number to listen on for HTTP getwork miners (-1 means disabled)"),
  2142. #endif
  2143. OPT_WITH_ARG("--expiry",
  2144. set_int_0_to_9999, opt_show_intval, &opt_expiry,
  2145. "Upper bound on how many seconds after getting work we consider a share from it stale (w/o longpoll active)"),
  2146. OPT_WITH_ARG("-E",
  2147. set_int_0_to_9999, opt_show_intval, &opt_expiry,
  2148. opt_hidden),
  2149. OPT_WITH_ARG("--expiry-lp",
  2150. set_int_0_to_9999, opt_show_intval, &opt_expiry_lp,
  2151. "Upper bound on how many seconds after getting work we consider a share from it stale (with longpoll active)"),
  2152. OPT_WITHOUT_ARG("--failover-only",
  2153. opt_set_bool, &opt_fail_only,
  2154. "Don't leak work to backup pools when primary pool is lagging"),
  2155. OPT_WITH_ARG("--failover-switch-delay",
  2156. set_int_1_to_65535, opt_show_intval, &opt_fail_switch_delay,
  2157. "Delay in seconds before switching back to a failed pool"),
  2158. #ifdef USE_FPGA
  2159. OPT_WITHOUT_ARG("--force-dev-init",
  2160. opt_set_bool, &opt_force_dev_init,
  2161. "Always initialize devices when possible (such as bitstream uploads to some FPGAs)"),
  2162. #endif
  2163. #if BLKMAKER_VERSION > 1
  2164. OPT_WITH_ARG("--generate-to",
  2165. set_generate_addr, NULL, NULL,
  2166. "Set an address to generate to for solo mining"),
  2167. OPT_WITH_ARG("--generate-to-addr|--generate-to-address|--genaddress|--genaddr|--gen-address|--gen-addr|--generate-address|--generate-addr|--coinbase-addr|--coinbase-address|--coinbase-payout|--cbaddress|--cbaddr|--cb-address|--cb-addr|--payout",
  2168. set_generate_addr, NULL, NULL,
  2169. opt_hidden),
  2170. #endif
  2171. #ifdef USE_OPENCL
  2172. OPT_WITH_ARG("--gpu-dyninterval",
  2173. set_int_1_to_65535, opt_show_intval, &opt_dynamic_interval,
  2174. opt_hidden),
  2175. OPT_WITH_ARG("--gpu-platform",
  2176. set_int_0_to_9999, opt_show_intval, &opt_platform_id,
  2177. "Select OpenCL platform ID to use for GPU mining"),
  2178. OPT_WITH_ARG("--gpu-threads|-g",
  2179. set_gpu_threads, opt_show_intval, &opt_g_threads,
  2180. opt_hidden),
  2181. #ifdef HAVE_ADL
  2182. OPT_WITH_ARG("--gpu-engine",
  2183. set_gpu_engine, NULL, NULL,
  2184. opt_hidden),
  2185. OPT_WITH_ARG("--gpu-fan",
  2186. set_gpu_fan, NULL, NULL,
  2187. opt_hidden),
  2188. OPT_WITH_ARG("--gpu-map",
  2189. set_gpu_map, NULL, NULL,
  2190. "Map OpenCL to ADL device order manually, paired CSV (e.g. 1:0,2:1 maps OpenCL 1 to ADL 0, 2 to 1)"),
  2191. OPT_WITH_ARG("--gpu-memclock",
  2192. set_gpu_memclock, NULL, NULL,
  2193. opt_hidden),
  2194. OPT_WITH_ARG("--gpu-memdiff",
  2195. set_gpu_memdiff, NULL, NULL,
  2196. opt_hidden),
  2197. OPT_WITH_ARG("--gpu-powertune",
  2198. set_gpu_powertune, NULL, NULL,
  2199. opt_hidden),
  2200. OPT_WITHOUT_ARG("--gpu-reorder",
  2201. opt_set_bool, &opt_reorder,
  2202. "Attempt to reorder GPU devices according to PCI Bus ID"),
  2203. OPT_WITH_ARG("--gpu-vddc",
  2204. set_gpu_vddc, NULL, NULL,
  2205. opt_hidden),
  2206. #endif
  2207. #ifdef USE_SCRYPT
  2208. OPT_WITH_ARG("--lookup-gap",
  2209. set_lookup_gap, NULL, NULL,
  2210. opt_hidden),
  2211. #endif
  2212. OPT_WITH_ARG("--intensity|-I",
  2213. set_intensity, NULL, NULL,
  2214. opt_hidden),
  2215. #endif
  2216. #if defined(USE_OPENCL) || defined(USE_MODMINER) || defined(USE_X6500) || defined(USE_ZTEX)
  2217. OPT_WITH_ARG("--kernel-path",
  2218. opt_set_charp, opt_show_charp, &opt_kernel_path,
  2219. "Specify a path to where bitstream and kernel files are"),
  2220. OPT_WITH_ARG("-K",
  2221. opt_set_charp, opt_show_charp, &opt_kernel_path,
  2222. opt_hidden),
  2223. #endif
  2224. #ifdef USE_OPENCL
  2225. OPT_WITH_ARG("--kernel|-k",
  2226. set_kernel, NULL, NULL,
  2227. opt_hidden),
  2228. #endif
  2229. #ifdef USE_ICARUS
  2230. OPT_WITH_ARG("--icarus-options",
  2231. set_icarus_options, NULL, NULL,
  2232. opt_hidden),
  2233. OPT_WITH_ARG("--icarus-timing",
  2234. set_icarus_timing, NULL, NULL,
  2235. opt_hidden),
  2236. #endif
  2237. #ifdef USE_AVALON
  2238. OPT_WITH_ARG("--avalon-options",
  2239. set_avalon_options, NULL, NULL,
  2240. opt_hidden),
  2241. #endif
  2242. #ifdef USE_KLONDIKE
  2243. OPT_WITH_ARG("--klondike-options",
  2244. set_klondike_options, NULL, NULL,
  2245. "Set klondike options clock:temptarget"),
  2246. #endif
  2247. OPT_WITHOUT_ARG("--load-balance",
  2248. set_loadbalance, &pool_strategy,
  2249. "Change multipool strategy from failover to quota based balance"),
  2250. OPT_WITH_ARG("--log|-l",
  2251. set_int_0_to_9999, opt_show_intval, &opt_log_interval,
  2252. "Interval in seconds between log output"),
  2253. OPT_WITH_ARG("--log-file|-L",
  2254. set_log_file, NULL, NULL,
  2255. "Append log file for output messages"),
  2256. OPT_WITH_ARG("--logfile",
  2257. set_log_file, NULL, NULL,
  2258. opt_hidden),
  2259. OPT_WITHOUT_ARG("--log-microseconds",
  2260. opt_set_bool, &opt_log_microseconds,
  2261. "Include microseconds in log output"),
  2262. #if defined(unix) || defined(__APPLE__)
  2263. OPT_WITH_ARG("--monitor|-m",
  2264. opt_set_charp, NULL, &opt_stderr_cmd,
  2265. "Use custom pipe cmd for output messages"),
  2266. #endif // defined(unix)
  2267. OPT_WITHOUT_ARG("--net-delay",
  2268. opt_set_bool, &opt_delaynet,
  2269. "Impose small delays in networking to avoid overloading slow routers"),
  2270. OPT_WITHOUT_ARG("--no-adl",
  2271. opt_set_bool, &opt_noadl,
  2272. #ifdef HAVE_ADL
  2273. "Disable the ATI display library used for monitoring and setting GPU parameters"
  2274. #else
  2275. opt_hidden
  2276. #endif
  2277. ),
  2278. OPT_WITHOUT_ARG("--no-gbt",
  2279. opt_set_invbool, &want_gbt,
  2280. "Disable getblocktemplate support"),
  2281. OPT_WITHOUT_ARG("--no-getwork",
  2282. opt_set_invbool, &want_getwork,
  2283. "Disable getwork support"),
  2284. OPT_WITHOUT_ARG("--no-hotplug",
  2285. #ifdef HAVE_BFG_HOTPLUG
  2286. opt_set_invbool, &opt_hotplug,
  2287. "Disable hotplug detection"
  2288. #else
  2289. set_null, &opt_hotplug,
  2290. opt_hidden
  2291. #endif
  2292. ),
  2293. OPT_WITHOUT_ARG("--no-local-bitcoin",
  2294. #if BLKMAKER_VERSION > 1
  2295. opt_set_invbool, &opt_load_bitcoin_conf,
  2296. "Disable adding pools for local bitcoin RPC servers"),
  2297. #else
  2298. set_null, NULL, opt_hidden),
  2299. #endif
  2300. OPT_WITHOUT_ARG("--no-longpoll",
  2301. opt_set_invbool, &want_longpoll,
  2302. "Disable X-Long-Polling support"),
  2303. OPT_WITHOUT_ARG("--no-pool-disable",
  2304. opt_set_invbool, &opt_disable_pool,
  2305. opt_hidden),
  2306. OPT_WITHOUT_ARG("--no-client-reconnect",
  2307. opt_set_invbool, &opt_disable_client_reconnect,
  2308. opt_hidden),
  2309. OPT_WITHOUT_ARG("--no-pool-redirect",
  2310. disable_pool_redirect, NULL,
  2311. "Ignore pool requests to redirect to another server"),
  2312. OPT_WITHOUT_ARG("--no-restart",
  2313. opt_set_invbool, &opt_restart,
  2314. "Do not attempt to restart devices that hang"
  2315. ),
  2316. OPT_WITHOUT_ARG("--no-show-processors",
  2317. opt_set_invbool, &opt_show_procs,
  2318. opt_hidden),
  2319. OPT_WITHOUT_ARG("--no-show-procs",
  2320. opt_set_invbool, &opt_show_procs,
  2321. opt_hidden),
  2322. OPT_WITHOUT_ARG("--no-stratum",
  2323. opt_set_invbool, &want_stratum,
  2324. "Disable Stratum detection"),
  2325. OPT_WITHOUT_ARG("--no-submit-stale",
  2326. opt_set_invbool, &opt_submit_stale,
  2327. "Don't submit shares if they are detected as stale"),
  2328. #ifdef USE_OPENCL
  2329. OPT_WITHOUT_ARG("--no-opencl-binaries",
  2330. set_no_opencl_binaries, NULL,
  2331. opt_hidden),
  2332. #endif
  2333. OPT_WITHOUT_ARG("--no-unicode",
  2334. #ifdef USE_UNICODE
  2335. opt_set_invbool, &use_unicode,
  2336. "Don't use Unicode characters in TUI"
  2337. #else
  2338. set_null, &use_unicode,
  2339. opt_hidden
  2340. #endif
  2341. ),
  2342. OPT_WITH_ARG("--noncelog",
  2343. set_noncelog, NULL, NULL,
  2344. "Create log of all nonces found"),
  2345. OPT_WITH_ARG("--pass|-p",
  2346. set_pass, NULL, NULL,
  2347. "Password for bitcoin JSON-RPC server"),
  2348. OPT_WITHOUT_ARG("--per-device-stats",
  2349. opt_set_bool, &want_per_device_stats,
  2350. "Force verbose mode and output per-device statistics"),
  2351. OPT_WITH_ARG("--userpass|-O",
  2352. set_userpass, NULL, NULL,
  2353. "Username:Password pair for bitcoin JSON-RPC server"),
  2354. OPT_WITH_ARG("--pool-goal",
  2355. set_pool_goal, NULL, NULL,
  2356. "Named goal for the previous-defined pool"),
  2357. OPT_WITH_ARG("--pool-priority",
  2358. set_pool_priority, NULL, NULL,
  2359. "Priority for just the previous-defined pool"),
  2360. OPT_WITH_ARG("--pool-proxy|-x",
  2361. set_pool_proxy, NULL, NULL,
  2362. "Proxy URI to use for connecting to just the previous-defined pool"),
  2363. OPT_WITH_ARG("--force-rollntime", // NOTE: must be after --pass for config file ordering
  2364. set_pool_force_rollntime, NULL, NULL,
  2365. opt_hidden),
  2366. OPT_WITHOUT_ARG("--protocol-dump|-P",
  2367. opt_set_bool, &opt_protocol,
  2368. "Verbose dump of protocol-level activities"),
  2369. OPT_WITH_ARG("--queue|-Q",
  2370. set_int_0_to_9999, opt_show_intval, &opt_queue,
  2371. "Minimum number of work items to have queued (0+)"),
  2372. OPT_WITHOUT_ARG("--quiet|-q",
  2373. opt_set_bool, &opt_quiet,
  2374. "Disable logging output, display status and errors"),
  2375. OPT_WITHOUT_ARG("--quiet-work-updates|--quiet-work-update",
  2376. opt_set_bool, &opt_quiet_work_updates,
  2377. opt_hidden),
  2378. OPT_WITH_ARG("--quit-summary",
  2379. set_quit_summary, NULL, NULL,
  2380. "Summary printed when you quit: none/devs/procs/detailed"),
  2381. OPT_WITH_ARG("--quota|-U",
  2382. set_quota, NULL, NULL,
  2383. "quota;URL combination for server with load-balance strategy quotas"),
  2384. OPT_WITHOUT_ARG("--real-quiet",
  2385. opt_set_bool, &opt_realquiet,
  2386. "Disable all output"),
  2387. OPT_WITH_ARG("--request-diff",
  2388. set_request_diff, opt_show_floatval, &request_pdiff,
  2389. "Request a specific difficulty from pools"),
  2390. OPT_WITH_ARG("--retries",
  2391. opt_set_intval, opt_show_intval, &opt_retries,
  2392. "Number of times to retry failed submissions before giving up (-1 means never)"),
  2393. OPT_WITH_ARG("--retry-pause",
  2394. set_null, NULL, NULL,
  2395. opt_hidden),
  2396. OPT_WITH_ARG("--rotate",
  2397. set_rotate, opt_show_intval, &opt_rotate_period,
  2398. "Change multipool strategy from failover to regularly rotate at N minutes"),
  2399. OPT_WITHOUT_ARG("--round-robin",
  2400. set_rr, &pool_strategy,
  2401. "Change multipool strategy from failover to round robin on failure"),
  2402. OPT_WITH_ARG("--scan|-S",
  2403. add_serial, NULL, NULL,
  2404. "Configure how to scan for mining devices"),
  2405. OPT_WITH_ARG("--scan-device|--scan-serial|--devscan",
  2406. add_serial, NULL, NULL,
  2407. opt_hidden),
  2408. OPT_WITH_ARG("--scan-time",
  2409. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  2410. "Upper bound on time spent scanning current work, in seconds"),
  2411. OPT_WITH_ARG("-s",
  2412. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  2413. opt_hidden),
  2414. OPT_WITH_ARG("--scantime",
  2415. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  2416. opt_hidden),
  2417. OPT_WITH_ARG("--sched-start",
  2418. set_schedtime, NULL, &schedstart,
  2419. "Set a time of day in HH:MM to start mining (a once off without a stop time)"),
  2420. OPT_WITH_ARG("--sched-stop",
  2421. set_schedtime, NULL, &schedstop,
  2422. "Set a time of day in HH:MM to stop mining (will quit without a start time)"),
  2423. #ifdef USE_SCRYPT
  2424. OPT_WITHOUT_ARG("--scrypt",
  2425. set_malgo_scrypt, NULL,
  2426. "Use the scrypt algorithm for mining (non-bitcoin)"),
  2427. #endif
  2428. OPT_WITH_ARG("--set-device|--set",
  2429. opt_string_elist_add, NULL, &opt_set_device_list,
  2430. "Set default parameters on devices; eg, NFY:osc6_bits=50"),
  2431. #if defined(USE_SCRYPT) && defined(USE_OPENCL)
  2432. OPT_WITH_ARG("--shaders",
  2433. set_shaders, NULL, NULL,
  2434. opt_hidden),
  2435. #endif
  2436. #ifdef HAVE_PWD_H
  2437. OPT_WITH_ARG("--setuid",
  2438. opt_set_charp, NULL, &opt_setuid,
  2439. "Username of an unprivileged user to run as"),
  2440. #endif
  2441. OPT_WITH_ARG("--sharelog",
  2442. set_sharelog, NULL, NULL,
  2443. "Append share log to file"),
  2444. OPT_WITH_ARG("--shares",
  2445. opt_set_floatval, NULL, &opt_shares,
  2446. "Quit after mining 2^32 * N hashes worth of shares (default: unlimited)"),
  2447. OPT_WITHOUT_ARG("--show-processors",
  2448. opt_set_bool, &opt_show_procs,
  2449. "Show per processor statistics in summary"),
  2450. OPT_WITHOUT_ARG("--show-procs",
  2451. opt_set_bool, &opt_show_procs,
  2452. opt_hidden),
  2453. OPT_WITH_ARG("--skip-security-checks",
  2454. set_int_0_to_9999, NULL, &opt_skip_checks,
  2455. "Skip security checks sometimes to save bandwidth; only check 1/<arg>th of the time (default: never skip)"),
  2456. OPT_WITH_ARG("--socks-proxy",
  2457. opt_set_charp, NULL, &opt_socks_proxy,
  2458. "Set socks proxy (host:port)"),
  2459. #ifdef USE_LIBEVENT
  2460. OPT_WITH_ARG("--stratum-port",
  2461. opt_set_intval, opt_show_intval, &stratumsrv_port,
  2462. "Port number to listen on for stratum miners (-1 means disabled)"),
  2463. #endif
  2464. OPT_WITHOUT_ARG("--submit-stale",
  2465. opt_set_bool, &opt_submit_stale,
  2466. opt_hidden),
  2467. OPT_WITH_ARG("--submit-threads",
  2468. opt_set_intval, opt_show_intval, &opt_submit_threads,
  2469. "Minimum number of concurrent share submissions (default: 64)"),
  2470. #ifdef HAVE_SYSLOG_H
  2471. OPT_WITHOUT_ARG("--syslog",
  2472. opt_set_bool, &use_syslog,
  2473. "Use system log for output messages (default: standard error)"),
  2474. #endif
  2475. OPT_WITH_ARG("--temp-cutoff",
  2476. set_temp_cutoff, NULL, &opt_cutofftemp,
  2477. opt_hidden),
  2478. OPT_WITH_ARG("--temp-hysteresis",
  2479. set_int_1_to_10, opt_show_intval, &opt_hysteresis,
  2480. "Set how much the temperature can fluctuate outside limits when automanaging speeds"),
  2481. #ifdef HAVE_ADL
  2482. OPT_WITH_ARG("--temp-overheat",
  2483. set_temp_overheat, opt_show_intval, &opt_overheattemp,
  2484. opt_hidden),
  2485. #endif
  2486. OPT_WITH_ARG("--temp-target",
  2487. set_temp_target, NULL, NULL,
  2488. opt_hidden),
  2489. OPT_WITHOUT_ARG("--text-only|-T",
  2490. opt_set_invbool, &use_curses,
  2491. #ifdef HAVE_CURSES
  2492. "Disable ncurses formatted screen output"
  2493. #else
  2494. opt_hidden
  2495. #endif
  2496. ),
  2497. #if defined(USE_SCRYPT) && defined(USE_OPENCL)
  2498. OPT_WITH_ARG("--thread-concurrency",
  2499. set_thread_concurrency, NULL, NULL,
  2500. opt_hidden),
  2501. #endif
  2502. #ifdef USE_UNICODE
  2503. OPT_WITHOUT_ARG("--unicode",
  2504. opt_set_bool, &use_unicode,
  2505. "Use Unicode characters in TUI"),
  2506. #endif
  2507. OPT_WITH_ARG("--url|-o",
  2508. set_url, NULL, NULL,
  2509. "URL for bitcoin JSON-RPC server"),
  2510. OPT_WITH_ARG("--user|-u",
  2511. set_user, NULL, NULL,
  2512. "Username for bitcoin JSON-RPC server"),
  2513. #ifdef USE_OPENCL
  2514. OPT_WITH_ARG("--vectors|-v",
  2515. set_vector, NULL, NULL,
  2516. opt_hidden),
  2517. #endif
  2518. OPT_WITHOUT_ARG("--verbose",
  2519. opt_set_bool, &opt_log_output,
  2520. "Log verbose output to stderr as well as status output"),
  2521. OPT_WITHOUT_ARG("--verbose-work-updates|--verbose-work-update",
  2522. opt_set_invbool, &opt_quiet_work_updates,
  2523. opt_hidden),
  2524. OPT_WITHOUT_ARG("--weighed-stats",
  2525. opt_set_bool, &opt_weighed_stats,
  2526. "Display statistics weighed to difficulty 1"),
  2527. #ifdef USE_OPENCL
  2528. OPT_WITH_ARG("--worksize|-w",
  2529. set_worksize, NULL, NULL,
  2530. opt_hidden),
  2531. #endif
  2532. OPT_WITHOUT_ARG("--unittest",
  2533. opt_set_bool, &opt_unittest, opt_hidden),
  2534. OPT_WITH_ARG("--coinbase-check-addr",
  2535. set_cbcaddr, NULL, NULL,
  2536. "A list of address to check against in coinbase payout list received from the previous-defined pool, separated by ','"),
  2537. OPT_WITH_ARG("--cbcheck-addr|--cbc-addr|--cbcaddr",
  2538. set_cbcaddr, NULL, NULL,
  2539. opt_hidden),
  2540. OPT_WITH_ARG("--coinbase-check-total",
  2541. set_cbctotal, NULL, NULL,
  2542. "The least total payout amount expected in coinbase received from the previous-defined pool"),
  2543. OPT_WITH_ARG("--cbcheck-total|--cbc-total|--cbctotal",
  2544. set_cbctotal, NULL, NULL,
  2545. opt_hidden),
  2546. OPT_WITH_ARG("--coinbase-check-percent",
  2547. set_cbcperc, NULL, NULL,
  2548. "The least benefit percentage expected for the sum of addr(s) listed in --cbaddr argument for previous-defined pool"),
  2549. OPT_WITH_ARG("--cbcheck-percent|--cbc-percent|--cbcpercent|--cbcperc",
  2550. set_cbcperc, NULL, NULL,
  2551. opt_hidden),
  2552. OPT_WITHOUT_ARG("--worktime",
  2553. opt_set_bool, &opt_worktime,
  2554. "Display extra work time debug information"),
  2555. OPT_WITH_ARG("--pools",
  2556. opt_set_bool, NULL, NULL, opt_hidden),
  2557. OPT_ENDTABLE
  2558. };
  2559. static char *load_config(const char *arg, void __maybe_unused *unused);
  2560. static char *parse_config(json_t *config, bool fileconf, int * const fileconf_load_p)
  2561. {
  2562. static char err_buf[200];
  2563. struct opt_table *opt;
  2564. json_t *val;
  2565. if (fileconf && !*fileconf_load_p)
  2566. *fileconf_load_p = 1;
  2567. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  2568. char *p, *name, *sp;
  2569. /* We don't handle subtables. */
  2570. assert(!(opt->type & OPT_SUBTABLE));
  2571. if (!opt->names)
  2572. continue;
  2573. /* Pull apart the option name(s). */
  2574. name = strdup(opt->names);
  2575. for (p = strtok_r(name, "|", &sp); p; p = strtok_r(NULL, "|", &sp)) {
  2576. char *err = "Invalid value";
  2577. /* Ignore short options. */
  2578. if (p[1] != '-')
  2579. continue;
  2580. val = json_object_get(config, p+2);
  2581. if (!val)
  2582. continue;
  2583. if (opt->type & OPT_HASARG) {
  2584. if (json_is_string(val)) {
  2585. err = opt->cb_arg(json_string_value(val),
  2586. opt->u.arg);
  2587. } else if (json_is_number(val)) {
  2588. char buf[256], *p, *q;
  2589. snprintf(buf, 256, "%f", json_number_value(val));
  2590. if ( (p = strchr(buf, '.')) ) {
  2591. // Trim /\.0*$/ to work properly with integer-only arguments
  2592. q = p;
  2593. while (*(++q) == '0') {}
  2594. if (*q == '\0')
  2595. *p = '\0';
  2596. }
  2597. err = opt->cb_arg(buf, opt->u.arg);
  2598. } else if (json_is_array(val)) {
  2599. int n, size = json_array_size(val);
  2600. err = NULL;
  2601. for (n = 0; n < size && !err; n++) {
  2602. if (json_is_string(json_array_get(val, n)))
  2603. err = opt->cb_arg(json_string_value(json_array_get(val, n)), opt->u.arg);
  2604. else if (json_is_object(json_array_get(val, n)))
  2605. err = parse_config(json_array_get(val, n), false, fileconf_load_p);
  2606. }
  2607. }
  2608. } else if (opt->type & OPT_NOARG) {
  2609. if (json_is_true(val))
  2610. err = opt->cb(opt->u.arg);
  2611. else if (json_is_boolean(val)) {
  2612. if (opt->cb == (void*)opt_set_bool)
  2613. err = opt_set_invbool(opt->u.arg);
  2614. else if (opt->cb == (void*)opt_set_invbool)
  2615. err = opt_set_bool(opt->u.arg);
  2616. }
  2617. }
  2618. if (err) {
  2619. /* Allow invalid values to be in configuration
  2620. * file, just skipping over them provided the
  2621. * JSON is still valid after that. */
  2622. if (fileconf) {
  2623. applog(LOG_ERR, "Invalid config option %s: %s", p, err);
  2624. *fileconf_load_p = -1;
  2625. } else {
  2626. snprintf(err_buf, sizeof(err_buf), "Parsing JSON option %s: %s",
  2627. p, err);
  2628. return err_buf;
  2629. }
  2630. }
  2631. }
  2632. free(name);
  2633. }
  2634. val = json_object_get(config, JSON_INCLUDE_CONF);
  2635. if (val && json_is_string(val))
  2636. return load_config(json_string_value(val), NULL);
  2637. return NULL;
  2638. }
  2639. struct bfg_loaded_configfile *bfg_loaded_configfiles;
  2640. static char *load_config(const char *arg, void __maybe_unused *unused)
  2641. {
  2642. json_error_t err;
  2643. json_t *config;
  2644. char *json_error;
  2645. size_t siz;
  2646. struct bfg_loaded_configfile *cfginfo;
  2647. cfginfo = malloc(sizeof(*cfginfo));
  2648. *cfginfo = (struct bfg_loaded_configfile){
  2649. .filename = strdup(arg),
  2650. };
  2651. LL_APPEND(bfg_loaded_configfiles, cfginfo);
  2652. if (++include_count > JSON_MAX_DEPTH)
  2653. return JSON_MAX_DEPTH_ERR;
  2654. #if JANSSON_MAJOR_VERSION > 1
  2655. config = json_load_file(arg, 0, &err);
  2656. #else
  2657. config = json_load_file(arg, &err);
  2658. #endif
  2659. if (!json_is_object(config)) {
  2660. siz = JSON_LOAD_ERROR_LEN + strlen(arg) + strlen(err.text);
  2661. json_error = malloc(siz);
  2662. if (!json_error)
  2663. quit(1, "Malloc failure in json error");
  2664. snprintf(json_error, siz, JSON_LOAD_ERROR, arg, err.text);
  2665. return json_error;
  2666. }
  2667. config_loaded = true;
  2668. /* Parse the config now, so we can override it. That can keep pointers
  2669. * so don't free config object. */
  2670. return parse_config(config, true, &cfginfo->fileconf_load);
  2671. }
  2672. static
  2673. bool _load_default_configs(const char * const filepath, void * __maybe_unused userp)
  2674. {
  2675. bool * const found_defcfg_p = userp;
  2676. *found_defcfg_p = true;
  2677. load_config(filepath, NULL);
  2678. // Regardless of status of loading the config file, we should continue loading other defaults
  2679. return false;
  2680. }
  2681. static void load_default_config(void)
  2682. {
  2683. bool found_defcfg = false;
  2684. appdata_file_call("BFGMiner", def_conf, _load_default_configs, &found_defcfg);
  2685. if (!found_defcfg)
  2686. {
  2687. // No BFGMiner config, try Cgminer's...
  2688. appdata_file_call("cgminer", "cgminer.conf", _load_default_configs, &found_defcfg);
  2689. }
  2690. }
  2691. extern const char *opt_argv0;
  2692. static char *opt_verusage_and_exit(const char *extra)
  2693. {
  2694. puts(packagename);
  2695. printf(" Lowlevel:%s\n", BFG_LOWLLIST);
  2696. printf(" Drivers:%s\n", BFG_DRIVERLIST);
  2697. printf(" Algorithms:%s\n", BFG_ALGOLIST);
  2698. printf(" Options:%s\n", BFG_OPTLIST);
  2699. printf("%s", opt_usage(opt_argv0, extra));
  2700. fflush(stdout);
  2701. exit(0);
  2702. }
  2703. /* These options are parsed before anything else */
  2704. static struct opt_table opt_early_table[] = {
  2705. // Default config is loaded in command line order, like a regular config
  2706. OPT_EARLY_WITH_ARG("--config|-c|--default-config",
  2707. set_bool_ignore_arg, NULL, &config_loaded,
  2708. opt_hidden),
  2709. OPT_EARLY_WITHOUT_ARG("--no-config|--no-default-config",
  2710. opt_set_bool, &config_loaded,
  2711. "Inhibit loading default config file"),
  2712. OPT_ENDTABLE
  2713. };
  2714. /* These options are available from commandline only */
  2715. static struct opt_table opt_cmdline_table[] = {
  2716. OPT_WITH_ARG("--config|-c",
  2717. load_config, NULL, NULL,
  2718. "Load a JSON-format configuration file\n"
  2719. "See example.conf for an example configuration."),
  2720. OPT_EARLY_WITHOUT_ARG("--no-config",
  2721. opt_set_bool, &config_loaded,
  2722. opt_hidden),
  2723. OPT_EARLY_WITHOUT_ARG("--no-default-config",
  2724. opt_set_bool, &config_loaded,
  2725. "Inhibit loading default config file"),
  2726. OPT_WITHOUT_ARG("--default-config",
  2727. load_default_config, NULL,
  2728. "Always load the default config file"),
  2729. OPT_WITHOUT_ARG("--help|-h",
  2730. opt_verusage_and_exit, NULL,
  2731. "Print this message"),
  2732. #ifdef USE_OPENCL
  2733. OPT_WITHOUT_ARG("--ndevs|-n",
  2734. print_ndevs_and_exit, &nDevs,
  2735. opt_hidden),
  2736. #endif
  2737. OPT_WITHOUT_ARG("--version|-V",
  2738. opt_version_and_exit, packagename,
  2739. "Display version and exit"),
  2740. OPT_ENDTABLE
  2741. };
  2742. static bool jobj_binary(const json_t *obj, const char *key,
  2743. void *buf, size_t buflen, bool required)
  2744. {
  2745. const char *hexstr;
  2746. json_t *tmp;
  2747. tmp = json_object_get(obj, key);
  2748. if (unlikely(!tmp)) {
  2749. if (unlikely(required))
  2750. applog(LOG_ERR, "JSON key '%s' not found", key);
  2751. return false;
  2752. }
  2753. hexstr = json_string_value(tmp);
  2754. if (unlikely(!hexstr)) {
  2755. applog(LOG_ERR, "JSON key '%s' is not a string", key);
  2756. return false;
  2757. }
  2758. if (!hex2bin(buf, hexstr, buflen))
  2759. return false;
  2760. return true;
  2761. }
  2762. static void calc_midstate(struct work *work)
  2763. {
  2764. union {
  2765. unsigned char c[64];
  2766. uint32_t i[16];
  2767. } data;
  2768. swap32yes(&data.i[0], work->data, 16);
  2769. sha256_ctx ctx;
  2770. sha256_init(&ctx);
  2771. sha256_update(&ctx, data.c, 64);
  2772. memcpy(work->midstate, ctx.h, sizeof(work->midstate));
  2773. swap32tole(work->midstate, work->midstate, 8);
  2774. }
  2775. static
  2776. struct bfg_tmpl_ref *tmpl_makeref(blktemplate_t * const tmpl)
  2777. {
  2778. struct bfg_tmpl_ref * const tr = malloc(sizeof(*tr));
  2779. *tr = (struct bfg_tmpl_ref){
  2780. .tmpl = tmpl,
  2781. .refcount = 1,
  2782. };
  2783. mutex_init(&tr->mutex);
  2784. return tr;
  2785. }
  2786. static
  2787. void tmpl_incref(struct bfg_tmpl_ref * const tr)
  2788. {
  2789. mutex_lock(&tr->mutex);
  2790. ++tr->refcount;
  2791. mutex_unlock(&tr->mutex);
  2792. }
  2793. void tmpl_decref(struct bfg_tmpl_ref * const tr)
  2794. {
  2795. mutex_lock(&tr->mutex);
  2796. bool free_tmpl = !--tr->refcount;
  2797. mutex_unlock(&tr->mutex);
  2798. if (free_tmpl)
  2799. {
  2800. blktmpl_free(tr->tmpl);
  2801. mutex_destroy(&tr->mutex);
  2802. free(tr);
  2803. }
  2804. }
  2805. static struct work *make_work(void)
  2806. {
  2807. struct work *work = calloc(1, sizeof(struct work));
  2808. if (unlikely(!work))
  2809. quit(1, "Failed to calloc work in make_work");
  2810. cg_wlock(&control_lock);
  2811. work->id = total_work++;
  2812. cg_wunlock(&control_lock);
  2813. return work;
  2814. }
  2815. /* This is the central place all work that is about to be retired should be
  2816. * cleaned to remove any dynamically allocated arrays within the struct */
  2817. void clean_work(struct work *work)
  2818. {
  2819. free(work->job_id);
  2820. bytes_free(&work->nonce2);
  2821. free(work->nonce1);
  2822. if (work->device_data_free_func)
  2823. work->device_data_free_func(work);
  2824. if (work->tr)
  2825. tmpl_decref(work->tr);
  2826. memset(work, 0, sizeof(struct work));
  2827. }
  2828. /* All dynamically allocated work structs should be freed here to not leak any
  2829. * ram from arrays allocated within the work struct */
  2830. void free_work(struct work *work)
  2831. {
  2832. clean_work(work);
  2833. free(work);
  2834. }
  2835. 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";
  2836. #define workpadding_bin bfg_workpadding_bin
  2837. static const size_t block_info_str_sz = 3 /* ... */ + 16 /* block hash segment */ + 1;
  2838. static
  2839. void block_info_str(char * const out, const struct block_info * const blkinfo)
  2840. {
  2841. unsigned char hash_swap[32];
  2842. swap256(hash_swap, blkinfo->prevblkhash);
  2843. swap32tole(hash_swap, hash_swap, 32 / 4);
  2844. memset(out, '.', 3);
  2845. // FIXME: The block number will overflow this sometime around AD 2025-2027
  2846. if (blkinfo->height > 0 && blkinfo->height < 1000000)
  2847. {
  2848. bin2hex(&out[3], &hash_swap[0x1c], 4);
  2849. snprintf(&out[11], block_info_str_sz-11, " #%6u", blkinfo->height);
  2850. }
  2851. else
  2852. bin2hex(&out[3], &hash_swap[0x18], 8);
  2853. }
  2854. #ifdef HAVE_CURSES
  2855. static void update_block_display(void);
  2856. #endif
  2857. // Must only be called with ch_lock held!
  2858. static
  2859. void __update_block_title(struct mining_goal_info * const goal)
  2860. {
  2861. struct blockchain_info * const blkchain = goal->blkchain;
  2862. if (!goal->current_goal_detail)
  2863. goal->current_goal_detail = malloc(block_info_str_sz);
  2864. block_info_str(goal->current_goal_detail, blkchain->currentblk);
  2865. #ifdef HAVE_CURSES
  2866. update_block_display();
  2867. #endif
  2868. }
  2869. static struct block_info *block_exists(const struct blockchain_info *, const void *);
  2870. static
  2871. void have_block_height(struct mining_goal_info * const goal, const void * const prevblkhash, uint32_t blkheight)
  2872. {
  2873. struct blockchain_info * const blkchain = goal->blkchain;
  2874. struct block_info * const blkinfo = block_exists(blkchain, prevblkhash);
  2875. if ((!blkinfo) || blkinfo->height)
  2876. return;
  2877. uint32_t block_id = ((uint32_t*)prevblkhash)[0];
  2878. applog(LOG_DEBUG, "Learned that block id %08" PRIx32 " is height %" PRIu32, (uint32_t)be32toh(block_id), blkheight);
  2879. cg_wlock(&ch_lock);
  2880. blkinfo->height = blkheight;
  2881. if (blkinfo == blkchain->currentblk)
  2882. {
  2883. blkchain->currentblk_subsidy = 5000000000LL >> (blkheight / 210000);
  2884. __update_block_title(goal);
  2885. }
  2886. cg_wunlock(&ch_lock);
  2887. }
  2888. static
  2889. void pool_set_opaque(struct pool *pool, bool opaque)
  2890. {
  2891. if (pool->swork.opaque == opaque)
  2892. return;
  2893. pool->swork.opaque = opaque;
  2894. if (opaque)
  2895. applog(LOG_WARNING, "Pool %u is hiding block contents from us",
  2896. pool->pool_no);
  2897. else
  2898. applog(LOG_NOTICE, "Pool %u now providing block contents to us",
  2899. pool->pool_no);
  2900. }
  2901. bool pool_may_redirect_to(struct pool * const pool, const char * const uri)
  2902. {
  2903. if (uri_get_param_bool(pool->rpc_url, "redirect", false))
  2904. return true;
  2905. return match_domains(pool->rpc_url, strlen(pool->rpc_url), uri, strlen(uri));
  2906. }
  2907. void pool_check_coinbase(struct pool * const pool, const uint8_t * const cbtxn, const size_t cbtxnsz)
  2908. {
  2909. if (uri_get_param_bool(pool->rpc_url, "skipcbcheck", false))
  2910. {}
  2911. else
  2912. if (!check_coinbase(cbtxn, cbtxnsz, &pool->cb_param))
  2913. {
  2914. if (pool->enabled == POOL_ENABLED)
  2915. {
  2916. applog(LOG_ERR, "Pool %d misbehaving (%s), disabling!", pool->pool_no, "coinbase check");
  2917. disable_pool(pool, POOL_MISBEHAVING);
  2918. }
  2919. }
  2920. else
  2921. if (pool->enabled == POOL_MISBEHAVING)
  2922. {
  2923. applog(LOG_NOTICE, "Pool %d no longer misbehaving, re-enabling!", pool->pool_no);
  2924. enable_pool(pool);
  2925. }
  2926. }
  2927. 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)
  2928. {
  2929. const int offsets = max(ntime_roll, 60);
  2930. *nrl = (struct ntime_roll_limits){
  2931. .min = ntime_base,
  2932. .max = ntime_base + ntime_roll,
  2933. .tv_ref = *tvp_ref,
  2934. .minoff = -offsets,
  2935. .maxoff = offsets,
  2936. };
  2937. }
  2938. void work_set_simple_ntime_roll_limit(struct work * const work, const int ntime_roll, const struct timeval * const tvp_ref)
  2939. {
  2940. set_simple_ntime_roll_limit(&work->ntime_roll_limits, upk_u32be(work->data, 0x44), ntime_roll, tvp_ref);
  2941. }
  2942. int work_ntime_range(struct work * const work, const struct timeval * const tvp_earliest, const struct timeval * const tvp_latest, const int desired_roll)
  2943. {
  2944. const struct ntime_roll_limits * const nrl = &work->ntime_roll_limits;
  2945. const uint32_t ref_ntime = work_get_ntime(work);
  2946. const int earliest_elapsed = timer_elapsed(&nrl->tv_ref, tvp_earliest);
  2947. const int latest_elapsed = timer_elapsed(&nrl->tv_ref, tvp_latest);
  2948. // minimum ntime is the latest possible result (add a second to spare) adjusted for minimum offset (or fixed minimum ntime)
  2949. uint32_t min_ntime = max(nrl->min, ref_ntime + latest_elapsed+1 + nrl->minoff);
  2950. // maximum ntime is the earliest possible result adjusted for maximum offset (or fixed maximum ntime)
  2951. uint32_t max_ntime = min(nrl->max, ref_ntime + earliest_elapsed + nrl->maxoff);
  2952. if (max_ntime < min_ntime)
  2953. return -1;
  2954. if (max_ntime - min_ntime > desired_roll)
  2955. {
  2956. // Adjust min_ntime upward for accuracy, when possible
  2957. const int mid_elapsed = ((latest_elapsed - earliest_elapsed) / 2) + earliest_elapsed;
  2958. uint32_t ideal_ntime = ref_ntime + mid_elapsed;
  2959. if (ideal_ntime > min_ntime)
  2960. min_ntime = min(ideal_ntime, max_ntime - desired_roll);
  2961. }
  2962. work_set_ntime(work, min_ntime);
  2963. return max_ntime - min_ntime;
  2964. }
  2965. #if BLKMAKER_VERSION > 1
  2966. static
  2967. bool goal_has_at_least_one_getcbaddr(const struct mining_goal_info * const goal)
  2968. {
  2969. for (int i = 0; i < total_pools; ++i)
  2970. {
  2971. struct pool * const pool = pools[i];
  2972. if (uri_get_param_bool(pool->rpc_url, "getcbaddr", false))
  2973. return true;
  2974. }
  2975. return false;
  2976. }
  2977. static
  2978. void refresh_bitcoind_address(struct mining_goal_info * const goal, const bool fresh)
  2979. {
  2980. struct blockchain_info * const blkchain = goal->blkchain;
  2981. if (!goal_has_at_least_one_getcbaddr(goal))
  2982. return;
  2983. char getcbaddr_req[60];
  2984. CURL *curl = NULL;
  2985. json_t *json, *j2;
  2986. const char *s, *s2;
  2987. bytes_t newscript = BYTES_INIT;
  2988. snprintf(getcbaddr_req, sizeof(getcbaddr_req), "{\"method\":\"get%saddress\",\"id\":0,\"params\":[\"BFGMiner\"]}", fresh ? "new" : "account");
  2989. for (int i = 0; i < total_pools; ++i)
  2990. {
  2991. struct pool * const pool = pools[i];
  2992. if (!uri_get_param_bool(pool->rpc_url, "getcbaddr", false))
  2993. continue;
  2994. if (pool->goal != goal)
  2995. continue;
  2996. applog(LOG_DEBUG, "Refreshing coinbase address from pool %d", pool->pool_no);
  2997. if (!curl)
  2998. {
  2999. curl = curl_easy_init();
  3000. if (unlikely(!curl))
  3001. {
  3002. applogfail(LOG_ERR, "curl_easy_init");
  3003. break;
  3004. }
  3005. }
  3006. json = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, getcbaddr_req, false, false, NULL, pool, true);
  3007. if (unlikely((!json) || !json_is_null( (j2 = json_object_get(json, "error")) )))
  3008. {
  3009. const char *estrc;
  3010. char *estr = NULL;
  3011. if (!(json && j2))
  3012. estrc = NULL;
  3013. else
  3014. {
  3015. estrc = json_string_value(j2);
  3016. if (!estrc)
  3017. estrc = estr = json_dumps_ANY(j2, JSON_ENSURE_ASCII | JSON_SORT_KEYS);
  3018. }
  3019. applog(LOG_WARNING, "Error %cetting coinbase address from pool %d: %s", 'g', pool->pool_no, estrc);
  3020. free(estr);
  3021. continue;
  3022. }
  3023. s = bfg_json_obj_string(json, "result", NULL);
  3024. if (unlikely(!s))
  3025. {
  3026. applog(LOG_WARNING, "Error %cetting coinbase address from pool %d: %s", 'g', pool->pool_no, "(return value was not a String)");
  3027. continue;
  3028. }
  3029. s2 = set_b58addr(s, &newscript);
  3030. if (unlikely(s2))
  3031. {
  3032. applog(LOG_WARNING, "Error %cetting coinbase address from pool %d: %s", 's', pool->pool_no, s2);
  3033. continue;
  3034. }
  3035. if (goal->generation_script)
  3036. {
  3037. if (bytes_eq(&newscript, goal->generation_script))
  3038. {
  3039. applog(LOG_DEBUG, "Pool %d returned coinbase address already in use (%s)", pool->pool_no, s2);
  3040. break;
  3041. }
  3042. }
  3043. else
  3044. {
  3045. goal->generation_script = malloc(sizeof(*goal->generation_script));
  3046. bytes_init(goal->generation_script);
  3047. }
  3048. bytes_assimilate(goal->generation_script, &newscript);
  3049. coinbase_script_block_id = blkchain->currentblk->block_id;
  3050. applog(LOG_NOTICE, "Now using coinbase address %s, provided by pool %d", s, pool->pool_no);
  3051. break;
  3052. }
  3053. bytes_free(&newscript);
  3054. if (curl)
  3055. curl_easy_cleanup(curl);
  3056. }
  3057. #endif
  3058. #define GBT_XNONCESZ (sizeof(uint32_t))
  3059. #if BLKMAKER_VERSION > 4
  3060. #define blkmk_append_coinbase_safe(tmpl, append, appendsz) \
  3061. blkmk_append_coinbase_safe2(tmpl, append, appendsz, GBT_XNONCESZ, false)
  3062. #endif
  3063. static bool work_decode(struct pool *pool, struct work *work, json_t *val)
  3064. {
  3065. json_t *res_val = json_object_get(val, "result");
  3066. json_t *tmp_val;
  3067. bool ret = false;
  3068. struct timeval tv_now;
  3069. if (unlikely(detect_algo == 1)) {
  3070. json_t *tmp = json_object_get(res_val, "algorithm");
  3071. const char *v = tmp ? json_string_value(tmp) : "";
  3072. if (strncasecmp(v, "scrypt", 6))
  3073. detect_algo = 2;
  3074. }
  3075. timer_set_now(&tv_now);
  3076. if (work->tr)
  3077. {
  3078. blktemplate_t * const tmpl = work->tr->tmpl;
  3079. const char *err = blktmpl_add_jansson(tmpl, res_val, tv_now.tv_sec);
  3080. if (err) {
  3081. applog(LOG_ERR, "blktmpl error: %s", err);
  3082. return false;
  3083. }
  3084. work->rolltime = blkmk_time_left(tmpl, tv_now.tv_sec);
  3085. #if BLKMAKER_VERSION > 1
  3086. struct mining_goal_info * const goal = pool->goal;
  3087. const uint32_t tmpl_block_id = ((uint32_t*)tmpl->prevblk)[0];
  3088. if ((!tmpl->cbtxn) && coinbase_script_block_id != tmpl_block_id)
  3089. refresh_bitcoind_address(goal, false);
  3090. if (goal->generation_script)
  3091. {
  3092. bool newcb;
  3093. #if BLKMAKER_VERSION > 2
  3094. blkmk_init_generation2(tmpl, bytes_buf(goal->generation_script), bytes_len(goal->generation_script), &newcb);
  3095. #else
  3096. newcb = !tmpl->cbtxn;
  3097. blkmk_init_generation(tmpl, bytes_buf(goal->generation_script), bytes_len(goal->generation_script));
  3098. #endif
  3099. if (newcb)
  3100. {
  3101. ssize_t ae = blkmk_append_coinbase_safe(tmpl, &template_nonce, sizeof(template_nonce));
  3102. if (ae < (ssize_t)sizeof(template_nonce))
  3103. 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);
  3104. ++template_nonce;
  3105. }
  3106. }
  3107. #endif
  3108. #if BLKMAKER_VERSION > 0
  3109. {
  3110. ssize_t ae = blkmk_append_coinbase_safe(tmpl, opt_coinbase_sig, 101);
  3111. static bool appenderr = false;
  3112. if (ae <= 0) {
  3113. if (opt_coinbase_sig) {
  3114. applog((appenderr ? LOG_DEBUG : LOG_WARNING), "Cannot append coinbase signature at all on pool %u (%"PRId64")", pool->pool_no, (int64_t)ae);
  3115. appenderr = true;
  3116. }
  3117. } else if (ae >= 3 || opt_coinbase_sig) {
  3118. const char *cbappend = opt_coinbase_sig;
  3119. const char full[] = PACKAGE " " VERSION;
  3120. char *need_free = NULL;
  3121. if (!cbappend) {
  3122. if ((size_t)ae >= sizeof(full) - 1)
  3123. cbappend = full;
  3124. else if ((size_t)ae >= sizeof(PACKAGE) - 1)
  3125. {
  3126. const char *pos = strchr(full, '-');
  3127. size_t sz = (pos - full);
  3128. if (pos && ae > sz)
  3129. {
  3130. cbappend = need_free = malloc(sz + 1);
  3131. memcpy(need_free, full, sz);
  3132. need_free[sz] = '\0';
  3133. }
  3134. else
  3135. cbappend = PACKAGE;
  3136. }
  3137. else
  3138. cbappend = "BFG";
  3139. }
  3140. size_t cbappendsz = strlen(cbappend);
  3141. static bool truncatewarning = false;
  3142. if (cbappendsz <= (size_t)ae) {
  3143. if (cbappendsz < (size_t)ae)
  3144. // If we have space, include the trailing \0
  3145. ++cbappendsz;
  3146. ae = cbappendsz;
  3147. truncatewarning = false;
  3148. } else {
  3149. char *tmp = malloc(ae + 1);
  3150. memcpy(tmp, opt_coinbase_sig, ae);
  3151. tmp[ae] = '\0';
  3152. applog((truncatewarning ? LOG_DEBUG : LOG_WARNING),
  3153. "Pool %u truncating appended coinbase signature at %"PRId64" bytes: %s(%s)",
  3154. pool->pool_no, (int64_t)ae, tmp, &opt_coinbase_sig[ae]);
  3155. free(tmp);
  3156. truncatewarning = true;
  3157. }
  3158. ae = blkmk_append_coinbase_safe(tmpl, cbappend, ae);
  3159. free(need_free);
  3160. if (ae <= 0) {
  3161. applog((appenderr ? LOG_DEBUG : LOG_WARNING), "Error appending coinbase signature (%"PRId64")", (int64_t)ae);
  3162. appenderr = true;
  3163. } else
  3164. appenderr = false;
  3165. }
  3166. }
  3167. #endif
  3168. if (blkmk_get_data(tmpl, work->data, 80, tv_now.tv_sec, NULL, &work->dataid) < 76)
  3169. return false;
  3170. swap32yes(work->data, work->data, 80 / 4);
  3171. memcpy(&work->data[80], workpadding_bin, 48);
  3172. work->ntime_roll_limits = (struct ntime_roll_limits){
  3173. .min = tmpl->mintime,
  3174. .max = tmpl->maxtime,
  3175. .tv_ref = tv_now,
  3176. .minoff = tmpl->mintimeoff,
  3177. .maxoff = tmpl->maxtimeoff,
  3178. };
  3179. const struct blktmpl_longpoll_req *lp;
  3180. if ((lp = blktmpl_get_longpoll(tmpl)) && ((!pool->lp_id) || strcmp(lp->id, pool->lp_id))) {
  3181. free(pool->lp_id);
  3182. pool->lp_id = strdup(lp->id);
  3183. #if 0 /* This just doesn't work :( */
  3184. curl_socket_t sock = pool->lp_socket;
  3185. if (sock != CURL_SOCKET_BAD) {
  3186. pool->lp_socket = CURL_SOCKET_BAD;
  3187. applog(LOG_WARNING, "Pool %u long poll request hanging, reconnecting", pool->pool_no);
  3188. shutdown(sock, SHUT_RDWR);
  3189. }
  3190. #endif
  3191. }
  3192. }
  3193. else
  3194. if (unlikely(!jobj_binary(res_val, "data", work->data, sizeof(work->data), true))) {
  3195. applog(LOG_ERR, "JSON inval data");
  3196. return false;
  3197. }
  3198. else
  3199. work_set_simple_ntime_roll_limit(work, 0, &tv_now);
  3200. if (!jobj_binary(res_val, "midstate", work->midstate, sizeof(work->midstate), false)) {
  3201. // Calculate it ourselves
  3202. applog(LOG_DEBUG, "Calculating midstate locally");
  3203. calc_midstate(work);
  3204. }
  3205. if (unlikely(!jobj_binary(res_val, "target", work->target, sizeof(work->target), true))) {
  3206. applog(LOG_ERR, "JSON inval target");
  3207. return false;
  3208. }
  3209. if (work->tr)
  3210. {
  3211. for (size_t i = 0; i < sizeof(work->target) / 2; ++i)
  3212. {
  3213. int p = (sizeof(work->target) - 1) - i;
  3214. unsigned char c = work->target[i];
  3215. work->target[i] = work->target[p];
  3216. work->target[p] = c;
  3217. }
  3218. }
  3219. if ( (tmp_val = json_object_get(res_val, "height")) ) {
  3220. struct mining_goal_info * const goal = pool->goal;
  3221. uint32_t blkheight = json_number_value(tmp_val);
  3222. const void * const prevblkhash = &work->data[4];
  3223. have_block_height(goal, prevblkhash, blkheight);
  3224. }
  3225. memset(work->hash, 0, sizeof(work->hash));
  3226. work->tv_staged = tv_now;
  3227. #if BLKMAKER_VERSION > 4
  3228. if (work->tr)
  3229. {
  3230. blktemplate_t * const tmpl = work->tr->tmpl;
  3231. uint8_t buf[80];
  3232. int16_t expire;
  3233. uint8_t *cbtxn;
  3234. size_t cbtxnsz;
  3235. size_t cbextranonceoffset;
  3236. int branchcount;
  3237. libblkmaker_hash_t *branches;
  3238. if (blkmk_get_mdata(tmpl, buf, sizeof(buf), tv_now.tv_sec, &expire, &cbtxn, &cbtxnsz, &cbextranonceoffset, &branchcount, &branches, GBT_XNONCESZ, false))
  3239. {
  3240. struct stratum_work * const swork = &pool->swork;
  3241. const size_t branchdatasz = branchcount * 0x20;
  3242. pool_check_coinbase(pool, cbtxn, cbtxnsz);
  3243. cg_wlock(&pool->data_lock);
  3244. swork->tr = work->tr;
  3245. bytes_assimilate_raw(&swork->coinbase, cbtxn, cbtxnsz, cbtxnsz);
  3246. swork->nonce2_offset = cbextranonceoffset;
  3247. bytes_assimilate_raw(&swork->merkle_bin, branches, branchdatasz, branchdatasz);
  3248. swork->merkles = branchcount;
  3249. memcpy(swork->header1, &buf[0], 36);
  3250. swork->ntime = le32toh(*(uint32_t *)(&buf[68]));
  3251. swork->tv_received = tv_now;
  3252. memcpy(swork->diffbits, &buf[72], 4);
  3253. memcpy(swork->target, work->target, sizeof(swork->target));
  3254. free(swork->job_id);
  3255. swork->job_id = NULL;
  3256. swork->clean = true;
  3257. swork->work_restart_id = pool->work_restart_id;
  3258. // FIXME: Do something with expire
  3259. pool->nonce2sz = swork->n2size = GBT_XNONCESZ;
  3260. pool->nonce2 = 0;
  3261. cg_wunlock(&pool->data_lock);
  3262. }
  3263. else
  3264. applog(LOG_DEBUG, "blkmk_get_mdata failed for pool %u", pool->pool_no);
  3265. }
  3266. #endif // BLKMAKER_VERSION > 4
  3267. pool_set_opaque(pool, !work->tr);
  3268. ret = true;
  3269. return ret;
  3270. }
  3271. /* Returns whether the pool supports local work generation or not. */
  3272. static bool pool_localgen(struct pool *pool)
  3273. {
  3274. return (pool->last_work_copy || pool->has_stratum);
  3275. }
  3276. int dev_from_id(int thr_id)
  3277. {
  3278. struct cgpu_info *cgpu = get_thr_cgpu(thr_id);
  3279. return cgpu->device_id;
  3280. }
  3281. /* Create an exponentially decaying average over the opt_log_interval */
  3282. void decay_time(double *f, double fadd, double fsecs)
  3283. {
  3284. double ftotal, fprop;
  3285. fprop = 1.0 - 1 / (exp(fsecs / (double)opt_log_interval));
  3286. ftotal = 1.0 + fprop;
  3287. *f += (fadd * fprop);
  3288. *f /= ftotal;
  3289. }
  3290. static
  3291. int __total_staged(const bool include_spares)
  3292. {
  3293. int tot = HASH_COUNT(staged_work);
  3294. if (!include_spares)
  3295. tot -= staged_spare;
  3296. return tot;
  3297. }
  3298. static int total_staged(const bool include_spares)
  3299. {
  3300. int ret;
  3301. mutex_lock(stgd_lock);
  3302. ret = __total_staged(include_spares);
  3303. mutex_unlock(stgd_lock);
  3304. return ret;
  3305. }
  3306. #ifdef HAVE_CURSES
  3307. WINDOW *mainwin, *statuswin, *logwin;
  3308. #endif
  3309. double total_secs = 1.0;
  3310. #ifdef HAVE_CURSES
  3311. static char statusline[256];
  3312. /* statusy is where the status window goes up to in cases where it won't fit at startup */
  3313. static int statusy;
  3314. static int devsummaryYOffset;
  3315. static int total_lines;
  3316. #endif
  3317. #ifdef USE_OPENCL
  3318. struct cgpu_info gpus[MAX_GPUDEVICES]; /* Maximum number apparently possible */
  3319. #endif
  3320. struct cgpu_info *cpus;
  3321. bool _bfg_console_cancel_disabled;
  3322. int _bfg_console_prev_cancelstate;
  3323. #ifdef HAVE_CURSES
  3324. #define lock_curses() bfg_console_lock()
  3325. #define unlock_curses() bfg_console_unlock()
  3326. static bool curses_active_locked(void)
  3327. {
  3328. bool ret;
  3329. lock_curses();
  3330. ret = curses_active;
  3331. if (!ret)
  3332. unlock_curses();
  3333. return ret;
  3334. }
  3335. // Cancellable getch
  3336. int my_cancellable_getch(void)
  3337. {
  3338. // This only works because the macro only hits direct getch() calls
  3339. typedef int (*real_getch_t)(void);
  3340. const real_getch_t real_getch = __real_getch;
  3341. int type, rv;
  3342. bool sct;
  3343. sct = !pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &type);
  3344. rv = real_getch();
  3345. if (sct)
  3346. pthread_setcanceltype(type, &type);
  3347. return rv;
  3348. }
  3349. #ifdef PDCURSES
  3350. static
  3351. int bfg_wresize(WINDOW *win, int lines, int columns)
  3352. {
  3353. int rv = wresize(win, lines, columns);
  3354. int x, y;
  3355. getyx(win, y, x);
  3356. if (unlikely(y >= lines || x >= columns))
  3357. {
  3358. if (y >= lines)
  3359. y = lines - 1;
  3360. if (x >= columns)
  3361. x = columns - 1;
  3362. wmove(win, y, x);
  3363. }
  3364. return rv;
  3365. }
  3366. #else
  3367. # define bfg_wresize wresize
  3368. #endif
  3369. #endif
  3370. void tailsprintf(char *buf, size_t bufsz, const char *fmt, ...)
  3371. {
  3372. va_list ap;
  3373. size_t presz = strlen(buf);
  3374. va_start(ap, fmt);
  3375. vsnprintf(&buf[presz], bufsz - presz, fmt, ap);
  3376. va_end(ap);
  3377. }
  3378. double stats_elapsed(struct cgminer_stats *stats)
  3379. {
  3380. struct timeval now;
  3381. double elapsed;
  3382. if (stats->start_tv.tv_sec == 0)
  3383. elapsed = total_secs;
  3384. else {
  3385. cgtime(&now);
  3386. elapsed = tdiff(&now, &stats->start_tv);
  3387. }
  3388. if (elapsed < 1.0)
  3389. elapsed = 1.0;
  3390. return elapsed;
  3391. }
  3392. bool drv_ready(struct cgpu_info *cgpu)
  3393. {
  3394. switch (cgpu->status) {
  3395. case LIFE_INIT:
  3396. case LIFE_DEAD2:
  3397. return false;
  3398. default:
  3399. return true;
  3400. }
  3401. }
  3402. double cgpu_utility(struct cgpu_info *cgpu)
  3403. {
  3404. double dev_runtime = cgpu_runtime(cgpu);
  3405. return cgpu->utility = cgpu->accepted / dev_runtime * 60;
  3406. }
  3407. #define suffix_string(val, buf, bufsiz, sigdigits) do{ \
  3408. _Static_assert(sigdigits == 0, "suffix_string only supported with sigdigits==0"); \
  3409. format_unit3(buf, bufsiz, FUP_DIFF, "", H2B_SHORTV, val, -1); \
  3410. }while(0)
  3411. static float
  3412. utility_to_hashrate(double utility)
  3413. {
  3414. return utility * 0x4444444;
  3415. }
  3416. static const char*_unitchar = "pn\xb5m kMGTPEZY?";
  3417. static const int _unitbase = 4;
  3418. static
  3419. void pick_unit(float hashrate, unsigned char *unit)
  3420. {
  3421. unsigned char i;
  3422. if (hashrate == 0 || !isfinite(hashrate))
  3423. {
  3424. if (*unit < _unitbase)
  3425. *unit = _unitbase;
  3426. return;
  3427. }
  3428. hashrate *= 1e12;
  3429. for (i = 0; i < *unit; ++i)
  3430. hashrate /= 1e3;
  3431. // 1000 but with tolerance for floating-point rounding, avoid showing "1000.0"
  3432. while (hashrate >= 999.95)
  3433. {
  3434. hashrate /= 1e3;
  3435. if (likely(_unitchar[*unit] != '?'))
  3436. ++*unit;
  3437. }
  3438. }
  3439. #define hashrate_pick_unit(hashrate, unit) pick_unit(hashrate, unit)
  3440. enum h2bs_fmt {
  3441. H2B_NOUNIT, // "xxx.x"
  3442. H2B_SHORT, // "xxx.xMH/s"
  3443. H2B_SPACED, // "xxx.x MH/s"
  3444. H2B_SHORTV, // Like H2B_SHORT, but omit space for base unit
  3445. };
  3446. enum bfu_floatprec {
  3447. FUP_INTEGER,
  3448. FUP_HASHES,
  3449. FUP_BTC,
  3450. FUP_DIFF,
  3451. };
  3452. static
  3453. int format_unit3(char *buf, size_t sz, enum bfu_floatprec fprec, const char *measurement, enum h2bs_fmt fmt, float hashrate, signed char unitin)
  3454. {
  3455. char *s = buf;
  3456. unsigned char prec, i, unit;
  3457. int rv = 0;
  3458. if (unitin == -1)
  3459. {
  3460. unit = 0;
  3461. hashrate_pick_unit(hashrate, &unit);
  3462. }
  3463. else
  3464. unit = unitin;
  3465. hashrate *= 1e12;
  3466. for (i = 0; i < unit; ++i)
  3467. hashrate /= 1000;
  3468. switch (fprec)
  3469. {
  3470. case FUP_HASHES:
  3471. // 100 but with tolerance for floating-point rounding, max "99.99" then "100.0"
  3472. if (hashrate >= 99.995 || unit < 6)
  3473. prec = 1;
  3474. else
  3475. prec = 2;
  3476. _SNP("%5.*f", prec, hashrate);
  3477. break;
  3478. case FUP_INTEGER:
  3479. _SNP("%3d", (int)hashrate);
  3480. break;
  3481. case FUP_BTC:
  3482. if (hashrate >= 99.995)
  3483. prec = 0;
  3484. else
  3485. prec = 2;
  3486. _SNP("%5.*f", prec, hashrate);
  3487. break;
  3488. case FUP_DIFF:
  3489. if (unit > _unitbase)
  3490. _SNP("%.3g", hashrate);
  3491. else
  3492. _SNP("%u", (unsigned int)hashrate);
  3493. }
  3494. if (fmt != H2B_NOUNIT)
  3495. {
  3496. char uc[3] = {_unitchar[unit], '\0'};
  3497. switch (fmt) {
  3498. case H2B_SPACED:
  3499. _SNP(" ");
  3500. default:
  3501. break;
  3502. case H2B_SHORTV:
  3503. if (isspace(uc[0]))
  3504. uc[0] = '\0';
  3505. }
  3506. if (uc[0] == '\xb5')
  3507. // Convert to UTF-8
  3508. snprintf(uc, sizeof(uc), "%s", U8_MICRO);
  3509. _SNP("%s%s", uc, measurement);
  3510. }
  3511. return rv;
  3512. }
  3513. #define format_unit2(buf, sz, floatprec, measurement, fmt, n, unit) \
  3514. format_unit3(buf, sz, floatprec ? FUP_HASHES : FUP_INTEGER, measurement, fmt, n, unit)
  3515. static
  3516. 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)
  3517. {
  3518. unsigned char unit = 0;
  3519. bool allzero = true;
  3520. int i;
  3521. size_t delimsz = 0;
  3522. char *buf = buflist[0];
  3523. size_t bufsz = bufszlist[0];
  3524. size_t itemwidth = (floatprec ? 5 : 3);
  3525. if (!isarray)
  3526. delimsz = strlen(delim);
  3527. for (i = 0; i < count; ++i)
  3528. if (numbers[i] != 0)
  3529. {
  3530. pick_unit(numbers[i], &unit);
  3531. allzero = false;
  3532. }
  3533. if (allzero)
  3534. unit = _unitbase;
  3535. --count;
  3536. for (i = 0; i < count; ++i)
  3537. {
  3538. format_unit2(buf, bufsz, floatprec, NULL, H2B_NOUNIT, numbers[i], unit);
  3539. if (isarray)
  3540. {
  3541. buf = buflist[i + 1];
  3542. bufsz = bufszlist[i + 1];
  3543. }
  3544. else
  3545. {
  3546. buf += itemwidth;
  3547. bufsz -= itemwidth;
  3548. if (delimsz > bufsz)
  3549. delimsz = bufsz;
  3550. memcpy(buf, delim, delimsz);
  3551. buf += delimsz;
  3552. bufsz -= delimsz;
  3553. }
  3554. }
  3555. // Last entry has the unit
  3556. format_unit2(buf, bufsz, floatprec, measurement, fmt, numbers[count], unit);
  3557. return buflist[0];
  3558. }
  3559. #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)
  3560. #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)
  3561. static
  3562. int percentf3(char * const buf, size_t sz, double p, const double t)
  3563. {
  3564. char *s = buf;
  3565. int rv = 0;
  3566. if (!p)
  3567. _SNP("none");
  3568. else
  3569. if (t <= p)
  3570. _SNP("100%%");
  3571. else
  3572. {
  3573. p /= t;
  3574. if (p < 0.00995) // 0.01 but with tolerance for floating-point rounding, max ".99%"
  3575. _SNP(".%02.0f%%", p * 10000); // ".01%"
  3576. else
  3577. if (p < 0.0995) // 0.1 but with tolerance for floating-point rounding, max "9.9%"
  3578. _SNP("%.1f%%", p * 100); // "9.1%"
  3579. else
  3580. _SNP("%3.0f%%", p * 100); // " 99%"
  3581. }
  3582. return rv;
  3583. }
  3584. #define percentf4(buf, bufsz, p, t) percentf3(buf, bufsz, p, p + t)
  3585. static
  3586. void test_decimal_width()
  3587. {
  3588. // The pipe character at end of each line should perfectly line up
  3589. char printbuf[512];
  3590. char testbuf1[64];
  3591. char testbuf2[64];
  3592. char testbuf3[64];
  3593. char testbuf4[64];
  3594. double testn;
  3595. int width;
  3596. int saved;
  3597. // Hotspots around 0.1 and 0.01
  3598. saved = -1;
  3599. for (testn = 0.09; testn <= 0.11; testn += 0.000001) {
  3600. percentf3(testbuf1, sizeof(testbuf1), testn, 1.0);
  3601. percentf3(testbuf2, sizeof(testbuf2), testn, 10.0);
  3602. width = snprintf(printbuf, sizeof(printbuf), "%10g %s %s |", testn, testbuf1, testbuf2);
  3603. if (unlikely((saved != -1) && (width != saved))) {
  3604. ++unittest_failures;
  3605. applog(LOG_ERR, "Test width mismatch in percentf3! %d not %d at %10g", width, saved, testn);
  3606. applog(LOG_ERR, "%s", printbuf);
  3607. }
  3608. saved = width;
  3609. }
  3610. // Hotspot around 100 (but test this in several units because format_unit2 also has unit<2 check)
  3611. saved = -1;
  3612. for (testn = 99.0; testn <= 101.0; testn += 0.0001) {
  3613. format_unit2(testbuf1, sizeof(testbuf1), true, "x", H2B_SHORT, testn , -1);
  3614. format_unit2(testbuf2, sizeof(testbuf2), true, "x", H2B_SHORT, testn * 1e3, -1);
  3615. format_unit2(testbuf3, sizeof(testbuf3), true, "x", H2B_SHORT, testn * 1e6, -1);
  3616. snprintf(printbuf, sizeof(printbuf), "%10g %s %s %s |", testn, testbuf1, testbuf2, testbuf3);
  3617. width = utf8_strlen(printbuf);
  3618. if (unlikely((saved != -1) && (width != saved))) {
  3619. ++unittest_failures;
  3620. applog(LOG_ERR, "Test width mismatch in format_unit2! %d not %d at %10g", width, saved, testn);
  3621. applog(LOG_ERR, "%s", printbuf);
  3622. }
  3623. saved = width;
  3624. }
  3625. // Hotspot around unit transition boundary in pick_unit
  3626. saved = -1;
  3627. for (testn = 999.0; testn <= 1001.0; testn += 0.0001) {
  3628. format_unit2(testbuf1, sizeof(testbuf1), true, "x", H2B_SHORT, testn , -1);
  3629. format_unit2(testbuf2, sizeof(testbuf2), true, "x", H2B_SHORT, testn * 1e3, -1);
  3630. format_unit2(testbuf3, sizeof(testbuf3), true, "x", H2B_SHORT, testn * 1e6, -1);
  3631. format_unit2(testbuf4, sizeof(testbuf4), true, "x", H2B_SHORT, testn * 1e9, -1);
  3632. snprintf(printbuf, sizeof(printbuf), "%10g %s %s %s %s |", testn, testbuf1, testbuf2, testbuf3, testbuf4);
  3633. width = utf8_strlen(printbuf);
  3634. if (unlikely((saved != -1) && (width != saved))) {
  3635. ++unittest_failures;
  3636. applog(LOG_ERR, "Test width mismatch in pick_unit! %d not %d at %10g", width, saved, testn);
  3637. applog(LOG_ERR, "%s", printbuf);
  3638. }
  3639. saved = width;
  3640. }
  3641. }
  3642. #ifdef HAVE_CURSES
  3643. static void adj_width(int var, int *length);
  3644. #endif
  3645. #ifdef HAVE_CURSES
  3646. static int awidth = 1, rwidth = 1, swidth = 1, hwwidth = 1;
  3647. static
  3648. 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)
  3649. {
  3650. char rejpcbuf[6];
  3651. char bnbuf[6];
  3652. adj_width(accepted, &awidth);
  3653. adj_width(rejected, &rwidth);
  3654. adj_width(stale, &swidth);
  3655. adj_width(hwerrs, &hwwidth);
  3656. percentf4(rejpcbuf, sizeof(rejpcbuf), wnotaccepted, waccepted);
  3657. percentf3(bnbuf, sizeof(bnbuf), bad_diff1, allnonces);
  3658. tailsprintf(buf, bufsz, "%s/%s/%s | A:%*d R:%*d+%*d(%s) HW:%*d/%s",
  3659. cHr, aHr, uHr,
  3660. awidth, accepted,
  3661. rwidth, rejected,
  3662. swidth, stale,
  3663. rejpcbuf,
  3664. hwwidth, hwerrs,
  3665. bnbuf
  3666. );
  3667. }
  3668. static
  3669. const char *pool_proto_str(const struct pool * const pool)
  3670. {
  3671. if (pool->idle)
  3672. return "Dead ";
  3673. if (pool->has_stratum)
  3674. return "Strtm";
  3675. if (pool->lp_url && pool->proto != pool->lp_proto)
  3676. return "Mixed";
  3677. switch (pool->proto)
  3678. {
  3679. case PLP_GETBLOCKTEMPLATE:
  3680. return " GBT ";
  3681. case PLP_GETWORK:
  3682. return "GWork";
  3683. default:
  3684. return "Alive";
  3685. }
  3686. }
  3687. #endif
  3688. static inline
  3689. void temperature_column(char *buf, size_t bufsz, bool maybe_unicode, const float * const temp)
  3690. {
  3691. if (!(use_unicode && have_unicode_degrees))
  3692. maybe_unicode = false;
  3693. if (temp && *temp > 0.)
  3694. if (maybe_unicode)
  3695. snprintf(buf, bufsz, "%4.1f"U8_DEGREE"C", *temp);
  3696. else
  3697. snprintf(buf, bufsz, "%4.1fC", *temp);
  3698. else
  3699. {
  3700. if (temp)
  3701. snprintf(buf, bufsz, " ");
  3702. if (maybe_unicode)
  3703. tailsprintf(buf, bufsz, " ");
  3704. }
  3705. tailsprintf(buf, bufsz, " | ");
  3706. }
  3707. void get_statline3(char *buf, size_t bufsz, struct cgpu_info *cgpu, bool for_curses, bool opt_show_procs)
  3708. {
  3709. #ifndef HAVE_CURSES
  3710. assert(for_curses == false);
  3711. #endif
  3712. struct device_drv *drv = cgpu->drv;
  3713. enum h2bs_fmt hashrate_style = for_curses ? H2B_SHORT : H2B_SPACED;
  3714. char cHr[ALLOC_H2B_NOUNIT+1], aHr[ALLOC_H2B_NOUNIT+1], uHr[max(ALLOC_H2B_SHORT, ALLOC_H2B_SPACED)+3+1];
  3715. char rejpcbuf[6];
  3716. char bnbuf[6];
  3717. double dev_runtime;
  3718. if (!opt_show_procs)
  3719. cgpu = cgpu->device;
  3720. dev_runtime = cgpu_runtime(cgpu);
  3721. double rolling, mhashes;
  3722. int accepted, rejected, stale;
  3723. double waccepted;
  3724. double wnotaccepted;
  3725. int hwerrs;
  3726. double bad_diff1, good_diff1;
  3727. rolling = mhashes = waccepted = wnotaccepted = 0;
  3728. accepted = rejected = stale = hwerrs = bad_diff1 = good_diff1 = 0;
  3729. {
  3730. struct cgpu_info *slave = cgpu;
  3731. for (int i = 0; i < cgpu->procs; ++i, (slave = slave->next_proc))
  3732. {
  3733. slave->utility = slave->accepted / dev_runtime * 60;
  3734. slave->utility_diff1 = slave->diff_accepted / dev_runtime * 60;
  3735. rolling += slave->rolling;
  3736. mhashes += slave->total_mhashes;
  3737. if (opt_weighed_stats)
  3738. {
  3739. accepted += slave->diff_accepted;
  3740. rejected += slave->diff_rejected;
  3741. stale += slave->diff_stale;
  3742. }
  3743. else
  3744. {
  3745. accepted += slave->accepted;
  3746. rejected += slave->rejected;
  3747. stale += slave->stale;
  3748. }
  3749. waccepted += slave->diff_accepted;
  3750. wnotaccepted += slave->diff_rejected + slave->diff_stale;
  3751. hwerrs += slave->hw_errors;
  3752. bad_diff1 += slave->bad_diff1;
  3753. good_diff1 += slave->diff1;
  3754. if (opt_show_procs)
  3755. break;
  3756. }
  3757. }
  3758. double wtotal = (waccepted + wnotaccepted);
  3759. multi_format_unit_array2(
  3760. ((char*[]){cHr, aHr, uHr}),
  3761. ((size_t[]){sizeof(cHr), sizeof(aHr), sizeof(uHr)}),
  3762. true, "h/s", hashrate_style,
  3763. 3,
  3764. 1e6*rolling,
  3765. 1e6*mhashes / dev_runtime,
  3766. utility_to_hashrate(good_diff1 * (wtotal ? (waccepted / wtotal) : 1) * 60 / dev_runtime));
  3767. // Processor representation
  3768. #ifdef HAVE_CURSES
  3769. if (for_curses)
  3770. {
  3771. if (opt_show_procs)
  3772. snprintf(buf, bufsz, " %*s: ", -(5 + max_lpdigits), cgpu->proc_repr);
  3773. else
  3774. snprintf(buf, bufsz, " %s: ", cgpu->dev_repr);
  3775. }
  3776. else
  3777. #endif
  3778. snprintf(buf, bufsz, "%s ", opt_show_procs ? cgpu->proc_repr_ns : cgpu->dev_repr_ns);
  3779. if (include_serial_in_statline && cgpu->dev_serial)
  3780. tailsprintf(buf, bufsz, "[serial=%s] ", cgpu->dev_serial);
  3781. if (unlikely(cgpu->status == LIFE_INIT))
  3782. {
  3783. tailsprintf(buf, bufsz, "Initializing...");
  3784. return;
  3785. }
  3786. {
  3787. const size_t bufln = strlen(buf);
  3788. const size_t abufsz = (bufln >= bufsz) ? 0 : (bufsz - bufln);
  3789. if (likely(cgpu->status != LIFE_DEAD2) && drv->override_statline_temp2 && drv->override_statline_temp2(buf, bufsz, cgpu, opt_show_procs))
  3790. temperature_column(&buf[bufln], abufsz, for_curses, NULL);
  3791. else
  3792. {
  3793. float temp = cgpu->temp;
  3794. if (!opt_show_procs)
  3795. {
  3796. // Find the highest temperature of all processors
  3797. struct cgpu_info *proc = cgpu;
  3798. for (int i = 0; i < cgpu->procs; ++i, (proc = proc->next_proc))
  3799. if (proc->temp > temp)
  3800. temp = proc->temp;
  3801. }
  3802. temperature_column(&buf[bufln], abufsz, for_curses, &temp);
  3803. }
  3804. }
  3805. #ifdef HAVE_CURSES
  3806. if (for_curses)
  3807. {
  3808. const char *cHrStatsOpt[] = {AS_BAD("DEAD "), AS_BAD("SICK "), "OFF ", AS_BAD("REST "), AS_BAD(" ERR "), AS_BAD("WAIT "), cHr};
  3809. const char *cHrStats;
  3810. int cHrStatsI = (sizeof(cHrStatsOpt) / sizeof(*cHrStatsOpt)) - 1;
  3811. bool all_dead = true, all_off = true, all_rdrv = true;
  3812. struct cgpu_info *proc = cgpu;
  3813. for (int i = 0; i < cgpu->procs; ++i, (proc = proc->next_proc))
  3814. {
  3815. switch (cHrStatsI) {
  3816. default:
  3817. if (proc->status == LIFE_WAIT)
  3818. cHrStatsI = 5;
  3819. case 5:
  3820. if (proc->deven == DEV_RECOVER_ERR)
  3821. cHrStatsI = 4;
  3822. case 4:
  3823. if (proc->deven == DEV_RECOVER)
  3824. cHrStatsI = 3;
  3825. case 3:
  3826. if (proc->status == LIFE_SICK || proc->status == LIFE_DEAD || proc->status == LIFE_DEAD2)
  3827. {
  3828. cHrStatsI = 1;
  3829. all_off = false;
  3830. }
  3831. else
  3832. {
  3833. if (likely(proc->deven == DEV_ENABLED))
  3834. all_off = false;
  3835. if (proc->deven != DEV_RECOVER_DRV)
  3836. all_rdrv = false;
  3837. }
  3838. case 1:
  3839. break;
  3840. }
  3841. if (likely(proc->status != LIFE_DEAD && proc->status != LIFE_DEAD2))
  3842. all_dead = false;
  3843. if (opt_show_procs)
  3844. break;
  3845. }
  3846. if (unlikely(all_dead))
  3847. cHrStatsI = 0;
  3848. else
  3849. if (unlikely(all_off))
  3850. cHrStatsI = 2;
  3851. cHrStats = cHrStatsOpt[cHrStatsI];
  3852. if (cHrStatsI == 2 && all_rdrv)
  3853. cHrStats = " RST ";
  3854. format_statline(buf, bufsz,
  3855. cHrStats,
  3856. aHr, uHr,
  3857. accepted, rejected, stale,
  3858. wnotaccepted, waccepted,
  3859. hwerrs,
  3860. bad_diff1, bad_diff1 + good_diff1);
  3861. }
  3862. else
  3863. #endif
  3864. {
  3865. percentf4(rejpcbuf, sizeof(rejpcbuf), wnotaccepted, waccepted);
  3866. percentf4(bnbuf, sizeof(bnbuf), bad_diff1, good_diff1);
  3867. tailsprintf(buf, bufsz, "%ds:%s avg:%s u:%s | A:%d R:%d+%d(%s) HW:%d/%s",
  3868. opt_log_interval,
  3869. cHr, aHr, uHr,
  3870. accepted,
  3871. rejected,
  3872. stale,
  3873. rejpcbuf,
  3874. hwerrs,
  3875. bnbuf
  3876. );
  3877. }
  3878. }
  3879. #define get_statline(buf, bufsz, cgpu) get_statline3(buf, bufsz, cgpu, false, opt_show_procs)
  3880. #define get_statline2(buf, bufsz, cgpu, for_curses) get_statline3(buf, bufsz, cgpu, for_curses, opt_show_procs)
  3881. static void text_print_status(int thr_id)
  3882. {
  3883. struct cgpu_info *cgpu;
  3884. char logline[256];
  3885. cgpu = get_thr_cgpu(thr_id);
  3886. if (cgpu) {
  3887. get_statline(logline, sizeof(logline), cgpu);
  3888. printf("\n%s\r", logline);
  3889. fflush(stdout);
  3890. }
  3891. }
  3892. #ifdef HAVE_CURSES
  3893. static int attr_bad = A_BOLD;
  3894. #ifdef WIN32
  3895. #define swprintf snwprintf
  3896. #endif
  3897. static
  3898. void bfg_waddstr(WINDOW *win, const char *s)
  3899. {
  3900. const char *p = s;
  3901. int32_t w;
  3902. int wlen;
  3903. unsigned char stop_ascii = (use_unicode ? '|' : 0x80);
  3904. while (true)
  3905. {
  3906. while (likely(p[0] == '\n' || (p[0] >= 0x20 && p[0] < stop_ascii)))
  3907. {
  3908. // Printable ASCII
  3909. ++p;
  3910. }
  3911. if (p != s)
  3912. waddnstr(win, s, p - s);
  3913. w = utf8_decode(p, &wlen);
  3914. s = p += wlen;
  3915. switch(w)
  3916. {
  3917. // NOTE: U+F000-U+F7FF are reserved for font hacks
  3918. case '\0':
  3919. return;
  3920. case 0xb5: // micro symbol
  3921. w = unicode_micro;
  3922. goto default_addch;
  3923. case 0xf000: // "bad" off
  3924. wattroff(win, attr_bad);
  3925. break;
  3926. case 0xf001: // "bad" on
  3927. wattron(win, attr_bad);
  3928. break;
  3929. #ifdef USE_UNICODE
  3930. case '|':
  3931. wadd_wch(win, WACS_VLINE);
  3932. break;
  3933. #endif
  3934. case 0x2500: // BOX DRAWINGS LIGHT HORIZONTAL
  3935. case 0x2534: // BOX DRAWINGS LIGHT UP AND HORIZONTAL
  3936. if (!use_unicode)
  3937. {
  3938. waddch(win, '-');
  3939. break;
  3940. }
  3941. #ifdef USE_UNICODE
  3942. wadd_wch(win, (w == 0x2500) ? WACS_HLINE : WACS_BTEE);
  3943. break;
  3944. #endif
  3945. case 0x2022:
  3946. if (w > WCHAR_MAX || !iswprint(w))
  3947. w = '*';
  3948. default:
  3949. default_addch:
  3950. if (w > WCHAR_MAX || !(iswprint(w) || w == '\n'))
  3951. {
  3952. #if REPLACEMENT_CHAR <= WCHAR_MAX
  3953. if (iswprint(REPLACEMENT_CHAR))
  3954. w = REPLACEMENT_CHAR;
  3955. else
  3956. #endif
  3957. w = '?';
  3958. }
  3959. {
  3960. #ifdef USE_UNICODE
  3961. wchar_t wbuf[0x10];
  3962. int wbuflen = sizeof(wbuf) / sizeof(*wbuf);
  3963. wbuflen = swprintf(wbuf, wbuflen, L"%lc", (wint_t)w);
  3964. waddnwstr(win, wbuf, wbuflen);
  3965. #else
  3966. wprintw(win, "%lc", (wint_t)w);
  3967. #endif
  3968. }
  3969. }
  3970. }
  3971. }
  3972. static inline
  3973. void bfg_hline(WINDOW *win, int y)
  3974. {
  3975. int maxx, __maybe_unused maxy;
  3976. getmaxyx(win, maxy, maxx);
  3977. #ifdef USE_UNICODE
  3978. if (use_unicode)
  3979. mvwhline_set(win, y, 0, WACS_HLINE, maxx);
  3980. else
  3981. #endif
  3982. mvwhline(win, y, 0, '-', maxx);
  3983. }
  3984. static
  3985. int bfg_win_linelen(WINDOW * const win)
  3986. {
  3987. int maxx;
  3988. int __maybe_unused y;
  3989. getmaxyx(win, y, maxx);
  3990. return maxx;
  3991. }
  3992. // Spaces until end of line, using current attributes (ie, not completely clear)
  3993. static
  3994. void bfg_wspctoeol(WINDOW * const win, const int offset)
  3995. {
  3996. int x, maxx;
  3997. int __maybe_unused y;
  3998. getmaxyx(win, y, maxx);
  3999. getyx(win, y, x);
  4000. const int space_count = (maxx - x) - offset;
  4001. // Check for negative - terminal too narrow
  4002. if (space_count <= 0)
  4003. return;
  4004. char buf[space_count];
  4005. memset(buf, ' ', space_count);
  4006. waddnstr(win, buf, space_count);
  4007. }
  4008. static int menu_attr = A_REVERSE;
  4009. #define CURBUFSIZ 256
  4010. #define cg_mvwprintw(win, y, x, fmt, ...) do { \
  4011. char tmp42[CURBUFSIZ]; \
  4012. snprintf(tmp42, sizeof(tmp42), fmt, ##__VA_ARGS__); \
  4013. wmove(win, y, x); \
  4014. bfg_waddstr(win, tmp42); \
  4015. } while (0)
  4016. #define cg_wprintw(win, fmt, ...) do { \
  4017. char tmp42[CURBUFSIZ]; \
  4018. snprintf(tmp42, sizeof(tmp42), fmt, ##__VA_ARGS__); \
  4019. bfg_waddstr(win, tmp42); \
  4020. } while (0)
  4021. static
  4022. void update_block_display_line(const int blky, struct mining_goal_info *goal)
  4023. {
  4024. struct blockchain_info * const blkchain = goal->blkchain;
  4025. struct block_info * const blkinfo = blkchain->currentblk;
  4026. double income;
  4027. char incomestr[ALLOC_H2B_SHORT+6+1];
  4028. if (blkinfo->height)
  4029. {
  4030. income = goal->diff_accepted * 3600 * blkchain->currentblk_subsidy / total_secs / goal->current_diff;
  4031. format_unit3(incomestr, sizeof(incomestr), FUP_BTC, "BTC/hr", H2B_SHORT, income/1e8, -1);
  4032. }
  4033. else
  4034. strcpy(incomestr, "?");
  4035. int linelen = bfg_win_linelen(statuswin);
  4036. wmove(statuswin, blky, 0);
  4037. bfg_waddstr(statuswin, " Block");
  4038. if (!goal->is_default)
  4039. linelen -= strlen(goal->name) + 1;
  4040. linelen -= 6; // " Block"
  4041. if (blkinfo->height && blkinfo->height < 1000000)
  4042. {
  4043. cg_wprintw(statuswin, " #%6u", blkinfo->height);
  4044. linelen -= 8;
  4045. }
  4046. bfg_waddstr(statuswin, ":");
  4047. if (linelen > 55)
  4048. bfg_waddstr(statuswin, " ");
  4049. if (linelen >= 65)
  4050. bfg_waddstr(statuswin, "...");
  4051. {
  4052. char hexpbh[0x11];
  4053. if (!(blkinfo->height && blkinfo->height < 1000000))
  4054. {
  4055. bin2hex(hexpbh, &blkinfo->prevblkhash[4], 4);
  4056. bfg_waddstr(statuswin, hexpbh);
  4057. }
  4058. bin2hex(hexpbh, &blkinfo->prevblkhash[0], 4);
  4059. bfg_waddstr(statuswin, hexpbh);
  4060. }
  4061. if (linelen >= 55)
  4062. bfg_waddstr(statuswin, " ");
  4063. cg_wprintw(statuswin, " Diff:%s", goal->current_diff_str);
  4064. if (linelen >= 69)
  4065. bfg_waddstr(statuswin, " ");
  4066. cg_wprintw(statuswin, "(%s) ", goal->net_hashrate);
  4067. if (linelen >= 62)
  4068. {
  4069. if (linelen >= 69)
  4070. bfg_waddstr(statuswin, " ");
  4071. bfg_waddstr(statuswin, "Started:");
  4072. }
  4073. else
  4074. bfg_waddstr(statuswin, "S:");
  4075. if (linelen >= 69)
  4076. bfg_waddstr(statuswin, " ");
  4077. bfg_waddstr(statuswin, blkchain->currentblk_first_seen_time_str);
  4078. if (linelen >= 69)
  4079. bfg_waddstr(statuswin, " ");
  4080. cg_wprintw(statuswin, " I:%s", incomestr);
  4081. if (!goal->is_default)
  4082. cg_wprintw(statuswin, " %s", goal->name);
  4083. wclrtoeol(statuswin);
  4084. }
  4085. static bool pool_actively_in_use(const struct pool *, const struct pool *);
  4086. static
  4087. void update_block_display(void)
  4088. {
  4089. struct mining_goal_info *goal, *tmpgoal;
  4090. int blky = 3, i, total_found_goals = 0;
  4091. HASH_ITER(hh, mining_goals, goal, tmpgoal)
  4092. {
  4093. for (i = 0; i < total_pools; ++i)
  4094. {
  4095. struct pool * const pool = pools[i];
  4096. if (pool->goal == goal && pool_actively_in_use(pool, NULL))
  4097. break;
  4098. }
  4099. if (i >= total_pools)
  4100. // no pools using this goal, so it's probably stale anyway
  4101. continue;
  4102. update_block_display_line(blky++, goal);
  4103. ++total_found_goals;
  4104. }
  4105. if (total_found_goals != active_goals)
  4106. {
  4107. active_goals = total_found_goals;
  4108. devcursor = 7 + active_goals;
  4109. switch_logsize();
  4110. }
  4111. }
  4112. static bool pool_unworkable(const struct pool *);
  4113. /* Must be called with curses mutex lock held and curses_active */
  4114. static void curses_print_status(const int ts)
  4115. {
  4116. struct pool *pool = currentpool;
  4117. struct timeval now, tv;
  4118. float efficiency;
  4119. int logdiv;
  4120. efficiency = total_bytes_xfer ? total_diff_accepted * 2048. / total_bytes_xfer : 0.0;
  4121. wattron(statuswin, attr_title);
  4122. const int linelen = bfg_win_linelen(statuswin);
  4123. int titlelen = 1 + strlen(PACKAGE) + 1 + strlen(VERSION) + 3 + 21 + 3 + 19;
  4124. cg_mvwprintw(statuswin, 0, 0, " " PACKAGE " ");
  4125. if (titlelen + 17 < linelen)
  4126. cg_wprintw(statuswin, "version ");
  4127. cg_wprintw(statuswin, VERSION " - ");
  4128. if (titlelen + 9 < linelen)
  4129. cg_wprintw(statuswin, "Started: ");
  4130. else
  4131. if (titlelen + 7 <= linelen)
  4132. cg_wprintw(statuswin, "Start: ");
  4133. cg_wprintw(statuswin, "%s", datestamp);
  4134. timer_set_now(&now);
  4135. {
  4136. unsigned int days, hours;
  4137. div_t d;
  4138. timersub(&now, &miner_started, &tv);
  4139. d = div(tv.tv_sec, 86400);
  4140. days = d.quot;
  4141. d = div(d.rem, 3600);
  4142. hours = d.quot;
  4143. d = div(d.rem, 60);
  4144. cg_wprintw(statuswin, " - [%3u day%c %02d:%02d:%02d]"
  4145. , days
  4146. , (days == 1) ? ' ' : 's'
  4147. , hours
  4148. , d.quot
  4149. , d.rem
  4150. );
  4151. }
  4152. bfg_wspctoeol(statuswin, 0);
  4153. wattroff(statuswin, attr_title);
  4154. wattron(statuswin, menu_attr);
  4155. wmove(statuswin, 1, 0);
  4156. bfg_waddstr(statuswin, " [M]anage devices [P]ool management [S]ettings [D]isplay options ");
  4157. bfg_wspctoeol(statuswin, 14);
  4158. bfg_waddstr(statuswin, "[H]elp [Q]uit ");
  4159. wattroff(statuswin, menu_attr);
  4160. if ((pool_strategy == POOL_LOADBALANCE || pool_strategy == POOL_BALANCE) && enabled_pools > 1) {
  4161. char poolinfo[20], poolinfo2[20];
  4162. int poolinfooff = 0, poolinfo2off, workable_pools = 0;
  4163. double lowdiff = DBL_MAX, highdiff = -1;
  4164. struct pool *lowdiff_pool = pools[0], *highdiff_pool = pools[0];
  4165. time_t oldest_work_restart = time(NULL) + 1;
  4166. struct pool *oldest_work_restart_pool = pools[0];
  4167. for (int i = 0; i < total_pools; ++i)
  4168. {
  4169. if (pool_unworkable(pools[i]))
  4170. continue;
  4171. // NOTE: Only set pool var when it's workable; if only one is, it gets used by single-pool code
  4172. pool = pools[i];
  4173. ++workable_pools;
  4174. if (poolinfooff < sizeof(poolinfo))
  4175. poolinfooff += snprintf(&poolinfo[poolinfooff], sizeof(poolinfo) - poolinfooff, "%u,", pool->pool_no);
  4176. struct cgminer_pool_stats * const pool_stats = &pool->cgminer_pool_stats;
  4177. if (pool_stats->last_diff < lowdiff)
  4178. {
  4179. lowdiff = pool_stats->last_diff;
  4180. lowdiff_pool = pool;
  4181. }
  4182. if (pool_stats->last_diff > highdiff)
  4183. {
  4184. highdiff = pool_stats->last_diff;
  4185. highdiff_pool = pool;
  4186. }
  4187. if (oldest_work_restart >= pool->work_restart_time)
  4188. {
  4189. oldest_work_restart = pool->work_restart_time;
  4190. oldest_work_restart_pool = pool;
  4191. }
  4192. }
  4193. if (unlikely(!workable_pools))
  4194. goto no_workable_pools;
  4195. if (workable_pools == 1)
  4196. goto one_workable_pool;
  4197. poolinfo2off = snprintf(poolinfo2, sizeof(poolinfo2), "%u (", workable_pools);
  4198. if (poolinfooff > sizeof(poolinfo2) - poolinfo2off - 1)
  4199. snprintf(&poolinfo2[poolinfo2off], sizeof(poolinfo2) - poolinfo2off, "%.*s...)", (int)(sizeof(poolinfo2) - poolinfo2off - 5), poolinfo);
  4200. else
  4201. snprintf(&poolinfo2[poolinfo2off], sizeof(poolinfo2) - poolinfo2off, "%.*s)%*s", (int)(poolinfooff - 1), poolinfo, (int)(sizeof(poolinfo2)), "");
  4202. cg_mvwprintw(statuswin, 2, 0, " Pools: %s Diff:%s%s%s %c LU:%s",
  4203. poolinfo2,
  4204. lowdiff_pool->diff,
  4205. (lowdiff == highdiff) ? "" : "-",
  4206. (lowdiff == highdiff) ? "" : highdiff_pool->diff,
  4207. pool->goal->have_longpoll ? '+' : '-',
  4208. oldest_work_restart_pool->work_restart_timestamp);
  4209. }
  4210. else
  4211. if (pool_unworkable(pool))
  4212. {
  4213. no_workable_pools: ;
  4214. wattron(statuswin, attr_bad);
  4215. cg_mvwprintw(statuswin, 2, 0, " (all pools are dead) ");
  4216. wattroff(statuswin, attr_bad);
  4217. }
  4218. else
  4219. {
  4220. one_workable_pool: ;
  4221. char pooladdr[19];
  4222. {
  4223. const char *rawaddr = pool->sockaddr_url;
  4224. BFGINIT(rawaddr, pool->rpc_url);
  4225. size_t pooladdrlen = strlen(rawaddr);
  4226. if (pooladdrlen > 20)
  4227. snprintf(pooladdr, sizeof(pooladdr), "...%s", &rawaddr[pooladdrlen - (sizeof(pooladdr) - 4)]);
  4228. else
  4229. snprintf(pooladdr, sizeof(pooladdr), "%*s", -(int)(sizeof(pooladdr) - 1), rawaddr);
  4230. }
  4231. cg_mvwprintw(statuswin, 2, 0, " Pool%2u: %s Diff:%s %c%s LU:%s User:%s",
  4232. pool->pool_no, pooladdr, pool->diff,
  4233. pool->goal->have_longpoll ? '+' : '-', pool_proto_str(pool),
  4234. pool->work_restart_timestamp,
  4235. pool->rpc_user);
  4236. }
  4237. wclrtoeol(statuswin);
  4238. char bwstr[(ALLOC_H2B_SHORT*2)+3+1];
  4239. cg_mvwprintw(statuswin, devcursor - 4, 0, " ST:%d F:%d NB:%d AS:%d BW:[%s] E:%.2f BS:%s",
  4240. ts,
  4241. total_go + total_ro,
  4242. new_blocks,
  4243. total_submitting,
  4244. multi_format_unit2(bwstr, sizeof(bwstr),
  4245. false, "B/s", H2B_SHORT, "/", 2,
  4246. (float)(total_bytes_rcvd / total_secs),
  4247. (float)(total_bytes_sent / total_secs)),
  4248. efficiency,
  4249. best_share);
  4250. wclrtoeol(statuswin);
  4251. mvwaddstr(statuswin, devcursor - 3, 0, " ");
  4252. bfg_waddstr(statuswin, statusline);
  4253. wclrtoeol(statuswin);
  4254. int devdiv = devcursor - 2;
  4255. logdiv = statusy - 1;
  4256. bfg_hline(statuswin, devdiv);
  4257. bfg_hline(statuswin, logdiv);
  4258. #ifdef USE_UNICODE
  4259. if (use_unicode)
  4260. {
  4261. int offset = 8 /* device */ + 5 /* temperature */ + 1 /* padding space */;
  4262. if (opt_show_procs && !opt_compact)
  4263. offset += max_lpdigits; // proc letter(s)
  4264. if (have_unicode_degrees)
  4265. ++offset; // degrees symbol
  4266. mvwadd_wch(statuswin, devdiv, offset, WACS_PLUS);
  4267. mvwadd_wch(statuswin, logdiv, offset, WACS_BTEE);
  4268. offset += 24; // hashrates etc
  4269. mvwadd_wch(statuswin, devdiv, offset, WACS_PLUS);
  4270. mvwadd_wch(statuswin, logdiv, offset, WACS_BTEE);
  4271. }
  4272. #endif
  4273. }
  4274. static void adj_width(int var, int *length)
  4275. {
  4276. if ((int)(log10(var) + 1) > *length)
  4277. (*length)++;
  4278. }
  4279. static int dev_width;
  4280. static void curses_print_devstatus(struct cgpu_info *cgpu)
  4281. {
  4282. char logline[256];
  4283. int ypos;
  4284. if (opt_compact)
  4285. return;
  4286. /* Check this isn't out of the window size */
  4287. if (opt_show_procs)
  4288. ypos = cgpu->cgminer_id;
  4289. else
  4290. {
  4291. if (cgpu->proc_id)
  4292. return;
  4293. ypos = cgpu->device_line_id;
  4294. }
  4295. ypos += devsummaryYOffset;
  4296. if (ypos < 0)
  4297. return;
  4298. ypos += devcursor - 1;
  4299. if (ypos >= statusy - 1)
  4300. return;
  4301. if (wmove(statuswin, ypos, 0) == ERR)
  4302. return;
  4303. get_statline2(logline, sizeof(logline), cgpu, true);
  4304. if (selecting_device && (opt_show_procs ? (selected_device == cgpu->cgminer_id) : (devices[selected_device]->device == cgpu)))
  4305. wattron(statuswin, A_REVERSE);
  4306. bfg_waddstr(statuswin, logline);
  4307. wattroff(statuswin, A_REVERSE);
  4308. wclrtoeol(statuswin);
  4309. }
  4310. static
  4311. void _refresh_devstatus(const bool already_have_lock) {
  4312. if ((!opt_compact) && (already_have_lock || curses_active_locked())) {
  4313. int i;
  4314. if (unlikely(!total_devices))
  4315. {
  4316. const int ypos = devcursor - 1;
  4317. if (ypos < statusy - 1 && wmove(statuswin, ypos, 0) != ERR)
  4318. {
  4319. wattron(statuswin, attr_bad);
  4320. bfg_waddstr(statuswin, "NO DEVICES FOUND: Press 'M' and '+' to add");
  4321. wclrtoeol(statuswin);
  4322. wattroff(statuswin, attr_bad);
  4323. }
  4324. }
  4325. for (i = 0; i < total_devices; i++)
  4326. curses_print_devstatus(get_devices(i));
  4327. touchwin(statuswin);
  4328. wrefresh(statuswin);
  4329. if (!already_have_lock)
  4330. unlock_curses();
  4331. }
  4332. }
  4333. #define refresh_devstatus() _refresh_devstatus(false)
  4334. #endif
  4335. static void print_status(int thr_id)
  4336. {
  4337. if (!curses_active)
  4338. text_print_status(thr_id);
  4339. }
  4340. #ifdef HAVE_CURSES
  4341. static
  4342. bool set_statusy(int maxy)
  4343. {
  4344. if (loginput_size)
  4345. {
  4346. maxy -= loginput_size;
  4347. if (maxy < 0)
  4348. maxy = 0;
  4349. }
  4350. if (logstart < maxy)
  4351. maxy = logstart;
  4352. if (statusy == maxy)
  4353. return false;
  4354. statusy = maxy;
  4355. logcursor = statusy;
  4356. return true;
  4357. }
  4358. /* Check for window resize. Called with curses mutex locked */
  4359. static inline void change_logwinsize(void)
  4360. {
  4361. int x, y, logx, logy;
  4362. getmaxyx(mainwin, y, x);
  4363. if (x < 80 || y < 25)
  4364. return;
  4365. if (y > statusy + 2 && statusy < logstart) {
  4366. set_statusy(y - 2);
  4367. mvwin(logwin, logcursor, 0);
  4368. bfg_wresize(statuswin, statusy, x);
  4369. }
  4370. y -= logcursor;
  4371. getmaxyx(logwin, logy, logx);
  4372. /* Detect screen size change */
  4373. if (x != logx || y != logy)
  4374. bfg_wresize(logwin, y, x);
  4375. }
  4376. static void check_winsizes(void)
  4377. {
  4378. if (!use_curses)
  4379. return;
  4380. if (curses_active_locked()) {
  4381. int y, x;
  4382. x = getmaxx(statuswin);
  4383. if (set_statusy(LINES - 2))
  4384. {
  4385. erase();
  4386. bfg_wresize(statuswin, statusy, x);
  4387. getmaxyx(mainwin, y, x);
  4388. y -= logcursor;
  4389. bfg_wresize(logwin, y, x);
  4390. mvwin(logwin, logcursor, 0);
  4391. }
  4392. unlock_curses();
  4393. }
  4394. }
  4395. static int device_line_id_count;
  4396. static void switch_logsize(void)
  4397. {
  4398. if (curses_active_locked()) {
  4399. if (opt_compact) {
  4400. logstart = devcursor - 1;
  4401. logcursor = logstart + 1;
  4402. } else {
  4403. total_lines = (opt_show_procs ? total_devices : device_line_id_count) ?: 1;
  4404. logstart = devcursor + total_lines;
  4405. logcursor = logstart;
  4406. }
  4407. unlock_curses();
  4408. }
  4409. check_winsizes();
  4410. update_block_display();
  4411. }
  4412. /* For mandatory printing when mutex is already locked */
  4413. void _wlog(const char *str)
  4414. {
  4415. static bool newline;
  4416. size_t end = strlen(str) - 1;
  4417. if (newline)
  4418. bfg_waddstr(logwin, "\n");
  4419. if (str[end] == '\n')
  4420. {
  4421. char *s;
  4422. newline = true;
  4423. s = alloca(end + 1);
  4424. memcpy(s, str, end);
  4425. s[end] = '\0';
  4426. str = s;
  4427. }
  4428. else
  4429. newline = false;
  4430. bfg_waddstr(logwin, str);
  4431. }
  4432. /* Mandatory printing */
  4433. void _wlogprint(const char *str)
  4434. {
  4435. if (curses_active_locked()) {
  4436. _wlog(str);
  4437. unlock_curses();
  4438. }
  4439. }
  4440. #endif
  4441. #ifdef HAVE_CURSES
  4442. bool _log_curses_only(int prio, const char *datetime, const char *str)
  4443. {
  4444. bool high_prio;
  4445. high_prio = (prio == LOG_WARNING || prio == LOG_ERR);
  4446. if (curses_active)
  4447. {
  4448. if (!loginput_size || high_prio) {
  4449. wlog(" %s %s\n", datetime, str);
  4450. if (high_prio) {
  4451. touchwin(logwin);
  4452. wrefresh(logwin);
  4453. }
  4454. }
  4455. return true;
  4456. }
  4457. return false;
  4458. }
  4459. void clear_logwin(void)
  4460. {
  4461. if (curses_active_locked()) {
  4462. wclear(logwin);
  4463. unlock_curses();
  4464. }
  4465. }
  4466. void logwin_update(void)
  4467. {
  4468. if (curses_active_locked()) {
  4469. touchwin(logwin);
  4470. wrefresh(logwin);
  4471. unlock_curses();
  4472. }
  4473. }
  4474. #endif
  4475. void enable_pool(struct pool * const pool)
  4476. {
  4477. if (pool->enabled != POOL_ENABLED) {
  4478. mutex_lock(&lp_lock);
  4479. enabled_pools++;
  4480. pool->enabled = POOL_ENABLED;
  4481. pthread_cond_broadcast(&lp_cond);
  4482. mutex_unlock(&lp_lock);
  4483. if (pool->prio < current_pool()->prio)
  4484. switch_pools(pool);
  4485. }
  4486. }
  4487. void manual_enable_pool(struct pool * const pool)
  4488. {
  4489. pool->failover_only = false;
  4490. BFGINIT(pool->quota, 1);
  4491. enable_pool(pool);
  4492. }
  4493. void disable_pool(struct pool * const pool, const enum pool_enable enable_status)
  4494. {
  4495. if (pool->enabled == POOL_DISABLED)
  4496. /* had been manually disabled before */
  4497. return;
  4498. if (pool->enabled != POOL_ENABLED)
  4499. {
  4500. /* has been programmatically disabled already, just change to the new status directly */
  4501. pool->enabled = enable_status;
  4502. return;
  4503. }
  4504. /* Fall into the lock area */
  4505. mutex_lock(&lp_lock);
  4506. --enabled_pools;
  4507. pool->enabled = enable_status;
  4508. mutex_unlock(&lp_lock);
  4509. if (pool == current_pool())
  4510. switch_pools(NULL);
  4511. }
  4512. static
  4513. void share_result_msg(const struct work *work, const char *disp, const char *reason, bool resubmit, const char *worktime) {
  4514. struct cgpu_info *cgpu;
  4515. const struct mining_algorithm * const malgo = work_mining_algorithm(work);
  4516. const unsigned char *hashpart = &work->hash[0x1c - malgo->ui_skip_hash_bytes];
  4517. char shrdiffdisp[ALLOC_H2B_SHORTV];
  4518. const double tgtdiff = work->work_difficulty;
  4519. char tgtdiffdisp[ALLOC_H2B_SHORTV];
  4520. char where[20];
  4521. cgpu = get_thr_cgpu(work->thr_id);
  4522. suffix_string(work->share_diff, shrdiffdisp, sizeof(shrdiffdisp), 0);
  4523. suffix_string(tgtdiff, tgtdiffdisp, sizeof(tgtdiffdisp), 0);
  4524. if (total_pools > 1)
  4525. snprintf(where, sizeof(where), " pool %d", work->pool->pool_no);
  4526. else
  4527. where[0] = '\0';
  4528. applog(LOG_NOTICE, "%s %02x%02x%02x%02x %"PRIprepr"%s Diff %s/%s%s %s%s",
  4529. disp,
  4530. (unsigned)hashpart[3], (unsigned)hashpart[2], (unsigned)hashpart[1], (unsigned)hashpart[0],
  4531. cgpu->proc_repr,
  4532. where,
  4533. shrdiffdisp, tgtdiffdisp,
  4534. reason,
  4535. resubmit ? "(resubmit)" : "",
  4536. worktime
  4537. );
  4538. }
  4539. static bool test_work_current(struct work *);
  4540. static void _submit_work_async(struct work *);
  4541. static
  4542. void maybe_local_submit(const struct work *work)
  4543. {
  4544. #if BLKMAKER_VERSION > 3
  4545. if (unlikely(work->block && work->tr))
  4546. {
  4547. // This is a block with a full template (GBT)
  4548. // Regardless of the result, submit to local bitcoind(s) as well
  4549. struct work *work_cp;
  4550. for (int i = 0; i < total_pools; ++i)
  4551. {
  4552. if (!uri_get_param_bool(pools[i]->rpc_url, "allblocks", false))
  4553. continue;
  4554. applog(LOG_DEBUG, "Attempting submission of full block to pool %d", pools[i]->pool_no);
  4555. work_cp = copy_work(work);
  4556. work_cp->pool = pools[i];
  4557. work_cp->do_foreign_submit = true;
  4558. _submit_work_async(work_cp);
  4559. }
  4560. }
  4561. #endif
  4562. }
  4563. static
  4564. json_t *extract_reject_reason_j(json_t * const val, json_t *res, json_t * const err, const struct work * const work)
  4565. {
  4566. if (json_is_string(res))
  4567. return res;
  4568. if ( (res = json_object_get(val, "reject-reason")) )
  4569. return res;
  4570. if (work->stratum && err && json_is_array(err) && json_array_size(err) >= 2 && (res = json_array_get(err, 1)) && json_is_string(res))
  4571. return res;
  4572. return NULL;
  4573. }
  4574. static
  4575. const char *extract_reject_reason(json_t * const val, json_t *res, json_t * const err, const struct work * const work)
  4576. {
  4577. json_t * const j = extract_reject_reason_j(val, res, err, work);
  4578. return j ? json_string_value(j) : NULL;
  4579. }
  4580. static
  4581. int put_in_parens(char * const buf, const size_t bufsz, const char * const s)
  4582. {
  4583. if (!s)
  4584. {
  4585. if (bufsz)
  4586. buf[0] = '\0';
  4587. return 0;
  4588. }
  4589. int p = snprintf(buf, bufsz, " (%s", s);
  4590. if (p >= bufsz - 1)
  4591. p = bufsz - 2;
  4592. strcpy(&buf[p], ")");
  4593. return p + 1;
  4594. }
  4595. /* Theoretically threads could race when modifying accepted and
  4596. * rejected values but the chance of two submits completing at the
  4597. * same time is zero so there is no point adding extra locking */
  4598. static void
  4599. share_result(json_t *val, json_t *res, json_t *err, const struct work *work,
  4600. /*char *hashshow,*/ bool resubmit, char *worktime)
  4601. {
  4602. struct pool *pool = work->pool;
  4603. struct cgpu_info *cgpu;
  4604. cgpu = get_thr_cgpu(work->thr_id);
  4605. if ((json_is_null(err) || !err) && (json_is_null(res) || json_is_true(res))) {
  4606. struct mining_goal_info * const goal = pool->goal;
  4607. mutex_lock(&stats_lock);
  4608. cgpu->accepted++;
  4609. total_accepted++;
  4610. pool->accepted++;
  4611. cgpu->diff_accepted += work->work_difficulty;
  4612. total_diff_accepted += work->work_difficulty;
  4613. pool->diff_accepted += work->work_difficulty;
  4614. goal->diff_accepted += work->work_difficulty;
  4615. mutex_unlock(&stats_lock);
  4616. pool->seq_rejects = 0;
  4617. cgpu->last_share_pool = pool->pool_no;
  4618. cgpu->last_share_pool_time = time(NULL);
  4619. cgpu->last_share_diff = work->work_difficulty;
  4620. pool->last_share_time = cgpu->last_share_pool_time;
  4621. pool->last_share_diff = work->work_difficulty;
  4622. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  4623. if (!QUIET) {
  4624. share_result_msg(work, "Accepted", "", resubmit, worktime);
  4625. }
  4626. sharelog("accept", work);
  4627. if (opt_shares && total_diff_accepted >= opt_shares) {
  4628. applog(LOG_WARNING, "Successfully mined %g accepted shares as requested and exiting.", opt_shares);
  4629. kill_work();
  4630. return;
  4631. }
  4632. /* Detect if a pool that has been temporarily disabled for
  4633. * continually rejecting shares has started accepting shares.
  4634. * This will only happen with the work returned from a
  4635. * longpoll */
  4636. if (unlikely(pool->enabled == POOL_REJECTING)) {
  4637. applog(LOG_WARNING, "Rejecting pool %d now accepting shares, re-enabling!", pool->pool_no);
  4638. enable_pool(pool);
  4639. }
  4640. if (unlikely(work->block)) {
  4641. // Force moving on to this new block :)
  4642. struct work fakework;
  4643. memset(&fakework, 0, sizeof(fakework));
  4644. fakework.pool = work->pool;
  4645. // Copy block version, bits, and time from share
  4646. memcpy(&fakework.data[ 0], &work->data[ 0], 4);
  4647. memcpy(&fakework.data[68], &work->data[68], 8);
  4648. // Set prevblock to winning hash (swap32'd)
  4649. swap32yes(&fakework.data[4], &work->hash[0], 32 / 4);
  4650. test_work_current(&fakework);
  4651. }
  4652. }
  4653. else
  4654. if (!hash_target_check(work->hash, work->target))
  4655. {
  4656. // This was submitted despite failing the proper target
  4657. // Quietly ignore the reject
  4658. char reason[32];
  4659. put_in_parens(reason, sizeof(reason), extract_reject_reason(val, res, err, work));
  4660. applog(LOG_DEBUG, "Share above target rejected%s by pool %u as expected, ignoring", reason, pool->pool_no);
  4661. } else {
  4662. mutex_lock(&stats_lock);
  4663. cgpu->rejected++;
  4664. total_rejected++;
  4665. pool->rejected++;
  4666. cgpu->diff_rejected += work->work_difficulty;
  4667. total_diff_rejected += work->work_difficulty;
  4668. pool->diff_rejected += work->work_difficulty;
  4669. pool->seq_rejects++;
  4670. mutex_unlock(&stats_lock);
  4671. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  4672. if (!QUIET) {
  4673. char disposition[36] = "reject";
  4674. char reason[32];
  4675. const char *reasontmp = extract_reject_reason(val, res, err, work);
  4676. int n = put_in_parens(reason, sizeof(reason), reasontmp);
  4677. if (reason[0])
  4678. snprintf(&disposition[6], sizeof(disposition) - 6, ":%.*s", n - 3, &reason[2]);
  4679. share_result_msg(work, "Rejected", reason, resubmit, worktime);
  4680. sharelog(disposition, work);
  4681. }
  4682. /* Once we have more than a nominal amount of sequential rejects,
  4683. * at least 10 and more than 3 mins at the current utility,
  4684. * disable the pool because some pool error is likely to have
  4685. * ensued. Do not do this if we know the share just happened to
  4686. * be stale due to networking delays.
  4687. */
  4688. if (pool->seq_rejects > 10 && !work->stale && opt_disable_pool && enabled_pools > 1) {
  4689. double utility = total_accepted / total_secs * 60;
  4690. if (pool->seq_rejects > utility * 3) {
  4691. applog(LOG_WARNING, "Pool %d rejected %d sequential shares, disabling!",
  4692. pool->pool_no, pool->seq_rejects);
  4693. disable_pool(pool, POOL_REJECTING);
  4694. pool->seq_rejects = 0;
  4695. }
  4696. }
  4697. }
  4698. maybe_local_submit(work);
  4699. }
  4700. static char *submit_upstream_work_request(struct work *work)
  4701. {
  4702. char *hexstr = NULL;
  4703. char *s, *sd;
  4704. struct pool *pool = work->pool;
  4705. if (work->tr)
  4706. {
  4707. blktemplate_t * const tmpl = work->tr->tmpl;
  4708. json_t *req;
  4709. unsigned char data[80];
  4710. swap32yes(data, work->data, 80 / 4);
  4711. #if BLKMAKER_VERSION > 3
  4712. if (work->do_foreign_submit)
  4713. req = blkmk_submit_foreign_jansson(tmpl, data, work->dataid, le32toh(*((uint32_t*)&work->data[76])));
  4714. else
  4715. #endif
  4716. req = blkmk_submit_jansson(tmpl, data, work->dataid, le32toh(*((uint32_t*)&work->data[76])));
  4717. s = json_dumps(req, 0);
  4718. json_decref(req);
  4719. sd = malloc(161);
  4720. bin2hex(sd, data, 80);
  4721. } else {
  4722. /* build hex string */
  4723. hexstr = malloc((sizeof(work->data) * 2) + 1);
  4724. bin2hex(hexstr, work->data, sizeof(work->data));
  4725. /* build JSON-RPC request */
  4726. s = strdup("{\"method\": \"getwork\", \"params\": [ \"");
  4727. s = realloc_strcat(s, hexstr);
  4728. s = realloc_strcat(s, "\" ], \"id\":1}");
  4729. free(hexstr);
  4730. sd = s;
  4731. }
  4732. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->rpc_url, sd);
  4733. if (work->tr)
  4734. free(sd);
  4735. else
  4736. s = realloc_strcat(s, "\n");
  4737. return s;
  4738. }
  4739. static bool submit_upstream_work_completed(struct work *work, bool resubmit, struct timeval *ptv_submit, json_t *val) {
  4740. json_t *res, *err;
  4741. bool rc = false;
  4742. int thr_id = work->thr_id;
  4743. struct pool *pool = work->pool;
  4744. struct timeval tv_submit_reply;
  4745. time_t ts_submit_reply;
  4746. char worktime[200] = "";
  4747. cgtime(&tv_submit_reply);
  4748. ts_submit_reply = time(NULL);
  4749. if (unlikely(!val)) {
  4750. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  4751. if (!pool_tset(pool, &pool->submit_fail)) {
  4752. total_ro++;
  4753. pool->remotefail_occasions++;
  4754. applog(LOG_WARNING, "Pool %d communication failure, caching submissions", pool->pool_no);
  4755. }
  4756. goto out;
  4757. } else if (pool_tclear(pool, &pool->submit_fail))
  4758. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  4759. res = json_object_get(val, "result");
  4760. err = json_object_get(val, "error");
  4761. if (!QUIET) {
  4762. if (opt_worktime) {
  4763. char workclone[20];
  4764. struct tm _tm;
  4765. struct tm *tm, tm_getwork, tm_submit_reply;
  4766. tm = &_tm;
  4767. double getwork_time = tdiff((struct timeval *)&(work->tv_getwork_reply),
  4768. (struct timeval *)&(work->tv_getwork));
  4769. double getwork_to_work = tdiff((struct timeval *)&(work->tv_work_start),
  4770. (struct timeval *)&(work->tv_getwork_reply));
  4771. double work_time = tdiff((struct timeval *)&(work->tv_work_found),
  4772. (struct timeval *)&(work->tv_work_start));
  4773. double work_to_submit = tdiff(ptv_submit,
  4774. (struct timeval *)&(work->tv_work_found));
  4775. double submit_time = tdiff(&tv_submit_reply, ptv_submit);
  4776. int diffplaces = 3;
  4777. localtime_r(&work->ts_getwork, tm);
  4778. memcpy(&tm_getwork, tm, sizeof(struct tm));
  4779. localtime_r(&ts_submit_reply, tm);
  4780. memcpy(&tm_submit_reply, tm, sizeof(struct tm));
  4781. if (work->clone) {
  4782. snprintf(workclone, sizeof(workclone), "C:%1.3f",
  4783. tdiff((struct timeval *)&(work->tv_cloned),
  4784. (struct timeval *)&(work->tv_getwork_reply)));
  4785. }
  4786. else
  4787. strcpy(workclone, "O");
  4788. if (work->work_difficulty < 1)
  4789. diffplaces = 6;
  4790. const struct mining_algorithm * const malgo = work_mining_algorithm(work);
  4791. const uint8_t * const prevblkhash = &work->data[4];
  4792. snprintf(worktime, sizeof(worktime),
  4793. " <-%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",
  4794. (unsigned long)be32toh(((uint32_t *)prevblkhash)[7 - malgo->worktime_skip_prevblk_u32]),
  4795. (unsigned long)be32toh(((uint32_t *)prevblkhash)[6 - malgo->worktime_skip_prevblk_u32]),
  4796. work->getwork_mode, diffplaces, work->work_difficulty,
  4797. tm_getwork.tm_hour, tm_getwork.tm_min,
  4798. tm_getwork.tm_sec, getwork_time, workclone,
  4799. getwork_to_work, work_time, work_to_submit, submit_time,
  4800. tm_submit_reply.tm_hour, tm_submit_reply.tm_min,
  4801. tm_submit_reply.tm_sec);
  4802. }
  4803. }
  4804. share_result(val, res, err, work, resubmit, worktime);
  4805. if (!opt_realquiet)
  4806. print_status(thr_id);
  4807. if (!want_per_device_stats) {
  4808. char logline[256];
  4809. struct cgpu_info *cgpu;
  4810. cgpu = get_thr_cgpu(thr_id);
  4811. get_statline(logline, sizeof(logline), cgpu);
  4812. applog(LOG_INFO, "%s", logline);
  4813. }
  4814. json_decref(val);
  4815. rc = true;
  4816. out:
  4817. return rc;
  4818. }
  4819. /* Specifies whether we can use this pool for work or not. */
  4820. static bool pool_unworkable(const struct pool * const pool)
  4821. {
  4822. if (pool->idle)
  4823. return true;
  4824. if (pool->enabled != POOL_ENABLED)
  4825. return true;
  4826. if (pool->has_stratum && !pool->stratum_active)
  4827. return true;
  4828. return false;
  4829. }
  4830. static struct pool *priority_pool(int);
  4831. static bool pool_unusable(struct pool *);
  4832. static
  4833. bool pool_actively_desired(const struct pool * const pool, const struct pool *cp)
  4834. {
  4835. if (pool->enabled != POOL_ENABLED)
  4836. return false;
  4837. if (pool_strategy == POOL_LOADBALANCE && pool->quota)
  4838. return true;
  4839. if (pool_strategy == POOL_BALANCE && !pool->failover_only)
  4840. return true;
  4841. if (!cp)
  4842. cp = current_pool();
  4843. if (pool == cp)
  4844. return true;
  4845. // If we are the highest priority, workable pool for a given algorithm, we are needed
  4846. struct mining_algorithm * const malgo = pool->goal->malgo;
  4847. for (int i = 0; i < total_pools; ++i)
  4848. {
  4849. struct pool * const other_pool = priority_pool(i);
  4850. if (other_pool == pool)
  4851. return true;
  4852. if (pool_unusable(other_pool))
  4853. continue;
  4854. if (other_pool->goal->malgo == malgo)
  4855. break;
  4856. }
  4857. return false;
  4858. }
  4859. static
  4860. bool pool_actively_in_use(const struct pool * const pool, const struct pool *cp)
  4861. {
  4862. return (!pool_unworkable(pool)) && pool_actively_desired(pool, cp);
  4863. }
  4864. static
  4865. bool pool_supports_block_change_notification(struct pool * const pool)
  4866. {
  4867. return pool->has_stratum || pool->lp_url;
  4868. }
  4869. static
  4870. bool pool_has_active_block_change_notification(struct pool * const pool)
  4871. {
  4872. return pool->stratum_active || pool->lp_active;
  4873. }
  4874. static struct pool *_select_longpoll_pool(struct pool *, bool(*)(struct pool *));
  4875. #define select_longpoll_pool(pool) _select_longpoll_pool(pool, pool_supports_block_change_notification)
  4876. #define pool_active_lp_pool(pool) _select_longpoll_pool(pool, pool_has_active_block_change_notification)
  4877. /* In balanced mode, the amount of diff1 solutions per pool is monitored as a
  4878. * rolling average per 10 minutes and if pools start getting more, it biases
  4879. * away from them to distribute work evenly. The share count is reset to the
  4880. * rolling average every 10 minutes to not send all work to one pool after it
  4881. * has been disabled/out for an extended period. */
  4882. static
  4883. struct pool *select_balanced(struct pool *cp, struct mining_algorithm * const malgo)
  4884. {
  4885. int i, lowest = cp->shares;
  4886. struct pool *ret = cp, *failover_pool = NULL;
  4887. for (i = 0; i < total_pools; i++) {
  4888. struct pool *pool = pools[i];
  4889. if (malgo && pool->goal->malgo != malgo)
  4890. continue;
  4891. if (pool_unworkable(pool))
  4892. continue;
  4893. if (pool->failover_only)
  4894. {
  4895. BFGINIT(failover_pool, pool);
  4896. continue;
  4897. }
  4898. if (pool->shares < lowest) {
  4899. lowest = pool->shares;
  4900. ret = pool;
  4901. }
  4902. }
  4903. if (malgo && ret->goal->malgo != malgo)
  4904. // Yes, we want failover_pool even if it's NULL
  4905. ret = failover_pool;
  4906. else
  4907. if (pool_unworkable(ret) && failover_pool)
  4908. ret = failover_pool;
  4909. if (ret)
  4910. ++ret->shares;
  4911. return ret;
  4912. }
  4913. static
  4914. struct pool *select_loadbalance(struct mining_algorithm * const malgo)
  4915. {
  4916. static int rotating_pool = 0;
  4917. struct pool *pool;
  4918. bool avail = false;
  4919. int tested, i, rpsave;
  4920. for (i = 0; i < total_pools; i++) {
  4921. struct pool *tp = pools[i];
  4922. if (tp->quota_used < tp->quota_gcd) {
  4923. avail = true;
  4924. break;
  4925. }
  4926. }
  4927. /* There are no pools with quota, so reset them. */
  4928. if (!avail) {
  4929. for (i = 0; i < total_pools; i++)
  4930. {
  4931. struct pool * const tp = pools[i];
  4932. tp->quota_used -= tp->quota_gcd;
  4933. }
  4934. if (++rotating_pool >= total_pools)
  4935. rotating_pool = 0;
  4936. }
  4937. /* Try to find the first pool in the rotation that is usable */
  4938. // Look for the lowest integer quota_used / quota_gcd in case we are imbalanced by algorithm demands
  4939. struct pool *pool_lowest = NULL;
  4940. int lowest = INT_MAX;
  4941. rpsave = rotating_pool;
  4942. for (tested = 0; tested < total_pools; ++tested)
  4943. {
  4944. pool = pools[rotating_pool];
  4945. if (malgo && pool->goal->malgo != malgo)
  4946. goto continue_tested;
  4947. if (pool->quota_used < pool->quota_gcd)
  4948. {
  4949. ++pool->quota_used;
  4950. if (!pool_unworkable(pool))
  4951. goto out;
  4952. /* Failover-only flag for load-balance means distribute
  4953. * unused quota to priority pool 0. */
  4954. if (opt_fail_only)
  4955. priority_pool(0)->quota_used--;
  4956. }
  4957. if (malgo)
  4958. {
  4959. const int count = pool->quota_used / pool->quota_gcd;
  4960. if (count < lowest)
  4961. {
  4962. pool_lowest = pool;
  4963. lowest = count;
  4964. }
  4965. }
  4966. continue_tested: ;
  4967. if (++rotating_pool >= total_pools)
  4968. rotating_pool = 0;
  4969. }
  4970. // Even if pool_lowest is NULL, we want to return that to indicate failure
  4971. // Note it isn't possible to get here if !malgo
  4972. pool = pool_lowest;
  4973. out: ;
  4974. // Restore rotating_pool static, so malgo searches don't affect the usual load balancing
  4975. if (malgo)
  4976. rotating_pool = rpsave;
  4977. return pool;
  4978. }
  4979. static
  4980. struct pool *select_failover(struct mining_algorithm * const malgo)
  4981. {
  4982. int i;
  4983. for (i = 0; i < total_pools; i++) {
  4984. struct pool *tp = priority_pool(i);
  4985. if (malgo && tp->goal->malgo != malgo)
  4986. continue;
  4987. if (!pool_unusable(tp)) {
  4988. return tp;
  4989. }
  4990. }
  4991. return NULL;
  4992. }
  4993. static bool pool_active(struct pool *, bool pinging);
  4994. static void pool_died(struct pool *);
  4995. /* Select any active pool in a rotating fashion when loadbalance is chosen if
  4996. * it has any quota left. */
  4997. static inline struct pool *select_pool(bool lagging, struct mining_algorithm * const malgo)
  4998. {
  4999. struct pool *pool = NULL, *cp;
  5000. retry:
  5001. cp = current_pool();
  5002. if (pool_strategy == POOL_BALANCE) {
  5003. pool = select_balanced(cp, malgo);
  5004. if ((!pool) || pool_unworkable(pool))
  5005. goto simple_failover;
  5006. goto out;
  5007. }
  5008. if (pool_strategy != POOL_LOADBALANCE && (!lagging || opt_fail_only)) {
  5009. if (malgo && cp->goal->malgo != malgo)
  5010. goto simple_failover;
  5011. pool = cp;
  5012. goto out;
  5013. } else
  5014. pool = select_loadbalance(malgo);
  5015. simple_failover:
  5016. /* If there are no alive pools with quota, choose according to
  5017. * priority. */
  5018. if (!pool) {
  5019. pool = select_failover(malgo);
  5020. }
  5021. /* If still nothing is usable, use the current pool */
  5022. if (!pool)
  5023. {
  5024. if (malgo && cp->goal->malgo != malgo)
  5025. {
  5026. applog(LOG_DEBUG, "Failed to select pool for specific mining algorithm '%s'", malgo->name);
  5027. return NULL;
  5028. }
  5029. pool = cp;
  5030. }
  5031. out:
  5032. if (!pool_actively_in_use(pool, cp))
  5033. {
  5034. if (!pool_active(pool, false))
  5035. {
  5036. pool_died(pool);
  5037. goto retry;
  5038. }
  5039. pool_tclear(pool, &pool->idle);
  5040. }
  5041. applog(LOG_DEBUG, "Selecting pool %d for %s%swork", pool->pool_no, malgo ? malgo->name : "", malgo ? " " : "");
  5042. return pool;
  5043. }
  5044. static double DIFFEXACTONE = 26959946667150639794667015087019630673637144422540572481103610249215.0;
  5045. double target_diff(const unsigned char *target)
  5046. {
  5047. double targ = 0;
  5048. signed int i;
  5049. for (i = 31; i >= 0; --i)
  5050. targ = (targ * 0x100) + target[i];
  5051. return DIFFEXACTONE / (targ ?: 1);
  5052. }
  5053. /*
  5054. * Calculate the work share difficulty
  5055. */
  5056. static void calc_diff(struct work *work, int known)
  5057. {
  5058. struct cgminer_pool_stats *pool_stats = &(work->pool->cgminer_pool_stats);
  5059. double difficulty;
  5060. if (!known) {
  5061. work->work_difficulty = target_diff(work->target);
  5062. } else
  5063. work->work_difficulty = known;
  5064. difficulty = work->work_difficulty;
  5065. pool_stats->last_diff = difficulty;
  5066. suffix_string(difficulty, work->pool->diff, sizeof(work->pool->diff), 0);
  5067. if (difficulty == pool_stats->min_diff)
  5068. pool_stats->min_diff_count++;
  5069. else if (difficulty < pool_stats->min_diff || pool_stats->min_diff == 0) {
  5070. pool_stats->min_diff = difficulty;
  5071. pool_stats->min_diff_count = 1;
  5072. }
  5073. if (difficulty == pool_stats->max_diff)
  5074. pool_stats->max_diff_count++;
  5075. else if (difficulty > pool_stats->max_diff) {
  5076. pool_stats->max_diff = difficulty;
  5077. pool_stats->max_diff_count = 1;
  5078. }
  5079. }
  5080. static void gen_stratum_work(struct pool *, struct work *);
  5081. static void pool_update_work_restart_time(struct pool *);
  5082. static void restart_threads(void);
  5083. static uint32_t benchmark_blkhdr[20];
  5084. static const int benchmark_update_interval = 1;
  5085. static
  5086. void *benchmark_intense_work_update_thread(void *userp)
  5087. {
  5088. pthread_detach(pthread_self());
  5089. RenameThread("benchmark-intense");
  5090. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  5091. struct pool * const pool = userp;
  5092. struct stratum_work * const swork = &pool->swork;
  5093. uint8_t * const blkhdr = swork->header1;
  5094. while (true)
  5095. {
  5096. sleep(benchmark_update_interval);
  5097. cg_wlock(&pool->data_lock);
  5098. for (int i = 36; --i >= 0; )
  5099. if (++blkhdr[i])
  5100. break;
  5101. cg_wunlock(&pool->data_lock);
  5102. struct work *work = make_work();
  5103. gen_stratum_work(pool, work);
  5104. pool->swork.work_restart_id = ++pool->work_restart_id;
  5105. pool_update_work_restart_time(pool);
  5106. test_work_current(work);
  5107. free_work(work);
  5108. restart_threads();
  5109. }
  5110. return NULL;
  5111. }
  5112. static
  5113. void setup_benchmark_pool()
  5114. {
  5115. struct pool *pool;
  5116. want_longpoll = false;
  5117. // Temporarily disable opt_benchmark to avoid auto-removal
  5118. opt_benchmark = false;
  5119. pool = add_pool();
  5120. opt_benchmark = true;
  5121. pool->rpc_url = malloc(255);
  5122. strcpy(pool->rpc_url, "Benchmark");
  5123. pool_set_uri(pool, pool->rpc_url);
  5124. pool->rpc_user = pool->rpc_url;
  5125. pool->rpc_pass = pool->rpc_url;
  5126. enable_pool(pool);
  5127. pool->idle = false;
  5128. successful_connect = true;
  5129. {
  5130. uint32_t * const blkhdr = benchmark_blkhdr;
  5131. blkhdr[2] = htobe32(1);
  5132. blkhdr[17] = htobe32(0x7fffffff); // timestamp
  5133. blkhdr[18] = htobe32(0x1700ffff); // "bits"
  5134. }
  5135. {
  5136. struct stratum_work * const swork = &pool->swork;
  5137. const int branchcount = 15; // 1 MB block
  5138. const size_t branchdatasz = branchcount * 0x20;
  5139. const size_t coinbase_sz = (opt_benchmark_intense ? 250 : 6) * 1024;
  5140. bytes_resize(&swork->coinbase, coinbase_sz);
  5141. memset(bytes_buf(&swork->coinbase), '\xff', coinbase_sz);
  5142. swork->nonce2_offset = 0;
  5143. bytes_resize(&swork->merkle_bin, branchdatasz);
  5144. memset(bytes_buf(&swork->merkle_bin), '\xff', branchdatasz);
  5145. swork->merkles = branchcount;
  5146. swork->header1[0] = '\xff';
  5147. memset(&swork->header1[1], '\0', 34);
  5148. swork->header1[35] = '\x01';
  5149. swork->ntime = 0x7fffffff;
  5150. timer_unset(&swork->tv_received);
  5151. memcpy(swork->diffbits, "\x17\0\xff\xff", 4);
  5152. const struct mining_goal_info * const goal = get_mining_goal("default");
  5153. const struct mining_algorithm * const malgo = goal->malgo;
  5154. set_target_to_pdiff(swork->target, malgo->reasonable_low_nonce_diff);
  5155. pool->nonce2sz = swork->n2size = GBT_XNONCESZ;
  5156. pool->nonce2 = 0;
  5157. }
  5158. if (opt_benchmark_intense)
  5159. {
  5160. pthread_t pth;
  5161. if (unlikely(pthread_create(&pth, NULL, benchmark_intense_work_update_thread, pool)))
  5162. applog(LOG_WARNING, "Failed to start benchmark intense work update thread");
  5163. }
  5164. }
  5165. void get_benchmark_work(struct work *work, bool use_swork)
  5166. {
  5167. if (use_swork)
  5168. {
  5169. struct timeval tv_now;
  5170. timer_set_now(&tv_now);
  5171. gen_stratum_work(pools[0], work);
  5172. work->getwork_mode = GETWORK_MODE_BENCHMARK;
  5173. work_set_simple_ntime_roll_limit(work, 0, &tv_now);
  5174. return;
  5175. }
  5176. struct pool * const pool = pools[0];
  5177. uint32_t * const blkhdr = benchmark_blkhdr;
  5178. for (int i = 16; i >= 0; --i)
  5179. if (++blkhdr[i])
  5180. break;
  5181. memcpy(&work->data[ 0], blkhdr, 80);
  5182. memcpy(&work->data[80], workpadding_bin, 48);
  5183. char hex[161];
  5184. bin2hex(hex, work->data, 80);
  5185. applog(LOG_DEBUG, "Generated benchmark header %s", hex);
  5186. calc_midstate(work);
  5187. memcpy(work->target, pool->swork.target, sizeof(work->target));
  5188. work->mandatory = true;
  5189. work->pool = pools[0];
  5190. cgtime(&work->tv_getwork);
  5191. copy_time(&work->tv_getwork_reply, &work->tv_getwork);
  5192. copy_time(&work->tv_staged, &work->tv_getwork);
  5193. work->getwork_mode = GETWORK_MODE_BENCHMARK;
  5194. calc_diff(work, 0);
  5195. work_set_simple_ntime_roll_limit(work, 60, &work->tv_getwork);
  5196. }
  5197. static void wake_gws(void);
  5198. static void update_last_work(struct work *work)
  5199. {
  5200. if (!work->tr)
  5201. // Only save GBT jobs, since rollntime isn't coordinated well yet
  5202. return;
  5203. struct pool *pool = work->pool;
  5204. mutex_lock(&pool->last_work_lock);
  5205. if (pool->last_work_copy)
  5206. free_work(pool->last_work_copy);
  5207. pool->last_work_copy = copy_work(work);
  5208. pool->last_work_copy->work_restart_id = pool->work_restart_id;
  5209. mutex_unlock(&pool->last_work_lock);
  5210. }
  5211. static
  5212. void gbt_req_target(json_t *req)
  5213. {
  5214. json_t *j;
  5215. json_t *n;
  5216. if (!request_target_str)
  5217. return;
  5218. j = json_object_get(req, "params");
  5219. if (!j)
  5220. {
  5221. n = json_array();
  5222. if (!n)
  5223. return;
  5224. if (json_object_set_new(req, "params", n))
  5225. goto erradd;
  5226. j = n;
  5227. }
  5228. n = json_array_get(j, 0);
  5229. if (!n)
  5230. {
  5231. n = json_object();
  5232. if (!n)
  5233. return;
  5234. if (json_array_append_new(j, n))
  5235. goto erradd;
  5236. }
  5237. j = n;
  5238. n = json_string(request_target_str);
  5239. if (!n)
  5240. return;
  5241. if (json_object_set_new(j, "target", n))
  5242. goto erradd;
  5243. return;
  5244. erradd:
  5245. json_decref(n);
  5246. }
  5247. static char *prepare_rpc_req2(struct work *work, enum pool_protocol proto, const char *lpid, bool probe, struct pool * const pool)
  5248. {
  5249. char *rpc_req;
  5250. clean_work(work);
  5251. switch (proto) {
  5252. case PLP_GETWORK:
  5253. work->getwork_mode = GETWORK_MODE_POOL;
  5254. return strdup(getwork_req);
  5255. case PLP_GETBLOCKTEMPLATE:
  5256. work->getwork_mode = GETWORK_MODE_GBT;
  5257. blktemplate_t * const tmpl = blktmpl_create();
  5258. if (!tmpl)
  5259. goto gbtfail2;
  5260. work->tr = tmpl_makeref(tmpl);
  5261. gbt_capabilities_t caps = blktmpl_addcaps(tmpl);
  5262. if (!caps)
  5263. goto gbtfail;
  5264. caps |= GBT_LONGPOLL;
  5265. #if BLKMAKER_VERSION > 1
  5266. const struct mining_goal_info * const goal = pool->goal;
  5267. if (goal->generation_script || goal_has_at_least_one_getcbaddr(goal))
  5268. caps |= GBT_CBVALUE;
  5269. #endif
  5270. json_t *req = blktmpl_request_jansson(caps, lpid);
  5271. if (!req)
  5272. goto gbtfail;
  5273. if (probe)
  5274. gbt_req_target(req);
  5275. rpc_req = json_dumps(req, 0);
  5276. if (!rpc_req)
  5277. goto gbtfail;
  5278. json_decref(req);
  5279. return rpc_req;
  5280. default:
  5281. return NULL;
  5282. }
  5283. return NULL;
  5284. gbtfail:
  5285. tmpl_decref(work->tr);
  5286. work->tr = NULL;
  5287. gbtfail2:
  5288. return NULL;
  5289. }
  5290. #define prepare_rpc_req(work, proto, lpid, pool) prepare_rpc_req2(work, proto, lpid, false, pool)
  5291. #define prepare_rpc_req_probe(work, proto, lpid, pool) prepare_rpc_req2(work, proto, lpid, true, pool)
  5292. static const char *pool_protocol_name(enum pool_protocol proto)
  5293. {
  5294. switch (proto) {
  5295. case PLP_GETBLOCKTEMPLATE:
  5296. return "getblocktemplate";
  5297. case PLP_GETWORK:
  5298. return "getwork";
  5299. default:
  5300. return "UNKNOWN";
  5301. }
  5302. }
  5303. static enum pool_protocol pool_protocol_fallback(enum pool_protocol proto)
  5304. {
  5305. switch (proto) {
  5306. case PLP_GETBLOCKTEMPLATE:
  5307. if (want_getwork)
  5308. return PLP_GETWORK;
  5309. default:
  5310. return PLP_NONE;
  5311. }
  5312. }
  5313. static bool get_upstream_work(struct work *work, CURL *curl)
  5314. {
  5315. struct pool *pool = work->pool;
  5316. struct cgminer_pool_stats *pool_stats = &(pool->cgminer_pool_stats);
  5317. struct timeval tv_elapsed;
  5318. json_t *val = NULL;
  5319. bool rc = false;
  5320. char *url;
  5321. enum pool_protocol proto;
  5322. char *rpc_req;
  5323. if (pool->proto == PLP_NONE)
  5324. pool->proto = PLP_GETBLOCKTEMPLATE;
  5325. tryagain:
  5326. rpc_req = prepare_rpc_req(work, pool->proto, NULL, pool);
  5327. work->pool = pool;
  5328. if (!rpc_req)
  5329. return false;
  5330. applog(LOG_DEBUG, "DBG: sending %s get RPC call: %s", pool->rpc_url, rpc_req);
  5331. url = pool->rpc_url;
  5332. cgtime(&work->tv_getwork);
  5333. val = json_rpc_call(curl, url, pool->rpc_userpass, rpc_req, false,
  5334. false, &work->rolltime, pool, false);
  5335. pool_stats->getwork_attempts++;
  5336. free(rpc_req);
  5337. if (likely(val)) {
  5338. rc = work_decode(pool, work, val);
  5339. if (unlikely(!rc))
  5340. applog(LOG_DEBUG, "Failed to decode work in get_upstream_work");
  5341. } else if (PLP_NONE != (proto = pool_protocol_fallback(pool->proto))) {
  5342. applog(LOG_WARNING, "Pool %u failed getblocktemplate request; falling back to getwork protocol", pool->pool_no);
  5343. pool->proto = proto;
  5344. goto tryagain;
  5345. } else
  5346. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  5347. cgtime(&work->tv_getwork_reply);
  5348. timersub(&(work->tv_getwork_reply), &(work->tv_getwork), &tv_elapsed);
  5349. pool_stats->getwork_wait_rolling += ((double)tv_elapsed.tv_sec + ((double)tv_elapsed.tv_usec / 1000000)) * 0.63;
  5350. pool_stats->getwork_wait_rolling /= 1.63;
  5351. timeradd(&tv_elapsed, &(pool_stats->getwork_wait), &(pool_stats->getwork_wait));
  5352. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_max), >)) {
  5353. pool_stats->getwork_wait_max.tv_sec = tv_elapsed.tv_sec;
  5354. pool_stats->getwork_wait_max.tv_usec = tv_elapsed.tv_usec;
  5355. }
  5356. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_min), <)) {
  5357. pool_stats->getwork_wait_min.tv_sec = tv_elapsed.tv_sec;
  5358. pool_stats->getwork_wait_min.tv_usec = tv_elapsed.tv_usec;
  5359. }
  5360. pool_stats->getwork_calls++;
  5361. work->pool = pool;
  5362. work->longpoll = false;
  5363. calc_diff(work, 0);
  5364. total_getworks++;
  5365. pool->getwork_requested++;
  5366. if (rc)
  5367. update_last_work(work);
  5368. if (likely(val))
  5369. json_decref(val);
  5370. return rc;
  5371. }
  5372. #ifdef HAVE_CURSES
  5373. static void disable_curses(void)
  5374. {
  5375. if (curses_active_locked()) {
  5376. use_curses = false;
  5377. curses_active = false;
  5378. leaveok(logwin, false);
  5379. leaveok(statuswin, false);
  5380. leaveok(mainwin, false);
  5381. nocbreak();
  5382. echo();
  5383. delwin(logwin);
  5384. delwin(statuswin);
  5385. delwin(mainwin);
  5386. endwin();
  5387. #ifdef WIN32
  5388. // Move the cursor to after curses output.
  5389. HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
  5390. CONSOLE_SCREEN_BUFFER_INFO csbi;
  5391. COORD coord;
  5392. if (GetConsoleScreenBufferInfo(hout, &csbi)) {
  5393. coord.X = 0;
  5394. coord.Y = csbi.dwSize.Y - 1;
  5395. SetConsoleCursorPosition(hout, coord);
  5396. }
  5397. #endif
  5398. unlock_curses();
  5399. }
  5400. }
  5401. #endif
  5402. static void __kill_work(void)
  5403. {
  5404. struct cgpu_info *cgpu;
  5405. struct thr_info *thr;
  5406. int i;
  5407. if (!successful_connect)
  5408. return;
  5409. applog(LOG_INFO, "Received kill message");
  5410. shutting_down = true;
  5411. applog(LOG_DEBUG, "Prompting submit_work thread to finish");
  5412. notifier_wake(submit_waiting_notifier);
  5413. #ifdef USE_LIBMICROHTTPD
  5414. httpsrv_stop();
  5415. #endif
  5416. applog(LOG_DEBUG, "Killing off watchpool thread");
  5417. /* Kill the watchpool thread */
  5418. thr = &control_thr[watchpool_thr_id];
  5419. thr_info_cancel(thr);
  5420. applog(LOG_DEBUG, "Killing off watchdog thread");
  5421. /* Kill the watchdog thread */
  5422. thr = &control_thr[watchdog_thr_id];
  5423. thr_info_cancel(thr);
  5424. applog(LOG_DEBUG, "Shutting down mining threads");
  5425. for (i = 0; i < mining_threads; i++) {
  5426. thr = get_thread(i);
  5427. if (!thr)
  5428. continue;
  5429. cgpu = thr->cgpu;
  5430. if (!cgpu)
  5431. continue;
  5432. if (!cgpu->threads)
  5433. continue;
  5434. cgpu->shutdown = true;
  5435. thr->work_restart = true;
  5436. notifier_wake(thr->notifier);
  5437. notifier_wake(thr->work_restart_notifier);
  5438. }
  5439. sleep(1);
  5440. applog(LOG_DEBUG, "Killing off mining threads");
  5441. /* Kill the mining threads*/
  5442. for (i = 0; i < mining_threads; i++) {
  5443. thr = get_thread(i);
  5444. if (!thr)
  5445. continue;
  5446. cgpu = thr->cgpu;
  5447. if (cgpu->threads)
  5448. {
  5449. applog(LOG_WARNING, "Killing %"PRIpreprv, thr->cgpu->proc_repr);
  5450. thr_info_cancel(thr);
  5451. }
  5452. cgpu->status = LIFE_DEAD2;
  5453. }
  5454. /* Stop the others */
  5455. applog(LOG_DEBUG, "Killing off API thread");
  5456. thr = &control_thr[api_thr_id];
  5457. thr_info_cancel(thr);
  5458. }
  5459. /* This should be the common exit path */
  5460. void kill_work(void)
  5461. {
  5462. __kill_work();
  5463. quit(0, "Shutdown signal received.");
  5464. }
  5465. static
  5466. #ifdef WIN32
  5467. #ifndef _WIN64
  5468. const
  5469. #endif
  5470. #endif
  5471. char **initial_args;
  5472. void _bfg_clean_up(bool);
  5473. void app_restart(void)
  5474. {
  5475. applog(LOG_WARNING, "Attempting to restart %s", packagename);
  5476. __kill_work();
  5477. _bfg_clean_up(true);
  5478. #if defined(unix) || defined(__APPLE__)
  5479. if (forkpid > 0) {
  5480. kill(forkpid, SIGTERM);
  5481. forkpid = 0;
  5482. }
  5483. #endif
  5484. execv(initial_args[0], initial_args);
  5485. applog(LOG_WARNING, "Failed to restart application");
  5486. }
  5487. static void sighandler(int __maybe_unused sig)
  5488. {
  5489. /* Restore signal handlers so we can still quit if kill_work fails */
  5490. sigaction(SIGTERM, &termhandler, NULL);
  5491. sigaction(SIGINT, &inthandler, NULL);
  5492. kill_work();
  5493. }
  5494. static void start_longpoll(void);
  5495. static void stop_longpoll(void);
  5496. /* Called with pool_lock held. Recruit an extra curl if none are available for
  5497. * this pool. */
  5498. static void recruit_curl(struct pool *pool)
  5499. {
  5500. struct curl_ent *ce = calloc(sizeof(struct curl_ent), 1);
  5501. if (unlikely(!ce))
  5502. quit(1, "Failed to calloc in recruit_curl");
  5503. ce->curl = curl_easy_init();
  5504. if (unlikely(!ce->curl))
  5505. quit(1, "Failed to init in recruit_curl");
  5506. LL_PREPEND(pool->curllist, ce);
  5507. pool->curls++;
  5508. }
  5509. /* Grab an available curl if there is one. If not, then recruit extra curls
  5510. * unless we are in a submit_fail situation, or we have opt_delaynet enabled
  5511. * and there are already 5 curls in circulation. Limit total number to the
  5512. * number of mining threads per pool as well to prevent blasting a pool during
  5513. * network delays/outages. */
  5514. static struct curl_ent *pop_curl_entry3(struct pool *pool, int blocking)
  5515. {
  5516. int curl_limit = opt_delaynet ? 5 : (mining_threads + opt_queue) * 2;
  5517. bool recruited = false;
  5518. struct curl_ent *ce;
  5519. mutex_lock(&pool->pool_lock);
  5520. retry:
  5521. if (!pool->curls) {
  5522. recruit_curl(pool);
  5523. recruited = true;
  5524. } else if (!pool->curllist) {
  5525. if (blocking < 2 && pool->curls >= curl_limit && (blocking || pool->curls >= opt_submit_threads)) {
  5526. if (!blocking) {
  5527. mutex_unlock(&pool->pool_lock);
  5528. return NULL;
  5529. }
  5530. pthread_cond_wait(&pool->cr_cond, &pool->pool_lock);
  5531. goto retry;
  5532. } else {
  5533. recruit_curl(pool);
  5534. recruited = true;
  5535. }
  5536. }
  5537. ce = pool->curllist;
  5538. LL_DELETE(pool->curllist, ce);
  5539. mutex_unlock(&pool->pool_lock);
  5540. if (recruited)
  5541. applog(LOG_DEBUG, "Recruited curl for pool %d", pool->pool_no);
  5542. return ce;
  5543. }
  5544. static struct curl_ent *pop_curl_entry2(struct pool *pool, bool blocking)
  5545. {
  5546. return pop_curl_entry3(pool, blocking ? 1 : 0);
  5547. }
  5548. __maybe_unused
  5549. static struct curl_ent *pop_curl_entry(struct pool *pool)
  5550. {
  5551. return pop_curl_entry3(pool, 1);
  5552. }
  5553. static void push_curl_entry(struct curl_ent *ce, struct pool *pool)
  5554. {
  5555. mutex_lock(&pool->pool_lock);
  5556. if (!ce || !ce->curl)
  5557. quithere(1, "Attempted to add NULL");
  5558. LL_PREPEND(pool->curllist, ce);
  5559. cgtime(&ce->tv);
  5560. pthread_cond_broadcast(&pool->cr_cond);
  5561. mutex_unlock(&pool->pool_lock);
  5562. }
  5563. bool stale_work(struct work *work, bool share);
  5564. static inline bool should_roll(struct work *work)
  5565. {
  5566. struct timeval now;
  5567. time_t expiry;
  5568. if (!pool_actively_in_use(work->pool, NULL))
  5569. return false;
  5570. if (stale_work(work, false))
  5571. return false;
  5572. if (work->rolltime > opt_scantime)
  5573. expiry = work->rolltime;
  5574. else
  5575. expiry = opt_scantime;
  5576. expiry = expiry * 2 / 3;
  5577. /* We shouldn't roll if we're unlikely to get one shares' duration
  5578. * work out of doing so */
  5579. cgtime(&now);
  5580. if (now.tv_sec - work->tv_staged.tv_sec > expiry)
  5581. return false;
  5582. return true;
  5583. }
  5584. /* Limit rolls to 7000 to not beyond 2 hours in the future where bitcoind will
  5585. * reject blocks as invalid. */
  5586. static inline bool can_roll(struct work *work)
  5587. {
  5588. if (work->stratum)
  5589. return false;
  5590. if (!(work->pool && !work->clone))
  5591. return false;
  5592. if (work->tr)
  5593. {
  5594. if (stale_work(work, false))
  5595. return false;
  5596. return blkmk_work_left(work->tr->tmpl);
  5597. }
  5598. return (work->rolltime &&
  5599. work->rolls < 7000 && !stale_work(work, false));
  5600. }
  5601. static void roll_work(struct work *work)
  5602. {
  5603. if (work->tr)
  5604. {
  5605. struct timeval tv_now;
  5606. cgtime(&tv_now);
  5607. if (blkmk_get_data(work->tr->tmpl, work->data, 80, tv_now.tv_sec, NULL, &work->dataid) < 76)
  5608. applog(LOG_ERR, "Failed to get next data from template; spinning wheels!");
  5609. swap32yes(work->data, work->data, 80 / 4);
  5610. calc_midstate(work);
  5611. applog(LOG_DEBUG, "Successfully rolled extranonce to dataid %u", work->dataid);
  5612. } else {
  5613. uint32_t *work_ntime;
  5614. uint32_t ntime;
  5615. work_ntime = (uint32_t *)(work->data + 68);
  5616. ntime = be32toh(*work_ntime);
  5617. ntime++;
  5618. *work_ntime = htobe32(ntime);
  5619. work_set_simple_ntime_roll_limit(work, 0, &work->ntime_roll_limits.tv_ref);
  5620. applog(LOG_DEBUG, "Successfully rolled time header in work");
  5621. }
  5622. local_work++;
  5623. work->rolls++;
  5624. work->blk.nonce = 0;
  5625. /* This is now a different work item so it needs a different ID for the
  5626. * hashtable */
  5627. work->id = total_work++;
  5628. }
  5629. /* Duplicates any dynamically allocated arrays within the work struct to
  5630. * prevent a copied work struct from freeing ram belonging to another struct */
  5631. static void _copy_work(struct work *work, const struct work *base_work, int noffset)
  5632. {
  5633. int id = work->id;
  5634. clean_work(work);
  5635. memcpy(work, base_work, sizeof(struct work));
  5636. /* Keep the unique new id assigned during make_work to prevent copied
  5637. * work from having the same id. */
  5638. work->id = id;
  5639. if (base_work->job_id)
  5640. work->job_id = strdup(base_work->job_id);
  5641. if (base_work->nonce1)
  5642. work->nonce1 = strdup(base_work->nonce1);
  5643. bytes_cpy(&work->nonce2, &base_work->nonce2);
  5644. if (base_work->tr)
  5645. tmpl_incref(base_work->tr);
  5646. if (noffset)
  5647. {
  5648. uint32_t *work_ntime = (uint32_t *)(work->data + 68);
  5649. uint32_t ntime = be32toh(*work_ntime);
  5650. ntime += noffset;
  5651. *work_ntime = htobe32(ntime);
  5652. }
  5653. if (work->device_data_dup_func)
  5654. work->device_data = work->device_data_dup_func(work);
  5655. }
  5656. /* Generates a copy of an existing work struct, creating fresh heap allocations
  5657. * for all dynamically allocated arrays within the struct. noffset is used for
  5658. * when a driver has internally rolled the ntime, noffset is a relative value.
  5659. * The macro copy_work() calls this function with an noffset of 0. */
  5660. struct work *copy_work_noffset(const struct work *base_work, int noffset)
  5661. {
  5662. struct work *work = make_work();
  5663. _copy_work(work, base_work, noffset);
  5664. return work;
  5665. }
  5666. void __copy_work(struct work *work, const struct work *base_work)
  5667. {
  5668. _copy_work(work, base_work, 0);
  5669. }
  5670. static struct work *make_clone(struct work *work)
  5671. {
  5672. struct work *work_clone = copy_work(work);
  5673. work_clone->clone = true;
  5674. cgtime((struct timeval *)&(work_clone->tv_cloned));
  5675. work_clone->longpoll = false;
  5676. work_clone->mandatory = false;
  5677. /* Make cloned work appear slightly older to bias towards keeping the
  5678. * master work item which can be further rolled */
  5679. work_clone->tv_staged.tv_sec -= 1;
  5680. return work_clone;
  5681. }
  5682. static void stage_work(struct work *work);
  5683. static bool clone_available(void)
  5684. {
  5685. struct work *work_clone = NULL, *work, *tmp;
  5686. bool cloned = false;
  5687. mutex_lock(stgd_lock);
  5688. if (!staged_rollable)
  5689. goto out_unlock;
  5690. HASH_ITER(hh, staged_work, work, tmp) {
  5691. if (can_roll(work) && should_roll(work)) {
  5692. roll_work(work);
  5693. work_clone = make_clone(work);
  5694. applog(LOG_DEBUG, "%s: Rolling work %d to %d", __func__, work->id, work_clone->id);
  5695. roll_work(work);
  5696. cloned = true;
  5697. break;
  5698. }
  5699. }
  5700. out_unlock:
  5701. mutex_unlock(stgd_lock);
  5702. if (cloned) {
  5703. applog(LOG_DEBUG, "Pushing cloned available work to stage thread");
  5704. stage_work(work_clone);
  5705. }
  5706. return cloned;
  5707. }
  5708. static void pool_died(struct pool *pool)
  5709. {
  5710. mutex_lock(&lp_lock);
  5711. if (!pool_tset(pool, &pool->idle)) {
  5712. cgtime(&pool->tv_idle);
  5713. pthread_cond_broadcast(&lp_cond);
  5714. mutex_unlock(&lp_lock);
  5715. if (pool == current_pool()) {
  5716. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  5717. switch_pools(NULL);
  5718. } else
  5719. applog(LOG_INFO, "Pool %d %s failed to return work", pool->pool_no, pool->rpc_url);
  5720. }
  5721. else
  5722. mutex_unlock(&lp_lock);
  5723. }
  5724. bool stale_work(struct work *work, bool share)
  5725. {
  5726. unsigned work_expiry;
  5727. struct pool *pool;
  5728. uint32_t block_id;
  5729. unsigned getwork_delay;
  5730. block_id = ((uint32_t*)work->data)[1];
  5731. pool = work->pool;
  5732. struct mining_goal_info * const goal = pool->goal;
  5733. struct blockchain_info * const blkchain = goal->blkchain;
  5734. /* Technically the rolltime should be correct but some pools
  5735. * advertise a broken expire= that is lower than a meaningful
  5736. * scantime */
  5737. if (work->rolltime >= opt_scantime || work->tr)
  5738. work_expiry = work->rolltime;
  5739. else
  5740. work_expiry = opt_expiry;
  5741. unsigned max_expiry = (goal->have_longpoll ? opt_expiry_lp : opt_expiry);
  5742. if (work_expiry > max_expiry)
  5743. work_expiry = max_expiry;
  5744. if (share) {
  5745. /* If the share isn't on this pool's latest block, it's stale */
  5746. if (pool->block_id && pool->block_id != block_id)
  5747. {
  5748. applog(LOG_DEBUG, "Share stale due to block mismatch (%08lx != %08lx)", (long)block_id, (long)pool->block_id);
  5749. return true;
  5750. }
  5751. /* If the pool doesn't want old shares, then any found in work before
  5752. * the most recent longpoll is stale */
  5753. if ((!pool->submit_old) && work->work_restart_id != pool->work_restart_id)
  5754. {
  5755. applog(LOG_DEBUG, "Share stale due to mandatory work update (%02x != %02x)", work->work_restart_id, pool->work_restart_id);
  5756. return true;
  5757. }
  5758. } else {
  5759. /* If this work isn't for the latest Bitcoin block, it's stale */
  5760. /* But only care about the current pool if failover-only */
  5761. if (enabled_pools <= 1 || opt_fail_only) {
  5762. if (pool->block_id && block_id != pool->block_id)
  5763. {
  5764. 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);
  5765. return true;
  5766. }
  5767. } else {
  5768. if (block_id != blkchain->currentblk->block_id)
  5769. {
  5770. 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);
  5771. return true;
  5772. }
  5773. }
  5774. /* If the pool has asked us to restart since this work, it's stale */
  5775. if (work->work_restart_id != pool->work_restart_id)
  5776. {
  5777. applog(LOG_DEBUG, "Work stale due to work update (%02x != %02x)", work->work_restart_id, pool->work_restart_id);
  5778. return true;
  5779. }
  5780. if (pool->has_stratum && work->job_id) {
  5781. bool same_job;
  5782. if (!pool->stratum_active || !pool->stratum_notify) {
  5783. applog(LOG_DEBUG, "Work stale due to stratum inactive");
  5784. return true;
  5785. }
  5786. same_job = true;
  5787. cg_rlock(&pool->data_lock);
  5788. if (strcmp(work->job_id, pool->swork.job_id))
  5789. same_job = false;
  5790. cg_runlock(&pool->data_lock);
  5791. if (!same_job) {
  5792. applog(LOG_DEBUG, "Work stale due to stratum job_id mismatch");
  5793. return true;
  5794. }
  5795. }
  5796. /* Factor in the average getwork delay of this pool, rounding it up to
  5797. * the nearest second */
  5798. getwork_delay = pool->cgminer_pool_stats.getwork_wait_rolling * 5 + 1;
  5799. if (unlikely(work_expiry <= getwork_delay + 5))
  5800. work_expiry = 5;
  5801. else
  5802. work_expiry -= getwork_delay;
  5803. }
  5804. int elapsed_since_staged = timer_elapsed(&work->tv_staged, NULL);
  5805. if (elapsed_since_staged > work_expiry) {
  5806. applog(LOG_DEBUG, "%s stale due to expiry (%d >= %u)", share?"Share":"Work", elapsed_since_staged, work_expiry);
  5807. return true;
  5808. }
  5809. /* If the user only wants strict failover, any work from a pool other than
  5810. * the current one is always considered stale */
  5811. if (opt_fail_only && !share && !work->mandatory && !pool_actively_in_use(pool, NULL))
  5812. {
  5813. applog(LOG_DEBUG, "Work stale due to fail only pool mismatch (pool %u vs %u)", pool->pool_no, current_pool()->pool_no);
  5814. return true;
  5815. }
  5816. return false;
  5817. }
  5818. double share_diff(const struct work *work)
  5819. {
  5820. double ret;
  5821. bool new_best = false;
  5822. ret = target_diff(work->hash);
  5823. cg_wlock(&control_lock);
  5824. if (unlikely(ret > best_diff)) {
  5825. new_best = true;
  5826. best_diff = ret;
  5827. suffix_string(best_diff, best_share, sizeof(best_share), 0);
  5828. }
  5829. if (unlikely(ret > work->pool->best_diff))
  5830. work->pool->best_diff = ret;
  5831. cg_wunlock(&control_lock);
  5832. if (unlikely(new_best))
  5833. applog(LOG_INFO, "New best share: %s", best_share);
  5834. return ret;
  5835. }
  5836. static
  5837. void work_check_for_block(struct work * const work)
  5838. {
  5839. struct pool * const pool = work->pool;
  5840. struct mining_goal_info * const goal = pool->goal;
  5841. work->share_diff = share_diff(work);
  5842. if (unlikely(work->share_diff >= goal->current_diff)) {
  5843. work->block = true;
  5844. work->pool->solved++;
  5845. found_blocks++;
  5846. work->mandatory = true;
  5847. applog(LOG_NOTICE, "Found block for pool %d!", work->pool->pool_no);
  5848. }
  5849. }
  5850. static void submit_discard_share2(const char *reason, struct work *work)
  5851. {
  5852. struct cgpu_info *cgpu = get_thr_cgpu(work->thr_id);
  5853. sharelog(reason, work);
  5854. mutex_lock(&stats_lock);
  5855. ++total_stale;
  5856. ++cgpu->stale;
  5857. ++(work->pool->stale_shares);
  5858. total_diff_stale += work->work_difficulty;
  5859. cgpu->diff_stale += work->work_difficulty;
  5860. work->pool->diff_stale += work->work_difficulty;
  5861. mutex_unlock(&stats_lock);
  5862. }
  5863. static void submit_discard_share(struct work *work)
  5864. {
  5865. submit_discard_share2("discard", work);
  5866. }
  5867. struct submit_work_state {
  5868. struct work *work;
  5869. bool resubmit;
  5870. struct curl_ent *ce;
  5871. int failures;
  5872. struct timeval tv_staleexpire;
  5873. char *s;
  5874. struct timeval tv_submit;
  5875. struct submit_work_state *next;
  5876. };
  5877. static int my_curl_timer_set(__maybe_unused CURLM *curlm, long timeout_ms, void *userp)
  5878. {
  5879. long *p_timeout_us = userp;
  5880. const long max_ms = LONG_MAX / 1000;
  5881. if (max_ms < timeout_ms)
  5882. timeout_ms = max_ms;
  5883. *p_timeout_us = timeout_ms * 1000;
  5884. return 0;
  5885. }
  5886. static void sws_has_ce(struct submit_work_state *sws)
  5887. {
  5888. struct pool *pool = sws->work->pool;
  5889. sws->s = submit_upstream_work_request(sws->work);
  5890. cgtime(&sws->tv_submit);
  5891. json_rpc_call_async(sws->ce->curl, pool->rpc_url, pool->rpc_userpass, sws->s, false, pool, true, sws);
  5892. }
  5893. static struct submit_work_state *begin_submission(struct work *work)
  5894. {
  5895. struct pool *pool;
  5896. struct submit_work_state *sws = NULL;
  5897. pool = work->pool;
  5898. sws = malloc(sizeof(*sws));
  5899. *sws = (struct submit_work_state){
  5900. .work = work,
  5901. };
  5902. work_check_for_block(work);
  5903. if (stale_work(work, true)) {
  5904. work->stale = true;
  5905. if (opt_submit_stale)
  5906. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as user requested", pool->pool_no);
  5907. else if (pool->submit_old)
  5908. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as pool requested", pool->pool_no);
  5909. else {
  5910. applog(LOG_NOTICE, "Pool %d stale share detected, discarding", pool->pool_no);
  5911. submit_discard_share(work);
  5912. goto out;
  5913. }
  5914. timer_set_delay_from_now(&sws->tv_staleexpire, 300000000);
  5915. }
  5916. if (work->stratum) {
  5917. char *s;
  5918. s = malloc(1024);
  5919. sws->s = s;
  5920. } else {
  5921. /* submit solution to bitcoin via JSON-RPC */
  5922. sws->ce = pop_curl_entry2(pool, false);
  5923. if (sws->ce) {
  5924. sws_has_ce(sws);
  5925. } else {
  5926. sws->next = pool->sws_waiting_on_curl;
  5927. pool->sws_waiting_on_curl = sws;
  5928. if (sws->next)
  5929. applog(LOG_DEBUG, "submit_thread queuing submission");
  5930. else
  5931. applog(LOG_WARNING, "submit_thread queuing submissions (see --submit-threads)");
  5932. }
  5933. }
  5934. return sws;
  5935. out:
  5936. free(sws);
  5937. return NULL;
  5938. }
  5939. static bool retry_submission(struct submit_work_state *sws)
  5940. {
  5941. struct work *work = sws->work;
  5942. struct pool *pool = work->pool;
  5943. sws->resubmit = true;
  5944. if ((!work->stale) && stale_work(work, true)) {
  5945. work->stale = true;
  5946. if (opt_submit_stale)
  5947. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, will retry as user requested", pool->pool_no);
  5948. else if (pool->submit_old)
  5949. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, will retry as pool requested", pool->pool_no);
  5950. else {
  5951. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, discarding", pool->pool_no);
  5952. submit_discard_share(work);
  5953. return false;
  5954. }
  5955. timer_set_delay_from_now(&sws->tv_staleexpire, 300000000);
  5956. }
  5957. if (unlikely((opt_retries >= 0) && (++sws->failures > opt_retries))) {
  5958. applog(LOG_ERR, "Pool %d failed %d submission retries, discarding", pool->pool_no, opt_retries);
  5959. submit_discard_share(work);
  5960. return false;
  5961. }
  5962. else if (work->stale) {
  5963. if (unlikely(opt_retries < 0 && timer_passed(&sws->tv_staleexpire, NULL)))
  5964. {
  5965. applog(LOG_NOTICE, "Pool %d stale share failed to submit for 5 minutes, discarding", pool->pool_no);
  5966. submit_discard_share(work);
  5967. return false;
  5968. }
  5969. }
  5970. /* pause, then restart work-request loop */
  5971. applog(LOG_INFO, "json_rpc_call failed on submit_work, retrying");
  5972. cgtime(&sws->tv_submit);
  5973. json_rpc_call_async(sws->ce->curl, pool->rpc_url, pool->rpc_userpass, sws->s, false, pool, true, sws);
  5974. return true;
  5975. }
  5976. static void free_sws(struct submit_work_state *sws)
  5977. {
  5978. free(sws->s);
  5979. free_work(sws->work);
  5980. free(sws);
  5981. }
  5982. static void *submit_work_thread(__maybe_unused void *userdata)
  5983. {
  5984. int wip = 0;
  5985. CURLM *curlm;
  5986. long curlm_timeout_us = -1;
  5987. struct timeval curlm_timer;
  5988. struct submit_work_state *sws, **swsp;
  5989. struct submit_work_state *write_sws = NULL;
  5990. unsigned tsreduce = 0;
  5991. pthread_detach(pthread_self());
  5992. RenameThread("submit_work");
  5993. applog(LOG_DEBUG, "Creating extra submit work thread");
  5994. curlm = curl_multi_init();
  5995. curlm_timeout_us = -1;
  5996. curl_multi_setopt(curlm, CURLMOPT_TIMERDATA, &curlm_timeout_us);
  5997. curl_multi_setopt(curlm, CURLMOPT_TIMERFUNCTION, my_curl_timer_set);
  5998. fd_set rfds, wfds, efds;
  5999. int maxfd;
  6000. struct timeval tv_timeout, tv_now;
  6001. int n;
  6002. CURLMsg *cm;
  6003. FD_ZERO(&rfds);
  6004. while (1) {
  6005. mutex_lock(&submitting_lock);
  6006. total_submitting -= tsreduce;
  6007. tsreduce = 0;
  6008. if (FD_ISSET(submit_waiting_notifier[0], &rfds)) {
  6009. notifier_read(submit_waiting_notifier);
  6010. }
  6011. // Receive any new submissions
  6012. while (submit_waiting) {
  6013. struct work *work = submit_waiting;
  6014. DL_DELETE(submit_waiting, work);
  6015. if ( (sws = begin_submission(work)) ) {
  6016. if (sws->ce)
  6017. curl_multi_add_handle(curlm, sws->ce->curl);
  6018. else if (sws->s) {
  6019. sws->next = write_sws;
  6020. write_sws = sws;
  6021. }
  6022. ++wip;
  6023. }
  6024. else {
  6025. --total_submitting;
  6026. free_work(work);
  6027. }
  6028. }
  6029. if (unlikely(shutting_down && !wip))
  6030. break;
  6031. mutex_unlock(&submitting_lock);
  6032. FD_ZERO(&rfds);
  6033. FD_ZERO(&wfds);
  6034. FD_ZERO(&efds);
  6035. tv_timeout.tv_sec = -1;
  6036. // Setup cURL with select
  6037. // Need to call perform to ensure the timeout gets updated
  6038. curl_multi_perform(curlm, &n);
  6039. curl_multi_fdset(curlm, &rfds, &wfds, &efds, &maxfd);
  6040. if (curlm_timeout_us >= 0)
  6041. {
  6042. timer_set_delay_from_now(&curlm_timer, curlm_timeout_us);
  6043. reduce_timeout_to(&tv_timeout, &curlm_timer);
  6044. }
  6045. // Setup waiting stratum submissions with select
  6046. for (sws = write_sws; sws; sws = sws->next)
  6047. {
  6048. struct pool *pool = sws->work->pool;
  6049. int fd = pool->sock;
  6050. if (fd == INVSOCK || (!pool->stratum_init) || !pool->stratum_notify)
  6051. continue;
  6052. FD_SET(fd, &wfds);
  6053. set_maxfd(&maxfd, fd);
  6054. }
  6055. // Setup "submit waiting" notifier with select
  6056. FD_SET(submit_waiting_notifier[0], &rfds);
  6057. set_maxfd(&maxfd, submit_waiting_notifier[0]);
  6058. // Wait for something interesting to happen :)
  6059. cgtime(&tv_now);
  6060. if (select(maxfd+1, &rfds, &wfds, &efds, select_timeout(&tv_timeout, &tv_now)) < 0) {
  6061. FD_ZERO(&rfds);
  6062. continue;
  6063. }
  6064. // Handle any stratum ready-to-write results
  6065. for (swsp = &write_sws; (sws = *swsp); ) {
  6066. struct work *work = sws->work;
  6067. struct pool *pool = work->pool;
  6068. int fd = pool->sock;
  6069. bool sessionid_match;
  6070. if (fd == INVSOCK || (!pool->stratum_init) || (!pool->stratum_notify) || !FD_ISSET(fd, &wfds)) {
  6071. next_write_sws:
  6072. // TODO: Check if stale, possibly discard etc
  6073. swsp = &sws->next;
  6074. continue;
  6075. }
  6076. cg_rlock(&pool->data_lock);
  6077. // 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
  6078. // NOTE: Worst case scenario for a false positive: the pool rejects it as H-not-zero
  6079. sessionid_match = (!pool->swork.nonce1) || !strcmp(work->nonce1, pool->swork.nonce1);
  6080. cg_runlock(&pool->data_lock);
  6081. if (!sessionid_match)
  6082. {
  6083. applog(LOG_DEBUG, "No matching session id for resubmitting stratum share");
  6084. submit_discard_share2("disconnect", work);
  6085. ++tsreduce;
  6086. next_write_sws_del:
  6087. // Clear the fd from wfds, to avoid potentially blocking on other submissions to the same socket
  6088. FD_CLR(fd, &wfds);
  6089. // Delete sws for this submission, since we're done with it
  6090. *swsp = sws->next;
  6091. free_sws(sws);
  6092. --wip;
  6093. continue;
  6094. }
  6095. char *s = sws->s;
  6096. struct stratum_share *sshare = calloc(sizeof(struct stratum_share), 1);
  6097. int sshare_id;
  6098. uint32_t nonce;
  6099. char nonce2hex[(bytes_len(&work->nonce2) * 2) + 1];
  6100. char noncehex[9];
  6101. char ntimehex[9];
  6102. sshare->work = copy_work(work);
  6103. bin2hex(nonce2hex, bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  6104. nonce = *((uint32_t *)(work->data + 76));
  6105. bin2hex(noncehex, (const unsigned char *)&nonce, 4);
  6106. bin2hex(ntimehex, (void *)&work->data[68], 4);
  6107. mutex_lock(&sshare_lock);
  6108. /* Give the stratum share a unique id */
  6109. sshare_id =
  6110. sshare->id = swork_id++;
  6111. HASH_ADD_INT(stratum_shares, id, sshare);
  6112. snprintf(s, 1024, "{\"params\": [\"%s\", \"%s\", \"%s\", \"%s\", \"%s\"], \"id\": %d, \"method\": \"mining.submit\"}",
  6113. pool->rpc_user, work->job_id, nonce2hex, ntimehex, noncehex, sshare->id);
  6114. mutex_unlock(&sshare_lock);
  6115. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->stratum_url, s);
  6116. if (likely(stratum_send(pool, s, strlen(s)))) {
  6117. if (pool_tclear(pool, &pool->submit_fail))
  6118. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  6119. applog(LOG_DEBUG, "Successfully submitted, adding to stratum_shares db");
  6120. goto next_write_sws_del;
  6121. } else if (!pool_tset(pool, &pool->submit_fail)) {
  6122. // Undo stuff
  6123. mutex_lock(&sshare_lock);
  6124. // NOTE: Need to find it again in case something else has consumed it already (like the stratum-disconnect resubmitter...)
  6125. HASH_FIND_INT(stratum_shares, &sshare_id, sshare);
  6126. if (sshare)
  6127. HASH_DEL(stratum_shares, sshare);
  6128. mutex_unlock(&sshare_lock);
  6129. if (sshare)
  6130. {
  6131. free_work(sshare->work);
  6132. free(sshare);
  6133. }
  6134. applog(LOG_WARNING, "Pool %d stratum share submission failure", pool->pool_no);
  6135. total_ro++;
  6136. pool->remotefail_occasions++;
  6137. if (!sshare)
  6138. goto next_write_sws_del;
  6139. goto next_write_sws;
  6140. }
  6141. }
  6142. // Handle any cURL activities
  6143. curl_multi_perform(curlm, &n);
  6144. while( (cm = curl_multi_info_read(curlm, &n)) ) {
  6145. if (cm->msg == CURLMSG_DONE)
  6146. {
  6147. bool finished;
  6148. json_t *val = json_rpc_call_completed(cm->easy_handle, cm->data.result, false, NULL, &sws);
  6149. curl_multi_remove_handle(curlm, cm->easy_handle);
  6150. finished = submit_upstream_work_completed(sws->work, sws->resubmit, &sws->tv_submit, val);
  6151. if (!finished) {
  6152. if (retry_submission(sws))
  6153. curl_multi_add_handle(curlm, sws->ce->curl);
  6154. else
  6155. finished = true;
  6156. }
  6157. if (finished) {
  6158. --wip;
  6159. ++tsreduce;
  6160. struct pool *pool = sws->work->pool;
  6161. if (pool->sws_waiting_on_curl) {
  6162. pool->sws_waiting_on_curl->ce = sws->ce;
  6163. sws_has_ce(pool->sws_waiting_on_curl);
  6164. pool->sws_waiting_on_curl = pool->sws_waiting_on_curl->next;
  6165. curl_multi_add_handle(curlm, sws->ce->curl);
  6166. } else {
  6167. push_curl_entry(sws->ce, sws->work->pool);
  6168. }
  6169. free_sws(sws);
  6170. }
  6171. }
  6172. }
  6173. }
  6174. assert(!write_sws);
  6175. mutex_unlock(&submitting_lock);
  6176. curl_multi_cleanup(curlm);
  6177. applog(LOG_DEBUG, "submit_work thread exiting");
  6178. return NULL;
  6179. }
  6180. /* Find the pool that currently has the highest priority */
  6181. static struct pool *priority_pool(int choice)
  6182. {
  6183. struct pool *ret = NULL;
  6184. int i;
  6185. for (i = 0; i < total_pools; i++) {
  6186. struct pool *pool = pools[i];
  6187. if (pool->prio == choice) {
  6188. ret = pool;
  6189. break;
  6190. }
  6191. }
  6192. if (unlikely(!ret)) {
  6193. applog(LOG_ERR, "WTF No pool %d found!", choice);
  6194. return pools[choice];
  6195. }
  6196. return ret;
  6197. }
  6198. int prioritize_pools(char *param, int *pid)
  6199. {
  6200. char *ptr, *next;
  6201. int i, pr, prio = 0;
  6202. if (total_pools == 0) {
  6203. return MSG_NOPOOL;
  6204. }
  6205. if (param == NULL || *param == '\0') {
  6206. return MSG_MISPID;
  6207. }
  6208. bool pools_changed[total_pools];
  6209. int new_prio[total_pools];
  6210. for (i = 0; i < total_pools; ++i)
  6211. pools_changed[i] = false;
  6212. next = param;
  6213. while (next && *next) {
  6214. ptr = next;
  6215. next = strchr(ptr, ',');
  6216. if (next)
  6217. *(next++) = '\0';
  6218. i = atoi(ptr);
  6219. if (i < 0 || i >= total_pools) {
  6220. *pid = i;
  6221. return MSG_INVPID;
  6222. }
  6223. if (pools_changed[i]) {
  6224. *pid = i;
  6225. return MSG_DUPPID;
  6226. }
  6227. pools_changed[i] = true;
  6228. new_prio[i] = prio++;
  6229. }
  6230. // Only change them if no errors
  6231. for (i = 0; i < total_pools; i++) {
  6232. if (pools_changed[i])
  6233. pools[i]->prio = new_prio[i];
  6234. }
  6235. // In priority order, cycle through the unchanged pools and append them
  6236. for (pr = 0; pr < total_pools; pr++)
  6237. for (i = 0; i < total_pools; i++) {
  6238. if (!pools_changed[i] && pools[i]->prio == pr) {
  6239. pools[i]->prio = prio++;
  6240. pools_changed[i] = true;
  6241. break;
  6242. }
  6243. }
  6244. if (current_pool()->prio)
  6245. switch_pools(NULL);
  6246. return MSG_POOLPRIO;
  6247. }
  6248. void validate_pool_priorities(void)
  6249. {
  6250. // TODO: this should probably do some sort of logging
  6251. int i, j;
  6252. bool used[total_pools];
  6253. bool valid[total_pools];
  6254. for (i = 0; i < total_pools; i++)
  6255. used[i] = valid[i] = false;
  6256. for (i = 0; i < total_pools; i++) {
  6257. if (pools[i]->prio >=0 && pools[i]->prio < total_pools) {
  6258. if (!used[pools[i]->prio]) {
  6259. valid[i] = true;
  6260. used[pools[i]->prio] = true;
  6261. }
  6262. }
  6263. }
  6264. for (i = 0; i < total_pools; i++) {
  6265. if (!valid[i]) {
  6266. for (j = 0; j < total_pools; j++) {
  6267. if (!used[j]) {
  6268. applog(LOG_WARNING, "Pool %d priority changed from %d to %d", i, pools[i]->prio, j);
  6269. pools[i]->prio = j;
  6270. used[j] = true;
  6271. break;
  6272. }
  6273. }
  6274. }
  6275. }
  6276. }
  6277. static void clear_pool_work(struct pool *pool);
  6278. /* Specifies whether we can switch to this pool or not. */
  6279. static bool pool_unusable(struct pool *pool)
  6280. {
  6281. if (pool->idle)
  6282. return true;
  6283. if (pool->enabled != POOL_ENABLED)
  6284. return true;
  6285. return false;
  6286. }
  6287. void switch_pools(struct pool *selected)
  6288. {
  6289. struct pool *pool, *last_pool, *failover_pool = NULL;
  6290. int i, pool_no, next_pool;
  6291. if (selected)
  6292. enable_pool(selected);
  6293. cg_wlock(&control_lock);
  6294. last_pool = currentpool;
  6295. pool_no = currentpool->pool_no;
  6296. /* Switch selected to pool number 0 and move the rest down */
  6297. if (selected) {
  6298. if (selected->prio != 0) {
  6299. for (i = 0; i < total_pools; i++) {
  6300. pool = pools[i];
  6301. if (pool->prio < selected->prio)
  6302. pool->prio++;
  6303. }
  6304. selected->prio = 0;
  6305. }
  6306. }
  6307. switch (pool_strategy) {
  6308. /* All of these set to the master pool */
  6309. case POOL_BALANCE:
  6310. case POOL_FAILOVER:
  6311. case POOL_LOADBALANCE:
  6312. for (i = 0; i < total_pools; i++) {
  6313. pool = priority_pool(i);
  6314. if (pool_unusable(pool))
  6315. continue;
  6316. pool_no = pool->pool_no;
  6317. break;
  6318. }
  6319. break;
  6320. /* Both of these simply increment and cycle */
  6321. case POOL_ROUNDROBIN:
  6322. case POOL_ROTATE:
  6323. if (selected && !selected->idle) {
  6324. pool_no = selected->pool_no;
  6325. break;
  6326. }
  6327. next_pool = pool_no;
  6328. /* Select the next alive pool */
  6329. for (i = 1; i < total_pools; i++) {
  6330. next_pool++;
  6331. if (next_pool >= total_pools)
  6332. next_pool = 0;
  6333. pool = pools[next_pool];
  6334. if (pool_unusable(pool))
  6335. continue;
  6336. if (pool->failover_only)
  6337. {
  6338. BFGINIT(failover_pool, pool);
  6339. continue;
  6340. }
  6341. pool_no = next_pool;
  6342. break;
  6343. }
  6344. break;
  6345. default:
  6346. break;
  6347. }
  6348. pool = pools[pool_no];
  6349. if (pool_unusable(pool) && failover_pool)
  6350. pool = failover_pool;
  6351. currentpool = pool;
  6352. cg_wunlock(&control_lock);
  6353. mutex_lock(&lp_lock);
  6354. pthread_cond_broadcast(&lp_cond);
  6355. mutex_unlock(&lp_lock);
  6356. /* Set the lagging flag to avoid pool not providing work fast enough
  6357. * messages in failover only mode since we have to get all fresh work
  6358. * as in restart_threads */
  6359. if (opt_fail_only)
  6360. pool_tset(pool, &pool->lagging);
  6361. if (pool != last_pool)
  6362. {
  6363. pool->block_id = 0;
  6364. if (pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  6365. applog(LOG_WARNING, "Switching to pool %d %s", pool->pool_no, pool->rpc_url);
  6366. if (pool_localgen(pool) || opt_fail_only)
  6367. clear_pool_work(last_pool);
  6368. }
  6369. }
  6370. mutex_lock(&lp_lock);
  6371. pthread_cond_broadcast(&lp_cond);
  6372. mutex_unlock(&lp_lock);
  6373. #ifdef HAVE_CURSES
  6374. update_block_display();
  6375. #endif
  6376. }
  6377. static void discard_work(struct work *work)
  6378. {
  6379. if (!work->clone && !work->rolls && !work->mined) {
  6380. if (work->pool) {
  6381. work->pool->discarded_work++;
  6382. work->pool->quota_used--;
  6383. work->pool->works--;
  6384. }
  6385. total_discarded++;
  6386. applog(LOG_DEBUG, "Discarded work");
  6387. } else
  6388. applog(LOG_DEBUG, "Discarded cloned or rolled work");
  6389. free_work(work);
  6390. }
  6391. static bool work_rollable(struct work *);
  6392. static
  6393. void unstage_work(struct work * const work)
  6394. {
  6395. HASH_DEL(staged_work, work);
  6396. --work_mining_algorithm(work)->staged;
  6397. if (work_rollable(work))
  6398. --staged_rollable;
  6399. if (work->spare)
  6400. --staged_spare;
  6401. staged_full = false;
  6402. }
  6403. static void wake_gws(void)
  6404. {
  6405. mutex_lock(stgd_lock);
  6406. pthread_cond_signal(&gws_cond);
  6407. mutex_unlock(stgd_lock);
  6408. }
  6409. static void discard_stale(void)
  6410. {
  6411. struct work *work, *tmp;
  6412. int stale = 0;
  6413. mutex_lock(stgd_lock);
  6414. HASH_ITER(hh, staged_work, work, tmp) {
  6415. if (stale_work(work, false)) {
  6416. unstage_work(work);
  6417. discard_work(work);
  6418. stale++;
  6419. }
  6420. }
  6421. pthread_cond_signal(&gws_cond);
  6422. mutex_unlock(stgd_lock);
  6423. if (stale)
  6424. applog(LOG_DEBUG, "Discarded %d stales that didn't match current hash", stale);
  6425. }
  6426. bool stale_work_future(struct work *work, bool share, unsigned long ustime)
  6427. {
  6428. bool rv;
  6429. struct timeval tv, orig;
  6430. ldiv_t d;
  6431. d = ldiv(ustime, 1000000);
  6432. tv = (struct timeval){
  6433. .tv_sec = d.quot,
  6434. .tv_usec = d.rem,
  6435. };
  6436. orig = work->tv_staged;
  6437. timersub(&orig, &tv, &work->tv_staged);
  6438. rv = stale_work(work, share);
  6439. work->tv_staged = orig;
  6440. return rv;
  6441. }
  6442. static
  6443. void pool_update_work_restart_time(struct pool * const pool)
  6444. {
  6445. pool->work_restart_time = time(NULL);
  6446. get_timestamp(pool->work_restart_timestamp, sizeof(pool->work_restart_timestamp), pool->work_restart_time);
  6447. }
  6448. static void restart_threads(void)
  6449. {
  6450. struct pool *cp = current_pool();
  6451. int i;
  6452. struct thr_info *thr;
  6453. /* Artificially set the lagging flag to avoid pool not providing work
  6454. * fast enough messages after every long poll */
  6455. pool_tset(cp, &cp->lagging);
  6456. /* Discard staged work that is now stale */
  6457. discard_stale();
  6458. rd_lock(&mining_thr_lock);
  6459. for (i = 0; i < mining_threads; i++)
  6460. {
  6461. thr = mining_thr[i];
  6462. thr->work_restart = true;
  6463. }
  6464. for (i = 0; i < mining_threads; i++)
  6465. {
  6466. thr = mining_thr[i];
  6467. notifier_wake(thr->work_restart_notifier);
  6468. }
  6469. rd_unlock(&mining_thr_lock);
  6470. }
  6471. void blkhashstr(char *rv, const unsigned char *hash)
  6472. {
  6473. unsigned char hash_swap[32];
  6474. swap256(hash_swap, hash);
  6475. swap32tole(hash_swap, hash_swap, 32 / 4);
  6476. bin2hex(rv, hash_swap, 32);
  6477. }
  6478. static
  6479. void set_curblock(struct mining_goal_info * const goal, struct block_info * const blkinfo)
  6480. {
  6481. struct blockchain_info * const blkchain = goal->blkchain;
  6482. blkchain->currentblk = blkinfo;
  6483. blkchain->currentblk_subsidy = 5000000000LL >> (blkinfo->height / 210000);
  6484. cg_wlock(&ch_lock);
  6485. __update_block_title(goal);
  6486. get_timestamp(blkchain->currentblk_first_seen_time_str, sizeof(blkchain->currentblk_first_seen_time_str), blkinfo->first_seen_time);
  6487. cg_wunlock(&ch_lock);
  6488. applog(LOG_INFO, "New block: %s diff %s (%s)", goal->current_goal_detail, goal->current_diff_str, goal->net_hashrate);
  6489. }
  6490. /* Search to see if this prevblkhash has been seen before */
  6491. static
  6492. struct block_info *block_exists(const struct blockchain_info * const blkchain, const void * const prevblkhash)
  6493. {
  6494. struct block_info *s;
  6495. rd_lock(&blk_lock);
  6496. HASH_FIND(hh, blkchain->blocks, prevblkhash, 0x20, s);
  6497. rd_unlock(&blk_lock);
  6498. return s;
  6499. }
  6500. static int block_sort(struct block_info * const blocka, struct block_info * const blockb)
  6501. {
  6502. return blocka->block_seen_order - blockb->block_seen_order;
  6503. }
  6504. static
  6505. void set_blockdiff(struct mining_goal_info * const goal, const struct work * const work)
  6506. {
  6507. unsigned char target[32];
  6508. double diff;
  6509. uint64_t diff64;
  6510. real_block_target(target, work->data);
  6511. diff = target_diff(target);
  6512. diff64 = diff;
  6513. suffix_string(diff64, goal->current_diff_str, sizeof(goal->current_diff_str), 0);
  6514. format_unit2(goal->net_hashrate, sizeof(goal->net_hashrate),
  6515. true, "h/s", H2B_SHORT, diff * 7158278, -1);
  6516. if (unlikely(goal->current_diff != diff))
  6517. applog(LOG_NOTICE, "Network difficulty changed to %s (%s)", goal->current_diff_str, goal->net_hashrate);
  6518. goal->current_diff = diff;
  6519. }
  6520. static bool test_work_current(struct work *work)
  6521. {
  6522. bool ret = true;
  6523. if (work->mandatory)
  6524. return ret;
  6525. uint32_t block_id = ((uint32_t*)(work->data))[1];
  6526. const uint8_t * const prevblkhash = &work->data[4];
  6527. {
  6528. /* Hack to work around dud work sneaking into test */
  6529. bool dudwork = true;
  6530. for (int i = 8; i < 26; ++i)
  6531. if (work->data[i])
  6532. {
  6533. dudwork = false;
  6534. break;
  6535. }
  6536. if (dudwork)
  6537. goto out_free;
  6538. }
  6539. struct pool * const pool = work->pool;
  6540. struct mining_goal_info * const goal = pool->goal;
  6541. struct blockchain_info * const blkchain = goal->blkchain;
  6542. /* Search to see if this block exists yet and if not, consider it a
  6543. * new block and set the current block details to this one */
  6544. if (!block_exists(blkchain, prevblkhash))
  6545. {
  6546. struct block_info * const s = calloc(sizeof(struct block_info), 1);
  6547. int deleted_block = 0;
  6548. ret = false;
  6549. if (unlikely(!s))
  6550. quit (1, "test_work_current OOM");
  6551. memcpy(s->prevblkhash, prevblkhash, sizeof(s->prevblkhash));
  6552. s->block_id = block_id;
  6553. s->block_seen_order = new_blocks++;
  6554. s->first_seen_time = time(NULL);
  6555. wr_lock(&blk_lock);
  6556. /* Only keep the last hour's worth of blocks in memory since
  6557. * work from blocks before this is virtually impossible and we
  6558. * want to prevent memory usage from continually rising */
  6559. if (HASH_COUNT(blkchain->blocks) > 6)
  6560. {
  6561. struct block_info *oldblock;
  6562. HASH_SORT(blkchain->blocks, block_sort);
  6563. oldblock = blkchain->blocks;
  6564. deleted_block = oldblock->block_seen_order;
  6565. HASH_DEL(blkchain->blocks, oldblock);
  6566. free(oldblock);
  6567. }
  6568. HASH_ADD(hh, blkchain->blocks, prevblkhash, sizeof(s->prevblkhash), s);
  6569. set_blockdiff(goal, work);
  6570. wr_unlock(&blk_lock);
  6571. pool->block_id = block_id;
  6572. pool_update_work_restart_time(pool);
  6573. if (deleted_block)
  6574. applog(LOG_DEBUG, "Deleted block %d from database", deleted_block);
  6575. #if BLKMAKER_VERSION > 1
  6576. template_nonce = 0;
  6577. #endif
  6578. set_curblock(goal, s);
  6579. if (unlikely(new_blocks == 1))
  6580. goto out_free;
  6581. if (!work->stratum)
  6582. {
  6583. if (work->longpoll)
  6584. {
  6585. applog(LOG_NOTICE, "Longpoll from pool %d detected new block",
  6586. pool->pool_no);
  6587. }
  6588. else
  6589. if (goal->have_longpoll)
  6590. applog(LOG_NOTICE, "New block detected on network before longpoll");
  6591. else
  6592. applog(LOG_NOTICE, "New block detected on network");
  6593. }
  6594. restart_threads();
  6595. }
  6596. else
  6597. {
  6598. bool restart = false;
  6599. if (unlikely(pool->block_id != block_id))
  6600. {
  6601. bool was_active = pool->block_id != 0;
  6602. pool->block_id = block_id;
  6603. pool_update_work_restart_time(pool);
  6604. if (!work->longpoll)
  6605. update_last_work(work);
  6606. if (was_active)
  6607. {
  6608. // Pool actively changed block
  6609. if (pool == current_pool())
  6610. restart = true;
  6611. if (block_id == blkchain->currentblk->block_id)
  6612. {
  6613. // Caught up, only announce if this pool is the one in use
  6614. if (restart)
  6615. applog(LOG_NOTICE, "%s %d caught up to new block",
  6616. work->longpoll ? "Longpoll from pool" : "Pool",
  6617. pool->pool_no);
  6618. }
  6619. else
  6620. {
  6621. // Switched to a block we know, but not the latest... why?
  6622. // This might detect pools trying to double-spend or 51%,
  6623. // but let's not make any accusations until it's had time
  6624. // in the real world.
  6625. char hexstr[65];
  6626. blkhashstr(hexstr, prevblkhash);
  6627. applog(LOG_WARNING, "%s %d is issuing work for an old block: %s",
  6628. work->longpoll ? "Longpoll from pool" : "Pool",
  6629. pool->pool_no,
  6630. hexstr);
  6631. }
  6632. }
  6633. }
  6634. if (work->longpoll)
  6635. {
  6636. struct pool * const cp = current_pool();
  6637. ++pool->work_restart_id;
  6638. if (work->tr && work->tr == pool->swork.tr)
  6639. pool->swork.work_restart_id = pool->work_restart_id;
  6640. update_last_work(work);
  6641. pool_update_work_restart_time(pool);
  6642. applog(
  6643. ((!opt_quiet_work_updates) && pool_actively_in_use(pool, cp) ? LOG_NOTICE : LOG_DEBUG),
  6644. "Longpoll from pool %d requested work update",
  6645. pool->pool_no);
  6646. if ((!restart) && pool == cp)
  6647. restart = true;
  6648. }
  6649. if (restart)
  6650. restart_threads();
  6651. }
  6652. work->longpoll = false;
  6653. out_free:
  6654. return ret;
  6655. }
  6656. static int tv_sort(struct work *worka, struct work *workb)
  6657. {
  6658. return worka->tv_staged.tv_sec - workb->tv_staged.tv_sec;
  6659. }
  6660. static bool work_rollable(struct work *work)
  6661. {
  6662. return (!work->clone && work->rolltime);
  6663. }
  6664. static bool hash_push(struct work *work)
  6665. {
  6666. bool rc = true;
  6667. mutex_lock(stgd_lock);
  6668. if (work_rollable(work))
  6669. staged_rollable++;
  6670. ++work_mining_algorithm(work)->staged;
  6671. if (work->spare)
  6672. ++staged_spare;
  6673. if (likely(!getq->frozen)) {
  6674. HASH_ADD_INT(staged_work, id, work);
  6675. HASH_SORT(staged_work, tv_sort);
  6676. } else
  6677. rc = false;
  6678. pthread_cond_broadcast(&getq->cond);
  6679. mutex_unlock(stgd_lock);
  6680. return rc;
  6681. }
  6682. static void stage_work(struct work *work)
  6683. {
  6684. applog(LOG_DEBUG, "Pushing work %d from pool %d to hash queue",
  6685. work->id, work->pool->pool_no);
  6686. work->work_restart_id = work->pool->work_restart_id;
  6687. work->pool->last_work_time = time(NULL);
  6688. cgtime(&work->pool->tv_last_work_time);
  6689. test_work_current(work);
  6690. work->pool->works++;
  6691. hash_push(work);
  6692. }
  6693. #ifdef HAVE_CURSES
  6694. int curses_int(const char *query)
  6695. {
  6696. int ret;
  6697. char *cvar;
  6698. cvar = curses_input(query);
  6699. if (unlikely(!cvar))
  6700. return -1;
  6701. ret = atoi(cvar);
  6702. free(cvar);
  6703. return ret;
  6704. }
  6705. #endif
  6706. #ifdef HAVE_CURSES
  6707. static bool input_pool(bool live);
  6708. #endif
  6709. #ifdef HAVE_CURSES
  6710. static void display_pool_summary(struct pool *pool)
  6711. {
  6712. double efficiency = 0.0;
  6713. char xfer[ALLOC_H2B_NOUNIT+ALLOC_H2B_SPACED+4+1], bw[ALLOC_H2B_NOUNIT+ALLOC_H2B_SPACED+6+1];
  6714. int pool_secs;
  6715. if (curses_active_locked()) {
  6716. wlog("Pool: %s Goal: %s\n", pool->rpc_url, pool->goal->name);
  6717. if (pool->solved)
  6718. wlog("SOLVED %d BLOCK%s!\n", pool->solved, pool->solved > 1 ? "S" : "");
  6719. if (!pool->has_stratum)
  6720. wlog("%s own long-poll support\n", pool->lp_url ? "Has" : "Does not have");
  6721. wlog(" Queued work requests: %d\n", pool->getwork_requested);
  6722. wlog(" Share submissions: %d\n", pool->accepted + pool->rejected);
  6723. wlog(" Accepted shares: %d\n", pool->accepted);
  6724. wlog(" Rejected shares: %d + %d stale (%.2f%%)\n",
  6725. pool->rejected, pool->stale_shares,
  6726. (float)(pool->rejected + pool->stale_shares) / (float)(pool->rejected + pool->stale_shares + pool->accepted)
  6727. );
  6728. wlog(" Accepted difficulty shares: %1.f\n", pool->diff_accepted);
  6729. wlog(" Rejected difficulty shares: %1.f\n", pool->diff_rejected);
  6730. pool_secs = timer_elapsed(&pool->cgminer_stats.start_tv, NULL);
  6731. wlog(" Network transfer: %s (%s)\n",
  6732. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  6733. (float)pool->cgminer_pool_stats.net_bytes_received,
  6734. (float)pool->cgminer_pool_stats.net_bytes_sent),
  6735. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  6736. (float)(pool->cgminer_pool_stats.net_bytes_received / pool_secs),
  6737. (float)(pool->cgminer_pool_stats.net_bytes_sent / pool_secs)));
  6738. uint64_t pool_bytes_xfer = pool->cgminer_pool_stats.net_bytes_received + pool->cgminer_pool_stats.net_bytes_sent;
  6739. efficiency = pool_bytes_xfer ? pool->diff_accepted * 2048. / pool_bytes_xfer : 0.0;
  6740. wlog(" Efficiency (accepted * difficulty / 2 KB): %.2f\n", efficiency);
  6741. wlog(" Items worked on: %d\n", pool->works);
  6742. wlog(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  6743. wlog(" Unable to get work from server occasions: %d\n", pool->getfail_occasions);
  6744. wlog(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  6745. unlock_curses();
  6746. }
  6747. }
  6748. #endif
  6749. /* We can't remove the memory used for this struct pool because there may
  6750. * still be work referencing it. We just remove it from the pools list */
  6751. void remove_pool(struct pool *pool)
  6752. {
  6753. int i, last_pool = total_pools - 1;
  6754. struct pool *other;
  6755. disable_pool(pool, POOL_DISABLED);
  6756. /* Boost priority of any lower prio than this one */
  6757. for (i = 0; i < total_pools; i++) {
  6758. other = pools[i];
  6759. if (other->prio > pool->prio)
  6760. other->prio--;
  6761. }
  6762. if (pool->pool_no < last_pool) {
  6763. /* Swap the last pool for this one */
  6764. (pools[last_pool])->pool_no = pool->pool_no;
  6765. pools[pool->pool_no] = pools[last_pool];
  6766. }
  6767. /* Give it an invalid number */
  6768. pool->pool_no = total_pools;
  6769. pool->removed = true;
  6770. pool->has_stratum = false;
  6771. total_pools--;
  6772. }
  6773. /* add a mutex if this needs to be thread safe in the future */
  6774. static struct JE {
  6775. char *buf;
  6776. struct JE *next;
  6777. } *jedata = NULL;
  6778. static void json_escape_free()
  6779. {
  6780. struct JE *jeptr = jedata;
  6781. struct JE *jenext;
  6782. jedata = NULL;
  6783. while (jeptr) {
  6784. jenext = jeptr->next;
  6785. free(jeptr->buf);
  6786. free(jeptr);
  6787. jeptr = jenext;
  6788. }
  6789. }
  6790. static
  6791. char *json_escape(const char *str)
  6792. {
  6793. struct JE *jeptr;
  6794. char *buf, *ptr;
  6795. /* 2x is the max, may as well just allocate that */
  6796. ptr = buf = malloc(strlen(str) * 2 + 1);
  6797. jeptr = malloc(sizeof(*jeptr));
  6798. jeptr->buf = buf;
  6799. jeptr->next = jedata;
  6800. jedata = jeptr;
  6801. while (*str) {
  6802. if (*str == '\\' || *str == '"')
  6803. *(ptr++) = '\\';
  6804. *(ptr++) = *(str++);
  6805. }
  6806. *ptr = '\0';
  6807. return buf;
  6808. }
  6809. static
  6810. void _write_config_string_elist(FILE *fcfg, const char *configname, struct string_elist * const elist)
  6811. {
  6812. if (!elist)
  6813. return;
  6814. static struct string_elist *entry;
  6815. fprintf(fcfg, ",\n\"%s\" : [", configname);
  6816. bool first = true;
  6817. DL_FOREACH(elist, entry)
  6818. {
  6819. const char * const s = entry->string;
  6820. fprintf(fcfg, "%s\n\t\"%s\"", first ? "" : ",", json_escape(s));
  6821. first = false;
  6822. }
  6823. fprintf(fcfg, "\n]");
  6824. }
  6825. void write_config(FILE *fcfg)
  6826. {
  6827. int i;
  6828. /* Write pool values */
  6829. fputs("{\n\"pools\" : [", fcfg);
  6830. for(i = 0; i < total_pools; i++) {
  6831. struct pool *pool = pools[i];
  6832. if (pool->failover_only)
  6833. // Don't write failover-only (automatically added) pools to the config file for now
  6834. continue;
  6835. if (pool->quota != 1) {
  6836. fprintf(fcfg, "%s\n\t{\n\t\t\"quota\" : \"%d;%s\",", i > 0 ? "," : "",
  6837. pool->quota,
  6838. json_escape(pool->rpc_url));
  6839. } else {
  6840. fprintf(fcfg, "%s\n\t{\n\t\t\"url\" : \"%s\",", i > 0 ? "," : "",
  6841. json_escape(pool->rpc_url));
  6842. }
  6843. if (pool->rpc_proxy)
  6844. fprintf(fcfg, "\n\t\t\"pool-proxy\" : \"%s\",", json_escape(pool->rpc_proxy));
  6845. fprintf(fcfg, "\n\t\t\"user\" : \"%s\",", json_escape(pool->rpc_user));
  6846. fprintf(fcfg, "\n\t\t\"pass\" : \"%s\",", json_escape(pool->rpc_pass));
  6847. if (strcmp(pool->goal->name, "default"))
  6848. fprintf(fcfg, "\n\t\t\"pool-goal\" : \"%s\",", pool->goal->name);
  6849. fprintf(fcfg, "\n\t\t\"pool-priority\" : \"%d\"", pool->prio);
  6850. if (pool->force_rollntime)
  6851. fprintf(fcfg, ",\n\t\t\"force-rollntime\" : %d", pool->force_rollntime);
  6852. fprintf(fcfg, "\n\t}");
  6853. }
  6854. fputs("\n]\n", fcfg);
  6855. #ifdef USE_OPENCL
  6856. write_config_opencl(fcfg);
  6857. #endif
  6858. #if defined(USE_CPUMINING) && defined(USE_SHA256D)
  6859. fprintf(fcfg, ",\n\"algo\" : \"%s\"", algo_names[opt_algo]);
  6860. #endif
  6861. /* Simple bool and int options */
  6862. struct opt_table *opt;
  6863. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  6864. char *p, *name = strdup(opt->names);
  6865. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  6866. if (p[1] != '-')
  6867. continue;
  6868. if (opt->type & OPT_NOARG &&
  6869. ((void *)opt->cb == (void *)opt_set_bool || (void *)opt->cb == (void *)opt_set_invbool) &&
  6870. (*(bool *)opt->u.arg == ((void *)opt->cb == (void *)opt_set_bool)))
  6871. fprintf(fcfg, ",\n\"%s\" : true", p+2);
  6872. if (opt->type & OPT_HASARG &&
  6873. ((void *)opt->cb_arg == (void *)set_int_0_to_9999 ||
  6874. (void *)opt->cb_arg == (void *)set_int_1_to_65535 ||
  6875. (void *)opt->cb_arg == (void *)set_int_0_to_10 ||
  6876. (void *)opt->cb_arg == (void *)set_int_1_to_10) &&
  6877. opt->desc != opt_hidden &&
  6878. 0 <= *(int *)opt->u.arg)
  6879. fprintf(fcfg, ",\n\"%s\" : \"%d\"", p+2, *(int *)opt->u.arg);
  6880. }
  6881. }
  6882. /* Special case options */
  6883. if (request_target_str)
  6884. {
  6885. if (request_pdiff == (long)request_pdiff)
  6886. fprintf(fcfg, ",\n\"request-diff\" : %ld", (long)request_pdiff);
  6887. else
  6888. fprintf(fcfg, ",\n\"request-diff\" : %f", request_pdiff);
  6889. }
  6890. fprintf(fcfg, ",\n\"shares\" : %g", opt_shares);
  6891. if (pool_strategy == POOL_BALANCE)
  6892. fputs(",\n\"balance\" : true", fcfg);
  6893. if (pool_strategy == POOL_LOADBALANCE)
  6894. fputs(",\n\"load-balance\" : true", fcfg);
  6895. if (pool_strategy == POOL_ROUNDROBIN)
  6896. fputs(",\n\"round-robin\" : true", fcfg);
  6897. if (pool_strategy == POOL_ROTATE)
  6898. fprintf(fcfg, ",\n\"rotate\" : \"%d\"", opt_rotate_period);
  6899. #if defined(unix) || defined(__APPLE__)
  6900. if (opt_stderr_cmd && *opt_stderr_cmd)
  6901. fprintf(fcfg, ",\n\"monitor\" : \"%s\"", json_escape(opt_stderr_cmd));
  6902. #endif // defined(unix)
  6903. if (opt_kernel_path && *opt_kernel_path) {
  6904. char *kpath = strdup(opt_kernel_path);
  6905. if (kpath[strlen(kpath)-1] == '/')
  6906. kpath[strlen(kpath)-1] = 0;
  6907. fprintf(fcfg, ",\n\"kernel-path\" : \"%s\"", json_escape(kpath));
  6908. free(kpath);
  6909. }
  6910. if (schedstart.enable)
  6911. fprintf(fcfg, ",\n\"sched-time\" : \"%d:%d\"", schedstart.tm.tm_hour, schedstart.tm.tm_min);
  6912. if (schedstop.enable)
  6913. fprintf(fcfg, ",\n\"stop-time\" : \"%d:%d\"", schedstop.tm.tm_hour, schedstop.tm.tm_min);
  6914. if (opt_socks_proxy && *opt_socks_proxy)
  6915. fprintf(fcfg, ",\n\"socks-proxy\" : \"%s\"", json_escape(opt_socks_proxy));
  6916. _write_config_string_elist(fcfg, "scan", scan_devices);
  6917. #ifdef USE_LIBMICROHTTPD
  6918. if (httpsrv_port != -1)
  6919. fprintf(fcfg, ",\n\"http-port\" : %d", httpsrv_port);
  6920. #endif
  6921. #ifdef USE_LIBEVENT
  6922. if (stratumsrv_port != -1)
  6923. fprintf(fcfg, ",\n\"stratum-port\" : %d", stratumsrv_port);
  6924. #endif
  6925. _write_config_string_elist(fcfg, "device", opt_devices_enabled_list);
  6926. _write_config_string_elist(fcfg, "set-device", opt_set_device_list);
  6927. if (opt_api_allow)
  6928. fprintf(fcfg, ",\n\"api-allow\" : \"%s\"", json_escape(opt_api_allow));
  6929. if (strcmp(opt_api_mcast_addr, API_MCAST_ADDR) != 0)
  6930. fprintf(fcfg, ",\n\"api-mcast-addr\" : \"%s\"", json_escape(opt_api_mcast_addr));
  6931. if (strcmp(opt_api_mcast_code, API_MCAST_CODE) != 0)
  6932. fprintf(fcfg, ",\n\"api-mcast-code\" : \"%s\"", json_escape(opt_api_mcast_code));
  6933. if (*opt_api_mcast_des)
  6934. fprintf(fcfg, ",\n\"api-mcast-des\" : \"%s\"", json_escape(opt_api_mcast_des));
  6935. if (strcmp(opt_api_description, PACKAGE_STRING) != 0)
  6936. fprintf(fcfg, ",\n\"api-description\" : \"%s\"", json_escape(opt_api_description));
  6937. if (opt_api_groups)
  6938. fprintf(fcfg, ",\n\"api-groups\" : \"%s\"", json_escape(opt_api_groups));
  6939. fputs("\n}\n", fcfg);
  6940. json_escape_free();
  6941. }
  6942. void zero_bestshare(void)
  6943. {
  6944. int i;
  6945. best_diff = 0;
  6946. suffix_string(best_diff, best_share, sizeof(best_share), 0);
  6947. for (i = 0; i < total_pools; i++) {
  6948. struct pool *pool = pools[i];
  6949. pool->best_diff = 0;
  6950. }
  6951. }
  6952. void zero_stats(void)
  6953. {
  6954. int i;
  6955. applog(LOG_DEBUG, "Zeroing stats");
  6956. cgtime(&total_tv_start);
  6957. miner_started = total_tv_start;
  6958. total_rolling = 0;
  6959. total_mhashes_done = 0;
  6960. total_getworks = 0;
  6961. total_accepted = 0;
  6962. total_rejected = 0;
  6963. hw_errors = 0;
  6964. total_stale = 0;
  6965. total_discarded = 0;
  6966. total_bytes_rcvd = total_bytes_sent = 0;
  6967. new_blocks = 0;
  6968. local_work = 0;
  6969. total_go = 0;
  6970. total_ro = 0;
  6971. total_secs = 1.0;
  6972. total_diff1 = 0;
  6973. total_bad_diff1 = 0;
  6974. found_blocks = 0;
  6975. total_diff_accepted = 0;
  6976. total_diff_rejected = 0;
  6977. total_diff_stale = 0;
  6978. #ifdef HAVE_CURSES
  6979. awidth = rwidth = swidth = hwwidth = 1;
  6980. #endif
  6981. struct mining_goal_info *goal, *tmpgoal;
  6982. HASH_ITER(hh, mining_goals, goal, tmpgoal)
  6983. {
  6984. goal->diff_accepted = 0;
  6985. }
  6986. for (i = 0; i < total_pools; i++) {
  6987. struct pool *pool = pools[i];
  6988. pool->getwork_requested = 0;
  6989. pool->accepted = 0;
  6990. pool->rejected = 0;
  6991. pool->solved = 0;
  6992. pool->getwork_requested = 0;
  6993. pool->stale_shares = 0;
  6994. pool->discarded_work = 0;
  6995. pool->getfail_occasions = 0;
  6996. pool->remotefail_occasions = 0;
  6997. pool->last_share_time = 0;
  6998. pool->works = 0;
  6999. pool->diff1 = 0;
  7000. pool->diff_accepted = 0;
  7001. pool->diff_rejected = 0;
  7002. pool->diff_stale = 0;
  7003. pool->last_share_diff = 0;
  7004. pool->cgminer_stats.start_tv = total_tv_start;
  7005. pool->cgminer_stats.getwork_calls = 0;
  7006. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  7007. pool->cgminer_stats.getwork_wait_max.tv_sec = 0;
  7008. pool->cgminer_stats.getwork_wait_max.tv_usec = 0;
  7009. pool->cgminer_pool_stats.getwork_calls = 0;
  7010. pool->cgminer_pool_stats.getwork_attempts = 0;
  7011. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  7012. pool->cgminer_pool_stats.getwork_wait_max.tv_sec = 0;
  7013. pool->cgminer_pool_stats.getwork_wait_max.tv_usec = 0;
  7014. pool->cgminer_pool_stats.min_diff = 0;
  7015. pool->cgminer_pool_stats.max_diff = 0;
  7016. pool->cgminer_pool_stats.min_diff_count = 0;
  7017. pool->cgminer_pool_stats.max_diff_count = 0;
  7018. pool->cgminer_pool_stats.times_sent = 0;
  7019. pool->cgminer_pool_stats.bytes_sent = 0;
  7020. pool->cgminer_pool_stats.net_bytes_sent = 0;
  7021. pool->cgminer_pool_stats.times_received = 0;
  7022. pool->cgminer_pool_stats.bytes_received = 0;
  7023. pool->cgminer_pool_stats.net_bytes_received = 0;
  7024. }
  7025. zero_bestshare();
  7026. for (i = 0; i < total_devices; ++i) {
  7027. struct cgpu_info *cgpu = get_devices(i);
  7028. mutex_lock(&hash_lock);
  7029. cgpu->total_mhashes = 0;
  7030. cgpu->accepted = 0;
  7031. cgpu->rejected = 0;
  7032. cgpu->stale = 0;
  7033. cgpu->hw_errors = 0;
  7034. cgpu->utility = 0.0;
  7035. cgpu->utility_diff1 = 0;
  7036. cgpu->last_share_pool_time = 0;
  7037. cgpu->bad_diff1 = 0;
  7038. cgpu->diff1 = 0;
  7039. cgpu->diff_accepted = 0;
  7040. cgpu->diff_rejected = 0;
  7041. cgpu->diff_stale = 0;
  7042. cgpu->last_share_diff = 0;
  7043. cgpu->thread_fail_init_count = 0;
  7044. cgpu->thread_zero_hash_count = 0;
  7045. cgpu->thread_fail_queue_count = 0;
  7046. cgpu->dev_sick_idle_60_count = 0;
  7047. cgpu->dev_dead_idle_600_count = 0;
  7048. cgpu->dev_nostart_count = 0;
  7049. cgpu->dev_over_heat_count = 0;
  7050. cgpu->dev_thermal_cutoff_count = 0;
  7051. cgpu->dev_comms_error_count = 0;
  7052. cgpu->dev_throttle_count = 0;
  7053. cgpu->cgminer_stats.start_tv = total_tv_start;
  7054. cgpu->cgminer_stats.getwork_calls = 0;
  7055. cgpu->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  7056. cgpu->cgminer_stats.getwork_wait_max.tv_sec = 0;
  7057. cgpu->cgminer_stats.getwork_wait_max.tv_usec = 0;
  7058. mutex_unlock(&hash_lock);
  7059. if (cgpu->drv->zero_stats)
  7060. cgpu->drv->zero_stats(cgpu);
  7061. }
  7062. }
  7063. #ifdef HAVE_CURSES
  7064. static
  7065. void loginput_mode(const int size)
  7066. {
  7067. clear_logwin();
  7068. loginput_size = size;
  7069. check_winsizes();
  7070. }
  7071. static void display_pools(void)
  7072. {
  7073. struct pool *pool;
  7074. int selected, i, j;
  7075. char input;
  7076. loginput_mode(7 + total_pools);
  7077. immedok(logwin, true);
  7078. updated:
  7079. for (j = 0; j < total_pools; j++) {
  7080. for (i = 0; i < total_pools; i++) {
  7081. pool = pools[i];
  7082. if (pool->prio != j)
  7083. continue;
  7084. if (pool_actively_in_use(pool, NULL))
  7085. wattron(logwin, A_BOLD);
  7086. if (pool->enabled != POOL_ENABLED || pool->failover_only)
  7087. wattron(logwin, A_DIM);
  7088. wlogprint("%d: ", pool->prio);
  7089. switch (pool->enabled) {
  7090. case POOL_ENABLED:
  7091. if ((pool_strategy == POOL_LOADBALANCE) ? (!pool->quota)
  7092. : ((pool_strategy != POOL_FAILOVER) ? pool->failover_only : 0))
  7093. wlogprint("Failover ");
  7094. else
  7095. wlogprint("Enabled ");
  7096. break;
  7097. case POOL_DISABLED:
  7098. wlogprint("Disabled ");
  7099. break;
  7100. case POOL_REJECTING:
  7101. wlogprint("Rejectin ");
  7102. break;
  7103. case POOL_MISBEHAVING:
  7104. wlogprint("Misbehav ");
  7105. break;
  7106. }
  7107. _wlogprint(pool_proto_str(pool));
  7108. wlogprint(" Quota %d Pool %d: %s User:%s\n",
  7109. pool->quota,
  7110. pool->pool_no,
  7111. pool->rpc_url, pool->rpc_user);
  7112. wattroff(logwin, A_BOLD | A_DIM);
  7113. break; //for (i = 0; i < total_pools; i++)
  7114. }
  7115. }
  7116. retry:
  7117. wlogprint("\nCurrent pool management strategy: %s\n",
  7118. strategies[pool_strategy].s);
  7119. if (pool_strategy == POOL_ROTATE)
  7120. wlogprint("Set to rotate every %d minutes\n", opt_rotate_period);
  7121. wlogprint("[F]ailover only %s\n", opt_fail_only ? "enabled" : "disabled");
  7122. wlogprint("Pool [A]dd [R]emove [D]isable [E]nable [P]rioritize [Q]uota change\n");
  7123. wlogprint("[C]hange management strategy [S]witch pool [I]nformation\n");
  7124. wlogprint("Or press any other key to continue\n");
  7125. logwin_update();
  7126. input = getch();
  7127. if (!strncasecmp(&input, "a", 1)) {
  7128. if (opt_benchmark)
  7129. {
  7130. wlogprint("Cannot add pools in benchmark mode");
  7131. goto retry;
  7132. }
  7133. input_pool(true);
  7134. goto updated;
  7135. } else if (!strncasecmp(&input, "r", 1)) {
  7136. if (total_pools <= 1) {
  7137. wlogprint("Cannot remove last pool");
  7138. goto retry;
  7139. }
  7140. selected = curses_int("Select pool number");
  7141. if (selected < 0 || selected >= total_pools) {
  7142. wlogprint("Invalid selection\n");
  7143. goto retry;
  7144. }
  7145. pool = pools[selected];
  7146. if (pool == current_pool())
  7147. switch_pools(NULL);
  7148. if (pool == current_pool()) {
  7149. wlogprint("Unable to remove pool due to activity\n");
  7150. goto retry;
  7151. }
  7152. remove_pool(pool);
  7153. goto updated;
  7154. } else if (!strncasecmp(&input, "s", 1)) {
  7155. selected = curses_int("Select pool number");
  7156. if (selected < 0 || selected >= total_pools) {
  7157. wlogprint("Invalid selection\n");
  7158. goto retry;
  7159. }
  7160. pool = pools[selected];
  7161. manual_enable_pool(pool);
  7162. switch_pools(pool);
  7163. goto updated;
  7164. } else if (!strncasecmp(&input, "d", 1)) {
  7165. if (enabled_pools <= 1) {
  7166. wlogprint("Cannot disable last pool");
  7167. goto retry;
  7168. }
  7169. selected = curses_int("Select pool number");
  7170. if (selected < 0 || selected >= total_pools) {
  7171. wlogprint("Invalid selection\n");
  7172. goto retry;
  7173. }
  7174. pool = pools[selected];
  7175. disable_pool(pool, POOL_DISABLED);
  7176. goto updated;
  7177. } else if (!strncasecmp(&input, "e", 1)) {
  7178. selected = curses_int("Select pool number");
  7179. if (selected < 0 || selected >= total_pools) {
  7180. wlogprint("Invalid selection\n");
  7181. goto retry;
  7182. }
  7183. pool = pools[selected];
  7184. manual_enable_pool(pool);
  7185. goto updated;
  7186. } else if (!strncasecmp(&input, "c", 1)) {
  7187. for (i = 0; i <= TOP_STRATEGY; i++)
  7188. wlogprint("%d: %s\n", i, strategies[i].s);
  7189. selected = curses_int("Select strategy number type");
  7190. if (selected < 0 || selected > TOP_STRATEGY) {
  7191. wlogprint("Invalid selection\n");
  7192. goto retry;
  7193. }
  7194. if (selected == POOL_ROTATE) {
  7195. opt_rotate_period = curses_int("Select interval in minutes");
  7196. if (opt_rotate_period < 0 || opt_rotate_period > 9999) {
  7197. opt_rotate_period = 0;
  7198. wlogprint("Invalid selection\n");
  7199. goto retry;
  7200. }
  7201. }
  7202. mutex_lock(&lp_lock);
  7203. pool_strategy = selected;
  7204. pthread_cond_broadcast(&lp_cond);
  7205. mutex_unlock(&lp_lock);
  7206. switch_pools(NULL);
  7207. goto updated;
  7208. } else if (!strncasecmp(&input, "i", 1)) {
  7209. selected = curses_int("Select pool number");
  7210. if (selected < 0 || selected >= total_pools) {
  7211. wlogprint("Invalid selection\n");
  7212. goto retry;
  7213. }
  7214. pool = pools[selected];
  7215. display_pool_summary(pool);
  7216. goto retry;
  7217. } else if (!strncasecmp(&input, "q", 1)) {
  7218. selected = curses_int("Select pool number");
  7219. if (selected < 0 || selected >= total_pools) {
  7220. wlogprint("Invalid selection\n");
  7221. goto retry;
  7222. }
  7223. pool = pools[selected];
  7224. selected = curses_int("Set quota");
  7225. if (selected < 0) {
  7226. wlogprint("Invalid negative quota\n");
  7227. goto retry;
  7228. }
  7229. if (selected > 0)
  7230. pool->failover_only = false;
  7231. pool->quota = selected;
  7232. adjust_quota_gcd();
  7233. goto updated;
  7234. } else if (!strncasecmp(&input, "f", 1)) {
  7235. opt_fail_only ^= true;
  7236. goto updated;
  7237. } else if (!strncasecmp(&input, "p", 1)) {
  7238. char *prilist = curses_input("Enter new pool priority (comma separated list)");
  7239. if (!prilist)
  7240. {
  7241. wlogprint("Not changing priorities\n");
  7242. goto retry;
  7243. }
  7244. int res = prioritize_pools(prilist, &i);
  7245. free(prilist);
  7246. switch (res) {
  7247. case MSG_NOPOOL:
  7248. wlogprint("No pools\n");
  7249. goto retry;
  7250. case MSG_MISPID:
  7251. wlogprint("Missing pool id parameter\n");
  7252. goto retry;
  7253. case MSG_INVPID:
  7254. wlogprint("Invalid pool id %d - range is 0 - %d\n", i, total_pools - 1);
  7255. goto retry;
  7256. case MSG_DUPPID:
  7257. wlogprint("Duplicate pool specified %d\n", i);
  7258. goto retry;
  7259. case MSG_POOLPRIO:
  7260. default:
  7261. goto updated;
  7262. }
  7263. }
  7264. immedok(logwin, false);
  7265. loginput_mode(0);
  7266. }
  7267. static const char *summary_detail_level_str(void)
  7268. {
  7269. if (opt_compact)
  7270. return "compact";
  7271. if (opt_show_procs)
  7272. return "processors";
  7273. return "devices";
  7274. }
  7275. static void display_options(void)
  7276. {
  7277. int selected;
  7278. char input;
  7279. immedok(logwin, true);
  7280. loginput_mode(12);
  7281. retry:
  7282. clear_logwin();
  7283. wlogprint("[N]ormal [C]lear [S]ilent mode (disable all output)\n");
  7284. wlogprint("[D]ebug:%s\n[P]er-device:%s\n[Q]uiet:%s\n[V]erbose:%s\n"
  7285. "[R]PC debug:%s\n[W]orkTime details:%s\nsu[M]mary detail level:%s\n"
  7286. "[L]og interval:%d\nS[T]atistical counts: %s\n[Z]ero statistics\n",
  7287. opt_debug_console ? "on" : "off",
  7288. want_per_device_stats? "on" : "off",
  7289. opt_quiet ? "on" : "off",
  7290. opt_log_output ? "on" : "off",
  7291. opt_protocol ? "on" : "off",
  7292. opt_worktime ? "on" : "off",
  7293. summary_detail_level_str(),
  7294. opt_log_interval,
  7295. opt_weighed_stats ? "weighed" : "absolute");
  7296. wlogprint("Select an option or any other key to return\n");
  7297. logwin_update();
  7298. input = getch();
  7299. if (!strncasecmp(&input, "q", 1)) {
  7300. opt_quiet ^= true;
  7301. wlogprint("Quiet mode %s\n", opt_quiet ? "enabled" : "disabled");
  7302. goto retry;
  7303. } else if (!strncasecmp(&input, "v", 1)) {
  7304. opt_log_output ^= true;
  7305. if (opt_log_output)
  7306. opt_quiet = false;
  7307. wlogprint("Verbose mode %s\n", opt_log_output ? "enabled" : "disabled");
  7308. goto retry;
  7309. } else if (!strncasecmp(&input, "n", 1)) {
  7310. opt_log_output = false;
  7311. opt_debug_console = false;
  7312. opt_quiet = false;
  7313. opt_protocol = false;
  7314. opt_compact = false;
  7315. opt_show_procs = false;
  7316. devsummaryYOffset = 0;
  7317. want_per_device_stats = false;
  7318. wlogprint("Output mode reset to normal\n");
  7319. switch_logsize();
  7320. goto retry;
  7321. } else if (!strncasecmp(&input, "d", 1)) {
  7322. opt_debug = true;
  7323. opt_debug_console ^= true;
  7324. opt_log_output = opt_debug_console;
  7325. if (opt_debug_console)
  7326. opt_quiet = false;
  7327. wlogprint("Debug mode %s\n", opt_debug_console ? "enabled" : "disabled");
  7328. goto retry;
  7329. } else if (!strncasecmp(&input, "m", 1)) {
  7330. if (opt_compact)
  7331. opt_compact = false;
  7332. else
  7333. if (!opt_show_procs)
  7334. opt_show_procs = true;
  7335. else
  7336. {
  7337. opt_compact = true;
  7338. opt_show_procs = false;
  7339. devsummaryYOffset = 0;
  7340. }
  7341. wlogprint("su[M]mary detail level changed to: %s\n", summary_detail_level_str());
  7342. switch_logsize();
  7343. goto retry;
  7344. } else if (!strncasecmp(&input, "p", 1)) {
  7345. want_per_device_stats ^= true;
  7346. opt_log_output = want_per_device_stats;
  7347. wlogprint("Per-device stats %s\n", want_per_device_stats ? "enabled" : "disabled");
  7348. goto retry;
  7349. } else if (!strncasecmp(&input, "r", 1)) {
  7350. opt_protocol ^= true;
  7351. if (opt_protocol)
  7352. opt_quiet = false;
  7353. wlogprint("RPC protocol debugging %s\n", opt_protocol ? "enabled" : "disabled");
  7354. goto retry;
  7355. } else if (!strncasecmp(&input, "c", 1))
  7356. clear_logwin();
  7357. else if (!strncasecmp(&input, "l", 1)) {
  7358. selected = curses_int("Interval in seconds");
  7359. if (selected < 0 || selected > 9999) {
  7360. wlogprint("Invalid selection\n");
  7361. goto retry;
  7362. }
  7363. opt_log_interval = selected;
  7364. wlogprint("Log interval set to %d seconds\n", opt_log_interval);
  7365. goto retry;
  7366. } else if (!strncasecmp(&input, "s", 1)) {
  7367. opt_realquiet = true;
  7368. } else if (!strncasecmp(&input, "w", 1)) {
  7369. opt_worktime ^= true;
  7370. wlogprint("WorkTime details %s\n", opt_worktime ? "enabled" : "disabled");
  7371. goto retry;
  7372. } else if (!strncasecmp(&input, "t", 1)) {
  7373. opt_weighed_stats ^= true;
  7374. wlogprint("Now displaying %s statistics\n", opt_weighed_stats ? "weighed" : "absolute");
  7375. goto retry;
  7376. } else if (!strncasecmp(&input, "z", 1)) {
  7377. zero_stats();
  7378. goto retry;
  7379. }
  7380. immedok(logwin, false);
  7381. loginput_mode(0);
  7382. }
  7383. #endif
  7384. void default_save_file(char *filename)
  7385. {
  7386. #if defined(unix) || defined(__APPLE__)
  7387. if (getenv("HOME") && *getenv("HOME")) {
  7388. strcpy(filename, getenv("HOME"));
  7389. strcat(filename, "/");
  7390. }
  7391. else
  7392. strcpy(filename, "");
  7393. strcat(filename, ".bfgminer/");
  7394. mkdir(filename, 0777);
  7395. #else
  7396. strcpy(filename, "");
  7397. #endif
  7398. strcat(filename, def_conf);
  7399. }
  7400. #ifdef HAVE_CURSES
  7401. static void set_options(void)
  7402. {
  7403. int selected;
  7404. char input;
  7405. immedok(logwin, true);
  7406. loginput_mode(8);
  7407. retry:
  7408. wlogprint("\n[L]ongpoll: %s\n", want_longpoll ? "On" : "Off");
  7409. wlogprint("[Q]ueue: %d\n[S]cantime: %d\n[E]xpiry: %d\n[R]etries: %d\n"
  7410. "[W]rite config file\n[B]FGMiner restart\n",
  7411. opt_queue, opt_scantime, opt_expiry, opt_retries);
  7412. wlogprint("Select an option or any other key to return\n");
  7413. logwin_update();
  7414. input = getch();
  7415. if (!strncasecmp(&input, "q", 1)) {
  7416. selected = curses_int("Extra work items to queue");
  7417. if (selected < 0 || selected > 9999) {
  7418. wlogprint("Invalid selection\n");
  7419. goto retry;
  7420. }
  7421. opt_queue = selected;
  7422. goto retry;
  7423. } else if (!strncasecmp(&input, "l", 1)) {
  7424. if (want_longpoll)
  7425. stop_longpoll();
  7426. else
  7427. start_longpoll();
  7428. applog(LOG_WARNING, "Longpoll %s", want_longpoll ? "enabled" : "disabled");
  7429. goto retry;
  7430. } else if (!strncasecmp(&input, "s", 1)) {
  7431. selected = curses_int("Set scantime in seconds");
  7432. if (selected < 0 || selected > 9999) {
  7433. wlogprint("Invalid selection\n");
  7434. goto retry;
  7435. }
  7436. opt_scantime = selected;
  7437. goto retry;
  7438. } else if (!strncasecmp(&input, "e", 1)) {
  7439. selected = curses_int("Set expiry time in seconds");
  7440. if (selected < 0 || selected > 9999) {
  7441. wlogprint("Invalid selection\n");
  7442. goto retry;
  7443. }
  7444. opt_expiry = selected;
  7445. goto retry;
  7446. } else if (!strncasecmp(&input, "r", 1)) {
  7447. selected = curses_int("Retries before failing (-1 infinite)");
  7448. if (selected < -1 || selected > 9999) {
  7449. wlogprint("Invalid selection\n");
  7450. goto retry;
  7451. }
  7452. opt_retries = selected;
  7453. goto retry;
  7454. } else if (!strncasecmp(&input, "w", 1)) {
  7455. FILE *fcfg;
  7456. char *str, filename[PATH_MAX], prompt[PATH_MAX + 50];
  7457. default_save_file(filename);
  7458. snprintf(prompt, sizeof(prompt), "Config filename to write (Enter for default) [%s]", filename);
  7459. str = curses_input(prompt);
  7460. if (str) {
  7461. struct stat statbuf;
  7462. strcpy(filename, str);
  7463. free(str);
  7464. if (!stat(filename, &statbuf)) {
  7465. wlogprint("File exists, overwrite?\n");
  7466. input = getch();
  7467. if (strncasecmp(&input, "y", 1))
  7468. goto retry;
  7469. }
  7470. }
  7471. fcfg = fopen(filename, "w");
  7472. if (!fcfg) {
  7473. wlogprint("Cannot open or create file\n");
  7474. goto retry;
  7475. }
  7476. write_config(fcfg);
  7477. fclose(fcfg);
  7478. goto retry;
  7479. } else if (!strncasecmp(&input, "b", 1)) {
  7480. wlogprint("Are you sure?\n");
  7481. input = getch();
  7482. if (!strncasecmp(&input, "y", 1))
  7483. app_restart();
  7484. else
  7485. clear_logwin();
  7486. } else
  7487. clear_logwin();
  7488. loginput_mode(0);
  7489. immedok(logwin, false);
  7490. }
  7491. int scan_serial(const char *);
  7492. static
  7493. void _managetui_msg(const char *repr, const char **msg)
  7494. {
  7495. if (*msg)
  7496. {
  7497. applog(LOG_DEBUG, "ManageTUI: %"PRIpreprv": %s", repr, *msg);
  7498. wattron(logwin, A_BOLD);
  7499. wlogprint("%s", *msg);
  7500. wattroff(logwin, A_BOLD);
  7501. *msg = NULL;
  7502. }
  7503. logwin_update();
  7504. }
  7505. void manage_device(void)
  7506. {
  7507. char logline[256];
  7508. const char *msg = NULL;
  7509. struct cgpu_info *cgpu;
  7510. const struct device_drv *drv;
  7511. selecting_device = true;
  7512. immedok(logwin, true);
  7513. loginput_mode(12);
  7514. devchange:
  7515. if (unlikely(!total_devices))
  7516. {
  7517. clear_logwin();
  7518. wlogprint("(no devices)\n");
  7519. wlogprint("[Plus] Add device(s) [Enter] Close device manager\n");
  7520. _managetui_msg("(none)", &msg);
  7521. int input = getch();
  7522. switch (input)
  7523. {
  7524. case '+': case '=': // add new device
  7525. goto addnew;
  7526. default:
  7527. goto out;
  7528. }
  7529. }
  7530. cgpu = devices[selected_device];
  7531. drv = cgpu->drv;
  7532. refresh_devstatus();
  7533. refresh:
  7534. clear_logwin();
  7535. wlogprint("Select processor to manage using up/down arrow keys\n");
  7536. get_statline3(logline, sizeof(logline), cgpu, true, true);
  7537. wattron(logwin, A_BOLD);
  7538. wlogprint("%s", logline);
  7539. wattroff(logwin, A_BOLD);
  7540. wlogprint("\n");
  7541. if (cgpu->dev_manufacturer)
  7542. wlogprint(" %s from %s\n", (cgpu->dev_product ?: "Device"), cgpu->dev_manufacturer);
  7543. else
  7544. if (cgpu->dev_product)
  7545. wlogprint(" %s\n", cgpu->dev_product);
  7546. if (cgpu->dev_serial)
  7547. wlogprint("Serial: %s\n", cgpu->dev_serial);
  7548. if (cgpu->kname)
  7549. wlogprint("Kernel: %s\n", cgpu->kname);
  7550. if (drv->proc_wlogprint_status && likely(cgpu->status != LIFE_INIT))
  7551. drv->proc_wlogprint_status(cgpu);
  7552. wlogprint("\n");
  7553. // TODO: Last share at TIMESTAMP on pool N
  7554. // TODO: Custom device info/commands
  7555. if (cgpu->deven != DEV_ENABLED)
  7556. wlogprint("[E]nable ");
  7557. if (cgpu->deven != DEV_DISABLED)
  7558. wlogprint("[D]isable ");
  7559. if (drv->identify_device)
  7560. wlogprint("[I]dentify ");
  7561. if (drv->proc_tui_wlogprint_choices && likely(cgpu->status != LIFE_INIT))
  7562. drv->proc_tui_wlogprint_choices(cgpu);
  7563. wlogprint("\n");
  7564. wlogprint("[Slash] Find processor [Plus] Add device(s) [Enter] Close device manager\n");
  7565. _managetui_msg(cgpu->proc_repr, &msg);
  7566. while (true)
  7567. {
  7568. int input = getch();
  7569. applog(LOG_DEBUG, "ManageTUI: %"PRIpreprv": (choice %d)", cgpu->proc_repr, input);
  7570. switch (input) {
  7571. case 'd': case 'D':
  7572. if (cgpu->deven == DEV_DISABLED)
  7573. msg = "Processor already disabled\n";
  7574. else
  7575. {
  7576. cgpu->deven = DEV_DISABLED;
  7577. msg = "Processor being disabled\n";
  7578. }
  7579. goto refresh;
  7580. case 'e': case 'E':
  7581. if (cgpu->deven == DEV_ENABLED)
  7582. msg = "Processor already enabled\n";
  7583. else
  7584. {
  7585. proc_enable(cgpu);
  7586. msg = "Processor being enabled\n";
  7587. }
  7588. goto refresh;
  7589. case 'i': case 'I':
  7590. if (drv->identify_device && drv->identify_device(cgpu))
  7591. msg = "Identify command sent\n";
  7592. else
  7593. goto key_default;
  7594. goto refresh;
  7595. case KEY_DOWN:
  7596. if (selected_device >= total_devices - 1)
  7597. break;
  7598. ++selected_device;
  7599. goto devchange;
  7600. case KEY_UP:
  7601. if (selected_device <= 0)
  7602. break;
  7603. --selected_device;
  7604. goto devchange;
  7605. case KEY_NPAGE:
  7606. {
  7607. if (selected_device >= total_devices - 1)
  7608. break;
  7609. struct cgpu_info *mdev = devices[selected_device]->device;
  7610. do {
  7611. ++selected_device;
  7612. } while (devices[selected_device]->device == mdev && selected_device < total_devices - 1);
  7613. goto devchange;
  7614. }
  7615. case KEY_PPAGE:
  7616. {
  7617. if (selected_device <= 0)
  7618. break;
  7619. struct cgpu_info *mdev = devices[selected_device]->device;
  7620. do {
  7621. --selected_device;
  7622. } while (devices[selected_device]->device == mdev && selected_device > 0);
  7623. goto devchange;
  7624. }
  7625. case '/': case '?': // find device
  7626. {
  7627. static char *pattern = NULL;
  7628. char *newpattern = curses_input("Enter pattern");
  7629. if (newpattern)
  7630. {
  7631. free(pattern);
  7632. pattern = newpattern;
  7633. }
  7634. else
  7635. if (!pattern)
  7636. pattern = calloc(1, 1);
  7637. int match = cgpu_search(pattern, selected_device + 1);
  7638. if (match == -1)
  7639. {
  7640. msg = "Couldn't find device\n";
  7641. goto refresh;
  7642. }
  7643. selected_device = match;
  7644. goto devchange;
  7645. }
  7646. case '+': case '=': // add new device
  7647. {
  7648. addnew:
  7649. clear_logwin();
  7650. _wlogprint(
  7651. "Enter \"auto\", \"all\", or a serial port to probe for mining devices.\n"
  7652. "Prefix by a driver name and colon to only probe a specific driver.\n"
  7653. "For example: erupter:"
  7654. #ifdef WIN32
  7655. "\\\\.\\COM40"
  7656. #elif defined(__APPLE__)
  7657. "/dev/cu.SLAB_USBtoUART"
  7658. #else
  7659. "/dev/ttyUSB39"
  7660. #endif
  7661. "\n"
  7662. );
  7663. char *scanser = curses_input("Enter target");
  7664. if (scan_serial(scanser))
  7665. {
  7666. selected_device = total_devices - 1;
  7667. msg = "Device scan succeeded\n";
  7668. }
  7669. else
  7670. msg = "No new devices found\n";
  7671. goto devchange;
  7672. }
  7673. case 'Q': case 'q':
  7674. case KEY_BREAK: case KEY_BACKSPACE: case KEY_CANCEL: case KEY_CLOSE: case KEY_EXIT:
  7675. case '\x1b': // ESC
  7676. case KEY_ENTER:
  7677. case '\r': // Ctrl-M on Windows, with nonl
  7678. #ifdef PADENTER
  7679. case PADENTER: // pdcurses, used by Enter key on Windows with nonl
  7680. #endif
  7681. case '\n':
  7682. goto out;
  7683. default:
  7684. ;
  7685. key_default:
  7686. if (drv->proc_tui_handle_choice && likely(drv_ready(cgpu)))
  7687. {
  7688. msg = drv->proc_tui_handle_choice(cgpu, input);
  7689. if (msg)
  7690. goto refresh;
  7691. }
  7692. }
  7693. }
  7694. out:
  7695. selecting_device = false;
  7696. loginput_mode(0);
  7697. immedok(logwin, false);
  7698. }
  7699. void show_help(void)
  7700. {
  7701. loginput_mode(11);
  7702. // NOTE: wlogprint is a macro with a buffer limit
  7703. _wlogprint(
  7704. "LU: oldest explicit work update currently being used for new work\n"
  7705. "ST: work in queue | F: network fails | NB: new blocks detected\n"
  7706. "AS: shares being submitted | BW: bandwidth (up/down)\n"
  7707. "E: # shares * diff per 2kB bw | I: expected income | BS: best share ever found\n"
  7708. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7709. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7710. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7711. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_BTEE
  7712. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7713. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7714. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_BTEE U8_HLINE U8_HLINE U8_HLINE
  7715. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7716. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7717. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7718. "\n"
  7719. "devices/processors hashing (only for totals line), hottest temperature\n"
  7720. );
  7721. wlogprint(
  7722. "hashrates: %ds decaying / all-time average / all-time average (effective)\n"
  7723. , opt_log_interval);
  7724. _wlogprint(
  7725. "A: accepted shares | R: rejected+discarded(% of total)\n"
  7726. "HW: hardware errors / % nonces invalid\n"
  7727. "\n"
  7728. "Press any key to clear"
  7729. );
  7730. logwin_update();
  7731. getch();
  7732. loginput_mode(0);
  7733. }
  7734. static void *input_thread(void __maybe_unused *userdata)
  7735. {
  7736. RenameThread("input");
  7737. if (!curses_active)
  7738. return NULL;
  7739. while (1) {
  7740. int input;
  7741. input = getch();
  7742. switch (input) {
  7743. case 'h': case 'H': case '?':
  7744. case KEY_F(1):
  7745. show_help();
  7746. break;
  7747. case 'q': case 'Q':
  7748. kill_work();
  7749. return NULL;
  7750. case 'd': case 'D':
  7751. display_options();
  7752. break;
  7753. case 'm': case 'M':
  7754. manage_device();
  7755. break;
  7756. case 'p': case 'P':
  7757. display_pools();
  7758. break;
  7759. case 's': case 'S':
  7760. set_options();
  7761. break;
  7762. #ifdef HAVE_CURSES
  7763. case KEY_DOWN:
  7764. {
  7765. const int visible_lines = logcursor - devcursor;
  7766. const int invisible_lines = total_lines - visible_lines;
  7767. if (devsummaryYOffset <= -invisible_lines)
  7768. break;
  7769. devsummaryYOffset -= 2;
  7770. }
  7771. case KEY_UP:
  7772. if (devsummaryYOffset == 0)
  7773. break;
  7774. ++devsummaryYOffset;
  7775. refresh_devstatus();
  7776. break;
  7777. case KEY_NPAGE:
  7778. {
  7779. const int visible_lines = logcursor - devcursor;
  7780. const int invisible_lines = total_lines - visible_lines;
  7781. if (devsummaryYOffset - visible_lines <= -invisible_lines)
  7782. devsummaryYOffset = -invisible_lines;
  7783. else
  7784. devsummaryYOffset -= visible_lines;
  7785. refresh_devstatus();
  7786. break;
  7787. }
  7788. case KEY_PPAGE:
  7789. {
  7790. const int visible_lines = logcursor - devcursor;
  7791. if (devsummaryYOffset + visible_lines >= 0)
  7792. devsummaryYOffset = 0;
  7793. else
  7794. devsummaryYOffset += visible_lines;
  7795. refresh_devstatus();
  7796. break;
  7797. }
  7798. #endif
  7799. }
  7800. if (opt_realquiet) {
  7801. disable_curses();
  7802. break;
  7803. }
  7804. }
  7805. return NULL;
  7806. }
  7807. #endif
  7808. static void *api_thread(void *userdata)
  7809. {
  7810. struct thr_info *mythr = userdata;
  7811. pthread_detach(pthread_self());
  7812. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  7813. RenameThread("rpc");
  7814. api(api_thr_id);
  7815. mythr->has_pth = false;
  7816. return NULL;
  7817. }
  7818. void thread_reportin(struct thr_info *thr)
  7819. {
  7820. cgtime(&thr->last);
  7821. thr->cgpu->status = LIFE_WELL;
  7822. thr->getwork = 0;
  7823. thr->cgpu->device_last_well = time(NULL);
  7824. }
  7825. void thread_reportout(struct thr_info *thr)
  7826. {
  7827. thr->getwork = time(NULL);
  7828. }
  7829. static void hashmeter(int thr_id, struct timeval *diff,
  7830. uint64_t hashes_done)
  7831. {
  7832. char logstatusline[256];
  7833. struct timeval temp_tv_end, total_diff;
  7834. double secs;
  7835. double local_secs;
  7836. static double local_mhashes_done = 0;
  7837. double local_mhashes = (double)hashes_done / 1000000.0;
  7838. bool showlog = false;
  7839. char cHr[ALLOC_H2B_NOUNIT+1], aHr[ALLOC_H2B_NOUNIT+1], uHr[ALLOC_H2B_SPACED+3+1];
  7840. char rejpcbuf[6];
  7841. char bnbuf[6];
  7842. struct thr_info *thr;
  7843. /* Update the last time this thread reported in */
  7844. if (thr_id >= 0) {
  7845. thr = get_thread(thr_id);
  7846. cgtime(&(thr->last));
  7847. thr->cgpu->device_last_well = time(NULL);
  7848. }
  7849. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  7850. /* So we can call hashmeter from a non worker thread */
  7851. if (thr_id >= 0) {
  7852. struct cgpu_info *cgpu = thr->cgpu;
  7853. int threadobj = cgpu->threads ?: 1;
  7854. double thread_rolling = 0.0;
  7855. int i;
  7856. applog(LOG_DEBUG, "[thread %d: %"PRIu64" hashes, %.1f khash/sec]",
  7857. thr_id, hashes_done, hashes_done / 1000 / secs);
  7858. /* Rolling average for each thread and each device */
  7859. decay_time(&thr->rolling, local_mhashes / secs, secs);
  7860. for (i = 0; i < threadobj; i++)
  7861. thread_rolling += cgpu->thr[i]->rolling;
  7862. mutex_lock(&hash_lock);
  7863. decay_time(&cgpu->rolling, thread_rolling, secs);
  7864. cgpu->total_mhashes += local_mhashes;
  7865. mutex_unlock(&hash_lock);
  7866. // If needed, output detailed, per-device stats
  7867. if (want_per_device_stats) {
  7868. struct timeval now;
  7869. struct timeval elapsed;
  7870. struct timeval *last_msg_tv = opt_show_procs ? &thr->cgpu->last_message_tv : &thr->cgpu->device->last_message_tv;
  7871. cgtime(&now);
  7872. timersub(&now, last_msg_tv, &elapsed);
  7873. if (opt_log_interval <= elapsed.tv_sec) {
  7874. struct cgpu_info *cgpu = thr->cgpu;
  7875. char logline[255];
  7876. *last_msg_tv = now;
  7877. get_statline(logline, sizeof(logline), cgpu);
  7878. if (!curses_active) {
  7879. printf("\n%s\r", logline);
  7880. fflush(stdout);
  7881. } else
  7882. applog(LOG_INFO, "%s", logline);
  7883. }
  7884. }
  7885. }
  7886. /* Totals are updated by all threads so can race without locking */
  7887. mutex_lock(&hash_lock);
  7888. cgtime(&temp_tv_end);
  7889. timersub(&temp_tv_end, &total_tv_start, &total_diff);
  7890. total_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  7891. timersub(&temp_tv_end, &total_tv_end, &total_diff);
  7892. total_mhashes_done += local_mhashes;
  7893. local_mhashes_done += local_mhashes;
  7894. /* Only update with opt_log_interval */
  7895. if (total_diff.tv_sec < opt_log_interval)
  7896. goto out_unlock;
  7897. showlog = true;
  7898. cgtime(&total_tv_end);
  7899. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  7900. decay_time(&total_rolling, local_mhashes_done / local_secs, local_secs);
  7901. global_hashrate = ((unsigned long long)lround(total_rolling)) * 1000000;
  7902. double wtotal = (total_diff_accepted + total_diff_rejected + total_diff_stale);
  7903. multi_format_unit_array2(
  7904. ((char*[]){cHr, aHr, uHr}),
  7905. ((size_t[]){sizeof(cHr), sizeof(aHr), sizeof(uHr)}),
  7906. true, "h/s", H2B_SHORT,
  7907. 3,
  7908. 1e6*total_rolling,
  7909. 1e6*total_mhashes_done / total_secs,
  7910. utility_to_hashrate(total_diff1 * (wtotal ? (total_diff_accepted / wtotal) : 1) * 60 / total_secs));
  7911. int ui_accepted, ui_rejected, ui_stale;
  7912. if (opt_weighed_stats)
  7913. {
  7914. ui_accepted = total_diff_accepted;
  7915. ui_rejected = total_diff_rejected;
  7916. ui_stale = total_diff_stale;
  7917. }
  7918. else
  7919. {
  7920. ui_accepted = total_accepted;
  7921. ui_rejected = total_rejected;
  7922. ui_stale = total_stale;
  7923. }
  7924. #ifdef HAVE_CURSES
  7925. if (curses_active_locked()) {
  7926. float temp = 0;
  7927. struct cgpu_info *proc, *last_working_dev = NULL;
  7928. int i, working_devs = 0, working_procs = 0;
  7929. int divx;
  7930. bool bad = false;
  7931. // Find the highest temperature of all processors
  7932. for (i = 0; i < total_devices; ++i)
  7933. {
  7934. proc = get_devices(i);
  7935. if (proc->temp > temp)
  7936. temp = proc->temp;
  7937. if (unlikely(proc->deven == DEV_DISABLED))
  7938. ; // Just need to block it off from both conditions
  7939. else
  7940. if (likely(proc->status == LIFE_WELL && proc->deven == DEV_ENABLED))
  7941. {
  7942. if (proc->rolling > .1)
  7943. {
  7944. ++working_procs;
  7945. if (proc->device != last_working_dev)
  7946. {
  7947. ++working_devs;
  7948. last_working_dev = proc->device;
  7949. }
  7950. }
  7951. }
  7952. else
  7953. bad = true;
  7954. }
  7955. if (working_devs == working_procs)
  7956. snprintf(statusline, sizeof(statusline), "%s%d ", bad ? U8_BAD_START : "", working_devs);
  7957. else
  7958. snprintf(statusline, sizeof(statusline), "%s%d/%d ", bad ? U8_BAD_START : "", working_devs, working_procs);
  7959. divx = 7;
  7960. if (opt_show_procs && !opt_compact)
  7961. divx += max_lpdigits;
  7962. if (bad)
  7963. {
  7964. divx += sizeof(U8_BAD_START)-1;
  7965. strcpy(&statusline[divx], U8_BAD_END);
  7966. divx += sizeof(U8_BAD_END)-1;
  7967. }
  7968. temperature_column(&statusline[divx], sizeof(statusline)-divx, true, &temp);
  7969. format_statline(statusline, sizeof(statusline),
  7970. cHr, aHr,
  7971. uHr,
  7972. ui_accepted,
  7973. ui_rejected,
  7974. ui_stale,
  7975. total_diff_rejected + total_diff_stale, total_diff_accepted,
  7976. hw_errors,
  7977. total_bad_diff1, total_bad_diff1 + total_diff1);
  7978. unlock_curses();
  7979. }
  7980. #endif
  7981. // Add a space
  7982. memmove(&uHr[6], &uHr[5], strlen(&uHr[5]) + 1);
  7983. uHr[5] = ' ';
  7984. percentf4(rejpcbuf, sizeof(rejpcbuf), total_diff_rejected + total_diff_stale, total_diff_accepted);
  7985. percentf4(bnbuf, sizeof(bnbuf), total_bad_diff1, total_diff1);
  7986. snprintf(logstatusline, sizeof(logstatusline),
  7987. "%s%ds:%s avg:%s u:%s | A:%d R:%d+%d(%s) HW:%d/%s",
  7988. want_per_device_stats ? "ALL " : "",
  7989. opt_log_interval,
  7990. cHr, aHr,
  7991. uHr,
  7992. ui_accepted,
  7993. ui_rejected,
  7994. ui_stale,
  7995. rejpcbuf,
  7996. hw_errors,
  7997. bnbuf
  7998. );
  7999. local_mhashes_done = 0;
  8000. out_unlock:
  8001. mutex_unlock(&hash_lock);
  8002. if (showlog) {
  8003. if (!curses_active) {
  8004. if (want_per_device_stats)
  8005. printf("\n%s\r", logstatusline);
  8006. else
  8007. {
  8008. const int logstatusline_len = strlen(logstatusline);
  8009. int padding;
  8010. if (last_logstatusline_len > logstatusline_len)
  8011. padding = (last_logstatusline_len - logstatusline_len);
  8012. else
  8013. {
  8014. padding = 0;
  8015. if (last_logstatusline_len == -1)
  8016. puts("");
  8017. }
  8018. printf("%s%*s\r", logstatusline, padding, "");
  8019. last_logstatusline_len = logstatusline_len;
  8020. }
  8021. fflush(stdout);
  8022. } else
  8023. applog(LOG_INFO, "%s", logstatusline);
  8024. }
  8025. }
  8026. void hashmeter2(struct thr_info *thr)
  8027. {
  8028. struct timeval tv_now, tv_elapsed;
  8029. timerclear(&thr->tv_hashes_done);
  8030. cgtime(&tv_now);
  8031. timersub(&tv_now, &thr->tv_lastupdate, &tv_elapsed);
  8032. /* Update the hashmeter at most 5 times per second */
  8033. if ((thr->hashes_done && (tv_elapsed.tv_sec > 0 || tv_elapsed.tv_usec > 200000)) ||
  8034. tv_elapsed.tv_sec >= opt_log_interval) {
  8035. hashmeter(thr->id, &tv_elapsed, thr->hashes_done);
  8036. thr->hashes_done = 0;
  8037. thr->tv_lastupdate = tv_now;
  8038. }
  8039. }
  8040. static void stratum_share_result(json_t *val, json_t *res_val, json_t *err_val,
  8041. struct stratum_share *sshare)
  8042. {
  8043. struct work *work = sshare->work;
  8044. share_result(val, res_val, err_val, work, false, "");
  8045. }
  8046. /* Parses stratum json responses and tries to find the id that the request
  8047. * matched to and treat it accordingly. */
  8048. bool parse_stratum_response(struct pool *pool, char *s)
  8049. {
  8050. json_t *val = NULL, *err_val, *res_val, *id_val;
  8051. struct stratum_share *sshare;
  8052. json_error_t err;
  8053. bool ret = false;
  8054. int id;
  8055. val = JSON_LOADS(s, &err);
  8056. if (!val) {
  8057. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  8058. goto out;
  8059. }
  8060. res_val = json_object_get(val, "result");
  8061. err_val = json_object_get(val, "error");
  8062. id_val = json_object_get(val, "id");
  8063. if (json_is_null(id_val) || !id_val) {
  8064. char *ss;
  8065. if (err_val)
  8066. ss = json_dumps(err_val, JSON_INDENT(3));
  8067. else
  8068. ss = strdup("(unknown reason)");
  8069. applog(LOG_INFO, "JSON-RPC non method decode failed: %s", ss);
  8070. free(ss);
  8071. goto out;
  8072. }
  8073. if (!json_is_integer(id_val)) {
  8074. if (json_is_string(id_val)
  8075. && !strncmp(json_string_value(id_val), "txlist", 6))
  8076. {
  8077. const bool is_array = json_is_array(res_val);
  8078. applog(LOG_DEBUG, "Received %s for pool %u job %s",
  8079. is_array ? "transaction list" : "no-transaction-list response",
  8080. pool->pool_no, &json_string_value(id_val)[6]);
  8081. if (!is_array)
  8082. {
  8083. // No need to wait for a timeout
  8084. timer_unset(&pool->swork.tv_transparency);
  8085. pool_set_opaque(pool, true);
  8086. goto fishy;
  8087. }
  8088. if (strcmp(json_string_value(id_val) + 6, pool->swork.job_id))
  8089. // We only care about a transaction list for the current job id
  8090. goto fishy;
  8091. // Check that the transactions actually hash to the merkle links
  8092. {
  8093. unsigned maxtx = 1 << pool->swork.merkles;
  8094. unsigned mintx = maxtx >> 1;
  8095. --maxtx;
  8096. unsigned acttx = (unsigned)json_array_size(res_val);
  8097. if (acttx < mintx || acttx > maxtx) {
  8098. applog(LOG_WARNING, "Pool %u is sending mismatched block contents to us (%u is not %u-%u)",
  8099. pool->pool_no, acttx, mintx, maxtx);
  8100. goto fishy;
  8101. }
  8102. // TODO: Check hashes match actual merkle links
  8103. }
  8104. pool_set_opaque(pool, false);
  8105. timer_unset(&pool->swork.tv_transparency);
  8106. fishy:
  8107. ret = true;
  8108. }
  8109. goto out;
  8110. }
  8111. id = json_integer_value(id_val);
  8112. mutex_lock(&sshare_lock);
  8113. HASH_FIND_INT(stratum_shares, &id, sshare);
  8114. if (sshare)
  8115. HASH_DEL(stratum_shares, sshare);
  8116. mutex_unlock(&sshare_lock);
  8117. if (!sshare) {
  8118. double pool_diff;
  8119. /* Since the share is untracked, we can only guess at what the
  8120. * work difficulty is based on the current pool diff. */
  8121. cg_rlock(&pool->data_lock);
  8122. pool_diff = target_diff(pool->swork.target);
  8123. cg_runlock(&pool->data_lock);
  8124. if (json_is_true(res_val)) {
  8125. struct mining_goal_info * const goal = pool->goal;
  8126. applog(LOG_NOTICE, "Accepted untracked stratum share from pool %d", pool->pool_no);
  8127. /* We don't know what device this came from so we can't
  8128. * attribute the work to the relevant cgpu */
  8129. mutex_lock(&stats_lock);
  8130. total_accepted++;
  8131. pool->accepted++;
  8132. total_diff_accepted += pool_diff;
  8133. pool->diff_accepted += pool_diff;
  8134. goal->diff_accepted += pool_diff;
  8135. mutex_unlock(&stats_lock);
  8136. } else {
  8137. applog(LOG_NOTICE, "Rejected untracked stratum share from pool %d", pool->pool_no);
  8138. mutex_lock(&stats_lock);
  8139. total_rejected++;
  8140. pool->rejected++;
  8141. total_diff_rejected += pool_diff;
  8142. pool->diff_rejected += pool_diff;
  8143. mutex_unlock(&stats_lock);
  8144. }
  8145. goto out;
  8146. }
  8147. else {
  8148. mutex_lock(&submitting_lock);
  8149. --total_submitting;
  8150. mutex_unlock(&submitting_lock);
  8151. }
  8152. stratum_share_result(val, res_val, err_val, sshare);
  8153. free_work(sshare->work);
  8154. free(sshare);
  8155. ret = true;
  8156. out:
  8157. if (val)
  8158. json_decref(val);
  8159. return ret;
  8160. }
  8161. static void shutdown_stratum(struct pool *pool)
  8162. {
  8163. // Shut down Stratum as if we never had it
  8164. pool->stratum_active = false;
  8165. pool->stratum_init = false;
  8166. pool->has_stratum = false;
  8167. shutdown(pool->sock, SHUT_RDWR);
  8168. free(pool->stratum_url);
  8169. if (pool->sockaddr_url == pool->stratum_url)
  8170. pool->sockaddr_url = NULL;
  8171. pool->stratum_url = NULL;
  8172. }
  8173. void clear_stratum_shares(struct pool *pool)
  8174. {
  8175. int my_mining_threads = mining_threads; // Cached outside of locking
  8176. struct stratum_share *sshare, *tmpshare;
  8177. struct work *work;
  8178. struct cgpu_info *cgpu;
  8179. double diff_cleared = 0;
  8180. double thr_diff_cleared[my_mining_threads];
  8181. int cleared = 0;
  8182. int thr_cleared[my_mining_threads];
  8183. // NOTE: This is per-thread rather than per-device to avoid getting devices lock in stratum_shares loop
  8184. for (int i = 0; i < my_mining_threads; ++i)
  8185. {
  8186. thr_diff_cleared[i] = 0;
  8187. thr_cleared[i] = 0;
  8188. }
  8189. mutex_lock(&sshare_lock);
  8190. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  8191. work = sshare->work;
  8192. if (sshare->work->pool == pool && work->thr_id < my_mining_threads) {
  8193. HASH_DEL(stratum_shares, sshare);
  8194. sharelog("disconnect", work);
  8195. diff_cleared += sshare->work->work_difficulty;
  8196. thr_diff_cleared[work->thr_id] += work->work_difficulty;
  8197. ++thr_cleared[work->thr_id];
  8198. free_work(sshare->work);
  8199. free(sshare);
  8200. cleared++;
  8201. }
  8202. }
  8203. mutex_unlock(&sshare_lock);
  8204. if (cleared) {
  8205. applog(LOG_WARNING, "Lost %d shares due to stratum disconnect on pool %d", cleared, pool->pool_no);
  8206. mutex_lock(&stats_lock);
  8207. pool->stale_shares += cleared;
  8208. total_stale += cleared;
  8209. pool->diff_stale += diff_cleared;
  8210. total_diff_stale += diff_cleared;
  8211. for (int i = 0; i < my_mining_threads; ++i)
  8212. if (thr_cleared[i])
  8213. {
  8214. cgpu = get_thr_cgpu(i);
  8215. cgpu->diff_stale += thr_diff_cleared[i];
  8216. cgpu->stale += thr_cleared[i];
  8217. }
  8218. mutex_unlock(&stats_lock);
  8219. mutex_lock(&submitting_lock);
  8220. total_submitting -= cleared;
  8221. mutex_unlock(&submitting_lock);
  8222. }
  8223. }
  8224. static void resubmit_stratum_shares(struct pool *pool)
  8225. {
  8226. struct stratum_share *sshare, *tmpshare;
  8227. struct work *work;
  8228. unsigned resubmitted = 0;
  8229. mutex_lock(&sshare_lock);
  8230. mutex_lock(&submitting_lock);
  8231. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  8232. if (sshare->work->pool != pool)
  8233. continue;
  8234. HASH_DEL(stratum_shares, sshare);
  8235. work = sshare->work;
  8236. DL_APPEND(submit_waiting, work);
  8237. free(sshare);
  8238. ++resubmitted;
  8239. }
  8240. mutex_unlock(&submitting_lock);
  8241. mutex_unlock(&sshare_lock);
  8242. if (resubmitted) {
  8243. notifier_wake(submit_waiting_notifier);
  8244. applog(LOG_DEBUG, "Resubmitting %u shares due to stratum disconnect on pool %u", resubmitted, pool->pool_no);
  8245. }
  8246. }
  8247. static void clear_pool_work(struct pool *pool)
  8248. {
  8249. struct work *work, *tmp;
  8250. int cleared = 0;
  8251. mutex_lock(stgd_lock);
  8252. HASH_ITER(hh, staged_work, work, tmp) {
  8253. if (work->pool == pool) {
  8254. unstage_work(work);
  8255. free_work(work);
  8256. cleared++;
  8257. }
  8258. }
  8259. mutex_unlock(stgd_lock);
  8260. }
  8261. static int cp_prio(void)
  8262. {
  8263. int prio;
  8264. cg_rlock(&control_lock);
  8265. prio = currentpool->prio;
  8266. cg_runlock(&control_lock);
  8267. return prio;
  8268. }
  8269. /* We only need to maintain a secondary pool connection when we need the
  8270. * capacity to get work from the backup pools while still on the primary */
  8271. static bool cnx_needed(struct pool *pool)
  8272. {
  8273. struct pool *cp;
  8274. // We want to keep a connection open for rejecting or misbehaving pools, to detect when/if they change their tune
  8275. if (pool->enabled == POOL_DISABLED)
  8276. return false;
  8277. /* Idle stratum pool needs something to kick it alive again */
  8278. if (pool->has_stratum && pool->idle)
  8279. return true;
  8280. /* Getwork pools without opt_fail_only need backup pools up to be able
  8281. * to leak shares */
  8282. cp = current_pool();
  8283. if (pool_actively_desired(pool, cp))
  8284. return true;
  8285. if (!pool_localgen(cp) && (!opt_fail_only || !cp->hdr_path))
  8286. return true;
  8287. /* Keep the connection open to allow any stray shares to be submitted
  8288. * on switching pools for 2 minutes. */
  8289. if (timer_elapsed(&pool->tv_last_work_time, NULL) < 120)
  8290. return true;
  8291. /* If the pool has only just come to life and is higher priority than
  8292. * the current pool keep the connection open so we can fail back to
  8293. * it. */
  8294. if (pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  8295. return true;
  8296. if (pool_unworkable(cp))
  8297. return true;
  8298. /* We've run out of work, bring anything back to life. */
  8299. if (no_work)
  8300. return true;
  8301. // If the current pool lacks its own block change detection, see if we are needed for that
  8302. if (pool_active_lp_pool(cp) == pool)
  8303. return true;
  8304. return false;
  8305. }
  8306. static void wait_lpcurrent(struct pool *pool);
  8307. static void pool_resus(struct pool *pool);
  8308. static void stratum_resumed(struct pool *pool)
  8309. {
  8310. if (!pool->stratum_notify)
  8311. return;
  8312. if (pool_tclear(pool, &pool->idle)) {
  8313. applog(LOG_INFO, "Stratum connection to pool %d resumed", pool->pool_no);
  8314. pool_resus(pool);
  8315. }
  8316. }
  8317. static bool supports_resume(struct pool *pool)
  8318. {
  8319. bool ret;
  8320. cg_rlock(&pool->data_lock);
  8321. ret = (pool->sessionid != NULL);
  8322. cg_runlock(&pool->data_lock);
  8323. return ret;
  8324. }
  8325. static bool pools_active;
  8326. /* One stratum thread per pool that has stratum waits on the socket checking
  8327. * for new messages and for the integrity of the socket connection. We reset
  8328. * the connection based on the integrity of the receive side only as the send
  8329. * side will eventually expire data it fails to send. */
  8330. static void *stratum_thread(void *userdata)
  8331. {
  8332. struct pool *pool = (struct pool *)userdata;
  8333. pthread_detach(pthread_self());
  8334. char threadname[20];
  8335. snprintf(threadname, 20, "stratum%u", pool->pool_no);
  8336. RenameThread(threadname);
  8337. srand(time(NULL) + (intptr_t)userdata);
  8338. while (42) {
  8339. struct timeval timeout;
  8340. int sel_ret;
  8341. fd_set rd;
  8342. char *s;
  8343. int sock;
  8344. if (unlikely(!pool->has_stratum))
  8345. break;
  8346. /* Check to see whether we need to maintain this connection
  8347. * indefinitely or just bring it up when we switch to this
  8348. * pool */
  8349. while (true)
  8350. {
  8351. sock = pool->sock;
  8352. if (sock == INVSOCK)
  8353. applog(LOG_DEBUG, "Pool %u: Invalid socket, suspending",
  8354. pool->pool_no);
  8355. else
  8356. if (!sock_full(pool) && !cnx_needed(pool) && pools_active)
  8357. applog(LOG_DEBUG, "Pool %u: Connection not needed, suspending",
  8358. pool->pool_no);
  8359. else
  8360. break;
  8361. suspend_stratum(pool);
  8362. clear_stratum_shares(pool);
  8363. clear_pool_work(pool);
  8364. wait_lpcurrent(pool);
  8365. if (!restart_stratum(pool)) {
  8366. pool_died(pool);
  8367. while (!restart_stratum(pool)) {
  8368. if (pool->removed)
  8369. goto out;
  8370. cgsleep_ms(30000);
  8371. }
  8372. }
  8373. }
  8374. FD_ZERO(&rd);
  8375. FD_SET(sock, &rd);
  8376. timeout.tv_sec = 120;
  8377. timeout.tv_usec = 0;
  8378. /* If we fail to receive any notify messages for 2 minutes we
  8379. * assume the connection has been dropped and treat this pool
  8380. * as dead */
  8381. if (!sock_full(pool) && (sel_ret = select(sock + 1, &rd, NULL, NULL, &timeout)) < 1) {
  8382. applog(LOG_DEBUG, "Stratum select failed on pool %d with value %d", pool->pool_no, sel_ret);
  8383. s = NULL;
  8384. } else
  8385. s = recv_line(pool);
  8386. if (!s) {
  8387. if (!pool->has_stratum)
  8388. break;
  8389. applog(LOG_NOTICE, "Stratum connection to pool %d interrupted", pool->pool_no);
  8390. pool->getfail_occasions++;
  8391. total_go++;
  8392. mutex_lock(&pool->stratum_lock);
  8393. pool->stratum_active = pool->stratum_notify = false;
  8394. pool->sock = INVSOCK;
  8395. mutex_unlock(&pool->stratum_lock);
  8396. /* If the socket to our stratum pool disconnects, all
  8397. * submissions need to be discarded or resent. */
  8398. if (!supports_resume(pool))
  8399. clear_stratum_shares(pool);
  8400. else
  8401. resubmit_stratum_shares(pool);
  8402. clear_pool_work(pool);
  8403. if (pool == current_pool())
  8404. restart_threads();
  8405. if (restart_stratum(pool))
  8406. continue;
  8407. shutdown_stratum(pool);
  8408. pool_died(pool);
  8409. break;
  8410. }
  8411. /* Check this pool hasn't died while being a backup pool and
  8412. * has not had its idle flag cleared */
  8413. stratum_resumed(pool);
  8414. if (!parse_method(pool, s) && !parse_stratum_response(pool, s))
  8415. applog(LOG_INFO, "Unknown stratum msg: %s", s);
  8416. free(s);
  8417. if (pool->swork.clean) {
  8418. struct work *work = make_work();
  8419. /* Generate a single work item to update the current
  8420. * block database */
  8421. pool->swork.clean = false;
  8422. gen_stratum_work(pool, work);
  8423. /* Try to extract block height from coinbase scriptSig */
  8424. uint8_t *bin_height = &bytes_buf(&pool->swork.coinbase)[4 /*version*/ + 1 /*txin count*/ + 36 /*prevout*/ + 1 /*scriptSig len*/ + 1 /*push opcode*/];
  8425. unsigned char cb_height_sz;
  8426. cb_height_sz = bin_height[-1];
  8427. if (cb_height_sz == 3) {
  8428. // FIXME: The block number will overflow this by AD 2173
  8429. struct mining_goal_info * const goal = pool->goal;
  8430. const void * const prevblkhash = &work->data[4];
  8431. uint32_t height = 0;
  8432. memcpy(&height, bin_height, 3);
  8433. height = le32toh(height);
  8434. have_block_height(goal, prevblkhash, height);
  8435. }
  8436. pool->swork.work_restart_id =
  8437. ++pool->work_restart_id;
  8438. pool_update_work_restart_time(pool);
  8439. if (test_work_current(work)) {
  8440. /* Only accept a work update if this stratum
  8441. * connection is from the current pool */
  8442. struct pool * const cp = current_pool();
  8443. if (pool == cp)
  8444. restart_threads();
  8445. applog(
  8446. ((!opt_quiet_work_updates) && pool_actively_in_use(pool, cp) ? LOG_NOTICE : LOG_DEBUG),
  8447. "Stratum from pool %d requested work update", pool->pool_no);
  8448. } else
  8449. applog(LOG_NOTICE, "Stratum from pool %d detected new block", pool->pool_no);
  8450. free_work(work);
  8451. }
  8452. if (timer_passed(&pool->swork.tv_transparency, NULL)) {
  8453. // More than 4 timmills past since requested transactions
  8454. timer_unset(&pool->swork.tv_transparency);
  8455. pool_set_opaque(pool, true);
  8456. }
  8457. }
  8458. out:
  8459. return NULL;
  8460. }
  8461. static void init_stratum_thread(struct pool *pool)
  8462. {
  8463. struct mining_goal_info * const goal = pool->goal;
  8464. goal->have_longpoll = true;
  8465. if (unlikely(pthread_create(&pool->stratum_thread, NULL, stratum_thread, (void *)pool)))
  8466. quit(1, "Failed to create stratum thread");
  8467. }
  8468. static void *longpoll_thread(void *userdata);
  8469. static bool stratum_works(struct pool *pool)
  8470. {
  8471. applog(LOG_INFO, "Testing pool %d stratum %s", pool->pool_no, pool->stratum_url);
  8472. if (!extract_sockaddr(pool->stratum_url, &pool->sockaddr_url, &pool->stratum_port))
  8473. return false;
  8474. if (pool->stratum_active)
  8475. return true;
  8476. if (!initiate_stratum(pool))
  8477. return false;
  8478. return true;
  8479. }
  8480. static
  8481. bool pool_recently_got_work(struct pool * const pool, const struct timeval * const tvp_now)
  8482. {
  8483. return (timer_isset(&pool->tv_last_work_time) && timer_elapsed(&pool->tv_last_work_time, tvp_now) < 60);
  8484. }
  8485. static bool pool_active(struct pool *pool, bool pinging)
  8486. {
  8487. struct timeval tv_now, tv_getwork, tv_getwork_reply;
  8488. bool ret = false;
  8489. json_t *val;
  8490. CURL *curl = NULL;
  8491. int rolltime;
  8492. char *rpc_req;
  8493. struct work *work;
  8494. enum pool_protocol proto;
  8495. if (pool->stratum_init)
  8496. {
  8497. if (pool->stratum_active)
  8498. return true;
  8499. }
  8500. else
  8501. if (!pool->idle)
  8502. {
  8503. timer_set_now(&tv_now);
  8504. if (pool_recently_got_work(pool, &tv_now))
  8505. return true;
  8506. }
  8507. mutex_lock(&pool->pool_test_lock);
  8508. if (pool->stratum_init)
  8509. {
  8510. ret = pool->stratum_active;
  8511. goto out;
  8512. }
  8513. timer_set_now(&tv_now);
  8514. if (pool->idle)
  8515. {
  8516. if (timer_elapsed(&pool->tv_idle, &tv_now) < 30)
  8517. goto out;
  8518. }
  8519. else
  8520. if (pool_recently_got_work(pool, &tv_now))
  8521. {
  8522. ret = true;
  8523. goto out;
  8524. }
  8525. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  8526. /* This is the central point we activate stratum when we can */
  8527. curl = curl_easy_init();
  8528. if (unlikely(!curl)) {
  8529. applog(LOG_ERR, "CURL initialisation failed");
  8530. goto out;
  8531. }
  8532. if (!(want_gbt || want_getwork))
  8533. goto nohttp;
  8534. work = make_work();
  8535. /* Probe for GBT support on first pass */
  8536. proto = want_gbt ? PLP_GETBLOCKTEMPLATE : PLP_GETWORK;
  8537. tryagain:
  8538. rpc_req = prepare_rpc_req_probe(work, proto, NULL, pool);
  8539. work->pool = pool;
  8540. if (!rpc_req)
  8541. goto out;
  8542. pool->probed = false;
  8543. cgtime(&tv_getwork);
  8544. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  8545. true, false, &rolltime, pool, false);
  8546. cgtime(&tv_getwork_reply);
  8547. free(rpc_req);
  8548. /* Detect if a http getwork pool has an X-Stratum header at startup,
  8549. * and if so, switch to that in preference to getwork if it works */
  8550. if (pool->stratum_url && want_stratum && pool_may_redirect_to(pool, pool->stratum_url) && (pool->has_stratum || stratum_works(pool))) {
  8551. if (!pool->has_stratum) {
  8552. applog(LOG_NOTICE, "Switching pool %d %s to %s", pool->pool_no, pool->rpc_url, pool->stratum_url);
  8553. if (!pool->rpc_url)
  8554. pool_set_uri(pool, strdup(pool->stratum_url));
  8555. pool->has_stratum = true;
  8556. }
  8557. free_work(work);
  8558. if (val)
  8559. json_decref(val);
  8560. retry_stratum:
  8561. ;
  8562. /* We create the stratum thread for each pool just after
  8563. * successful authorisation. Once the init flag has been set
  8564. * we never unset it and the stratum thread is responsible for
  8565. * setting/unsetting the active flag */
  8566. bool init = pool_tset(pool, &pool->stratum_init);
  8567. if (!init) {
  8568. ret = initiate_stratum(pool) && auth_stratum(pool);
  8569. if (ret)
  8570. {
  8571. detect_algo = 2;
  8572. init_stratum_thread(pool);
  8573. }
  8574. else
  8575. {
  8576. pool_tclear(pool, &pool->stratum_init);
  8577. pool->tv_idle = tv_getwork_reply;
  8578. }
  8579. goto out;
  8580. }
  8581. ret = pool->stratum_active;
  8582. goto out;
  8583. }
  8584. else if (pool->has_stratum)
  8585. shutdown_stratum(pool);
  8586. if (val) {
  8587. bool rc;
  8588. json_t *res;
  8589. res = json_object_get(val, "result");
  8590. if ((!json_is_object(res)) || (proto == PLP_GETBLOCKTEMPLATE && !json_object_get(res, "bits")))
  8591. goto badwork;
  8592. work->rolltime = rolltime;
  8593. rc = work_decode(pool, work, val);
  8594. if (rc) {
  8595. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  8596. pool->pool_no, pool->rpc_url);
  8597. work->pool = pool;
  8598. copy_time(&work->tv_getwork, &tv_getwork);
  8599. copy_time(&work->tv_getwork_reply, &tv_getwork_reply);
  8600. work->getwork_mode = GETWORK_MODE_TESTPOOL;
  8601. calc_diff(work, 0);
  8602. update_last_work(work);
  8603. applog(LOG_DEBUG, "Pushing pooltest work to base pool");
  8604. stage_work(work);
  8605. total_getworks++;
  8606. pool->getwork_requested++;
  8607. ret = true;
  8608. pool->tv_idle = tv_getwork_reply;
  8609. } else {
  8610. badwork:
  8611. json_decref(val);
  8612. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher work from pool %u %s",
  8613. pool->pool_no, pool->rpc_url);
  8614. pool->proto = proto = pool_protocol_fallback(proto);
  8615. if (PLP_NONE != proto)
  8616. goto tryagain;
  8617. pool->tv_idle = tv_getwork_reply;
  8618. free_work(work);
  8619. goto out;
  8620. }
  8621. json_decref(val);
  8622. if (proto != pool->proto) {
  8623. pool->proto = proto;
  8624. applog(LOG_INFO, "Selected %s protocol for pool %u", pool_protocol_name(proto), pool->pool_no);
  8625. }
  8626. if (pool->lp_url)
  8627. goto out;
  8628. /* Decipher the longpoll URL, if any, and store it in ->lp_url */
  8629. const struct blktmpl_longpoll_req *lp;
  8630. if (work->tr && (lp = blktmpl_get_longpoll(work->tr->tmpl))) {
  8631. // NOTE: work_decode takes care of lp id
  8632. pool->lp_url = lp->uri ? absolute_uri(lp->uri, pool->rpc_url) : pool->rpc_url;
  8633. if (!pool->lp_url)
  8634. {
  8635. ret = false;
  8636. goto out;
  8637. }
  8638. pool->lp_proto = PLP_GETBLOCKTEMPLATE;
  8639. }
  8640. else
  8641. if (pool->hdr_path && want_getwork) {
  8642. pool->lp_url = absolute_uri(pool->hdr_path, pool->rpc_url);
  8643. if (!pool->lp_url)
  8644. {
  8645. ret = false;
  8646. goto out;
  8647. }
  8648. pool->lp_proto = PLP_GETWORK;
  8649. } else
  8650. pool->lp_url = NULL;
  8651. if (want_longpoll && !pool->lp_started) {
  8652. pool->lp_started = true;
  8653. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  8654. quit(1, "Failed to create pool longpoll thread");
  8655. }
  8656. } else if (PLP_NONE != (proto = pool_protocol_fallback(proto))) {
  8657. pool->proto = proto;
  8658. goto tryagain;
  8659. } else {
  8660. pool->tv_idle = tv_getwork_reply;
  8661. free_work(work);
  8662. nohttp:
  8663. /* If we failed to parse a getwork, this could be a stratum
  8664. * url without the prefix stratum+tcp:// so let's check it */
  8665. if (extract_sockaddr(pool->rpc_url, &pool->sockaddr_url, &pool->stratum_port) && initiate_stratum(pool)) {
  8666. pool->has_stratum = true;
  8667. goto retry_stratum;
  8668. }
  8669. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  8670. pool->pool_no, pool->rpc_url);
  8671. if (!pinging)
  8672. applog(LOG_WARNING, "Pool %u slow/down or URL or credentials invalid", pool->pool_no);
  8673. }
  8674. out:
  8675. if (curl)
  8676. curl_easy_cleanup(curl);
  8677. mutex_unlock(&pool->pool_test_lock);
  8678. return ret;
  8679. }
  8680. static void pool_resus(struct pool *pool)
  8681. {
  8682. if (pool->enabled == POOL_ENABLED && pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  8683. applog(LOG_WARNING, "Pool %d %s alive, testing stability", pool->pool_no, pool->rpc_url);
  8684. else
  8685. applog(LOG_INFO, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  8686. }
  8687. static
  8688. void *cmd_idle_thread(void * const __maybe_unused userp)
  8689. {
  8690. pthread_detach(pthread_self());
  8691. RenameThread("cmd-idle");
  8692. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  8693. sleep(opt_log_interval);
  8694. pthread_testcancel();
  8695. run_cmd(cmd_idle);
  8696. return NULL;
  8697. }
  8698. static struct work *hash_pop(struct cgpu_info * const proc)
  8699. {
  8700. int hc;
  8701. struct work *work, *work_found, *tmp;
  8702. enum {
  8703. HPWS_NONE,
  8704. HPWS_LOWDIFF,
  8705. HPWS_SPARE,
  8706. HPWS_ROLLABLE,
  8707. HPWS_PERFECT,
  8708. } work_score = HPWS_NONE;
  8709. bool did_cmd_idle = false;
  8710. pthread_t cmd_idle_thr;
  8711. retry:
  8712. mutex_lock(stgd_lock);
  8713. while (true)
  8714. {
  8715. work_found = NULL;
  8716. work_score = 0;
  8717. hc = HASH_COUNT(staged_work);
  8718. HASH_ITER(hh, staged_work, work, tmp)
  8719. {
  8720. const struct mining_algorithm * const work_malgo = work_mining_algorithm(work);
  8721. const float min_nonce_diff = drv_min_nonce_diff(proc->drv, proc, work_malgo);
  8722. #define FOUND_WORK(score) do{ \
  8723. if (work_score < score) \
  8724. { \
  8725. work_found = work; \
  8726. work_score = score; \
  8727. } \
  8728. continue; \
  8729. }while(0)
  8730. if (min_nonce_diff < work->work_difficulty)
  8731. {
  8732. if (min_nonce_diff < 0)
  8733. continue;
  8734. FOUND_WORK(HPWS_LOWDIFF);
  8735. }
  8736. if (work->spare)
  8737. FOUND_WORK(HPWS_SPARE);
  8738. if (work->rolltime && hc > staged_rollable)
  8739. FOUND_WORK(HPWS_ROLLABLE);
  8740. #undef FOUND_WORK
  8741. // Good match
  8742. work_found = work;
  8743. work_score = HPWS_PERFECT;
  8744. break;
  8745. }
  8746. if (work_found)
  8747. {
  8748. work = work_found;
  8749. break;
  8750. }
  8751. // Failed to get a usable work
  8752. if (unlikely(staged_full))
  8753. {
  8754. if (likely(opt_queue < 10 + mining_threads))
  8755. {
  8756. ++opt_queue;
  8757. applog(LOG_WARNING, "Staged work underrun; increasing queue minimum to %d", opt_queue);
  8758. }
  8759. else
  8760. applog(LOG_WARNING, "Staged work underrun; not automatically increasing above %d", opt_queue);
  8761. staged_full = false; // Let it fill up before triggering an underrun again
  8762. no_work = true;
  8763. }
  8764. pthread_cond_signal(&gws_cond);
  8765. if (cmd_idle && !did_cmd_idle)
  8766. {
  8767. if (likely(!pthread_create(&cmd_idle_thr, NULL, cmd_idle_thread, NULL)))
  8768. did_cmd_idle = true;
  8769. }
  8770. pthread_cond_wait(&getq->cond, stgd_lock);
  8771. }
  8772. if (did_cmd_idle)
  8773. pthread_cancel(cmd_idle_thr);
  8774. no_work = false;
  8775. if (can_roll(work) && should_roll(work))
  8776. {
  8777. // Instead of consuming it, force it to be cloned and grab the clone
  8778. mutex_unlock(stgd_lock);
  8779. clone_available();
  8780. goto retry;
  8781. }
  8782. unstage_work(work);
  8783. /* Signal the getwork scheduler to look for more work */
  8784. pthread_cond_signal(&gws_cond);
  8785. /* Signal hash_pop again in case there are mutliple hash_pop waiters */
  8786. pthread_cond_signal(&getq->cond);
  8787. mutex_unlock(stgd_lock);
  8788. work->pool->last_work_time = time(NULL);
  8789. cgtime(&work->pool->tv_last_work_time);
  8790. return work;
  8791. }
  8792. /* Clones work by rolling it if possible, and returning a clone instead of the
  8793. * original work item which gets staged again to possibly be rolled again in
  8794. * the future */
  8795. static struct work *clone_work(struct work *work)
  8796. {
  8797. int mrs = mining_threads + opt_queue - total_staged(false);
  8798. struct work *work_clone;
  8799. bool cloned;
  8800. if (mrs < 1)
  8801. return work;
  8802. cloned = false;
  8803. work_clone = make_clone(work);
  8804. while (mrs-- > 0 && can_roll(work) && should_roll(work)) {
  8805. applog(LOG_DEBUG, "Pushing rolled converted work to stage thread");
  8806. stage_work(work_clone);
  8807. roll_work(work);
  8808. work_clone = make_clone(work);
  8809. /* Roll it again to prevent duplicates should this be used
  8810. * directly later on */
  8811. roll_work(work);
  8812. cloned = true;
  8813. }
  8814. if (cloned) {
  8815. stage_work(work);
  8816. return work_clone;
  8817. }
  8818. free_work(work_clone);
  8819. return work;
  8820. }
  8821. void gen_hash(unsigned char *data, unsigned char *hash, int len)
  8822. {
  8823. unsigned char hash1[32];
  8824. sha256(data, len, hash1);
  8825. sha256(hash1, 32, hash);
  8826. }
  8827. /* PDiff 1 is a 256 bit unsigned integer of
  8828. * 0x00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff
  8829. * so we use a big endian 32 bit unsigned integer positioned at the Nth byte to
  8830. * cover a huge range of difficulty targets, though not all 256 bits' worth */
  8831. static void pdiff_target_leadzero(void * const target_p, double diff)
  8832. {
  8833. uint8_t *target = target_p;
  8834. diff *= 0x100000000;
  8835. int skip = log2(diff) / 8;
  8836. if (skip)
  8837. {
  8838. if (skip > 0x1c)
  8839. skip = 0x1c;
  8840. diff /= pow(0x100, skip);
  8841. memset(target, 0, skip);
  8842. }
  8843. uint32_t n = 0xffffffff;
  8844. n = (double)n / diff;
  8845. n = htobe32(n);
  8846. memcpy(&target[skip], &n, sizeof(n));
  8847. memset(&target[skip + sizeof(n)], 0xff, 32 - (skip + sizeof(n)));
  8848. }
  8849. void set_target_to_pdiff(void * const dest_target, const double pdiff)
  8850. {
  8851. unsigned char rtarget[32];
  8852. pdiff_target_leadzero(rtarget, pdiff);
  8853. swab256(dest_target, rtarget);
  8854. if (opt_debug) {
  8855. char htarget[65];
  8856. bin2hex(htarget, rtarget, 32);
  8857. applog(LOG_DEBUG, "Generated target %s", htarget);
  8858. }
  8859. }
  8860. void set_target_to_bdiff(void * const dest_target, const double bdiff)
  8861. {
  8862. set_target_to_pdiff(dest_target, bdiff_to_pdiff(bdiff));
  8863. }
  8864. void _test_target(void * const funcp, const char * const funcname, const bool little_endian, const void * const expectp, const double diff)
  8865. {
  8866. uint8_t bufr[32], buf[32], expectr[32], expect[32];
  8867. int off;
  8868. void (*func)(void *, double) = funcp;
  8869. func(little_endian ? bufr : buf, diff);
  8870. if (little_endian)
  8871. swab256(buf, bufr);
  8872. swap32tobe(expect, expectp, 256/32);
  8873. // Fuzzy comparison: the first 32 bits set must match, and the actual target must be >= the expected
  8874. for (off = 0; off < 28 && !buf[off]; ++off)
  8875. {}
  8876. if (memcmp(&buf[off], &expect[off], 4))
  8877. {
  8878. testfail: ;
  8879. ++unittest_failures;
  8880. char hexbuf[65], expectbuf[65];
  8881. bin2hex(hexbuf, buf, 32);
  8882. bin2hex(expectbuf, expect, 32);
  8883. applogr(, LOG_WARNING, "%s test failed: diff %g got %s (expected %s)",
  8884. funcname, diff, hexbuf, expectbuf);
  8885. }
  8886. if (!little_endian)
  8887. swab256(bufr, buf);
  8888. swab256(expectr, expect);
  8889. if (!hash_target_check(expectr, bufr))
  8890. goto testfail;
  8891. }
  8892. #define TEST_TARGET(func, le, expect, diff) \
  8893. _test_target(func, #func, le, expect, diff)
  8894. void test_target()
  8895. {
  8896. uint32_t expect[8] = {0};
  8897. // bdiff 1 should be exactly 00000000ffff0000000006f29cfd29510a6caee84634e86a57257cf03152537f due to floating-point imprecision (pdiff1 / 1.0000152590218966)
  8898. expect[0] = 0x0000ffff;
  8899. TEST_TARGET(set_target_to_bdiff, true, expect, 1./0x10000);
  8900. expect[0] = 0;
  8901. expect[1] = 0xffff0000;
  8902. TEST_TARGET(set_target_to_bdiff, true, expect, 1);
  8903. expect[1] >>= 1;
  8904. TEST_TARGET(set_target_to_bdiff, true, expect, 2);
  8905. expect[1] >>= 3;
  8906. TEST_TARGET(set_target_to_bdiff, true, expect, 0x10);
  8907. expect[1] >>= 4;
  8908. TEST_TARGET(set_target_to_bdiff, true, expect, 0x100);
  8909. memset(&expect[1], '\xff', 28);
  8910. expect[0] = 0x0000ffff;
  8911. TEST_TARGET(set_target_to_pdiff, true, expect, 1./0x10000);
  8912. expect[0] = 0;
  8913. TEST_TARGET(set_target_to_pdiff, true, expect, 1);
  8914. expect[1] >>= 1;
  8915. TEST_TARGET(set_target_to_pdiff, true, expect, 2);
  8916. expect[1] >>= 3;
  8917. TEST_TARGET(set_target_to_pdiff, true, expect, 0x10);
  8918. expect[1] >>= 4;
  8919. TEST_TARGET(set_target_to_pdiff, true, expect, 0x100);
  8920. }
  8921. void stratum_work_cpy(struct stratum_work * const dst, const struct stratum_work * const src)
  8922. {
  8923. *dst = *src;
  8924. if (dst->tr)
  8925. tmpl_incref(dst->tr);
  8926. dst->nonce1 = maybe_strdup(src->nonce1);
  8927. dst->job_id = maybe_strdup(src->job_id);
  8928. bytes_cpy(&dst->coinbase, &src->coinbase);
  8929. bytes_cpy(&dst->merkle_bin, &src->merkle_bin);
  8930. }
  8931. void stratum_work_clean(struct stratum_work * const swork)
  8932. {
  8933. if (swork->tr)
  8934. tmpl_decref(swork->tr);
  8935. free(swork->nonce1);
  8936. free(swork->job_id);
  8937. bytes_free(&swork->coinbase);
  8938. bytes_free(&swork->merkle_bin);
  8939. }
  8940. bool pool_has_usable_swork(const struct pool * const pool)
  8941. {
  8942. if (opt_benchmark)
  8943. return true;
  8944. if (pool->swork.tr)
  8945. {
  8946. // GBT
  8947. struct timeval tv_now;
  8948. timer_set_now(&tv_now);
  8949. return blkmk_time_left(pool->swork.tr->tmpl, tv_now.tv_sec);
  8950. }
  8951. return pool->stratum_notify;
  8952. }
  8953. /* Generates stratum based work based on the most recent notify information
  8954. * from the pool. This will keep generating work while a pool is down so we use
  8955. * other means to detect when the pool has died in stratum_thread */
  8956. static void gen_stratum_work(struct pool *pool, struct work *work)
  8957. {
  8958. clean_work(work);
  8959. cg_wlock(&pool->data_lock);
  8960. pool->swork.data_lock_p = &pool->data_lock;
  8961. const int n2size = pool->swork.n2size;
  8962. bytes_resize(&work->nonce2, n2size);
  8963. if (pool->nonce2sz < n2size)
  8964. memset(&bytes_buf(&work->nonce2)[pool->nonce2sz], 0, n2size - pool->nonce2sz);
  8965. memcpy(bytes_buf(&work->nonce2),
  8966. #ifdef WORDS_BIGENDIAN
  8967. // NOTE: On big endian, the most significant bits are stored at the end, so skip the LSBs
  8968. &((char*)&pool->nonce2)[pool->nonce2off],
  8969. #else
  8970. &pool->nonce2,
  8971. #endif
  8972. pool->nonce2sz);
  8973. pool->nonce2++;
  8974. work->pool = pool;
  8975. work->work_restart_id = pool->swork.work_restart_id;
  8976. gen_stratum_work2(work, &pool->swork);
  8977. cgtime(&work->tv_staged);
  8978. }
  8979. void gen_stratum_work2(struct work *work, struct stratum_work *swork)
  8980. {
  8981. unsigned char *coinbase, merkle_root[32], merkle_sha[64];
  8982. uint8_t *merkle_bin;
  8983. uint32_t *data32, *swap32;
  8984. int i;
  8985. /* Generate coinbase */
  8986. coinbase = bytes_buf(&swork->coinbase);
  8987. memcpy(&coinbase[swork->nonce2_offset], bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  8988. /* Downgrade to a read lock to read off the variables */
  8989. if (swork->data_lock_p)
  8990. cg_dwlock(swork->data_lock_p);
  8991. /* Generate merkle root */
  8992. gen_hash(coinbase, merkle_root, bytes_len(&swork->coinbase));
  8993. memcpy(merkle_sha, merkle_root, 32);
  8994. merkle_bin = bytes_buf(&swork->merkle_bin);
  8995. for (i = 0; i < swork->merkles; ++i, merkle_bin += 32) {
  8996. memcpy(merkle_sha + 32, merkle_bin, 32);
  8997. gen_hash(merkle_sha, merkle_root, 64);
  8998. memcpy(merkle_sha, merkle_root, 32);
  8999. }
  9000. data32 = (uint32_t *)merkle_sha;
  9001. swap32 = (uint32_t *)merkle_root;
  9002. flip32(swap32, data32);
  9003. memcpy(&work->data[0], swork->header1, 36);
  9004. memcpy(&work->data[36], merkle_root, 32);
  9005. *((uint32_t*)&work->data[68]) = htobe32(swork->ntime + timer_elapsed(&swork->tv_received, NULL));
  9006. memcpy(&work->data[72], swork->diffbits, 4);
  9007. memset(&work->data[76], 0, 4); // nonce
  9008. memcpy(&work->data[80], workpadding_bin, 48);
  9009. work->ntime_roll_limits = swork->ntime_roll_limits;
  9010. /* Copy parameters required for share submission */
  9011. memcpy(work->target, swork->target, sizeof(work->target));
  9012. work->job_id = maybe_strdup(swork->job_id);
  9013. work->nonce1 = maybe_strdup(swork->nonce1);
  9014. if (swork->data_lock_p)
  9015. cg_runlock(swork->data_lock_p);
  9016. if (opt_debug)
  9017. {
  9018. char header[161];
  9019. char nonce2hex[(bytes_len(&work->nonce2) * 2) + 1];
  9020. bin2hex(header, work->data, 80);
  9021. bin2hex(nonce2hex, bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  9022. applog(LOG_DEBUG, "Generated stratum header %s", header);
  9023. applog(LOG_DEBUG, "Work job_id %s nonce2 %s", work->job_id, nonce2hex);
  9024. }
  9025. calc_midstate(work);
  9026. local_work++;
  9027. work->stratum = true;
  9028. work->blk.nonce = 0;
  9029. work->id = total_work++;
  9030. work->longpoll = false;
  9031. work->getwork_mode = GETWORK_MODE_STRATUM;
  9032. calc_diff(work, 0);
  9033. }
  9034. void request_work(struct thr_info *thr)
  9035. {
  9036. struct cgpu_info *cgpu = thr->cgpu;
  9037. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  9038. /* Tell the watchdog thread this thread is waiting on getwork and
  9039. * should not be restarted */
  9040. thread_reportout(thr);
  9041. // HACK: Since get_work still blocks, reportout all processors dependent on this thread
  9042. for (struct cgpu_info *proc = thr->cgpu->next_proc; proc; proc = proc->next_proc)
  9043. {
  9044. if (proc->threads)
  9045. break;
  9046. thread_reportout(proc->thr[0]);
  9047. }
  9048. cgtime(&dev_stats->_get_start);
  9049. }
  9050. // FIXME: Make this non-blocking (and remove HACK above)
  9051. struct work *get_work(struct thr_info *thr)
  9052. {
  9053. const int thr_id = thr->id;
  9054. struct cgpu_info *cgpu = thr->cgpu;
  9055. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  9056. struct cgminer_stats *pool_stats;
  9057. struct timeval tv_get;
  9058. struct work *work = NULL;
  9059. applog(LOG_DEBUG, "%"PRIpreprv": Popping work from get queue to get work", cgpu->proc_repr);
  9060. while (!work) {
  9061. work = hash_pop(cgpu);
  9062. if (stale_work(work, false)) {
  9063. staged_full = false; // It wasn't really full, since it was stale :(
  9064. discard_work(work);
  9065. work = NULL;
  9066. wake_gws();
  9067. }
  9068. }
  9069. last_getwork = time(NULL);
  9070. applog(LOG_DEBUG, "%"PRIpreprv": Got work %d from get queue to get work for thread %d",
  9071. cgpu->proc_repr, work->id, thr_id);
  9072. work->thr_id = thr_id;
  9073. thread_reportin(thr);
  9074. // HACK: Since get_work still blocks, reportin all processors dependent on this thread
  9075. for (struct cgpu_info *proc = thr->cgpu->next_proc; proc; proc = proc->next_proc)
  9076. {
  9077. if (proc->threads)
  9078. break;
  9079. thread_reportin(proc->thr[0]);
  9080. }
  9081. work->mined = true;
  9082. work->blk.nonce = 0;
  9083. cgtime(&tv_get);
  9084. timersub(&tv_get, &dev_stats->_get_start, &tv_get);
  9085. timeradd(&tv_get, &dev_stats->getwork_wait, &dev_stats->getwork_wait);
  9086. if (timercmp(&tv_get, &dev_stats->getwork_wait_max, >))
  9087. dev_stats->getwork_wait_max = tv_get;
  9088. if (timercmp(&tv_get, &dev_stats->getwork_wait_min, <))
  9089. dev_stats->getwork_wait_min = tv_get;
  9090. ++dev_stats->getwork_calls;
  9091. pool_stats = &(work->pool->cgminer_stats);
  9092. timeradd(&tv_get, &pool_stats->getwork_wait, &pool_stats->getwork_wait);
  9093. if (timercmp(&tv_get, &pool_stats->getwork_wait_max, >))
  9094. pool_stats->getwork_wait_max = tv_get;
  9095. if (timercmp(&tv_get, &pool_stats->getwork_wait_min, <))
  9096. pool_stats->getwork_wait_min = tv_get;
  9097. ++pool_stats->getwork_calls;
  9098. if (work->work_difficulty < 1)
  9099. {
  9100. const float min_nonce_diff = drv_min_nonce_diff(cgpu->drv, cgpu, work_mining_algorithm(work));
  9101. if (unlikely(work->work_difficulty < min_nonce_diff))
  9102. {
  9103. if (min_nonce_diff - work->work_difficulty > 1./0x10000000)
  9104. applog(LOG_WARNING, "%"PRIpreprv": Using work with lower difficulty than device supports",
  9105. cgpu->proc_repr);
  9106. work->nonce_diff = min_nonce_diff;
  9107. }
  9108. else
  9109. work->nonce_diff = work->work_difficulty;
  9110. }
  9111. else
  9112. work->nonce_diff = 1;
  9113. return work;
  9114. }
  9115. struct dupe_hash_elem {
  9116. uint8_t hash[0x20];
  9117. struct timeval tv_prune;
  9118. UT_hash_handle hh;
  9119. };
  9120. static
  9121. void _submit_work_async(struct work *work)
  9122. {
  9123. applog(LOG_DEBUG, "Pushing submit work to work thread");
  9124. if (opt_benchmark)
  9125. {
  9126. json_t * const jn = json_null(), *result = NULL;
  9127. work_check_for_block(work);
  9128. {
  9129. static struct dupe_hash_elem *dupe_hashes;
  9130. struct dupe_hash_elem *dhe, *dhetmp;
  9131. HASH_FIND(hh, dupe_hashes, &work->hash, sizeof(dhe->hash), dhe);
  9132. if (dhe)
  9133. result = json_string("duplicate");
  9134. else
  9135. {
  9136. struct timeval tv_now;
  9137. timer_set_now(&tv_now);
  9138. // Prune old entries
  9139. HASH_ITER(hh, dupe_hashes, dhe, dhetmp)
  9140. {
  9141. if (!timer_passed(&dhe->tv_prune, &tv_now))
  9142. break;
  9143. HASH_DEL(dupe_hashes, dhe);
  9144. free(dhe);
  9145. }
  9146. dhe = malloc(sizeof(*dhe));
  9147. memcpy(dhe->hash, work->hash, sizeof(dhe->hash));
  9148. timer_set_delay(&dhe->tv_prune, &tv_now, 337500000);
  9149. HASH_ADD(hh, dupe_hashes, hash, sizeof(dhe->hash), dhe);
  9150. }
  9151. }
  9152. if (result)
  9153. {}
  9154. else
  9155. if (stale_work(work, true))
  9156. {
  9157. char stalemsg[0x10];
  9158. snprintf(stalemsg, sizeof(stalemsg), "stale %us", benchmark_update_interval * (work->pool->work_restart_id - work->work_restart_id));
  9159. result = json_string(stalemsg);
  9160. }
  9161. else
  9162. result = json_incref(jn);
  9163. share_result(jn, result, jn, work, false, "");
  9164. free_work(work);
  9165. json_decref(result);
  9166. json_decref(jn);
  9167. return;
  9168. }
  9169. mutex_lock(&submitting_lock);
  9170. ++total_submitting;
  9171. DL_APPEND(submit_waiting, work);
  9172. mutex_unlock(&submitting_lock);
  9173. notifier_wake(submit_waiting_notifier);
  9174. }
  9175. /* Submit a copy of the tested, statistic recorded work item asynchronously */
  9176. static void submit_work_async2(struct work *work, struct timeval *tv_work_found)
  9177. {
  9178. if (tv_work_found)
  9179. copy_time(&work->tv_work_found, tv_work_found);
  9180. _submit_work_async(work);
  9181. }
  9182. void inc_hw_errors3(struct thr_info *thr, const struct work *work, const uint32_t *bad_nonce_p, float nonce_diff)
  9183. {
  9184. struct cgpu_info * const cgpu = thr->cgpu;
  9185. if (bad_nonce_p)
  9186. {
  9187. if (bad_nonce_p == UNKNOWN_NONCE)
  9188. applog(LOG_DEBUG, "%"PRIpreprv": invalid nonce - HW error",
  9189. cgpu->proc_repr);
  9190. else
  9191. applog(LOG_DEBUG, "%"PRIpreprv": invalid nonce (%08lx) - HW error",
  9192. cgpu->proc_repr, (unsigned long)be32toh(*bad_nonce_p));
  9193. }
  9194. mutex_lock(&stats_lock);
  9195. hw_errors++;
  9196. ++cgpu->hw_errors;
  9197. if (bad_nonce_p)
  9198. {
  9199. total_bad_diff1 += nonce_diff;
  9200. cgpu->bad_diff1 += nonce_diff;
  9201. }
  9202. mutex_unlock(&stats_lock);
  9203. if (thr->cgpu->drv->hw_error)
  9204. thr->cgpu->drv->hw_error(thr);
  9205. }
  9206. void work_hash(struct work * const work)
  9207. {
  9208. const struct mining_algorithm * const malgo = work_mining_algorithm(work);
  9209. malgo->hash_data_f(work->hash, work->data);
  9210. }
  9211. static
  9212. bool test_hash(const void * const phash, const float diff)
  9213. {
  9214. const uint32_t * const hash = phash;
  9215. if (diff >= 1.)
  9216. // FIXME: > 1 should check more
  9217. return !hash[7];
  9218. const uint32_t Htarg = (uint32_t)ceil((1. / diff) - 1);
  9219. const uint32_t tmp_hash7 = le32toh(hash[7]);
  9220. applog(LOG_DEBUG, "htarget %08lx hash %08lx",
  9221. (long unsigned int)Htarg,
  9222. (long unsigned int)tmp_hash7);
  9223. return (tmp_hash7 <= Htarg);
  9224. }
  9225. enum test_nonce2_result _test_nonce2(struct work *work, uint32_t nonce, bool checktarget)
  9226. {
  9227. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  9228. *work_nonce = htole32(nonce);
  9229. work_hash(work);
  9230. if (!test_hash(work->hash, work->nonce_diff))
  9231. return TNR_BAD;
  9232. if (checktarget && !hash_target_check_v(work->hash, work->target))
  9233. {
  9234. bool high_hash = true;
  9235. struct pool * const pool = work->pool;
  9236. if (pool->stratum_active)
  9237. {
  9238. // 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
  9239. if (memcmp(pool->next_target, work->target, sizeof(work->target)))
  9240. {
  9241. applog(LOG_DEBUG, "Stratum pool %u target has changed since work job issued, checking that too",
  9242. pool->pool_no);
  9243. if (hash_target_check_v(work->hash, pool->next_target))
  9244. high_hash = false;
  9245. }
  9246. }
  9247. if (high_hash)
  9248. return TNR_HIGH;
  9249. }
  9250. return TNR_GOOD;
  9251. }
  9252. /* Returns true if nonce for work was a valid share */
  9253. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  9254. {
  9255. return submit_noffset_nonce(thr, work, nonce, 0);
  9256. }
  9257. /* Allows drivers to submit work items where the driver has changed the ntime
  9258. * value by noffset. Must be only used with a work protocol that does not ntime
  9259. * roll itself intrinsically to generate work (eg stratum). We do not touch
  9260. * the original work struct, but the copy of it only. */
  9261. bool submit_noffset_nonce(struct thr_info *thr, struct work *work_in, uint32_t nonce,
  9262. int noffset)
  9263. {
  9264. struct work *work = make_work();
  9265. _copy_work(work, work_in, noffset);
  9266. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  9267. struct timeval tv_work_found;
  9268. enum test_nonce2_result res;
  9269. bool ret = true;
  9270. thread_reportout(thr);
  9271. cgtime(&tv_work_found);
  9272. *work_nonce = htole32(nonce);
  9273. work->thr_id = thr->id;
  9274. /* Do one last check before attempting to submit the work */
  9275. /* Side effect: sets work->data and work->hash for us */
  9276. res = test_nonce2(work, nonce);
  9277. if (unlikely(res == TNR_BAD))
  9278. {
  9279. inc_hw_errors(thr, work, nonce);
  9280. ret = false;
  9281. goto out;
  9282. }
  9283. mutex_lock(&stats_lock);
  9284. total_diff1 += work->nonce_diff;
  9285. thr ->cgpu->diff1 += work->nonce_diff;
  9286. work->pool->diff1 += work->nonce_diff;
  9287. thr->cgpu->last_device_valid_work = time(NULL);
  9288. mutex_unlock(&stats_lock);
  9289. if (noncelog_file)
  9290. noncelog(work);
  9291. if (res == TNR_HIGH)
  9292. {
  9293. // Share above target, normal
  9294. /* Check the diff of the share, even if it didn't reach the
  9295. * target, just to set the best share value if it's higher. */
  9296. share_diff(work);
  9297. goto out;
  9298. }
  9299. submit_work_async2(work, &tv_work_found);
  9300. work = NULL; // Taken by submit_work_async2
  9301. out:
  9302. if (work)
  9303. free_work(work);
  9304. thread_reportin(thr);
  9305. return ret;
  9306. }
  9307. // return true of we should stop working on this piece of work
  9308. // returning false means we will keep scanning for a nonce
  9309. // assumptions: work->blk.nonce is the number of nonces completed in the work
  9310. // see minerloop_scanhash comments for more details & usage
  9311. bool abandon_work(struct work *work, struct timeval *wdiff, uint64_t max_hashes)
  9312. {
  9313. if (work->blk.nonce == 0xffffffff || // known we are scanning a full nonce range
  9314. wdiff->tv_sec > opt_scantime || // scan-time has elapsed (user specified, default 60s)
  9315. work->blk.nonce >= 0xfffffffe - max_hashes || // are there enough nonces left in the work
  9316. max_hashes >= 0xfffffffe || // assume we are scanning a full nonce range
  9317. stale_work(work, false)) // work is stale
  9318. return true;
  9319. return false;
  9320. }
  9321. void __thr_being_msg(int prio, struct thr_info *thr, const char *being)
  9322. {
  9323. struct cgpu_info *proc = thr->cgpu;
  9324. if (proc->threads > 1)
  9325. applog(prio, "%"PRIpreprv" (thread %d) %s", proc->proc_repr, thr->id, being);
  9326. else
  9327. applog(prio, "%"PRIpreprv" %s", proc->proc_repr, being);
  9328. }
  9329. // Called by asynchronous minerloops, when they find their processor should be disabled
  9330. void mt_disable_start(struct thr_info *mythr)
  9331. {
  9332. struct cgpu_info *cgpu = mythr->cgpu;
  9333. struct device_drv *drv = cgpu->drv;
  9334. if (drv->thread_disable)
  9335. drv->thread_disable(mythr);
  9336. hashmeter2(mythr);
  9337. __thr_being_msg(LOG_WARNING, mythr, "being disabled");
  9338. mythr->rolling = mythr->cgpu->rolling = 0;
  9339. thread_reportout(mythr);
  9340. mythr->_mt_disable_called = true;
  9341. }
  9342. /* Put a new unqueued work item in cgpu->unqueued_work under cgpu->qlock till
  9343. * the driver tells us it's full so that it may extract the work item using
  9344. * the get_queued() function which adds it to the hashtable on
  9345. * cgpu->queued_work. */
  9346. static void fill_queue(struct thr_info *mythr, struct cgpu_info *cgpu, struct device_drv *drv, const int thr_id)
  9347. {
  9348. thread_reportout(mythr);
  9349. do {
  9350. bool need_work;
  9351. /* Do this lockless just to know if we need more unqueued work. */
  9352. need_work = (!cgpu->unqueued_work);
  9353. /* get_work is a blocking function so do it outside of lock
  9354. * to prevent deadlocks with other locks. */
  9355. if (need_work) {
  9356. struct work *work = get_work(mythr);
  9357. wr_lock(&cgpu->qlock);
  9358. /* Check we haven't grabbed work somehow between
  9359. * checking and picking up the lock. */
  9360. if (likely(!cgpu->unqueued_work))
  9361. cgpu->unqueued_work = work;
  9362. else
  9363. need_work = false;
  9364. wr_unlock(&cgpu->qlock);
  9365. if (unlikely(!need_work))
  9366. discard_work(work);
  9367. }
  9368. /* The queue_full function should be used by the driver to
  9369. * actually place work items on the physical device if it
  9370. * does have a queue. */
  9371. } while (drv->queue_full && !drv->queue_full(cgpu));
  9372. }
  9373. /* Add a work item to a cgpu's queued hashlist */
  9374. void __add_queued(struct cgpu_info *cgpu, struct work *work)
  9375. {
  9376. cgpu->queued_count++;
  9377. HASH_ADD_INT(cgpu->queued_work, id, work);
  9378. }
  9379. /* This function is for retrieving one work item from the unqueued pointer and
  9380. * adding it to the hashtable of queued work. Code using this function must be
  9381. * able to handle NULL as a return which implies there is no work available. */
  9382. struct work *get_queued(struct cgpu_info *cgpu)
  9383. {
  9384. struct work *work = NULL;
  9385. wr_lock(&cgpu->qlock);
  9386. if (cgpu->unqueued_work) {
  9387. work = cgpu->unqueued_work;
  9388. if (unlikely(stale_work(work, false))) {
  9389. discard_work(work);
  9390. work = NULL;
  9391. wake_gws();
  9392. } else
  9393. __add_queued(cgpu, work);
  9394. cgpu->unqueued_work = NULL;
  9395. }
  9396. wr_unlock(&cgpu->qlock);
  9397. return work;
  9398. }
  9399. void add_queued(struct cgpu_info *cgpu, struct work *work)
  9400. {
  9401. wr_lock(&cgpu->qlock);
  9402. __add_queued(cgpu, work);
  9403. wr_unlock(&cgpu->qlock);
  9404. }
  9405. /* Get fresh work and add it to cgpu's queued hashlist */
  9406. struct work *get_queue_work(struct thr_info *thr, struct cgpu_info *cgpu, int thr_id)
  9407. {
  9408. struct work *work = get_work(thr);
  9409. add_queued(cgpu, work);
  9410. return work;
  9411. }
  9412. /* This function is for finding an already queued work item in the
  9413. * given que hashtable. Code using this function must be able
  9414. * to handle NULL as a return which implies there is no matching work.
  9415. * The calling function must lock access to the que if it is required.
  9416. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  9417. struct work *__find_work_bymidstate(struct work *que, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  9418. {
  9419. struct work *work, *tmp, *ret = NULL;
  9420. HASH_ITER(hh, que, work, tmp) {
  9421. if (memcmp(work->midstate, midstate, midstatelen) == 0 &&
  9422. memcmp(work->data + offset, data, datalen) == 0) {
  9423. ret = work;
  9424. break;
  9425. }
  9426. }
  9427. return ret;
  9428. }
  9429. /* This function is for finding an already queued work item in the
  9430. * device's queued_work hashtable. Code using this function must be able
  9431. * to handle NULL as a return which implies there is no matching work.
  9432. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  9433. struct work *find_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  9434. {
  9435. struct work *ret;
  9436. rd_lock(&cgpu->qlock);
  9437. ret = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  9438. rd_unlock(&cgpu->qlock);
  9439. return ret;
  9440. }
  9441. struct work *clone_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  9442. {
  9443. struct work *work, *ret = NULL;
  9444. rd_lock(&cgpu->qlock);
  9445. work = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  9446. if (work)
  9447. ret = copy_work(work);
  9448. rd_unlock(&cgpu->qlock);
  9449. return ret;
  9450. }
  9451. void __work_completed(struct cgpu_info *cgpu, struct work *work)
  9452. {
  9453. cgpu->queued_count--;
  9454. HASH_DEL(cgpu->queued_work, work);
  9455. }
  9456. /* This iterates over a queued hashlist finding work started more than secs
  9457. * seconds ago and discards the work as completed. The driver must set the
  9458. * work->tv_work_start value appropriately. Returns the number of items aged. */
  9459. int age_queued_work(struct cgpu_info *cgpu, double secs)
  9460. {
  9461. struct work *work, *tmp;
  9462. struct timeval tv_now;
  9463. int aged = 0;
  9464. cgtime(&tv_now);
  9465. wr_lock(&cgpu->qlock);
  9466. HASH_ITER(hh, cgpu->queued_work, work, tmp) {
  9467. if (tdiff(&tv_now, &work->tv_work_start) > secs) {
  9468. __work_completed(cgpu, work);
  9469. aged++;
  9470. }
  9471. }
  9472. wr_unlock(&cgpu->qlock);
  9473. return aged;
  9474. }
  9475. /* This function should be used by queued device drivers when they're sure
  9476. * the work struct is no longer in use. */
  9477. void work_completed(struct cgpu_info *cgpu, struct work *work)
  9478. {
  9479. wr_lock(&cgpu->qlock);
  9480. __work_completed(cgpu, work);
  9481. wr_unlock(&cgpu->qlock);
  9482. free_work(work);
  9483. }
  9484. /* Combines find_queued_work_bymidstate and work_completed in one function
  9485. * withOUT destroying the work so the driver must free it. */
  9486. struct work *take_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  9487. {
  9488. struct work *work;
  9489. wr_lock(&cgpu->qlock);
  9490. work = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  9491. if (work)
  9492. __work_completed(cgpu, work);
  9493. wr_unlock(&cgpu->qlock);
  9494. return work;
  9495. }
  9496. void flush_queue(struct cgpu_info *cgpu)
  9497. {
  9498. struct work *work = NULL;
  9499. wr_lock(&cgpu->qlock);
  9500. work = cgpu->unqueued_work;
  9501. cgpu->unqueued_work = NULL;
  9502. wr_unlock(&cgpu->qlock);
  9503. if (work) {
  9504. free_work(work);
  9505. applog(LOG_DEBUG, "Discarded queued work item");
  9506. }
  9507. }
  9508. /* This version of hash work is for devices that are fast enough to always
  9509. * perform a full nonce range and need a queue to maintain the device busy.
  9510. * Work creation and destruction is not done from within this function
  9511. * directly. */
  9512. void hash_queued_work(struct thr_info *mythr)
  9513. {
  9514. const long cycle = opt_log_interval / 5 ? : 1;
  9515. struct timeval tv_start = {0, 0}, tv_end;
  9516. struct cgpu_info *cgpu = mythr->cgpu;
  9517. struct device_drv *drv = cgpu->drv;
  9518. const int thr_id = mythr->id;
  9519. int64_t hashes_done = 0;
  9520. if (unlikely(cgpu->deven != DEV_ENABLED))
  9521. mt_disable(mythr);
  9522. while (likely(!cgpu->shutdown)) {
  9523. struct timeval diff;
  9524. int64_t hashes;
  9525. fill_queue(mythr, cgpu, drv, thr_id);
  9526. thread_reportin(mythr);
  9527. hashes = drv->scanwork(mythr);
  9528. /* Reset the bool here in case the driver looks for it
  9529. * synchronously in the scanwork loop. */
  9530. mythr->work_restart = false;
  9531. if (unlikely(hashes == -1 )) {
  9532. applog(LOG_ERR, "%s %d failure, disabling!", drv->name, cgpu->device_id);
  9533. cgpu->deven = DEV_DISABLED;
  9534. dev_error(cgpu, REASON_THREAD_ZERO_HASH);
  9535. mt_disable(mythr);
  9536. }
  9537. hashes_done += hashes;
  9538. cgtime(&tv_end);
  9539. timersub(&tv_end, &tv_start, &diff);
  9540. if (diff.tv_sec >= cycle) {
  9541. hashmeter(thr_id, &diff, hashes_done);
  9542. hashes_done = 0;
  9543. copy_time(&tv_start, &tv_end);
  9544. }
  9545. if (unlikely(mythr->pause || cgpu->deven != DEV_ENABLED))
  9546. mt_disable(mythr);
  9547. if (unlikely(mythr->work_restart)) {
  9548. flush_queue(cgpu);
  9549. if (drv->flush_work)
  9550. drv->flush_work(cgpu);
  9551. }
  9552. }
  9553. // cgpu->deven = DEV_DISABLED; set in miner_thread
  9554. }
  9555. // Called by minerloop, when it is re-enabling a processor
  9556. void mt_disable_finish(struct thr_info *mythr)
  9557. {
  9558. struct device_drv *drv = mythr->cgpu->drv;
  9559. thread_reportin(mythr);
  9560. __thr_being_msg(LOG_WARNING, mythr, "being re-enabled");
  9561. if (drv->thread_enable)
  9562. drv->thread_enable(mythr);
  9563. mythr->_mt_disable_called = false;
  9564. }
  9565. // Called by synchronous minerloops, when they find their processor should be disabled
  9566. // Calls mt_disable_start, waits until it's re-enabled, then calls mt_disable_finish
  9567. void mt_disable(struct thr_info *mythr)
  9568. {
  9569. const struct cgpu_info * const cgpu = mythr->cgpu;
  9570. mt_disable_start(mythr);
  9571. applog(LOG_DEBUG, "Waiting for wakeup notification in miner thread");
  9572. do {
  9573. notifier_read(mythr->notifier);
  9574. } while (mythr->pause || cgpu->deven != DEV_ENABLED);
  9575. mt_disable_finish(mythr);
  9576. }
  9577. enum {
  9578. STAT_SLEEP_INTERVAL = 1,
  9579. STAT_CTR_INTERVAL = 10000000,
  9580. FAILURE_INTERVAL = 30,
  9581. };
  9582. /* Stage another work item from the work returned in a longpoll */
  9583. 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)
  9584. {
  9585. bool rc;
  9586. work->rolltime = rolltime;
  9587. rc = work_decode(pool, work, val);
  9588. if (unlikely(!rc)) {
  9589. applog(LOG_ERR, "Could not convert longpoll data to work");
  9590. free_work(work);
  9591. return;
  9592. }
  9593. total_getworks++;
  9594. pool->getwork_requested++;
  9595. work->pool = pool;
  9596. copy_time(&work->tv_getwork, tv_lp);
  9597. copy_time(&work->tv_getwork_reply, tv_lp_reply);
  9598. calc_diff(work, 0);
  9599. if (pool->enabled == POOL_REJECTING)
  9600. work->mandatory = true;
  9601. work->longpoll = true;
  9602. work->getwork_mode = GETWORK_MODE_LP;
  9603. update_last_work(work);
  9604. /* We'll be checking this work item twice, but we already know it's
  9605. * from a new block so explicitly force the new block detection now
  9606. * rather than waiting for it to hit the stage thread. This also
  9607. * allows testwork to know whether LP discovered the block or not. */
  9608. test_work_current(work);
  9609. /* Don't use backup LPs as work if we have failover-only enabled. Use
  9610. * the longpoll work from a pool that has been rejecting shares as a
  9611. * way to detect when the pool has recovered.
  9612. */
  9613. if (pool != current_pool() && opt_fail_only && pool->enabled != POOL_REJECTING) {
  9614. free_work(work);
  9615. return;
  9616. }
  9617. work = clone_work(work);
  9618. applog(LOG_DEBUG, "Pushing converted work to stage thread");
  9619. stage_work(work);
  9620. applog(LOG_DEBUG, "Converted longpoll data to work");
  9621. }
  9622. /* If we want longpoll, enable it for the chosen default pool, or, if
  9623. * the pool does not support longpoll, find the first one that does
  9624. * and use its longpoll support */
  9625. static
  9626. struct pool *_select_longpoll_pool(struct pool *cp, bool(*func)(struct pool *))
  9627. {
  9628. int i;
  9629. if (func(cp))
  9630. return cp;
  9631. for (i = 0; i < total_pools; i++) {
  9632. struct pool *pool = pools[i];
  9633. if (cp->goal != pool->goal)
  9634. continue;
  9635. if (func(pool))
  9636. return pool;
  9637. }
  9638. return NULL;
  9639. }
  9640. /* This will make the longpoll thread wait till it's the current pool, or it
  9641. * has been flagged as rejecting, before attempting to open any connections.
  9642. */
  9643. static void wait_lpcurrent(struct pool *pool)
  9644. {
  9645. mutex_lock(&lp_lock);
  9646. while (!cnx_needed(pool))
  9647. {
  9648. pool->lp_active = false;
  9649. pthread_cond_wait(&lp_cond, &lp_lock);
  9650. }
  9651. mutex_unlock(&lp_lock);
  9652. }
  9653. static curl_socket_t save_curl_socket(void *vpool, __maybe_unused curlsocktype purpose, struct curl_sockaddr *addr) {
  9654. struct pool *pool = vpool;
  9655. curl_socket_t sock = bfg_socket(addr->family, addr->socktype, addr->protocol);
  9656. pool->lp_socket = sock;
  9657. return sock;
  9658. }
  9659. static void *longpoll_thread(void *userdata)
  9660. {
  9661. struct pool *cp = (struct pool *)userdata;
  9662. /* This *pool is the source of the actual longpoll, not the pool we've
  9663. * tied it to */
  9664. struct timeval start, reply, end;
  9665. struct pool *pool = NULL;
  9666. char threadname[20];
  9667. CURL *curl = NULL;
  9668. int failures = 0;
  9669. char *lp_url;
  9670. int rolltime;
  9671. #ifndef HAVE_PTHREAD_CANCEL
  9672. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  9673. #endif
  9674. snprintf(threadname, 20, "longpoll%u", cp->pool_no);
  9675. RenameThread(threadname);
  9676. curl = curl_easy_init();
  9677. if (unlikely(!curl)) {
  9678. applog(LOG_ERR, "CURL initialisation failed");
  9679. return NULL;
  9680. }
  9681. retry_pool:
  9682. pool = select_longpoll_pool(cp);
  9683. if (!pool) {
  9684. applog(LOG_WARNING, "No suitable long-poll found for %s", cp->rpc_url);
  9685. while (!pool) {
  9686. cgsleep_ms(60000);
  9687. pool = select_longpoll_pool(cp);
  9688. }
  9689. }
  9690. if (pool->has_stratum) {
  9691. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  9692. cp->rpc_url, pool->rpc_url);
  9693. goto out;
  9694. }
  9695. /* Any longpoll from any pool is enough for this to be true */
  9696. pool->goal->have_longpoll = true;
  9697. wait_lpcurrent(cp);
  9698. {
  9699. lp_url = pool->lp_url;
  9700. if (cp == pool)
  9701. applog(LOG_WARNING, "Long-polling activated for %s (%s)", lp_url, pool_protocol_name(pool->lp_proto));
  9702. else
  9703. applog(LOG_WARNING, "Long-polling activated for %s via %s (%s)", cp->rpc_url, lp_url, pool_protocol_name(pool->lp_proto));
  9704. }
  9705. while (42) {
  9706. json_t *val, *soval;
  9707. struct work *work = make_work();
  9708. char *lpreq;
  9709. lpreq = prepare_rpc_req(work, pool->lp_proto, pool->lp_id, pool);
  9710. work->pool = pool;
  9711. if (!lpreq)
  9712. {
  9713. free_work(work);
  9714. goto lpfail;
  9715. }
  9716. wait_lpcurrent(cp);
  9717. cgtime(&start);
  9718. /* Longpoll connections can be persistent for a very long time
  9719. * and any number of issues could have come up in the meantime
  9720. * so always establish a fresh connection instead of relying on
  9721. * a persistent one. */
  9722. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  9723. curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, save_curl_socket);
  9724. curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, pool);
  9725. val = json_rpc_call(curl, lp_url, pool->rpc_userpass,
  9726. lpreq, false, true, &rolltime, pool, false);
  9727. pool->lp_socket = CURL_SOCKET_BAD;
  9728. cgtime(&reply);
  9729. free(lpreq);
  9730. if (likely(val)) {
  9731. soval = json_object_get(json_object_get(val, "result"), "submitold");
  9732. if (soval)
  9733. pool->submit_old = json_is_true(soval);
  9734. else
  9735. pool->submit_old = false;
  9736. convert_to_work(val, rolltime, pool, work, &start, &reply);
  9737. failures = 0;
  9738. json_decref(val);
  9739. } else {
  9740. /* Some pools regularly drop the longpoll request so
  9741. * only see this as longpoll failure if it happens
  9742. * immediately and just restart it the rest of the
  9743. * time. */
  9744. cgtime(&end);
  9745. free_work(work);
  9746. if (end.tv_sec - start.tv_sec <= 30)
  9747. {
  9748. if (failures == 1)
  9749. applog(LOG_WARNING, "longpoll failed for %s, retrying every 30s", lp_url);
  9750. lpfail:
  9751. cgsleep_ms(30000);
  9752. }
  9753. }
  9754. if (pool != cp) {
  9755. pool = select_longpoll_pool(cp);
  9756. if (pool->has_stratum) {
  9757. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  9758. cp->rpc_url, pool->rpc_url);
  9759. break;
  9760. }
  9761. if (unlikely(!pool))
  9762. goto retry_pool;
  9763. }
  9764. if (unlikely(pool->removed))
  9765. break;
  9766. }
  9767. out:
  9768. pool->lp_active = false;
  9769. curl_easy_cleanup(curl);
  9770. return NULL;
  9771. }
  9772. static void stop_longpoll(void)
  9773. {
  9774. int i;
  9775. want_longpoll = false;
  9776. for (i = 0; i < total_pools; ++i)
  9777. {
  9778. struct pool *pool = pools[i];
  9779. if (unlikely(!pool->lp_started))
  9780. continue;
  9781. pool->lp_started = false;
  9782. pthread_cancel(pool->longpoll_thread);
  9783. }
  9784. struct mining_goal_info *goal, *tmpgoal;
  9785. HASH_ITER(hh, mining_goals, goal, tmpgoal)
  9786. {
  9787. goal->have_longpoll = false;
  9788. }
  9789. }
  9790. static void start_longpoll(void)
  9791. {
  9792. int i;
  9793. want_longpoll = true;
  9794. for (i = 0; i < total_pools; ++i)
  9795. {
  9796. struct pool *pool = pools[i];
  9797. if (unlikely(pool->removed || pool->lp_started || !pool->lp_url))
  9798. continue;
  9799. pool->lp_started = true;
  9800. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  9801. quit(1, "Failed to create pool longpoll thread");
  9802. }
  9803. }
  9804. void reinit_device(struct cgpu_info *cgpu)
  9805. {
  9806. if (cgpu->drv->reinit_device)
  9807. cgpu->drv->reinit_device(cgpu);
  9808. }
  9809. static struct timeval rotate_tv;
  9810. /* We reap curls if they are unused for over a minute */
  9811. static void reap_curl(struct pool *pool)
  9812. {
  9813. struct curl_ent *ent, *iter;
  9814. struct timeval now;
  9815. int reaped = 0;
  9816. cgtime(&now);
  9817. mutex_lock(&pool->pool_lock);
  9818. LL_FOREACH_SAFE(pool->curllist, ent, iter) {
  9819. if (pool->curls < 2)
  9820. break;
  9821. if (now.tv_sec - ent->tv.tv_sec > 300) {
  9822. reaped++;
  9823. pool->curls--;
  9824. LL_DELETE(pool->curllist, ent);
  9825. curl_easy_cleanup(ent->curl);
  9826. free(ent);
  9827. }
  9828. }
  9829. mutex_unlock(&pool->pool_lock);
  9830. if (reaped)
  9831. applog(LOG_DEBUG, "Reaped %d curl%s from pool %d", reaped, reaped > 1 ? "s" : "", pool->pool_no);
  9832. }
  9833. static void *watchpool_thread(void __maybe_unused *userdata)
  9834. {
  9835. int intervals = 0;
  9836. #ifndef HAVE_PTHREAD_CANCEL
  9837. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  9838. #endif
  9839. RenameThread("watchpool");
  9840. while (42) {
  9841. struct timeval now;
  9842. int i;
  9843. if (++intervals > 20)
  9844. intervals = 0;
  9845. cgtime(&now);
  9846. for (i = 0; i < total_pools; i++) {
  9847. struct pool *pool = pools[i];
  9848. if (!opt_benchmark)
  9849. reap_curl(pool);
  9850. /* Get a rolling utility per pool over 10 mins */
  9851. if (intervals > 19) {
  9852. int shares = pool->diff1 - pool->last_shares;
  9853. pool->last_shares = pool->diff1;
  9854. pool->utility = (pool->utility + (double)shares * 0.63) / 1.63;
  9855. pool->shares = pool->utility;
  9856. }
  9857. if (pool->enabled == POOL_DISABLED)
  9858. continue;
  9859. /* Don't start testing any pools if the test threads
  9860. * from startup are still doing their first attempt. */
  9861. if (unlikely(pool->testing)) {
  9862. pthread_join(pool->test_thread, NULL);
  9863. }
  9864. /* Test pool is idle once every minute */
  9865. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 30) {
  9866. if (pool_active(pool, true) && pool_tclear(pool, &pool->idle))
  9867. pool_resus(pool);
  9868. }
  9869. /* Only switch pools if the failback pool has been
  9870. * alive for more than 5 minutes (default) to prevent
  9871. * intermittently failing pools from being used. */
  9872. 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)
  9873. {
  9874. if (opt_fail_switch_delay % 60)
  9875. applog(LOG_WARNING, "Pool %d %s stable for %d second%s",
  9876. pool->pool_no, pool->rpc_url,
  9877. opt_fail_switch_delay,
  9878. (opt_fail_switch_delay == 1 ? "" : "s"));
  9879. else
  9880. applog(LOG_WARNING, "Pool %d %s stable for %d minute%s",
  9881. pool->pool_no, pool->rpc_url,
  9882. opt_fail_switch_delay / 60,
  9883. (opt_fail_switch_delay == 60 ? "" : "s"));
  9884. switch_pools(NULL);
  9885. }
  9886. }
  9887. if (current_pool()->idle)
  9888. switch_pools(NULL);
  9889. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  9890. cgtime(&rotate_tv);
  9891. switch_pools(NULL);
  9892. }
  9893. cgsleep_ms(30000);
  9894. }
  9895. return NULL;
  9896. }
  9897. void mt_enable(struct thr_info *thr)
  9898. {
  9899. applog(LOG_DEBUG, "Waking up thread %d", thr->id);
  9900. notifier_wake(thr->notifier);
  9901. }
  9902. void proc_enable(struct cgpu_info *cgpu)
  9903. {
  9904. int j;
  9905. cgpu->deven = DEV_ENABLED;
  9906. for (j = cgpu->threads ?: 1; j--; )
  9907. mt_enable(cgpu->thr[j]);
  9908. }
  9909. #define device_recovered(cgpu) proc_enable(cgpu)
  9910. void cgpu_set_defaults(struct cgpu_info * const cgpu)
  9911. {
  9912. struct string_elist *setstr_elist;
  9913. const char *p, *p2;
  9914. char replybuf[0x2000];
  9915. size_t L;
  9916. DL_FOREACH(opt_set_device_list, setstr_elist)
  9917. {
  9918. const char * const setstr = setstr_elist->string;
  9919. p = strchr(setstr, ':');
  9920. if (!p)
  9921. p = setstr;
  9922. {
  9923. L = p - setstr;
  9924. char pattern[L + 1];
  9925. if (L)
  9926. memcpy(pattern, setstr, L);
  9927. pattern[L] = '\0';
  9928. if (!cgpu_match(pattern, cgpu))
  9929. continue;
  9930. }
  9931. applog(LOG_DEBUG, "%"PRIpreprv": %s: Matched with set default: %s",
  9932. cgpu->proc_repr, __func__, setstr);
  9933. if (p[0] == ':')
  9934. ++p;
  9935. p2 = strchr(p, '=');
  9936. if (!p2)
  9937. {
  9938. L = strlen(p);
  9939. p2 = "";
  9940. }
  9941. else
  9942. {
  9943. L = p2 - p;
  9944. ++p2;
  9945. }
  9946. char opt[L + 1];
  9947. if (L)
  9948. memcpy(opt, p, L);
  9949. opt[L] = '\0';
  9950. L = strlen(p2);
  9951. char setval[L + 1];
  9952. if (L)
  9953. memcpy(setval, p2, L);
  9954. setval[L] = '\0';
  9955. enum bfg_set_device_replytype success;
  9956. p = proc_set_device(cgpu, opt, setval, replybuf, &success);
  9957. switch (success)
  9958. {
  9959. case SDR_OK:
  9960. applog(LOG_DEBUG, "%"PRIpreprv": Applied rule %s%s%s",
  9961. cgpu->proc_repr, setstr,
  9962. p ? ": " : "", p ?: "");
  9963. break;
  9964. case SDR_ERR:
  9965. case SDR_HELP:
  9966. case SDR_UNKNOWN:
  9967. applog(LOG_DEBUG, "%"PRIpreprv": Applying rule %s: %s",
  9968. cgpu->proc_repr, setstr, p);
  9969. break;
  9970. case SDR_AUTO:
  9971. case SDR_NOSUPP:
  9972. applog(LOG_DEBUG, "%"PRIpreprv": set_device is not implemented (trying to apply rule: %s)",
  9973. cgpu->proc_repr, setstr);
  9974. }
  9975. }
  9976. cgpu->already_set_defaults = true;
  9977. }
  9978. 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)
  9979. {
  9980. struct device_drv dummy_drv = *drv;
  9981. struct cgpu_info dummy_cgpu = {
  9982. .drv = &dummy_drv,
  9983. .device = &dummy_cgpu,
  9984. .device_id = -1,
  9985. .proc_id = -1,
  9986. .device_data = userp,
  9987. .device_path = devpath,
  9988. .dev_serial = serial,
  9989. };
  9990. strcpy(dummy_cgpu.proc_repr, drv->name);
  9991. switch (mode)
  9992. {
  9993. case 0:
  9994. dummy_drv.set_device = datap;
  9995. break;
  9996. case 1:
  9997. dummy_drv.set_device = NULL;
  9998. dummy_cgpu.set_device_funcs = datap;
  9999. break;
  10000. }
  10001. cgpu_set_defaults(&dummy_cgpu);
  10002. }
  10003. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  10004. * the screen at regular intervals, and restarts threads if they appear to have
  10005. * died. */
  10006. #define WATCHDOG_SICK_TIME 60
  10007. #define WATCHDOG_DEAD_TIME 600
  10008. #define WATCHDOG_SICK_COUNT (WATCHDOG_SICK_TIME/WATCHDOG_INTERVAL)
  10009. #define WATCHDOG_DEAD_COUNT (WATCHDOG_DEAD_TIME/WATCHDOG_INTERVAL)
  10010. static void *watchdog_thread(void __maybe_unused *userdata)
  10011. {
  10012. const unsigned int interval = WATCHDOG_INTERVAL;
  10013. struct timeval zero_tv;
  10014. #ifndef HAVE_PTHREAD_CANCEL
  10015. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  10016. #endif
  10017. RenameThread("watchdog");
  10018. memset(&zero_tv, 0, sizeof(struct timeval));
  10019. cgtime(&rotate_tv);
  10020. while (1) {
  10021. int i;
  10022. struct timeval now;
  10023. sleep(interval);
  10024. discard_stale();
  10025. hashmeter(-1, &zero_tv, 0);
  10026. #ifdef HAVE_CURSES
  10027. const int ts = total_staged(true);
  10028. if (curses_active_locked()) {
  10029. change_logwinsize();
  10030. curses_print_status(ts);
  10031. _refresh_devstatus(true);
  10032. touchwin(logwin);
  10033. wrefresh(logwin);
  10034. unlock_curses();
  10035. }
  10036. #endif
  10037. cgtime(&now);
  10038. if (!sched_paused && !should_run()) {
  10039. applog(LOG_WARNING, "Pausing execution as per stop time %02d:%02d scheduled",
  10040. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  10041. if (!schedstart.enable) {
  10042. quit(0, "Terminating execution as planned");
  10043. break;
  10044. }
  10045. applog(LOG_WARNING, "Will restart execution as scheduled at %02d:%02d",
  10046. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  10047. sched_paused = true;
  10048. rd_lock(&mining_thr_lock);
  10049. for (i = 0; i < mining_threads; i++)
  10050. mining_thr[i]->pause = true;
  10051. rd_unlock(&mining_thr_lock);
  10052. } else if (sched_paused && should_run()) {
  10053. applog(LOG_WARNING, "Restarting execution as per start time %02d:%02d scheduled",
  10054. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  10055. if (schedstop.enable)
  10056. applog(LOG_WARNING, "Will pause execution as scheduled at %02d:%02d",
  10057. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  10058. sched_paused = false;
  10059. for (i = 0; i < mining_threads; i++) {
  10060. struct thr_info *thr;
  10061. thr = get_thread(i);
  10062. thr->pause = false;
  10063. }
  10064. for (i = 0; i < total_devices; ++i)
  10065. {
  10066. struct cgpu_info *cgpu = get_devices(i);
  10067. /* Don't touch disabled devices */
  10068. if (cgpu->deven == DEV_DISABLED)
  10069. continue;
  10070. proc_enable(cgpu);
  10071. }
  10072. }
  10073. for (i = 0; i < total_devices; ++i) {
  10074. struct cgpu_info *cgpu = get_devices(i);
  10075. if (!cgpu->disable_watchdog)
  10076. bfg_watchdog(cgpu, &now);
  10077. }
  10078. }
  10079. return NULL;
  10080. }
  10081. void bfg_watchdog(struct cgpu_info * const cgpu, struct timeval * const tvp_now)
  10082. {
  10083. struct thr_info *thr = cgpu->thr[0];
  10084. enum dev_enable *denable;
  10085. char *dev_str = cgpu->proc_repr;
  10086. if (likely(drv_ready(cgpu)))
  10087. {
  10088. if (unlikely(!cgpu->already_set_defaults))
  10089. cgpu_set_defaults(cgpu);
  10090. if (cgpu->drv->get_stats)
  10091. cgpu->drv->get_stats(cgpu);
  10092. }
  10093. denable = &cgpu->deven;
  10094. if (cgpu->drv->watchdog)
  10095. cgpu->drv->watchdog(cgpu, tvp_now);
  10096. /* Thread is disabled */
  10097. if (*denable == DEV_DISABLED)
  10098. return;
  10099. else
  10100. if (*denable == DEV_RECOVER_ERR) {
  10101. if (opt_restart && timer_elapsed(&cgpu->tv_device_last_not_well, NULL) > cgpu->reinit_backoff) {
  10102. applog(LOG_NOTICE, "Attempting to reinitialize %s",
  10103. dev_str);
  10104. if (cgpu->reinit_backoff < 300)
  10105. cgpu->reinit_backoff *= 2;
  10106. device_recovered(cgpu);
  10107. }
  10108. return;
  10109. }
  10110. else
  10111. if (*denable == DEV_RECOVER) {
  10112. if (opt_restart && cgpu->temp < cgpu->targettemp) {
  10113. applog(LOG_NOTICE, "%s recovered to temperature below target, re-enabling",
  10114. dev_str);
  10115. device_recovered(cgpu);
  10116. }
  10117. dev_error_update(cgpu, REASON_DEV_THERMAL_CUTOFF);
  10118. return;
  10119. }
  10120. else
  10121. if (cgpu->temp > cgpu->cutofftemp)
  10122. {
  10123. applog(LOG_WARNING, "%s hit thermal cutoff limit at %dC, disabling!",
  10124. dev_str, (int)cgpu->temp);
  10125. *denable = DEV_RECOVER;
  10126. dev_error(cgpu, REASON_DEV_THERMAL_CUTOFF);
  10127. run_cmd(cmd_idle);
  10128. }
  10129. if (thr->getwork) {
  10130. if (cgpu->status == LIFE_WELL && thr->getwork < tvp_now->tv_sec - opt_log_interval) {
  10131. int thrid;
  10132. bool cgpu_idle = true;
  10133. thr->rolling = 0;
  10134. for (thrid = 0; thrid < cgpu->threads; ++thrid)
  10135. if (!cgpu->thr[thrid]->getwork)
  10136. cgpu_idle = false;
  10137. if (cgpu_idle) {
  10138. cgpu->rolling = 0;
  10139. cgpu->status = LIFE_WAIT;
  10140. }
  10141. }
  10142. return;
  10143. }
  10144. else if (cgpu->status == LIFE_WAIT)
  10145. cgpu->status = LIFE_WELL;
  10146. #ifdef USE_CPUMINING
  10147. if (!strcmp(cgpu->drv->dname, "cpu"))
  10148. return;
  10149. #endif
  10150. if (cgpu->status != LIFE_WELL && (tvp_now->tv_sec - thr->last.tv_sec < WATCHDOG_SICK_TIME)) {
  10151. if (likely(cgpu->status != LIFE_INIT && cgpu->status != LIFE_INIT2))
  10152. applog(LOG_ERR, "%s: Recovered, declaring WELL!", dev_str);
  10153. cgpu->status = LIFE_WELL;
  10154. cgpu->device_last_well = time(NULL);
  10155. } else if (cgpu->status == LIFE_WELL && (tvp_now->tv_sec - thr->last.tv_sec > WATCHDOG_SICK_TIME)) {
  10156. thr->rolling = cgpu->rolling = 0;
  10157. cgpu->status = LIFE_SICK;
  10158. applog(LOG_ERR, "%s: Idle for more than 60 seconds, declaring SICK!", dev_str);
  10159. cgtime(&thr->sick);
  10160. dev_error(cgpu, REASON_DEV_SICK_IDLE_60);
  10161. run_cmd(cmd_sick);
  10162. if (opt_restart && cgpu->drv->reinit_device) {
  10163. applog(LOG_ERR, "%s: Attempting to restart", dev_str);
  10164. reinit_device(cgpu);
  10165. }
  10166. } else if (cgpu->status == LIFE_SICK && (tvp_now->tv_sec - thr->last.tv_sec > WATCHDOG_DEAD_TIME)) {
  10167. cgpu->status = LIFE_DEAD;
  10168. applog(LOG_ERR, "%s: Not responded for more than 10 minutes, declaring DEAD!", dev_str);
  10169. cgtime(&thr->sick);
  10170. dev_error(cgpu, REASON_DEV_DEAD_IDLE_600);
  10171. run_cmd(cmd_dead);
  10172. } else if (tvp_now->tv_sec - thr->sick.tv_sec > 60 &&
  10173. (cgpu->status == LIFE_SICK || cgpu->status == LIFE_DEAD)) {
  10174. /* Attempt to restart a GPU that's sick or dead once every minute */
  10175. cgtime(&thr->sick);
  10176. if (opt_restart)
  10177. reinit_device(cgpu);
  10178. }
  10179. }
  10180. static void log_print_status(struct cgpu_info *cgpu)
  10181. {
  10182. char logline[255];
  10183. get_statline(logline, sizeof(logline), cgpu);
  10184. applog(LOG_WARNING, "%s", logline);
  10185. }
  10186. void print_summary(void)
  10187. {
  10188. struct timeval diff;
  10189. int hours, mins, secs, i;
  10190. double utility, efficiency = 0.0;
  10191. char xfer[(ALLOC_H2B_SPACED*2)+4+1], bw[(ALLOC_H2B_SPACED*2)+6+1];
  10192. int pool_secs;
  10193. timersub(&total_tv_end, &total_tv_start, &diff);
  10194. hours = diff.tv_sec / 3600;
  10195. mins = (diff.tv_sec % 3600) / 60;
  10196. secs = diff.tv_sec % 60;
  10197. utility = total_accepted / total_secs * 60;
  10198. efficiency = total_bytes_xfer ? total_diff_accepted * 2048. / total_bytes_xfer : 0.0;
  10199. applog(LOG_WARNING, "\nSummary of runtime statistics:\n");
  10200. applog(LOG_WARNING, "Started at %s", datestamp);
  10201. if (total_pools == 1)
  10202. applog(LOG_WARNING, "Pool: %s", pools[0]->rpc_url);
  10203. #if defined(USE_CPUMINING) && defined(USE_SHA256D)
  10204. if (opt_n_threads > 0)
  10205. applog(LOG_WARNING, "CPU hasher algorithm used: %s", algo_names[opt_algo]);
  10206. #endif
  10207. applog(LOG_WARNING, "Runtime: %d hrs : %d mins : %d secs", hours, mins, secs);
  10208. applog(LOG_WARNING, "Average hashrate: %.1f Megahash/s", total_mhashes_done / total_secs);
  10209. applog(LOG_WARNING, "Solved blocks: %d", found_blocks);
  10210. applog(LOG_WARNING, "Best share difficulty: %s", best_share);
  10211. applog(LOG_WARNING, "Share submissions: %d", total_accepted + total_rejected);
  10212. applog(LOG_WARNING, "Accepted shares: %d", total_accepted);
  10213. applog(LOG_WARNING, "Rejected shares: %d + %d stale (%.2f%%)",
  10214. total_rejected, total_stale,
  10215. (float)(total_rejected + total_stale) / (float)(total_rejected + total_stale + total_accepted)
  10216. );
  10217. applog(LOG_WARNING, "Accepted difficulty shares: %1.f", total_diff_accepted);
  10218. applog(LOG_WARNING, "Rejected difficulty shares: %1.f", total_diff_rejected);
  10219. applog(LOG_WARNING, "Hardware errors: %d", hw_errors);
  10220. applog(LOG_WARNING, "Network transfer: %s (%s)",
  10221. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  10222. (float)total_bytes_rcvd,
  10223. (float)total_bytes_sent),
  10224. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  10225. (float)(total_bytes_rcvd / total_secs),
  10226. (float)(total_bytes_sent / total_secs)));
  10227. applog(LOG_WARNING, "Efficiency (accepted shares * difficulty / 2 KB): %.2f", efficiency);
  10228. applog(LOG_WARNING, "Utility (accepted shares / min): %.2f/min\n", utility);
  10229. applog(LOG_WARNING, "Unable to get work from server occasions: %d", total_go);
  10230. applog(LOG_WARNING, "Work items generated locally: %d", local_work);
  10231. applog(LOG_WARNING, "Submitting work remotely delay occasions: %d", total_ro);
  10232. applog(LOG_WARNING, "New blocks detected on network: %d\n", new_blocks);
  10233. if (total_pools > 1) {
  10234. for (i = 0; i < total_pools; i++) {
  10235. struct pool *pool = pools[i];
  10236. applog(LOG_WARNING, "Pool: %s", pool->rpc_url);
  10237. if (pool->solved)
  10238. applog(LOG_WARNING, "SOLVED %d BLOCK%s!", pool->solved, pool->solved > 1 ? "S" : "");
  10239. applog(LOG_WARNING, " Share submissions: %d", pool->accepted + pool->rejected);
  10240. applog(LOG_WARNING, " Accepted shares: %d", pool->accepted);
  10241. applog(LOG_WARNING, " Rejected shares: %d + %d stale (%.2f%%)",
  10242. pool->rejected, pool->stale_shares,
  10243. (float)(pool->rejected + pool->stale_shares) / (float)(pool->rejected + pool->stale_shares + pool->accepted)
  10244. );
  10245. applog(LOG_WARNING, " Accepted difficulty shares: %1.f", pool->diff_accepted);
  10246. applog(LOG_WARNING, " Rejected difficulty shares: %1.f", pool->diff_rejected);
  10247. pool_secs = timer_elapsed(&pool->cgminer_stats.start_tv, NULL);
  10248. applog(LOG_WARNING, " Network transfer: %s (%s)",
  10249. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  10250. (float)pool->cgminer_pool_stats.net_bytes_received,
  10251. (float)pool->cgminer_pool_stats.net_bytes_sent),
  10252. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  10253. (float)(pool->cgminer_pool_stats.net_bytes_received / pool_secs),
  10254. (float)(pool->cgminer_pool_stats.net_bytes_sent / pool_secs)));
  10255. uint64_t pool_bytes_xfer = pool->cgminer_pool_stats.net_bytes_received + pool->cgminer_pool_stats.net_bytes_sent;
  10256. efficiency = pool_bytes_xfer ? pool->diff_accepted * 2048. / pool_bytes_xfer : 0.0;
  10257. applog(LOG_WARNING, " Efficiency (accepted * difficulty / 2 KB): %.2f", efficiency);
  10258. applog(LOG_WARNING, " Items worked on: %d", pool->works);
  10259. applog(LOG_WARNING, " Unable to get work from server occasions: %d", pool->getfail_occasions);
  10260. applog(LOG_WARNING, " Submitting work remotely delay occasions: %d\n", pool->remotefail_occasions);
  10261. }
  10262. }
  10263. if (opt_quit_summary != BQS_NONE)
  10264. {
  10265. if (opt_quit_summary == BQS_DEFAULT)
  10266. {
  10267. if (total_devices < 25)
  10268. opt_quit_summary = BQS_PROCS;
  10269. else
  10270. opt_quit_summary = BQS_DEVS;
  10271. }
  10272. if (opt_quit_summary == BQS_DETAILED)
  10273. include_serial_in_statline = true;
  10274. applog(LOG_WARNING, "Summary of per device statistics:\n");
  10275. for (i = 0; i < total_devices; ++i) {
  10276. struct cgpu_info *cgpu = get_devices(i);
  10277. if (!cgpu->proc_id)
  10278. {
  10279. // Device summary line
  10280. opt_show_procs = false;
  10281. log_print_status(cgpu);
  10282. opt_show_procs = true;
  10283. }
  10284. if ((opt_quit_summary == BQS_PROCS || opt_quit_summary == BQS_DETAILED) && cgpu->procs > 1)
  10285. log_print_status(cgpu);
  10286. }
  10287. }
  10288. if (opt_shares) {
  10289. applog(LOG_WARNING, "Mined %g accepted shares of %g requested\n", total_diff_accepted, opt_shares);
  10290. if (opt_shares > total_diff_accepted)
  10291. applog(LOG_WARNING, "WARNING - Mined only %g shares of %g requested.", total_diff_accepted, opt_shares);
  10292. }
  10293. applog(LOG_WARNING, " ");
  10294. fflush(stderr);
  10295. fflush(stdout);
  10296. }
  10297. void _bfg_clean_up(bool restarting)
  10298. {
  10299. #ifdef USE_OPENCL
  10300. clear_adl(nDevs);
  10301. #endif
  10302. #ifdef HAVE_LIBUSB
  10303. if (likely(have_libusb))
  10304. libusb_exit(NULL);
  10305. #endif
  10306. cgtime(&total_tv_end);
  10307. #ifdef WIN32
  10308. timeEndPeriod(1);
  10309. #endif
  10310. if (!restarting) {
  10311. /* Attempting to disable curses or print a summary during a
  10312. * restart can lead to a deadlock. */
  10313. #ifdef HAVE_CURSES
  10314. disable_curses();
  10315. #endif
  10316. if (!opt_realquiet && successful_connect)
  10317. print_summary();
  10318. }
  10319. if (opt_n_threads > 0)
  10320. free(cpus);
  10321. curl_global_cleanup();
  10322. #ifdef WIN32
  10323. WSACleanup();
  10324. #endif
  10325. }
  10326. void _quit(int status)
  10327. {
  10328. if (status) {
  10329. const char *ev = getenv("__BFGMINER_SEGFAULT_ERRQUIT");
  10330. if (unlikely(ev && ev[0] && ev[0] != '0')) {
  10331. int *p = NULL;
  10332. // NOTE debugger can bypass with: p = &p
  10333. *p = status; // Segfault, hopefully dumping core
  10334. }
  10335. }
  10336. #if defined(unix) || defined(__APPLE__)
  10337. if (forkpid > 0) {
  10338. kill(forkpid, SIGTERM);
  10339. forkpid = 0;
  10340. }
  10341. #endif
  10342. exit(status);
  10343. }
  10344. #ifdef HAVE_CURSES
  10345. char *curses_input(const char *query)
  10346. {
  10347. char *input;
  10348. echo();
  10349. input = malloc(255);
  10350. if (!input)
  10351. quit(1, "Failed to malloc input");
  10352. leaveok(logwin, false);
  10353. wlogprint("%s:\n", query);
  10354. wgetnstr(logwin, input, 255);
  10355. if (!strlen(input))
  10356. {
  10357. free(input);
  10358. input = NULL;
  10359. }
  10360. leaveok(logwin, true);
  10361. noecho();
  10362. return input;
  10363. }
  10364. #endif
  10365. static void *test_pool_thread(void *arg)
  10366. {
  10367. struct pool *pool = (struct pool *)arg;
  10368. if (pool_active(pool, false)) {
  10369. pool_tset(pool, &pool->lagging);
  10370. pool_tclear(pool, &pool->idle);
  10371. bool first_pool = false;
  10372. cg_wlock(&control_lock);
  10373. if (!pools_active) {
  10374. currentpool = pool;
  10375. if (pool->pool_no != 0)
  10376. first_pool = true;
  10377. pools_active = true;
  10378. }
  10379. cg_wunlock(&control_lock);
  10380. if (unlikely(first_pool))
  10381. applog(LOG_NOTICE, "Switching to pool %d %s - first alive pool", pool->pool_no, pool->rpc_url);
  10382. else
  10383. applog(LOG_NOTICE, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  10384. switch_pools(NULL);
  10385. } else
  10386. pool_died(pool);
  10387. pool->testing = false;
  10388. return NULL;
  10389. }
  10390. /* Always returns true that the pool details were added unless we are not
  10391. * live, implying this is the only pool being added, so if no pools are
  10392. * active it returns false. */
  10393. bool add_pool_details(struct pool *pool, bool live, char *url, char *user, char *pass)
  10394. {
  10395. size_t siz;
  10396. pool_set_uri(pool, url);
  10397. pool->rpc_user = user;
  10398. pool->rpc_pass = pass;
  10399. siz = strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2;
  10400. pool->rpc_userpass = malloc(siz);
  10401. if (!pool->rpc_userpass)
  10402. quit(1, "Failed to malloc userpass");
  10403. snprintf(pool->rpc_userpass, siz, "%s:%s", pool->rpc_user, pool->rpc_pass);
  10404. pool->testing = true;
  10405. pool->idle = true;
  10406. enable_pool(pool);
  10407. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  10408. if (!live) {
  10409. pthread_join(pool->test_thread, NULL);
  10410. return pools_active;
  10411. }
  10412. return true;
  10413. }
  10414. #ifdef HAVE_CURSES
  10415. static bool input_pool(bool live)
  10416. {
  10417. char *url = NULL, *user = NULL, *pass = NULL;
  10418. struct pool *pool;
  10419. bool ret = false;
  10420. immedok(logwin, true);
  10421. wlogprint("Input server details.\n");
  10422. url = curses_input("URL");
  10423. if (!url)
  10424. goto out;
  10425. user = curses_input("Username");
  10426. if (!user)
  10427. goto out;
  10428. pass = curses_input("Password");
  10429. if (!pass)
  10430. pass = calloc(1, 1);
  10431. pool = add_pool();
  10432. if (!detect_stratum(pool, url) && strncmp(url, "http://", 7) &&
  10433. strncmp(url, "https://", 8)) {
  10434. char *httpinput;
  10435. httpinput = malloc(256);
  10436. if (!httpinput)
  10437. quit(1, "Failed to malloc httpinput");
  10438. strcpy(httpinput, "http://");
  10439. strncat(httpinput, url, 248);
  10440. free(url);
  10441. url = httpinput;
  10442. }
  10443. ret = add_pool_details(pool, live, url, user, pass);
  10444. out:
  10445. immedok(logwin, false);
  10446. if (!ret) {
  10447. if (url)
  10448. free(url);
  10449. if (user)
  10450. free(user);
  10451. if (pass)
  10452. free(pass);
  10453. }
  10454. return ret;
  10455. }
  10456. #endif
  10457. #if BLKMAKER_VERSION > 1 && defined(USE_SHA256D)
  10458. static
  10459. bool _add_local_gbt(const char * const filepath, void *userp)
  10460. {
  10461. const bool * const live_p = userp;
  10462. struct pool *pool;
  10463. char buf[0x100];
  10464. char *rpcuser = NULL, *rpcpass = NULL, *rpcconnect = NULL;
  10465. int rpcport = 0, rpcssl = -101;
  10466. FILE * const F = fopen(filepath, "r");
  10467. if (!F)
  10468. applogr(false, LOG_WARNING, "%s: Failed to open %s for reading", "add_local_gbt", filepath);
  10469. while (fgets(buf, sizeof(buf), F))
  10470. {
  10471. if (!strncasecmp(buf, "rpcuser=", 8))
  10472. rpcuser = trimmed_strdup(&buf[8]);
  10473. else
  10474. if (!strncasecmp(buf, "rpcpassword=", 12))
  10475. rpcpass = trimmed_strdup(&buf[12]);
  10476. else
  10477. if (!strncasecmp(buf, "rpcport=", 8))
  10478. rpcport = atoi(&buf[8]);
  10479. else
  10480. if (!strncasecmp(buf, "rpcssl=", 7))
  10481. rpcssl = atoi(&buf[7]);
  10482. else
  10483. if (!strncasecmp(buf, "rpcconnect=", 11))
  10484. rpcconnect = trimmed_strdup(&buf[11]);
  10485. else
  10486. continue;
  10487. if (rpcuser && rpcpass && rpcport && rpcssl != -101 && rpcconnect)
  10488. break;
  10489. }
  10490. fclose(F);
  10491. if (!rpcpass)
  10492. {
  10493. applog(LOG_DEBUG, "%s: Did not find rpcpassword in %s", "add_local_gbt", filepath);
  10494. err:
  10495. free(rpcuser);
  10496. free(rpcpass);
  10497. goto out;
  10498. }
  10499. if (!rpcport)
  10500. rpcport = 8332;
  10501. if (rpcssl == -101)
  10502. rpcssl = 0;
  10503. const bool have_cbaddr = get_mining_goal("default")->generation_script;
  10504. const int uri_sz = 0x30;
  10505. char * const uri = malloc(uri_sz);
  10506. snprintf(uri, uri_sz, "http%s://%s:%d/%s#allblocks", rpcssl ? "s" : "", rpcconnect ?: "localhost", rpcport, have_cbaddr ? "" : "#getcbaddr");
  10507. char hfuri[0x40];
  10508. if (rpcconnect)
  10509. snprintf(hfuri, sizeof(hfuri), "%s:%d", rpcconnect, rpcport);
  10510. else
  10511. snprintf(hfuri, sizeof(hfuri), "port %d", rpcport);
  10512. applog(LOG_DEBUG, "Local bitcoin RPC server on %s found in %s", hfuri, filepath);
  10513. for (int i = 0; i < total_pools; ++i)
  10514. {
  10515. struct pool *pool = pools[i];
  10516. if (!(strcmp(pool->rpc_url, uri) || strcmp(pool->rpc_pass, rpcpass)))
  10517. {
  10518. applog(LOG_DEBUG, "Server on %s is already configured, not adding as failover", hfuri);
  10519. free(uri);
  10520. goto err;
  10521. }
  10522. }
  10523. pool = add_pool();
  10524. if (!pool)
  10525. {
  10526. applog(LOG_ERR, "%s: Error adding pool for bitcoin configured in %s", "add_local_gbt", filepath);
  10527. goto err;
  10528. }
  10529. if (!rpcuser)
  10530. rpcuser = "";
  10531. pool->quota = 0;
  10532. adjust_quota_gcd();
  10533. pool->failover_only = true;
  10534. add_pool_details(pool, *live_p, uri, rpcuser, rpcpass);
  10535. applog(LOG_NOTICE, "Added local bitcoin RPC server on %s as pool %d", hfuri, pool->pool_no);
  10536. out:
  10537. return false;
  10538. }
  10539. static
  10540. void add_local_gbt(bool live)
  10541. {
  10542. appdata_file_call("Bitcoin", "bitcoin.conf", _add_local_gbt, &live);
  10543. }
  10544. #endif
  10545. #if defined(unix) || defined(__APPLE__)
  10546. static void fork_monitor()
  10547. {
  10548. // Make a pipe: [readFD, writeFD]
  10549. int pfd[2];
  10550. int r = pipe(pfd);
  10551. if (r < 0) {
  10552. perror("pipe - failed to create pipe for --monitor");
  10553. exit(1);
  10554. }
  10555. // Make stderr write end of pipe
  10556. fflush(stderr);
  10557. r = dup2(pfd[1], 2);
  10558. if (r < 0) {
  10559. perror("dup2 - failed to alias stderr to write end of pipe for --monitor");
  10560. exit(1);
  10561. }
  10562. r = close(pfd[1]);
  10563. if (r < 0) {
  10564. perror("close - failed to close write end of pipe for --monitor");
  10565. exit(1);
  10566. }
  10567. // Don't allow a dying monitor to kill the main process
  10568. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  10569. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  10570. if (SIG_ERR == sr0 || SIG_ERR == sr1) {
  10571. perror("signal - failed to edit signal mask for --monitor");
  10572. exit(1);
  10573. }
  10574. // Fork a child process
  10575. forkpid = fork();
  10576. if (forkpid < 0) {
  10577. perror("fork - failed to fork child process for --monitor");
  10578. exit(1);
  10579. }
  10580. // Child: launch monitor command
  10581. if (0 == forkpid) {
  10582. // Make stdin read end of pipe
  10583. r = dup2(pfd[0], 0);
  10584. if (r < 0) {
  10585. perror("dup2 - in child, failed to alias read end of pipe to stdin for --monitor");
  10586. exit(1);
  10587. }
  10588. close(pfd[0]);
  10589. if (r < 0) {
  10590. perror("close - in child, failed to close read end of pipe for --monitor");
  10591. exit(1);
  10592. }
  10593. // Launch user specified command
  10594. execl("/bin/bash", "/bin/bash", "-c", opt_stderr_cmd, (char*)NULL);
  10595. perror("execl - in child failed to exec user specified command for --monitor");
  10596. exit(1);
  10597. }
  10598. // Parent: clean up unused fds and bail
  10599. r = close(pfd[0]);
  10600. if (r < 0) {
  10601. perror("close - failed to close read end of pipe for --monitor");
  10602. exit(1);
  10603. }
  10604. }
  10605. #endif // defined(unix)
  10606. #ifdef HAVE_CURSES
  10607. #ifdef USE_UNICODE
  10608. static
  10609. wchar_t select_unicode_char(const wchar_t *opt)
  10610. {
  10611. for ( ; *opt; ++opt)
  10612. if (iswprint(*opt))
  10613. return *opt;
  10614. return '?';
  10615. }
  10616. #endif
  10617. void enable_curses(void) {
  10618. int x;
  10619. __maybe_unused int y;
  10620. lock_curses();
  10621. if (curses_active) {
  10622. unlock_curses();
  10623. return;
  10624. }
  10625. #ifdef USE_UNICODE
  10626. if (use_unicode)
  10627. {
  10628. setlocale(LC_CTYPE, "");
  10629. if (iswprint(0xb0))
  10630. have_unicode_degrees = true;
  10631. unicode_micro = select_unicode_char(L"\xb5\u03bcu");
  10632. }
  10633. #endif
  10634. mainwin = initscr();
  10635. start_color();
  10636. #if defined(PDCURSES) || defined(NCURSES_VERSION)
  10637. if (ERR != use_default_colors())
  10638. default_bgcolor = -1;
  10639. #endif
  10640. if (has_colors() && ERR != init_pair(1, COLOR_WHITE, COLOR_BLUE))
  10641. {
  10642. menu_attr = COLOR_PAIR(1);
  10643. if (ERR != init_pair(2, COLOR_RED, default_bgcolor))
  10644. attr_bad |= COLOR_PAIR(2);
  10645. }
  10646. keypad(mainwin, true);
  10647. getmaxyx(mainwin, y, x);
  10648. statuswin = newwin(logstart, x, 0, 0);
  10649. leaveok(statuswin, true);
  10650. // For whatever reason, PDCurses crashes if the logwin is initialized to height y-logcursor
  10651. // We resize the window later anyway, so just start it off at 1 :)
  10652. logwin = newwin(1, 0, logcursor, 0);
  10653. idlok(logwin, true);
  10654. scrollok(logwin, true);
  10655. leaveok(logwin, true);
  10656. cbreak();
  10657. noecho();
  10658. nonl();
  10659. curses_active = true;
  10660. statusy = logstart;
  10661. unlock_curses();
  10662. }
  10663. #endif
  10664. /* TODO: fix need a dummy CPU device_drv even if no support for CPU mining */
  10665. #ifndef USE_CPUMINING
  10666. struct device_drv cpu_drv;
  10667. struct device_drv cpu_drv = {
  10668. .name = "CPU",
  10669. };
  10670. #endif
  10671. static int cgminer_id_count = 0;
  10672. static int device_line_id_count;
  10673. void register_device(struct cgpu_info *cgpu)
  10674. {
  10675. cgpu->deven = DEV_ENABLED;
  10676. wr_lock(&devices_lock);
  10677. devices[cgpu->cgminer_id = cgminer_id_count++] = cgpu;
  10678. wr_unlock(&devices_lock);
  10679. if (!cgpu->proc_id)
  10680. cgpu->device_line_id = device_line_id_count++;
  10681. int thr_objs = cgpu->threads ?: 1;
  10682. mining_threads += thr_objs;
  10683. base_queue += thr_objs + cgpu->extra_work_queue;
  10684. {
  10685. const struct device_drv * const drv = cgpu->drv;
  10686. struct mining_algorithm *malgo;
  10687. LL_FOREACH(mining_algorithms, malgo)
  10688. {
  10689. if (drv_min_nonce_diff(drv, cgpu, malgo) < 0)
  10690. continue;
  10691. malgo->base_queue += thr_objs + cgpu->extra_work_queue;
  10692. }
  10693. }
  10694. #ifdef HAVE_CURSES
  10695. adj_width(mining_threads, &dev_width);
  10696. #endif
  10697. rwlock_init(&cgpu->qlock);
  10698. cgpu->queued_work = NULL;
  10699. }
  10700. struct _cgpu_devid_counter {
  10701. char name[4];
  10702. int lastid;
  10703. UT_hash_handle hh;
  10704. };
  10705. void renumber_cgpu(struct cgpu_info *cgpu)
  10706. {
  10707. static struct _cgpu_devid_counter *devids = NULL;
  10708. struct _cgpu_devid_counter *d;
  10709. HASH_FIND_STR(devids, cgpu->drv->name, d);
  10710. if (d)
  10711. cgpu->device_id = ++d->lastid;
  10712. else {
  10713. d = malloc(sizeof(*d));
  10714. memcpy(d->name, cgpu->drv->name, sizeof(d->name));
  10715. cgpu->device_id = d->lastid = 0;
  10716. HASH_ADD_STR(devids, name, d);
  10717. }
  10718. // Build repr strings
  10719. sprintf(cgpu->dev_repr, "%s%2u", cgpu->drv->name, cgpu->device_id % 100);
  10720. sprintf(cgpu->dev_repr_ns, "%s%u", cgpu->drv->name, cgpu->device_id % 100);
  10721. strcpy(cgpu->proc_repr, cgpu->dev_repr);
  10722. sprintf(cgpu->proc_repr_ns, "%s%u", cgpu->drv->name, cgpu->device_id);
  10723. const int lpcount = cgpu->procs;
  10724. if (lpcount > 1)
  10725. {
  10726. int ns;
  10727. struct cgpu_info *slave;
  10728. int lpdigits = 1;
  10729. for (int i = lpcount; i > 26 && lpdigits < 3; i /= 26)
  10730. ++lpdigits;
  10731. if (lpdigits > max_lpdigits)
  10732. max_lpdigits = lpdigits;
  10733. memset(&cgpu->proc_repr[5], 'a', lpdigits);
  10734. cgpu->proc_repr[5 + lpdigits] = '\0';
  10735. ns = strlen(cgpu->proc_repr_ns);
  10736. strcpy(&cgpu->proc_repr_ns[ns], &cgpu->proc_repr[5]);
  10737. slave = cgpu;
  10738. for (int i = 1; i < lpcount; ++i)
  10739. {
  10740. slave = slave->next_proc;
  10741. strcpy(slave->proc_repr, cgpu->proc_repr);
  10742. strcpy(slave->proc_repr_ns, cgpu->proc_repr_ns);
  10743. for (int x = i, y = lpdigits; --y, x; x /= 26)
  10744. {
  10745. slave->proc_repr_ns[ns + y] =
  10746. slave->proc_repr[5 + y] += (x % 26);
  10747. }
  10748. }
  10749. }
  10750. }
  10751. static bool my_blkmaker_sha256_callback(void *digest, const void *buffer, size_t length)
  10752. {
  10753. sha256(buffer, length, digest);
  10754. return true;
  10755. }
  10756. static
  10757. bool drv_algo_check(const struct device_drv * const drv)
  10758. {
  10759. struct mining_goal_info *goal, *tmpgoal;
  10760. HASH_ITER(hh, mining_goals, goal, tmpgoal)
  10761. {
  10762. if (drv_min_nonce_diff(drv, NULL, goal->malgo) >= 0)
  10763. return true;
  10764. }
  10765. return false;
  10766. }
  10767. #ifndef HAVE_PTHREAD_CANCEL
  10768. extern void setup_pthread_cancel_workaround();
  10769. extern struct sigaction pcwm_orig_term_handler;
  10770. #endif
  10771. bool bfg_need_detect_rescan;
  10772. extern void probe_device(struct lowlevel_device_info *);
  10773. static void schedule_rescan(const struct timeval *);
  10774. static
  10775. void drv_detect_all()
  10776. {
  10777. bool rescanning = false;
  10778. rescan:
  10779. bfg_need_detect_rescan = false;
  10780. #ifdef HAVE_BFG_LOWLEVEL
  10781. struct lowlevel_device_info * const infolist = lowlevel_scan(), *info, *infotmp;
  10782. LL_FOREACH_SAFE(infolist, info, infotmp)
  10783. probe_device(info);
  10784. LL_FOREACH_SAFE(infolist, info, infotmp)
  10785. pthread_join(info->probe_pth, NULL);
  10786. #endif
  10787. struct driver_registration *reg, *tmp;
  10788. BFG_FOREACH_DRIVER_BY_PRIORITY(reg, tmp)
  10789. {
  10790. const struct device_drv * const drv = reg->drv;
  10791. if (!(drv_algo_check(drv) && drv->drv_detect))
  10792. continue;
  10793. drv->drv_detect();
  10794. }
  10795. #ifdef HAVE_BFG_LOWLEVEL
  10796. lowlevel_scan_free();
  10797. #endif
  10798. if (bfg_need_detect_rescan)
  10799. {
  10800. if (rescanning)
  10801. {
  10802. applog(LOG_DEBUG, "Device rescan requested a second time, delaying");
  10803. struct timeval tv_when;
  10804. timer_set_delay_from_now(&tv_when, rescan_delay_ms * 1000);
  10805. schedule_rescan(&tv_when);
  10806. }
  10807. else
  10808. {
  10809. rescanning = true;
  10810. applog(LOG_DEBUG, "Device rescan requested");
  10811. goto rescan;
  10812. }
  10813. }
  10814. }
  10815. static
  10816. void allocate_cgpu(struct cgpu_info *cgpu, unsigned int *kp)
  10817. {
  10818. struct thr_info *thr;
  10819. int j;
  10820. struct device_drv *api = cgpu->drv;
  10821. cgpu->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  10822. int threadobj = cgpu->threads;
  10823. if (!threadobj)
  10824. // Create a fake thread object to handle hashmeter etc
  10825. threadobj = 1;
  10826. cgpu->thr = calloc(threadobj + 1, sizeof(*cgpu->thr));
  10827. cgpu->thr[threadobj] = NULL;
  10828. cgpu->status = LIFE_INIT;
  10829. if (opt_devices_enabled_list)
  10830. {
  10831. struct string_elist *enablestr_elist;
  10832. cgpu->deven = DEV_DISABLED;
  10833. DL_FOREACH(opt_devices_enabled_list, enablestr_elist)
  10834. {
  10835. const char * const enablestr = enablestr_elist->string;
  10836. if (cgpu_match(enablestr, cgpu))
  10837. {
  10838. cgpu->deven = DEV_ENABLED;
  10839. break;
  10840. }
  10841. }
  10842. }
  10843. cgpu->max_hashes = 0;
  10844. BFGINIT(cgpu->cutofftemp, opt_cutofftemp);
  10845. BFGINIT(cgpu->targettemp, cgpu->cutofftemp - 6);
  10846. // Setup thread structs before starting any of the threads, in case they try to interact
  10847. for (j = 0; j < threadobj; ++j, ++*kp) {
  10848. thr = get_thread(*kp);
  10849. thr->id = *kp;
  10850. thr->cgpu = cgpu;
  10851. thr->device_thread = j;
  10852. thr->work_restart_notifier[1] = INVSOCK;
  10853. thr->mutex_request[1] = INVSOCK;
  10854. thr->_job_transition_in_progress = true;
  10855. timerclear(&thr->tv_morework);
  10856. thr->scanhash_working = true;
  10857. thr->hashes_done = 0;
  10858. timerclear(&thr->tv_hashes_done);
  10859. cgtime(&thr->tv_lastupdate);
  10860. thr->tv_poll.tv_sec = -1;
  10861. thr->_max_nonce = api->can_limit_work ? api->can_limit_work(thr) : 0xffffffff;
  10862. cgpu->thr[j] = thr;
  10863. }
  10864. if (!cgpu->device->threads)
  10865. notifier_init_invalid(cgpu->thr[0]->notifier);
  10866. else
  10867. if (!cgpu->threads)
  10868. memcpy(&cgpu->thr[0]->notifier, &cgpu->device->thr[0]->notifier, sizeof(cgpu->thr[0]->notifier));
  10869. else
  10870. for (j = 0; j < cgpu->threads; ++j)
  10871. {
  10872. thr = cgpu->thr[j];
  10873. notifier_init(thr->notifier);
  10874. }
  10875. }
  10876. static
  10877. void start_cgpu(struct cgpu_info *cgpu)
  10878. {
  10879. struct thr_info *thr;
  10880. int j;
  10881. for (j = 0; j < cgpu->threads; ++j) {
  10882. thr = cgpu->thr[j];
  10883. /* Enable threads for devices set not to mine but disable
  10884. * their queue in case we wish to enable them later */
  10885. if (cgpu->drv->thread_prepare && !cgpu->drv->thread_prepare(thr))
  10886. continue;
  10887. thread_reportout(thr);
  10888. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  10889. quit(1, "thread %d create failed", thr->id);
  10890. notifier_wake(thr->notifier);
  10891. }
  10892. if (cgpu->deven == DEV_ENABLED)
  10893. proc_enable(cgpu);
  10894. }
  10895. static
  10896. void _scan_serial(void *p)
  10897. {
  10898. const char *s = p;
  10899. struct string_elist *iter, *tmp;
  10900. struct string_elist *orig_scan_devices = scan_devices;
  10901. if (s)
  10902. {
  10903. // Make temporary scan_devices list
  10904. scan_devices = NULL;
  10905. string_elist_add("noauto", &scan_devices);
  10906. add_serial(s);
  10907. }
  10908. drv_detect_all();
  10909. if (s)
  10910. {
  10911. DL_FOREACH_SAFE(scan_devices, iter, tmp)
  10912. {
  10913. string_elist_del(&scan_devices, iter);
  10914. }
  10915. scan_devices = orig_scan_devices;
  10916. }
  10917. }
  10918. #ifdef HAVE_BFG_LOWLEVEL
  10919. static
  10920. bool _probe_device_match(const struct lowlevel_device_info * const info, const char * const ser)
  10921. {
  10922. if (!(false
  10923. || (info->serial && !strcasecmp(ser, info->serial))
  10924. || (info->path && !strcasecmp(ser, info->path ))
  10925. || (info->devid && !strcasecmp(ser, info->devid ))
  10926. ))
  10927. {
  10928. char *devid = devpath_to_devid(ser);
  10929. if (!devid)
  10930. return false;
  10931. const bool different = strcmp(info->devid, devid);
  10932. free(devid);
  10933. if (different)
  10934. return false;
  10935. }
  10936. return true;
  10937. }
  10938. static
  10939. const struct device_drv *_probe_device_find_drv(const char * const _dname, const size_t dnamelen)
  10940. {
  10941. struct driver_registration *dreg;
  10942. char dname[dnamelen];
  10943. int i;
  10944. for (i = 0; i < dnamelen; ++i)
  10945. dname[i] = tolower(_dname[i]);
  10946. BFG_FIND_DRV_BY_DNAME(dreg, dname, dnamelen);
  10947. if (!dreg)
  10948. {
  10949. for (i = 0; i < dnamelen; ++i)
  10950. dname[i] = toupper(_dname[i]);
  10951. BFG_FIND_DRV_BY_NAME(dreg, dname, dnamelen);
  10952. if (!dreg)
  10953. return NULL;
  10954. }
  10955. if (!drv_algo_check(dreg->drv))
  10956. return NULL;
  10957. return dreg->drv;
  10958. }
  10959. static
  10960. bool _probe_device_do_probe(const struct device_drv * const drv, const struct lowlevel_device_info * const info, bool * const request_rescan_p)
  10961. {
  10962. bfg_probe_result_flags = 0;
  10963. if (drv->lowl_probe(info))
  10964. {
  10965. if (!(bfg_probe_result_flags & BPR_CONTINUE_PROBES))
  10966. return true;
  10967. }
  10968. else
  10969. if (request_rescan_p && opt_hotplug && !(bfg_probe_result_flags & BPR_DONT_RESCAN))
  10970. *request_rescan_p = true;
  10971. return false;
  10972. }
  10973. bool dummy_check_never_true = false;
  10974. static
  10975. void *probe_device_thread(void *p)
  10976. {
  10977. struct lowlevel_device_info * const infolist = p;
  10978. struct lowlevel_device_info *info = infolist;
  10979. bool request_rescan = false;
  10980. {
  10981. char threadname[5 + strlen(info->devid) + 1];
  10982. sprintf(threadname, "probe_%s", info->devid);
  10983. RenameThread(threadname);
  10984. }
  10985. // If already in use, ignore
  10986. if (bfg_claim_any(NULL, NULL, info->devid))
  10987. applogr(NULL, LOG_DEBUG, "%s: \"%s\" already in use",
  10988. __func__, info->product);
  10989. // if lowlevel device matches specific user assignment, probe requested driver(s)
  10990. struct string_elist *sd_iter, *sd_tmp;
  10991. struct driver_registration *dreg, *dreg_tmp;
  10992. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  10993. {
  10994. const char * const dname = sd_iter->string;
  10995. const char * const colon = strpbrk(dname, ":@");
  10996. if (!(colon && colon != dname))
  10997. continue;
  10998. const char * const ser = &colon[1];
  10999. LL_FOREACH2(infolist, info, same_devid_next)
  11000. {
  11001. if (!_probe_device_match(info, ser))
  11002. continue;
  11003. const size_t dnamelen = (colon - dname);
  11004. const struct device_drv * const drv = _probe_device_find_drv(dname, dnamelen);
  11005. if (!(drv && drv->lowl_probe && drv_algo_check(drv)))
  11006. continue;
  11007. if (_probe_device_do_probe(drv, info, &request_rescan))
  11008. return NULL;
  11009. }
  11010. }
  11011. // probe driver(s) with auto enabled and matching VID/PID/Product/etc of device
  11012. BFG_FOREACH_DRIVER_BY_PRIORITY(dreg, dreg_tmp)
  11013. {
  11014. const struct device_drv * const drv = dreg->drv;
  11015. if (!drv_algo_check(drv))
  11016. continue;
  11017. // Check for "noauto" flag
  11018. // NOTE: driver-specific configuration overrides general
  11019. bool doauto = true;
  11020. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  11021. {
  11022. const char * const dname = sd_iter->string;
  11023. // NOTE: Only checking flags here, NOT path/serial, so @ is unacceptable
  11024. const char *colon = strchr(dname, ':');
  11025. if (!colon)
  11026. colon = &dname[-1];
  11027. if (strcasecmp("noauto", &colon[1]) && strcasecmp("auto", &colon[1]))
  11028. continue;
  11029. const ssize_t dnamelen = (colon - dname);
  11030. if (dnamelen >= 0 && _probe_device_find_drv(dname, dnamelen) != drv)
  11031. continue;
  11032. doauto = (tolower(colon[1]) == 'a');
  11033. if (dnamelen != -1)
  11034. break;
  11035. }
  11036. if (doauto && drv->lowl_match)
  11037. {
  11038. LL_FOREACH2(infolist, info, same_devid_next)
  11039. {
  11040. /*
  11041. The below call to applog is absolutely necessary
  11042. Starting with commit 76d0cc183b1c9ddcc0ef34d2e43bc696ef9de92e installing BFGMiner on
  11043. Mac OS X using Homebrew results in a binary that segfaults on startup
  11044. There are two unresolved issues:
  11045. 1) The BFGMiner authors cannot find a way to install BFGMiner with Homebrew that results
  11046. in debug symbols being available to help troubleshoot the issue
  11047. 2) The issue disappears when unrelated code changes are made, such as adding the following
  11048. call to applog with infolist and / or p
  11049. We would encourage revisiting this in the future to come up with a more concrete solution
  11050. Reproducing should only require commenting / removing the following line and installing
  11051. BFGMiner using "brew install bfgminer --HEAD"
  11052. */
  11053. if (dummy_check_never_true)
  11054. applog(LOG_DEBUG, "lowl_match: %p(%s) %p %p %p", drv, drv->dname, info, infolist, p);
  11055. if (!drv->lowl_match(info))
  11056. continue;
  11057. if (_probe_device_do_probe(drv, info, &request_rescan))
  11058. return NULL;
  11059. }
  11060. }
  11061. }
  11062. // probe driver(s) with 'all' enabled
  11063. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  11064. {
  11065. const char * const dname = sd_iter->string;
  11066. // NOTE: Only checking flags here, NOT path/serial, so @ is unacceptable
  11067. const char * const colon = strchr(dname, ':');
  11068. if (!colon)
  11069. {
  11070. LL_FOREACH2(infolist, info, same_devid_next)
  11071. {
  11072. if (
  11073. #ifdef NEED_BFG_LOWL_VCOM
  11074. (info->lowl == &lowl_vcom && !strcasecmp(dname, "all")) ||
  11075. #endif
  11076. _probe_device_match(info, (dname[0] == '@') ? &dname[1] : dname))
  11077. {
  11078. bool dont_rescan = false;
  11079. BFG_FOREACH_DRIVER_BY_PRIORITY(dreg, dreg_tmp)
  11080. {
  11081. const struct device_drv * const drv = dreg->drv;
  11082. if (!drv_algo_check(drv))
  11083. continue;
  11084. if (drv->lowl_probe_by_name_only)
  11085. continue;
  11086. if (!drv->lowl_probe)
  11087. continue;
  11088. if (_probe_device_do_probe(drv, info, NULL))
  11089. return NULL;
  11090. if (bfg_probe_result_flags & BPR_DONT_RESCAN)
  11091. dont_rescan = true;
  11092. }
  11093. if (opt_hotplug && !dont_rescan)
  11094. request_rescan = true;
  11095. break;
  11096. }
  11097. }
  11098. continue;
  11099. }
  11100. if (strcasecmp(&colon[1], "all"))
  11101. continue;
  11102. const size_t dnamelen = (colon - dname);
  11103. const struct device_drv * const drv = _probe_device_find_drv(dname, dnamelen);
  11104. if (!(drv && drv->lowl_probe && drv_algo_check(drv)))
  11105. continue;
  11106. LL_FOREACH2(infolist, info, same_devid_next)
  11107. {
  11108. if (info->lowl->exclude_from_all)
  11109. continue;
  11110. if (_probe_device_do_probe(drv, info, NULL))
  11111. return NULL;
  11112. }
  11113. }
  11114. // Only actually request a rescan if we never found any cgpu
  11115. if (request_rescan)
  11116. bfg_need_detect_rescan = true;
  11117. return NULL;
  11118. }
  11119. void probe_device(struct lowlevel_device_info * const info)
  11120. {
  11121. pthread_create(&info->probe_pth, NULL, probe_device_thread, info);
  11122. }
  11123. #endif
  11124. int create_new_cgpus(void (*addfunc)(void*), void *arg)
  11125. {
  11126. static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  11127. int devcount, i, mining_threads_new = 0;
  11128. unsigned int k;
  11129. struct cgpu_info *cgpu;
  11130. struct thr_info *thr;
  11131. void *p;
  11132. mutex_lock(&mutex);
  11133. devcount = total_devices;
  11134. addfunc(arg);
  11135. if (!total_devices_new)
  11136. goto out;
  11137. wr_lock(&devices_lock);
  11138. p = realloc(devices, sizeof(struct cgpu_info *) * (total_devices + total_devices_new + 1));
  11139. if (unlikely(!p))
  11140. {
  11141. wr_unlock(&devices_lock);
  11142. applog(LOG_ERR, "scan_serial: realloc failed trying to grow devices array");
  11143. goto out;
  11144. }
  11145. devices = p;
  11146. wr_unlock(&devices_lock);
  11147. for (i = 0; i < total_devices_new; ++i)
  11148. {
  11149. cgpu = devices_new[i];
  11150. mining_threads_new += cgpu->threads ?: 1;
  11151. }
  11152. wr_lock(&mining_thr_lock);
  11153. mining_threads_new += mining_threads;
  11154. p = realloc(mining_thr, sizeof(struct thr_info *) * mining_threads_new);
  11155. if (unlikely(!p))
  11156. {
  11157. wr_unlock(&mining_thr_lock);
  11158. applog(LOG_ERR, "scan_serial: realloc failed trying to grow mining_thr");
  11159. goto out;
  11160. }
  11161. mining_thr = p;
  11162. wr_unlock(&mining_thr_lock);
  11163. for (i = mining_threads; i < mining_threads_new; ++i) {
  11164. mining_thr[i] = calloc(1, sizeof(*thr));
  11165. if (!mining_thr[i])
  11166. {
  11167. applog(LOG_ERR, "scan_serial: Failed to calloc mining_thr[%d]", i);
  11168. for ( ; --i >= mining_threads; )
  11169. free(mining_thr[i]);
  11170. goto out;
  11171. }
  11172. }
  11173. k = mining_threads;
  11174. for (i = 0; i < total_devices_new; ++i)
  11175. {
  11176. cgpu = devices_new[i];
  11177. allocate_cgpu(cgpu, &k);
  11178. }
  11179. for (i = 0; i < total_devices_new; ++i)
  11180. {
  11181. cgpu = devices_new[i];
  11182. start_cgpu(cgpu);
  11183. register_device(cgpu);
  11184. ++total_devices;
  11185. }
  11186. #ifdef HAVE_CURSES
  11187. switch_logsize();
  11188. #endif
  11189. out:
  11190. total_devices_new = 0;
  11191. devcount = total_devices - devcount;
  11192. mutex_unlock(&mutex);
  11193. return devcount;
  11194. }
  11195. int scan_serial(const char *s)
  11196. {
  11197. return create_new_cgpus(_scan_serial, (void*)s);
  11198. }
  11199. static pthread_mutex_t rescan_mutex = PTHREAD_MUTEX_INITIALIZER;
  11200. static bool rescan_active;
  11201. static struct timeval tv_rescan;
  11202. static notifier_t rescan_notifier;
  11203. static
  11204. void *rescan_thread(__maybe_unused void *p)
  11205. {
  11206. pthread_detach(pthread_self());
  11207. RenameThread("rescan");
  11208. struct timeval tv_timeout, tv_now;
  11209. fd_set rfds;
  11210. while (true)
  11211. {
  11212. mutex_lock(&rescan_mutex);
  11213. tv_timeout = tv_rescan;
  11214. if (!timer_isset(&tv_timeout))
  11215. {
  11216. rescan_active = false;
  11217. mutex_unlock(&rescan_mutex);
  11218. break;
  11219. }
  11220. mutex_unlock(&rescan_mutex);
  11221. FD_ZERO(&rfds);
  11222. FD_SET(rescan_notifier[0], &rfds);
  11223. const int maxfd = rescan_notifier[0];
  11224. timer_set_now(&tv_now);
  11225. if (select(maxfd+1, &rfds, NULL, NULL, select_timeout(&tv_timeout, &tv_now)) > 0)
  11226. notifier_read(rescan_notifier);
  11227. mutex_lock(&rescan_mutex);
  11228. if (timer_passed(&tv_rescan, NULL))
  11229. {
  11230. timer_unset(&tv_rescan);
  11231. mutex_unlock(&rescan_mutex);
  11232. applog(LOG_DEBUG, "Rescan timer expired, triggering");
  11233. scan_serial(NULL);
  11234. }
  11235. else
  11236. mutex_unlock(&rescan_mutex);
  11237. }
  11238. return NULL;
  11239. }
  11240. static
  11241. void _schedule_rescan(const struct timeval * const tvp_when)
  11242. {
  11243. if (rescan_active)
  11244. {
  11245. if (timercmp(tvp_when, &tv_rescan, <))
  11246. applog(LOG_DEBUG, "schedule_rescan: New schedule is before current, waiting it out");
  11247. else
  11248. {
  11249. applog(LOG_DEBUG, "schedule_rescan: New schedule is after current, delaying rescan");
  11250. tv_rescan = *tvp_when;
  11251. }
  11252. return;
  11253. }
  11254. applog(LOG_DEBUG, "schedule_rescan: Scheduling rescan (no rescans currently pending)");
  11255. tv_rescan = *tvp_when;
  11256. rescan_active = true;
  11257. static pthread_t pth;
  11258. if (unlikely(pthread_create(&pth, NULL, rescan_thread, NULL)))
  11259. applog(LOG_ERR, "Failed to start rescan thread");
  11260. }
  11261. static
  11262. void schedule_rescan(const struct timeval * const tvp_when)
  11263. {
  11264. mutex_lock(&rescan_mutex);
  11265. _schedule_rescan(tvp_when);
  11266. mutex_unlock(&rescan_mutex);
  11267. }
  11268. static
  11269. void hotplug_trigger()
  11270. {
  11271. applog(LOG_DEBUG, "%s: Scheduling rescan immediately", __func__);
  11272. struct timeval tv_now;
  11273. timer_set_now(&tv_now);
  11274. schedule_rescan(&tv_now);
  11275. }
  11276. #if defined(HAVE_LIBUDEV) && defined(HAVE_SYS_EPOLL_H)
  11277. static
  11278. void *hotplug_thread(__maybe_unused void *p)
  11279. {
  11280. pthread_detach(pthread_self());
  11281. RenameThread("hotplug");
  11282. struct udev * const udev = udev_new();
  11283. if (unlikely(!udev))
  11284. applogfailr(NULL, LOG_ERR, "udev_new");
  11285. struct udev_monitor * const mon = udev_monitor_new_from_netlink(udev, "udev");
  11286. if (unlikely(!mon))
  11287. applogfailr(NULL, LOG_ERR, "udev_monitor_new_from_netlink");
  11288. if (unlikely(udev_monitor_enable_receiving(mon)))
  11289. applogfailr(NULL, LOG_ERR, "udev_monitor_enable_receiving");
  11290. const int epfd = epoll_create(1);
  11291. if (unlikely(epfd == -1))
  11292. applogfailr(NULL, LOG_ERR, "epoll_create");
  11293. {
  11294. const int fd = udev_monitor_get_fd(mon);
  11295. struct epoll_event ev = {
  11296. .events = EPOLLIN | EPOLLPRI,
  11297. .data.fd = fd,
  11298. };
  11299. if (epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev))
  11300. applogfailr(NULL, LOG_ERR, "epoll_ctl");
  11301. }
  11302. struct epoll_event ev;
  11303. int rv;
  11304. bool pending = false;
  11305. while (true)
  11306. {
  11307. rv = epoll_wait(epfd, &ev, 1, pending ? hotplug_delay_ms : -1);
  11308. if (rv == -1)
  11309. {
  11310. if (errno == EAGAIN || errno == EINTR)
  11311. continue;
  11312. break;
  11313. }
  11314. if (!rv)
  11315. {
  11316. hotplug_trigger();
  11317. pending = false;
  11318. continue;
  11319. }
  11320. struct udev_device * const device = udev_monitor_receive_device(mon);
  11321. if (!device)
  11322. continue;
  11323. const char * const action = udev_device_get_action(device);
  11324. applog(LOG_DEBUG, "%s: Received %s event", __func__, action);
  11325. if (!strcmp(action, "add"))
  11326. pending = true;
  11327. udev_device_unref(device);
  11328. }
  11329. applogfailr(NULL, LOG_ERR, "epoll_wait");
  11330. }
  11331. #elif defined(WIN32)
  11332. static UINT_PTR _hotplug_wintimer_id;
  11333. VOID CALLBACK hotplug_win_timer(HWND hwnd, UINT msg, UINT_PTR idEvent, DWORD dwTime)
  11334. {
  11335. KillTimer(NULL, _hotplug_wintimer_id);
  11336. _hotplug_wintimer_id = 0;
  11337. hotplug_trigger();
  11338. }
  11339. LRESULT CALLBACK hotplug_win_callback(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
  11340. {
  11341. if (msg == WM_DEVICECHANGE && wParam == DBT_DEVNODES_CHANGED)
  11342. {
  11343. applog(LOG_DEBUG, "%s: Received DBT_DEVNODES_CHANGED event", __func__);
  11344. _hotplug_wintimer_id = SetTimer(NULL, _hotplug_wintimer_id, hotplug_delay_ms, hotplug_win_timer);
  11345. }
  11346. return DefWindowProc(hwnd, msg, wParam, lParam);
  11347. }
  11348. static
  11349. void *hotplug_thread(__maybe_unused void *p)
  11350. {
  11351. pthread_detach(pthread_self());
  11352. WNDCLASS DummyWinCls = {
  11353. .lpszClassName = "BFGDummyWinCls",
  11354. .lpfnWndProc = hotplug_win_callback,
  11355. };
  11356. ATOM a = RegisterClass(&DummyWinCls);
  11357. if (unlikely(!a))
  11358. applogfailinfor(NULL, LOG_ERR, "RegisterClass", "%d", (int)GetLastError());
  11359. HWND hwnd = CreateWindow((void*)(intptr_t)a, NULL, WS_OVERLAPPED, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, NULL, NULL);
  11360. if (unlikely(!hwnd))
  11361. applogfailinfor(NULL, LOG_ERR, "CreateWindow", "%d", (int)GetLastError());
  11362. MSG msg;
  11363. while (GetMessage(&msg, NULL, 0, 0))
  11364. {
  11365. TranslateMessage(&msg);
  11366. DispatchMessage(&msg);
  11367. }
  11368. quit(0, "WM_QUIT received");
  11369. return NULL;
  11370. }
  11371. #endif
  11372. #ifdef HAVE_BFG_HOTPLUG
  11373. static
  11374. void hotplug_start()
  11375. {
  11376. pthread_t pth;
  11377. if (unlikely(pthread_create(&pth, NULL, hotplug_thread, NULL)))
  11378. applog(LOG_ERR, "Failed to start hotplug thread");
  11379. }
  11380. #endif
  11381. static void probe_pools(void)
  11382. {
  11383. int i;
  11384. for (i = 0; i < total_pools; i++) {
  11385. struct pool *pool = pools[i];
  11386. pool->testing = true;
  11387. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  11388. }
  11389. }
  11390. static void raise_fd_limits(void)
  11391. {
  11392. #ifdef HAVE_SETRLIMIT
  11393. struct rlimit fdlimit;
  11394. rlim_t old_soft_limit;
  11395. char frombuf[0x10] = "unlimited";
  11396. char hardbuf[0x10] = "unlimited";
  11397. if (getrlimit(RLIMIT_NOFILE, &fdlimit))
  11398. applogr(, LOG_DEBUG, "setrlimit: Failed to getrlimit(RLIMIT_NOFILE)");
  11399. old_soft_limit = fdlimit.rlim_cur;
  11400. if (fdlimit.rlim_max > FD_SETSIZE || fdlimit.rlim_max == RLIM_INFINITY)
  11401. fdlimit.rlim_cur = FD_SETSIZE;
  11402. else
  11403. fdlimit.rlim_cur = fdlimit.rlim_max;
  11404. if (fdlimit.rlim_max != RLIM_INFINITY)
  11405. snprintf(hardbuf, sizeof(hardbuf), "%lu", (unsigned long)fdlimit.rlim_max);
  11406. if (old_soft_limit != RLIM_INFINITY)
  11407. snprintf(frombuf, sizeof(frombuf), "%lu", (unsigned long)old_soft_limit);
  11408. if (fdlimit.rlim_cur == old_soft_limit)
  11409. applogr(, LOG_DEBUG, "setrlimit: Soft fd limit not being changed from %lu (FD_SETSIZE=%lu; hard limit=%s)",
  11410. (unsigned long)old_soft_limit, (unsigned long)FD_SETSIZE, hardbuf);
  11411. if (setrlimit(RLIMIT_NOFILE, &fdlimit))
  11412. applogr(, LOG_DEBUG, "setrlimit: Failed to change soft fd limit from %s to %lu (FD_SETSIZE=%lu; hard limit=%s)",
  11413. frombuf, (unsigned long)fdlimit.rlim_cur, (unsigned long)FD_SETSIZE, hardbuf);
  11414. applog(LOG_DEBUG, "setrlimit: Changed soft fd limit from %s to %lu (FD_SETSIZE=%lu; hard limit=%s)",
  11415. frombuf, (unsigned long)fdlimit.rlim_cur, (unsigned long)FD_SETSIZE, hardbuf);
  11416. #else
  11417. applog(LOG_DEBUG, "setrlimit: Not supported by platform");
  11418. #endif
  11419. }
  11420. static
  11421. void bfg_atexit(void)
  11422. {
  11423. puts("");
  11424. }
  11425. extern void bfg_init_threadlocal();
  11426. extern void stratumsrv_start();
  11427. extern void test_aan_pll(void);
  11428. int main(int argc, char *argv[])
  11429. {
  11430. struct sigaction handler;
  11431. struct thr_info *thr;
  11432. unsigned int k;
  11433. int i;
  11434. int rearrange_pools = 0;
  11435. char *s;
  11436. #ifdef WIN32
  11437. LoadLibrary("backtrace.dll");
  11438. #endif
  11439. atexit(bfg_atexit);
  11440. b58_sha256_impl = my_blkmaker_sha256_callback;
  11441. blkmk_sha256_impl = my_blkmaker_sha256_callback;
  11442. bfg_init_threadlocal();
  11443. #ifndef HAVE_PTHREAD_CANCEL
  11444. setup_pthread_cancel_workaround();
  11445. #endif
  11446. bfg_init_checksums();
  11447. #ifdef WIN32
  11448. {
  11449. WSADATA wsa;
  11450. i = WSAStartup(MAKEWORD(2, 2), &wsa);
  11451. if (i)
  11452. quit(1, "Failed to initialise Winsock: %s", bfg_strerror(i, BST_SOCKET));
  11453. }
  11454. #endif
  11455. /* This dangerous functions tramples random dynamically allocated
  11456. * variables so do it before anything at all */
  11457. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  11458. quit(1, "Failed to curl_global_init");
  11459. initial_args = malloc(sizeof(char *) * (argc + 1));
  11460. for (i = 0; i < argc; i++)
  11461. initial_args[i] = strdup(argv[i]);
  11462. initial_args[argc] = NULL;
  11463. mutex_init(&hash_lock);
  11464. mutex_init(&console_lock);
  11465. cglock_init(&control_lock);
  11466. mutex_init(&stats_lock);
  11467. mutex_init(&sharelog_lock);
  11468. cglock_init(&ch_lock);
  11469. mutex_init(&sshare_lock);
  11470. rwlock_init(&blk_lock);
  11471. rwlock_init(&netacc_lock);
  11472. rwlock_init(&mining_thr_lock);
  11473. rwlock_init(&devices_lock);
  11474. mutex_init(&lp_lock);
  11475. if (unlikely(pthread_cond_init(&lp_cond, bfg_condattr)))
  11476. quit(1, "Failed to pthread_cond_init lp_cond");
  11477. if (unlikely(pthread_cond_init(&gws_cond, bfg_condattr)))
  11478. quit(1, "Failed to pthread_cond_init gws_cond");
  11479. notifier_init(submit_waiting_notifier);
  11480. timer_unset(&tv_rescan);
  11481. notifier_init(rescan_notifier);
  11482. /* Create a unique get work queue */
  11483. getq = tq_new();
  11484. if (!getq)
  11485. quit(1, "Failed to create getq");
  11486. /* We use the getq mutex as the staged lock */
  11487. stgd_lock = &getq->mutex;
  11488. snprintf(packagename, sizeof(packagename), "%s %s", PACKAGE, VERSION);
  11489. #if defined(USE_CPUMINING) && defined(USE_SHA256D)
  11490. init_max_name_len();
  11491. #endif
  11492. handler.sa_handler = &sighandler;
  11493. handler.sa_flags = 0;
  11494. sigemptyset(&handler.sa_mask);
  11495. #ifdef HAVE_PTHREAD_CANCEL
  11496. sigaction(SIGTERM, &handler, &termhandler);
  11497. #else
  11498. // Need to let pthread_cancel emulation handle SIGTERM first
  11499. termhandler = pcwm_orig_term_handler;
  11500. pcwm_orig_term_handler = handler;
  11501. #endif
  11502. sigaction(SIGINT, &handler, &inthandler);
  11503. #ifndef WIN32
  11504. signal(SIGPIPE, SIG_IGN);
  11505. #else
  11506. timeBeginPeriod(1);
  11507. #endif
  11508. opt_kernel_path = CGMINER_PREFIX;
  11509. cgminer_path = alloca(PATH_MAX);
  11510. s = strdup(argv[0]);
  11511. strcpy(cgminer_path, dirname(s));
  11512. free(s);
  11513. strcat(cgminer_path, "/");
  11514. #if defined(USE_CPUMINING) && defined(WIN32)
  11515. {
  11516. char buf[32];
  11517. int gev = GetEnvironmentVariable("BFGMINER_BENCH_ALGO", buf, sizeof(buf));
  11518. if (gev > 0 && gev < sizeof(buf))
  11519. {
  11520. setup_benchmark_pool();
  11521. double rate = bench_algo_stage3(atoi(buf));
  11522. // Write result to shared memory for parent
  11523. char unique_name[64];
  11524. if (GetEnvironmentVariable("BFGMINER_SHARED_MEM", unique_name, 32))
  11525. {
  11526. HANDLE map_handle = CreateFileMapping(
  11527. INVALID_HANDLE_VALUE, // use paging file
  11528. NULL, // default security attributes
  11529. PAGE_READWRITE, // read/write access
  11530. 0, // size: high 32-bits
  11531. 4096, // size: low 32-bits
  11532. unique_name // name of map object
  11533. );
  11534. if (NULL != map_handle) {
  11535. void *shared_mem = MapViewOfFile(
  11536. map_handle, // object to map view of
  11537. FILE_MAP_WRITE, // read/write access
  11538. 0, // high offset: map from
  11539. 0, // low offset: beginning
  11540. 0 // default: map entire file
  11541. );
  11542. if (NULL != shared_mem)
  11543. CopyMemory(shared_mem, &rate, sizeof(rate));
  11544. (void)UnmapViewOfFile(shared_mem);
  11545. }
  11546. (void)CloseHandle(map_handle);
  11547. }
  11548. exit(0);
  11549. }
  11550. }
  11551. #endif
  11552. #ifdef HAVE_CURSES
  11553. devcursor = 8;
  11554. logstart = devcursor;
  11555. logcursor = logstart;
  11556. #endif
  11557. mutex_init(&submitting_lock);
  11558. // Ensure at least the default goal is created
  11559. get_mining_goal("default");
  11560. #ifdef USE_OPENCL
  11561. opencl_early_init();
  11562. #endif
  11563. schedstart.tm.tm_sec = 1;
  11564. schedstop .tm.tm_sec = 1;
  11565. opt_register_table(opt_early_table, NULL);
  11566. opt_register_table(opt_config_table, NULL);
  11567. opt_register_table(opt_cmdline_table, NULL);
  11568. opt_early_parse(argc, argv, applog_and_exit);
  11569. if (!config_loaded)
  11570. {
  11571. load_default_config();
  11572. rearrange_pools = total_pools;
  11573. }
  11574. opt_free_table();
  11575. /* parse command line */
  11576. opt_register_table(opt_config_table,
  11577. "Options for both config file and command line");
  11578. opt_register_table(opt_cmdline_table,
  11579. "Options for command line only");
  11580. opt_parse(&argc, argv, applog_and_exit);
  11581. if (argc != 1)
  11582. quit(1, "Unexpected extra commandline arguments");
  11583. if (rearrange_pools && rearrange_pools < total_pools)
  11584. {
  11585. // Prioritise commandline pools before default-config pools
  11586. for (i = 0; i < rearrange_pools; ++i)
  11587. pools[i]->prio += rearrange_pools;
  11588. for ( ; i < total_pools; ++i)
  11589. pools[i]->prio -= rearrange_pools;
  11590. }
  11591. #ifndef HAVE_PTHREAD_CANCEL
  11592. // Can't do this any earlier, or config isn't loaded
  11593. applog(LOG_DEBUG, "pthread_cancel workaround in use");
  11594. #endif
  11595. #ifdef HAVE_PWD_H
  11596. struct passwd *user_info = NULL;
  11597. if (opt_setuid != NULL) {
  11598. if ((user_info = getpwnam(opt_setuid)) == NULL) {
  11599. quit(1, "Unable to find setuid user information");
  11600. }
  11601. }
  11602. #endif
  11603. #ifdef HAVE_CHROOT
  11604. if (chroot_dir != NULL) {
  11605. #ifdef HAVE_PWD_H
  11606. if (user_info == NULL && getuid() == 0) {
  11607. applog(LOG_WARNING, "Running as root inside chroot");
  11608. }
  11609. #endif
  11610. if (chroot(chroot_dir) != 0) {
  11611. quit(1, "Unable to chroot");
  11612. }
  11613. if (chdir("/"))
  11614. quit(1, "Unable to chdir to chroot");
  11615. }
  11616. #endif
  11617. #ifdef HAVE_PWD_H
  11618. if (user_info != NULL) {
  11619. if (setgid((*user_info).pw_gid) != 0)
  11620. quit(1, "Unable to setgid");
  11621. if (setuid((*user_info).pw_uid) != 0)
  11622. quit(1, "Unable to setuid");
  11623. }
  11624. #endif
  11625. raise_fd_limits();
  11626. if (opt_benchmark) {
  11627. while (total_pools)
  11628. remove_pool(pools[0]);
  11629. setup_benchmark_pool();
  11630. }
  11631. if (opt_unittest) {
  11632. test_cgpu_match();
  11633. test_intrange();
  11634. test_decimal_width();
  11635. test_domain_funcs();
  11636. #ifdef USE_SCRYPT
  11637. test_scrypt();
  11638. #endif
  11639. test_target();
  11640. test_uri_get_param();
  11641. utf8_test();
  11642. #ifdef USE_JINGTIAN
  11643. test_aan_pll();
  11644. #endif
  11645. if (unittest_failures)
  11646. quit(1, "Unit tests failed");
  11647. }
  11648. #ifdef HAVE_CURSES
  11649. if (opt_realquiet || opt_display_devs)
  11650. use_curses = false;
  11651. setlocale(LC_ALL, "C");
  11652. if (use_curses)
  11653. enable_curses();
  11654. #endif
  11655. #ifdef HAVE_LIBUSB
  11656. int err = libusb_init(NULL);
  11657. if (err)
  11658. applog(LOG_WARNING, "libusb_init() failed err %d", err);
  11659. else
  11660. have_libusb = true;
  11661. #endif
  11662. applog(LOG_WARNING, "Started %s", packagename);
  11663. {
  11664. struct bfg_loaded_configfile *configfile;
  11665. LL_FOREACH(bfg_loaded_configfiles, configfile)
  11666. {
  11667. char * const cnfbuf = configfile->filename;
  11668. int fileconf_load = configfile->fileconf_load;
  11669. applog(LOG_NOTICE, "Loaded configuration file %s", cnfbuf);
  11670. switch (fileconf_load) {
  11671. case 0:
  11672. applog(LOG_WARNING, "Fatal JSON error in configuration file.");
  11673. applog(LOG_WARNING, "Configuration file could not be used.");
  11674. break;
  11675. case -1:
  11676. applog(LOG_WARNING, "Error in configuration file, partially loaded.");
  11677. if (use_curses)
  11678. applog(LOG_WARNING, "Start BFGMiner with -T to see what failed to load.");
  11679. break;
  11680. default:
  11681. break;
  11682. }
  11683. }
  11684. }
  11685. i = strlen(opt_kernel_path) + 2;
  11686. char __kernel_path[i];
  11687. snprintf(__kernel_path, i, "%s/", opt_kernel_path);
  11688. opt_kernel_path = __kernel_path;
  11689. if (want_per_device_stats)
  11690. opt_log_output = true;
  11691. bfg_devapi_init();
  11692. drv_detect_all();
  11693. total_devices = total_devices_new;
  11694. devices = devices_new;
  11695. total_devices_new = 0;
  11696. devices_new = NULL;
  11697. if (opt_display_devs) {
  11698. int devcount = 0;
  11699. applog(LOG_ERR, "Devices detected:");
  11700. for (i = 0; i < total_devices; ++i) {
  11701. struct cgpu_info *cgpu = devices[i];
  11702. char buf[0x100];
  11703. if (cgpu->device != cgpu)
  11704. continue;
  11705. if (cgpu->name)
  11706. snprintf(buf, sizeof(buf), " %s", cgpu->name);
  11707. else
  11708. if (cgpu->dev_manufacturer)
  11709. snprintf(buf, sizeof(buf), " %s by %s", (cgpu->dev_product ?: "Device"), cgpu->dev_manufacturer);
  11710. else
  11711. if (cgpu->dev_product)
  11712. snprintf(buf, sizeof(buf), " %s", cgpu->dev_product);
  11713. else
  11714. strcpy(buf, " Device");
  11715. tailsprintf(buf, sizeof(buf), " (driver=%s; procs=%d", cgpu->drv->dname, cgpu->procs);
  11716. if (cgpu->dev_serial)
  11717. tailsprintf(buf, sizeof(buf), "; serial=%s", cgpu->dev_serial);
  11718. if (cgpu->device_path)
  11719. tailsprintf(buf, sizeof(buf), "; path=%s", cgpu->device_path);
  11720. tailsprintf(buf, sizeof(buf), ")");
  11721. _applog(LOG_NOTICE, buf);
  11722. ++devcount;
  11723. }
  11724. quit(0, "%d devices listed", devcount);
  11725. }
  11726. mining_threads = 0;
  11727. for (i = 0; i < total_devices; ++i)
  11728. register_device(devices[i]);
  11729. if (!total_devices) {
  11730. applog(LOG_WARNING, "No devices detected!");
  11731. if (use_curses)
  11732. applog(LOG_WARNING, "Waiting for devices; press 'M+' to add, or 'Q' to quit");
  11733. else
  11734. applog(LOG_WARNING, "Waiting for devices");
  11735. }
  11736. #ifdef HAVE_CURSES
  11737. switch_logsize();
  11738. #endif
  11739. #if BLKMAKER_VERSION > 1 && defined(USE_SHA256D)
  11740. if (opt_load_bitcoin_conf && !(get_mining_goal("default")->malgo->algo != POW_SHA256D || opt_benchmark))
  11741. add_local_gbt(total_pools);
  11742. #endif
  11743. if (!total_pools) {
  11744. applog(LOG_WARNING, "Need to specify at least one pool server.");
  11745. #ifdef HAVE_CURSES
  11746. if (!use_curses || !input_pool(false))
  11747. #endif
  11748. quit(1, "Pool setup failed");
  11749. }
  11750. for (i = 0; i < total_pools; i++) {
  11751. struct pool *pool = pools[i];
  11752. size_t siz;
  11753. if (!pool->rpc_url)
  11754. quit(1, "No URI supplied for pool %u", i);
  11755. if (!pool->rpc_userpass) {
  11756. if (!pool->rpc_user || !pool->rpc_pass)
  11757. quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  11758. siz = strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2;
  11759. pool->rpc_userpass = malloc(siz);
  11760. if (!pool->rpc_userpass)
  11761. quit(1, "Failed to malloc userpass");
  11762. snprintf(pool->rpc_userpass, siz, "%s:%s", pool->rpc_user, pool->rpc_pass);
  11763. }
  11764. }
  11765. /* Set the currentpool to pool with priority 0 */
  11766. validate_pool_priorities();
  11767. for (i = 0; i < total_pools; i++) {
  11768. struct pool *pool = pools[i];
  11769. if (!pool->prio)
  11770. currentpool = pool;
  11771. }
  11772. #ifdef HAVE_SYSLOG_H
  11773. if (use_syslog)
  11774. openlog(PACKAGE, LOG_PID, LOG_USER);
  11775. #endif
  11776. #if defined(unix) || defined(__APPLE__)
  11777. if (opt_stderr_cmd)
  11778. fork_monitor();
  11779. #endif // defined(unix)
  11780. mining_thr = calloc(mining_threads, sizeof(thr));
  11781. if (!mining_thr)
  11782. quit(1, "Failed to calloc mining_thr");
  11783. for (i = 0; i < mining_threads; i++) {
  11784. mining_thr[i] = calloc(1, sizeof(*thr));
  11785. if (!mining_thr[i])
  11786. quit(1, "Failed to calloc mining_thr[%d]", i);
  11787. }
  11788. total_control_threads = 6;
  11789. control_thr = calloc(total_control_threads, sizeof(*thr));
  11790. if (!control_thr)
  11791. quit(1, "Failed to calloc control_thr");
  11792. if (opt_benchmark)
  11793. goto begin_bench;
  11794. applog(LOG_NOTICE, "Probing for an alive pool");
  11795. do {
  11796. bool still_testing;
  11797. int i;
  11798. /* Look for at least one active pool before starting */
  11799. probe_pools();
  11800. do {
  11801. sleep(1);
  11802. if (pools_active)
  11803. break;
  11804. still_testing = false;
  11805. for (int i = 0; i < total_pools; ++i)
  11806. if (pools[i]->testing)
  11807. still_testing = true;
  11808. } while (still_testing);
  11809. if (!pools_active) {
  11810. applog(LOG_ERR, "No servers were found that could be used to get work from.");
  11811. applog(LOG_ERR, "Please check the details from the list below of the servers you have input");
  11812. applog(LOG_ERR, "Most likely you have input the wrong URL, forgotten to add a port, or have not set up workers");
  11813. for (i = 0; i < total_pools; i++) {
  11814. struct pool *pool;
  11815. pool = pools[i];
  11816. applog(LOG_WARNING, "Pool: %d URL: %s User: %s Password: %s",
  11817. i, pool->rpc_url, pool->rpc_user, pool->rpc_pass);
  11818. }
  11819. #ifdef HAVE_CURSES
  11820. if (use_curses) {
  11821. halfdelay(150);
  11822. applog(LOG_ERR, "Press any key to exit, or BFGMiner will try again in 15s.");
  11823. if (getch() != ERR)
  11824. quit(0, "No servers could be used! Exiting.");
  11825. cbreak();
  11826. } else
  11827. #endif
  11828. quit(0, "No servers could be used! Exiting.");
  11829. }
  11830. } while (!pools_active);
  11831. #ifdef USE_SCRYPT
  11832. if (detect_algo == 1 && get_mining_goal("default")->malgo->algo != POW_SCRYPT) {
  11833. applog(LOG_NOTICE, "Detected scrypt algorithm");
  11834. set_malgo_scrypt();
  11835. }
  11836. #endif
  11837. detect_algo = 0;
  11838. begin_bench:
  11839. total_mhashes_done = 0;
  11840. for (i = 0; i < total_devices; i++) {
  11841. struct cgpu_info *cgpu = devices[i];
  11842. cgpu->rolling = cgpu->total_mhashes = 0;
  11843. }
  11844. cgtime(&total_tv_start);
  11845. cgtime(&total_tv_end);
  11846. miner_started = total_tv_start;
  11847. time_t miner_start_ts = time(NULL);
  11848. if (schedstart.tm.tm_sec)
  11849. localtime_r(&miner_start_ts, &schedstart.tm);
  11850. if (schedstop.tm.tm_sec)
  11851. localtime_r(&miner_start_ts, &schedstop .tm);
  11852. get_datestamp(datestamp, sizeof(datestamp), miner_start_ts);
  11853. // Initialise processors and threads
  11854. k = 0;
  11855. for (i = 0; i < total_devices; ++i) {
  11856. struct cgpu_info *cgpu = devices[i];
  11857. allocate_cgpu(cgpu, &k);
  11858. }
  11859. // Start threads
  11860. for (i = 0; i < total_devices; ++i) {
  11861. struct cgpu_info *cgpu = devices[i];
  11862. start_cgpu(cgpu);
  11863. }
  11864. #ifdef USE_OPENCL
  11865. for (i = 0; i < nDevs; i++)
  11866. pause_dynamic_threads(i);
  11867. #endif
  11868. #if defined(USE_CPUMINING) && defined(USE_SHA256D)
  11869. if (opt_n_threads > 0)
  11870. applog(LOG_INFO, "%d cpu miner threads started, using '%s' algorithm.",
  11871. opt_n_threads, algo_names[opt_algo]);
  11872. #endif
  11873. cgtime(&total_tv_start);
  11874. cgtime(&total_tv_end);
  11875. if (!opt_benchmark)
  11876. {
  11877. pthread_t submit_thread;
  11878. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, NULL)))
  11879. quit(1, "submit_work thread create failed");
  11880. }
  11881. watchpool_thr_id = 1;
  11882. thr = &control_thr[watchpool_thr_id];
  11883. /* start watchpool thread */
  11884. if (thr_info_create(thr, NULL, watchpool_thread, NULL))
  11885. quit(1, "watchpool thread create failed");
  11886. pthread_detach(thr->pth);
  11887. watchdog_thr_id = 2;
  11888. thr = &control_thr[watchdog_thr_id];
  11889. /* start watchdog thread */
  11890. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  11891. quit(1, "watchdog thread create failed");
  11892. pthread_detach(thr->pth);
  11893. #ifdef USE_OPENCL
  11894. /* Create reinit gpu thread */
  11895. gpur_thr_id = 3;
  11896. thr = &control_thr[gpur_thr_id];
  11897. thr->q = tq_new();
  11898. if (!thr->q)
  11899. quit(1, "tq_new failed for gpur_thr_id");
  11900. if (thr_info_create(thr, NULL, reinit_gpu, thr))
  11901. quit(1, "reinit_gpu thread create failed");
  11902. #endif
  11903. /* Create API socket thread */
  11904. api_thr_id = 4;
  11905. thr = &control_thr[api_thr_id];
  11906. if (thr_info_create(thr, NULL, api_thread, thr))
  11907. quit(1, "API thread create failed");
  11908. #ifdef USE_LIBMICROHTTPD
  11909. if (httpsrv_port != -1)
  11910. httpsrv_start(httpsrv_port);
  11911. #endif
  11912. #ifdef USE_LIBEVENT
  11913. if (stratumsrv_port != -1)
  11914. stratumsrv_start();
  11915. #endif
  11916. #ifdef HAVE_BFG_HOTPLUG
  11917. if (opt_hotplug)
  11918. hotplug_start();
  11919. #endif
  11920. #ifdef HAVE_CURSES
  11921. /* Create curses input thread for keyboard input. Create this last so
  11922. * that we know all threads are created since this can call kill_work
  11923. * to try and shut down ll previous threads. */
  11924. input_thr_id = 5;
  11925. thr = &control_thr[input_thr_id];
  11926. if (thr_info_create(thr, NULL, input_thread, thr))
  11927. quit(1, "input thread create failed");
  11928. pthread_detach(thr->pth);
  11929. #endif
  11930. /* Just to be sure */
  11931. if (total_control_threads != 6)
  11932. quit(1, "incorrect total_control_threads (%d) should be 7", total_control_threads);
  11933. /* Once everything is set up, main() becomes the getwork scheduler */
  11934. while (42) {
  11935. int ts, max_staged = opt_queue;
  11936. struct pool *pool, *cp;
  11937. bool lagging = false;
  11938. struct curl_ent *ce;
  11939. struct work *work;
  11940. struct mining_algorithm *malgo = NULL;
  11941. cp = current_pool();
  11942. // Generally, each processor needs a new work, and all at once during work restarts
  11943. max_staged += base_queue;
  11944. mutex_lock(stgd_lock);
  11945. ts = __total_staged(false);
  11946. if (!pool_localgen(cp) && !ts && !opt_fail_only)
  11947. lagging = true;
  11948. /* Wait until hash_pop tells us we need to create more work */
  11949. if (ts > max_staged) {
  11950. {
  11951. LL_FOREACH(mining_algorithms, malgo)
  11952. {
  11953. if (!malgo->goal_refs)
  11954. continue;
  11955. if (!malgo->base_queue)
  11956. continue;
  11957. if (malgo->staged < malgo->base_queue + opt_queue)
  11958. {
  11959. mutex_unlock(stgd_lock);
  11960. pool = select_pool(lagging, malgo);
  11961. if (pool)
  11962. {
  11963. work = make_work();
  11964. work->spare = true;
  11965. goto retry;
  11966. }
  11967. }
  11968. }
  11969. malgo = NULL;
  11970. }
  11971. staged_full = true;
  11972. pthread_cond_wait(&gws_cond, stgd_lock);
  11973. ts = __total_staged(false);
  11974. }
  11975. mutex_unlock(stgd_lock);
  11976. if (ts > max_staged)
  11977. continue;
  11978. work = make_work();
  11979. if (lagging && !pool_tset(cp, &cp->lagging)) {
  11980. applog(LOG_WARNING, "Pool %d not providing work fast enough", cp->pool_no);
  11981. cp->getfail_occasions++;
  11982. total_go++;
  11983. }
  11984. pool = select_pool(lagging, malgo);
  11985. retry:
  11986. if (pool->has_stratum) {
  11987. while (!pool->stratum_active || !pool->stratum_notify) {
  11988. struct pool *altpool = select_pool(true, malgo);
  11989. if (altpool == pool && pool->has_stratum)
  11990. cgsleep_ms(5000);
  11991. pool = altpool;
  11992. goto retry;
  11993. }
  11994. gen_stratum_work(pool, work);
  11995. applog(LOG_DEBUG, "Generated stratum work");
  11996. stage_work(work);
  11997. continue;
  11998. }
  11999. if (pool->last_work_copy) {
  12000. mutex_lock(&pool->last_work_lock);
  12001. struct work *last_work = pool->last_work_copy;
  12002. if (!last_work)
  12003. {}
  12004. else
  12005. if (can_roll(last_work) && should_roll(last_work)) {
  12006. struct timeval tv_now;
  12007. cgtime(&tv_now);
  12008. free_work(work);
  12009. work = make_clone(pool->last_work_copy);
  12010. mutex_unlock(&pool->last_work_lock);
  12011. roll_work(work);
  12012. 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));
  12013. stage_work(work);
  12014. continue;
  12015. } else if (last_work->tr && pool->proto == PLP_GETBLOCKTEMPLATE && blkmk_work_left(last_work->tr->tmpl) > (unsigned long)mining_threads) {
  12016. // Don't free last_work_copy, since it is used to detect upstream provides plenty of work per template
  12017. } else {
  12018. free_work(last_work);
  12019. pool->last_work_copy = NULL;
  12020. }
  12021. mutex_unlock(&pool->last_work_lock);
  12022. }
  12023. if (clone_available()) {
  12024. applog(LOG_DEBUG, "Cloned getwork work");
  12025. free_work(work);
  12026. continue;
  12027. }
  12028. if (opt_benchmark) {
  12029. get_benchmark_work(work, opt_benchmark_intense);
  12030. applog(LOG_DEBUG, "Generated benchmark work");
  12031. stage_work(work);
  12032. continue;
  12033. }
  12034. work->pool = pool;
  12035. ce = pop_curl_entry3(pool, 2);
  12036. /* obtain new work from bitcoin via JSON-RPC */
  12037. if (!get_upstream_work(work, ce->curl)) {
  12038. struct pool *next_pool;
  12039. /* Make sure the pool just hasn't stopped serving
  12040. * requests but is up as we'll keep hammering it */
  12041. push_curl_entry(ce, pool);
  12042. ++pool->seq_getfails;
  12043. pool_died(pool);
  12044. next_pool = select_pool(!opt_fail_only, malgo);
  12045. if (pool == next_pool) {
  12046. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, retrying in 5s", pool->pool_no);
  12047. cgsleep_ms(5000);
  12048. } else {
  12049. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, failover activated", pool->pool_no);
  12050. pool = next_pool;
  12051. }
  12052. goto retry;
  12053. }
  12054. if (ts >= max_staged)
  12055. pool_tclear(pool, &pool->lagging);
  12056. if (pool_tclear(pool, &pool->idle))
  12057. pool_resus(pool);
  12058. applog(LOG_DEBUG, "Generated getwork work");
  12059. stage_work(work);
  12060. push_curl_entry(ce, pool);
  12061. }
  12062. return 0;
  12063. }