miner.c 356 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795
  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 "util.h"
  76. #ifdef USE_AVALON
  77. #include "driver-avalon.h"
  78. #endif
  79. #ifdef HAVE_BFG_LOWLEVEL
  80. #include "lowlevel.h"
  81. #endif
  82. #if defined(unix) || defined(__APPLE__)
  83. #include <errno.h>
  84. #include <fcntl.h>
  85. #include <sys/wait.h>
  86. #endif
  87. #ifdef USE_SCRYPT
  88. #include "malgo/scrypt.h"
  89. #endif
  90. #if defined(USE_AVALON) || defined(USE_BITFORCE) || defined(USE_ICARUS) || defined(USE_MODMINER) || defined(USE_NANOFURY) || defined(USE_X6500) || defined(USE_ZTEX)
  91. # define USE_FPGA
  92. #endif
  93. enum bfg_quit_summary {
  94. BQS_DEFAULT,
  95. BQS_NONE,
  96. BQS_DEVS,
  97. BQS_PROCS,
  98. BQS_DETAILED,
  99. };
  100. struct strategies strategies[] = {
  101. { "Failover" },
  102. { "Round Robin" },
  103. { "Rotate" },
  104. { "Load Balance" },
  105. { "Balance" },
  106. };
  107. #define packagename bfgminer_name_space_ver
  108. bool opt_protocol;
  109. bool opt_dev_protocol;
  110. static bool opt_benchmark, opt_benchmark_intense;
  111. static bool want_longpoll = true;
  112. static bool want_gbt = true;
  113. static bool want_getwork = true;
  114. #if BLKMAKER_VERSION > 1
  115. static bool opt_load_bitcoin_conf = true;
  116. static uint32_t coinbase_script_block_id;
  117. static uint32_t template_nonce;
  118. #endif
  119. #if BLKMAKER_VERSION > 0
  120. char *opt_coinbase_sig;
  121. #endif
  122. static enum bfg_quit_summary opt_quit_summary = BQS_DEFAULT;
  123. static bool include_serial_in_statline;
  124. char *request_target_str;
  125. float request_pdiff = 1.0;
  126. double request_bdiff;
  127. static bool want_stratum = true;
  128. int opt_skip_checks;
  129. bool want_per_device_stats;
  130. bool use_syslog;
  131. bool opt_quiet_work_updates = true;
  132. bool opt_quiet;
  133. bool opt_realquiet;
  134. int loginput_size;
  135. bool opt_compact;
  136. bool opt_show_procs;
  137. const int opt_cutofftemp = 95;
  138. int opt_hysteresis = 3;
  139. static int opt_retries = -1;
  140. int opt_fail_pause = 5;
  141. int opt_log_interval = 20;
  142. int opt_queue = 1;
  143. int opt_scantime = 60;
  144. int opt_expiry = 120;
  145. int opt_expiry_lp = 3600;
  146. unsigned long long global_hashrate;
  147. static bool opt_unittest = false;
  148. unsigned unittest_failures;
  149. unsigned long global_quota_gcd = 1;
  150. time_t last_getwork;
  151. #ifdef USE_OPENCL
  152. int opt_dynamic_interval = 7;
  153. int nDevs;
  154. int opt_g_threads = -1;
  155. #endif
  156. #ifdef USE_SCRYPT
  157. static char detect_algo = 1;
  158. #else
  159. static char detect_algo;
  160. #endif
  161. bool opt_restart = true;
  162. #ifdef USE_LIBMICROHTTPD
  163. #include "httpsrv.h"
  164. int httpsrv_port = -1;
  165. #endif
  166. #ifdef USE_LIBEVENT
  167. int stratumsrv_port = -1;
  168. #endif
  169. const
  170. int rescan_delay_ms = 1000;
  171. #ifdef HAVE_BFG_HOTPLUG
  172. bool opt_hotplug = 1;
  173. const
  174. int hotplug_delay_ms = 100;
  175. #else
  176. const bool opt_hotplug;
  177. #endif
  178. struct string_elist *scan_devices;
  179. static struct string_elist *opt_set_device_list;
  180. bool opt_force_dev_init;
  181. static struct string_elist *opt_devices_enabled_list;
  182. static bool opt_display_devs;
  183. int total_devices;
  184. struct cgpu_info **devices;
  185. int total_devices_new;
  186. struct cgpu_info **devices_new;
  187. bool have_opencl;
  188. int opt_n_threads = -1;
  189. int mining_threads;
  190. int base_queue;
  191. int num_processors;
  192. #ifdef HAVE_CURSES
  193. bool use_curses = true;
  194. #else
  195. bool use_curses;
  196. #endif
  197. int last_logstatusline_len;
  198. #ifdef HAVE_LIBUSB
  199. bool have_libusb;
  200. #endif
  201. static bool opt_submit_stale = true;
  202. static float opt_shares;
  203. static int opt_submit_threads = 0x40;
  204. bool opt_fail_only;
  205. int opt_fail_switch_delay = 300;
  206. bool opt_autofan;
  207. bool opt_autoengine;
  208. bool opt_noadl;
  209. char *opt_api_allow = NULL;
  210. char *opt_api_groups;
  211. char *opt_api_description = PACKAGE_STRING;
  212. int opt_api_port = 4028;
  213. bool opt_api_listen;
  214. bool opt_api_mcast;
  215. char *opt_api_mcast_addr = API_MCAST_ADDR;
  216. char *opt_api_mcast_code = API_MCAST_CODE;
  217. char *opt_api_mcast_des = "";
  218. int opt_api_mcast_port = 4028;
  219. bool opt_api_network;
  220. bool opt_delaynet;
  221. bool opt_disable_pool;
  222. bool opt_disable_client_reconnect = false;
  223. static bool no_work;
  224. bool opt_worktime;
  225. bool opt_weighed_stats;
  226. char *opt_kernel_path;
  227. char *cgminer_path;
  228. #if defined(USE_BITFORCE)
  229. bool opt_bfl_noncerange;
  230. #endif
  231. #define QUIET (opt_quiet || opt_realquiet)
  232. struct thr_info *control_thr;
  233. struct thr_info **mining_thr;
  234. static int watchpool_thr_id;
  235. static int watchdog_thr_id;
  236. #ifdef HAVE_CURSES
  237. static int input_thr_id;
  238. #endif
  239. int gpur_thr_id;
  240. static int api_thr_id;
  241. static int total_control_threads;
  242. pthread_mutex_t hash_lock;
  243. static pthread_mutex_t *stgd_lock;
  244. pthread_mutex_t console_lock;
  245. cglock_t ch_lock;
  246. static pthread_rwlock_t blk_lock;
  247. static pthread_mutex_t sshare_lock;
  248. pthread_rwlock_t netacc_lock;
  249. pthread_rwlock_t mining_thr_lock;
  250. pthread_rwlock_t devices_lock;
  251. static pthread_mutex_t lp_lock;
  252. static pthread_cond_t lp_cond;
  253. pthread_cond_t gws_cond;
  254. bool shutting_down;
  255. double total_rolling;
  256. double total_mhashes_done;
  257. static struct timeval total_tv_start, total_tv_end;
  258. static struct timeval miner_started;
  259. cglock_t control_lock;
  260. pthread_mutex_t stats_lock;
  261. static pthread_mutex_t submitting_lock;
  262. static int total_submitting;
  263. static struct work *submit_waiting;
  264. notifier_t submit_waiting_notifier;
  265. int hw_errors;
  266. int total_accepted, total_rejected;
  267. int total_getworks, total_stale, total_discarded;
  268. uint64_t total_bytes_rcvd, total_bytes_sent;
  269. double total_diff1, total_bad_diff1;
  270. double total_diff_accepted, total_diff_rejected, total_diff_stale;
  271. static int staged_rollable, staged_spare;
  272. unsigned int new_blocks;
  273. unsigned int found_blocks;
  274. unsigned int local_work;
  275. unsigned int total_go, total_ro;
  276. struct pool **pools;
  277. static struct pool *currentpool = NULL;
  278. int total_pools, enabled_pools;
  279. enum pool_strategy pool_strategy = POOL_FAILOVER;
  280. int opt_rotate_period;
  281. static int total_urls, total_users, total_passes;
  282. static
  283. #ifndef HAVE_CURSES
  284. const
  285. #endif
  286. bool curses_active;
  287. #ifdef HAVE_CURSES
  288. #if !(defined(PDCURSES) || defined(NCURSES_VERSION))
  289. const
  290. #endif
  291. short default_bgcolor = COLOR_BLACK;
  292. static int attr_title = A_BOLD;
  293. #endif
  294. static
  295. #if defined(HAVE_CURSES) && defined(USE_UNICODE)
  296. bool use_unicode;
  297. static
  298. bool have_unicode_degrees;
  299. static
  300. wchar_t unicode_micro = 'u';
  301. #else
  302. const bool use_unicode;
  303. static
  304. const bool have_unicode_degrees;
  305. #ifdef HAVE_CURSES
  306. static
  307. const char unicode_micro = 'u';
  308. #endif
  309. #endif
  310. #ifdef HAVE_CURSES
  311. #define U8_BAD_START "\xef\x80\x81"
  312. #define U8_BAD_END "\xef\x80\x80"
  313. #define AS_BAD(x) U8_BAD_START x U8_BAD_END
  314. /* logstart is where the log window should start */
  315. static int devcursor, logstart, logcursor;
  316. bool selecting_device;
  317. unsigned selected_device;
  318. #endif
  319. static int max_lpdigits;
  320. // current_hash was replaced with goal->current_goal_detail
  321. // current_block_id was replaced with blkchain->currentblk->block_id
  322. static char datestamp[40];
  323. static char best_share[ALLOC_H2B_SHORTV] = "0";
  324. double best_diff = 0;
  325. struct mining_algorithm *mining_algorithms;
  326. struct mining_goal_info *mining_goals;
  327. int active_goals = 1;
  328. int swork_id;
  329. /* For creating a hash database of stratum shares submitted that have not had
  330. * a response yet */
  331. struct stratum_share {
  332. UT_hash_handle hh;
  333. bool block;
  334. struct work *work;
  335. int id;
  336. };
  337. static struct stratum_share *stratum_shares = NULL;
  338. char *opt_socks_proxy = NULL;
  339. static const char def_conf[] = "bfgminer.conf";
  340. static bool config_loaded;
  341. static int include_count;
  342. #define JSON_INCLUDE_CONF "include"
  343. #define JSON_LOAD_ERROR "JSON decode of file '%s' failed\n %s"
  344. #define JSON_LOAD_ERROR_LEN strlen(JSON_LOAD_ERROR)
  345. #define JSON_MAX_DEPTH 10
  346. #define JSON_MAX_DEPTH_ERR "Too many levels of JSON includes (limit 10) or a loop"
  347. char *cmd_idle, *cmd_sick, *cmd_dead;
  348. #if defined(unix) || defined(__APPLE__)
  349. static char *opt_stderr_cmd = NULL;
  350. static int forkpid;
  351. #endif // defined(unix)
  352. #ifdef HAVE_CHROOT
  353. char *chroot_dir;
  354. #endif
  355. #ifdef HAVE_PWD_H
  356. char *opt_setuid;
  357. #endif
  358. struct sigaction termhandler, inthandler;
  359. struct thread_q *getq;
  360. static int total_work;
  361. static bool staged_full;
  362. struct work *staged_work = NULL;
  363. struct schedtime {
  364. bool enable;
  365. struct tm tm;
  366. };
  367. struct schedtime schedstart;
  368. struct schedtime schedstop;
  369. bool sched_paused;
  370. static bool time_before(struct tm *tm1, struct tm *tm2)
  371. {
  372. if (tm1->tm_hour < tm2->tm_hour)
  373. return true;
  374. if (tm1->tm_hour == tm2->tm_hour && tm1->tm_min < tm2->tm_min)
  375. return true;
  376. return false;
  377. }
  378. static bool should_run(void)
  379. {
  380. struct tm tm;
  381. time_t tt;
  382. bool within_range;
  383. if (!schedstart.enable && !schedstop.enable)
  384. return true;
  385. tt = time(NULL);
  386. localtime_r(&tt, &tm);
  387. // NOTE: This is delicately balanced so that should_run is always false if schedstart==schedstop
  388. if (time_before(&schedstop.tm, &schedstart.tm))
  389. within_range = (time_before(&tm, &schedstop.tm) || !time_before(&tm, &schedstart.tm));
  390. else
  391. within_range = (time_before(&tm, &schedstop.tm) && !time_before(&tm, &schedstart.tm));
  392. if (within_range && !schedstop.enable)
  393. /* This is a once off event with no stop time set */
  394. schedstart.enable = false;
  395. return within_range;
  396. }
  397. void get_datestamp(char *f, size_t fsiz, time_t tt)
  398. {
  399. struct tm _tm;
  400. struct tm *tm = &_tm;
  401. if (tt == INVALID_TIMESTAMP)
  402. tt = time(NULL);
  403. localtime_r(&tt, tm);
  404. snprintf(f, fsiz, "[%d-%02d-%02d %02d:%02d:%02d]",
  405. tm->tm_year + 1900,
  406. tm->tm_mon + 1,
  407. tm->tm_mday,
  408. tm->tm_hour,
  409. tm->tm_min,
  410. tm->tm_sec);
  411. }
  412. static
  413. void get_timestamp(char *f, size_t fsiz, time_t tt)
  414. {
  415. struct tm _tm;
  416. struct tm *tm = &_tm;
  417. localtime_r(&tt, tm);
  418. snprintf(f, fsiz, "[%02d:%02d:%02d]",
  419. tm->tm_hour,
  420. tm->tm_min,
  421. tm->tm_sec);
  422. }
  423. static void applog_and_exit(const char *fmt, ...) FORMAT_SYNTAX_CHECK(printf, 1, 2);
  424. static char exit_buf[512];
  425. static void applog_and_exit(const char *fmt, ...)
  426. {
  427. va_list ap;
  428. va_start(ap, fmt);
  429. vsnprintf(exit_buf, sizeof(exit_buf), fmt, ap);
  430. va_end(ap);
  431. _applog(LOG_ERR, exit_buf);
  432. exit(1);
  433. }
  434. static
  435. float drv_min_nonce_diff(const struct device_drv * const drv, struct cgpu_info * const proc, const struct mining_algorithm * const malgo)
  436. {
  437. if (drv->drv_min_nonce_diff)
  438. return drv->drv_min_nonce_diff(proc, malgo);
  439. #ifdef USE_SHA256D
  440. return (malgo->algo == POW_SHA256D) ? 1. : -1.;
  441. #else
  442. return -1.;
  443. #endif
  444. }
  445. char *devpath_to_devid(const char *devpath)
  446. {
  447. #ifndef WIN32
  448. if (devpath[0] != '/')
  449. return NULL;
  450. struct stat my_stat;
  451. if (stat(devpath, &my_stat))
  452. return NULL;
  453. char *devs = malloc(6 + (sizeof(dev_t) * 2) + 1);
  454. memcpy(devs, "dev_t:", 6);
  455. bin2hex(&devs[6], &my_stat.st_rdev, sizeof(dev_t));
  456. #else
  457. if (!strncmp(devpath, "\\\\.\\", 4))
  458. devpath += 4;
  459. if (strncasecmp(devpath, "COM", 3) || !devpath[3])
  460. return NULL;
  461. devpath += 3;
  462. char *p;
  463. strtol(devpath, &p, 10);
  464. if (p[0])
  465. return NULL;
  466. const int sz = (p - devpath);
  467. char *devs = malloc(4 + sz + 1);
  468. sprintf(devs, "com:%s", devpath);
  469. #endif
  470. return devs;
  471. }
  472. static
  473. bool devpaths_match(const char * const ap, const char * const bp)
  474. {
  475. char * const a = devpath_to_devid(ap);
  476. if (!a)
  477. return false;
  478. char * const b = devpath_to_devid(bp);
  479. bool rv = false;
  480. if (b)
  481. {
  482. rv = !strcmp(a, b);
  483. free(b);
  484. }
  485. free(a);
  486. return rv;
  487. }
  488. static
  489. int proc_letter_to_number(const char *s, const char ** const rem)
  490. {
  491. int n = 0, c;
  492. for ( ; s[0]; ++s)
  493. {
  494. if (unlikely(n > INT_MAX / 26))
  495. break;
  496. c = tolower(s[0]) - 'a';
  497. if (unlikely(c < 0 || c > 25))
  498. break;
  499. if (unlikely(INT_MAX - c < n))
  500. break;
  501. n = (n * 26) + c;
  502. }
  503. *rem = s;
  504. return n;
  505. }
  506. static
  507. bool cgpu_match(const char * const pattern, const struct cgpu_info * const cgpu)
  508. {
  509. // all - matches anything
  510. // d0 - matches all processors of device 0
  511. // d0-3 - matches all processors of device 0, 1, 2, or 3
  512. // d0a - matches first processor of device 0
  513. // 0 - matches processor 0
  514. // 0-4 - matches processors 0, 1, 2, 3, or 4
  515. // ___ - matches all processors on all devices using driver/name ___
  516. // ___0 - matches all processors of 0th device using driver/name ___
  517. // ___0a - matches first processor of 0th device using driver/name ___
  518. // @* - matches device with serial or path *
  519. // @*@a - matches first processor of device with serial or path *
  520. // ___@* - matches device with serial or path * using driver/name ___
  521. if (!strcasecmp(pattern, "all"))
  522. return true;
  523. const struct device_drv * const drv = cgpu->drv;
  524. const char *p = pattern, *p2;
  525. size_t L;
  526. int n, i, c = -1;
  527. int n2;
  528. int proc_first = -1, proc_last = -1;
  529. struct cgpu_info *device;
  530. if (!(strncasecmp(drv->dname, p, (L = strlen(drv->dname)))
  531. && strncasecmp(drv-> name, p, (L = strlen(drv-> name)))))
  532. // dname or name
  533. p = &pattern[L];
  534. else
  535. if (p[0] == 'd' && (isdigit(p[1]) || p[1] == '-'))
  536. // d#
  537. ++p;
  538. else
  539. if (isdigit(p[0]) || p[0] == '@' || p[0] == '-')
  540. // # or @
  541. {}
  542. else
  543. return false;
  544. L = p - pattern;
  545. while (isspace(p[0]))
  546. ++p;
  547. if (p[0] == '@')
  548. {
  549. // Serial/path
  550. const char * const ser = &p[1];
  551. for (p = ser; p[0] != '@' && p[0] != '\0'; ++p)
  552. {}
  553. p2 = (p[0] == '@') ? &p[1] : p;
  554. const size_t serlen = (p - ser);
  555. p = "";
  556. n = n2 = 0;
  557. const char * const devpath = cgpu->device_path ?: "";
  558. const char * const devser = cgpu->dev_serial ?: "";
  559. if ((!strncmp(devpath, ser, serlen)) && devpath[serlen] == '\0')
  560. {} // Match
  561. else
  562. if ((!strncmp(devser, ser, serlen)) && devser[serlen] == '\0')
  563. {} // Match
  564. else
  565. {
  566. char devpath2[serlen + 1];
  567. memcpy(devpath2, ser, serlen);
  568. devpath2[serlen] = '\0';
  569. if (!devpaths_match(devpath, ser))
  570. return false;
  571. }
  572. }
  573. else
  574. {
  575. if (isdigit(p[0]))
  576. n = strtol(p, (void*)&p2, 0);
  577. else
  578. {
  579. n = 0;
  580. p2 = p;
  581. }
  582. if (p2[0] == '-')
  583. {
  584. ++p2;
  585. if (p2[0] && isdigit(p2[0]))
  586. n2 = strtol(p2, (void*)&p2, 0);
  587. else
  588. n2 = INT_MAX;
  589. }
  590. else
  591. n2 = n;
  592. if (p == pattern)
  593. {
  594. if (!p[0])
  595. return true;
  596. if (p2 && p2[0])
  597. goto invsyntax;
  598. for (i = n; i <= n2; ++i)
  599. {
  600. if (i >= total_devices)
  601. break;
  602. if (cgpu == devices[i])
  603. return true;
  604. }
  605. return false;
  606. }
  607. }
  608. if (p2[0])
  609. {
  610. proc_first = proc_letter_to_number(&p2[0], &p2);
  611. if (p2[0] == '-')
  612. {
  613. ++p2;
  614. if (p2[0])
  615. proc_last = proc_letter_to_number(p2, &p2);
  616. else
  617. proc_last = INT_MAX;
  618. }
  619. else
  620. proc_last = proc_first;
  621. if (p2[0])
  622. goto invsyntax;
  623. }
  624. if (L > 1 || tolower(pattern[0]) != 'd' || !p[0])
  625. {
  626. if ((L == 3 && !strncasecmp(pattern, drv->name, 3)) ||
  627. (!L) ||
  628. (L == strlen(drv->dname) && !strncasecmp(pattern, drv->dname, L)))
  629. {} // Matched name or dname
  630. else
  631. return false;
  632. if (p[0] && (cgpu->device_id < n || cgpu->device_id > n2))
  633. return false;
  634. if (proc_first != -1 && (cgpu->proc_id < proc_first || cgpu->proc_id > proc_last))
  635. return false;
  636. return true;
  637. }
  638. // d#
  639. c = -1;
  640. for (i = 0; ; ++i)
  641. {
  642. if (i == total_devices)
  643. return false;
  644. if (devices[i]->device != devices[i])
  645. continue;
  646. ++c;
  647. if (c < n)
  648. continue;
  649. if (c > n2)
  650. break;
  651. for (device = devices[i]; device; device = device->next_proc)
  652. {
  653. if (proc_first != -1 && (device->proc_id < proc_first || device->proc_id > proc_last))
  654. continue;
  655. if (device == cgpu)
  656. return true;
  657. }
  658. }
  659. return false;
  660. invsyntax:
  661. applog(LOG_WARNING, "%s: Invalid syntax: %s", __func__, pattern);
  662. return false;
  663. }
  664. #define TEST_CGPU_MATCH(pattern) \
  665. if (!cgpu_match(pattern, &cgpu)) \
  666. { \
  667. ++unittest_failures; \
  668. applog(LOG_ERR, "%s: Pattern \"%s\" should have matched!", __func__, pattern); \
  669. } \
  670. // END TEST_CGPU_MATCH
  671. #define TEST_CGPU_NOMATCH(pattern) \
  672. if (cgpu_match(pattern, &cgpu)) \
  673. { \
  674. ++unittest_failures; \
  675. applog(LOG_ERR, "%s: Pattern \"%s\" should NOT have matched!", __func__, pattern); \
  676. } \
  677. // END TEST_CGPU_MATCH
  678. static __maybe_unused
  679. void test_cgpu_match()
  680. {
  681. struct device_drv drv = {
  682. .dname = "test",
  683. .name = "TST",
  684. };
  685. struct cgpu_info cgpu = {
  686. .drv = &drv,
  687. .device = &cgpu,
  688. .device_id = 1,
  689. .proc_id = 1,
  690. .proc_repr = "TST 1b",
  691. }, cgpu0a = {
  692. .drv = &drv,
  693. .device = &cgpu0a,
  694. .device_id = 0,
  695. .proc_id = 0,
  696. .proc_repr = "TST 0a",
  697. }, cgpu1a = {
  698. .drv = &drv,
  699. .device = &cgpu0a,
  700. .device_id = 1,
  701. .proc_id = 0,
  702. .proc_repr = "TST 1a",
  703. };
  704. struct cgpu_info *devices_list[3] = {&cgpu0a, &cgpu1a, &cgpu,};
  705. devices = devices_list;
  706. total_devices = 3;
  707. TEST_CGPU_MATCH("all")
  708. TEST_CGPU_MATCH("d1")
  709. TEST_CGPU_NOMATCH("d2")
  710. TEST_CGPU_MATCH("d0-5")
  711. TEST_CGPU_NOMATCH("d0-0")
  712. TEST_CGPU_NOMATCH("d2-5")
  713. TEST_CGPU_MATCH("d-1")
  714. TEST_CGPU_MATCH("d1-")
  715. TEST_CGPU_NOMATCH("d-0")
  716. TEST_CGPU_NOMATCH("d2-")
  717. TEST_CGPU_MATCH("2")
  718. TEST_CGPU_NOMATCH("3")
  719. TEST_CGPU_MATCH("1-2")
  720. TEST_CGPU_MATCH("2-3")
  721. TEST_CGPU_NOMATCH("1-1")
  722. TEST_CGPU_NOMATCH("3-4")
  723. TEST_CGPU_MATCH("TST")
  724. TEST_CGPU_MATCH("test")
  725. TEST_CGPU_MATCH("tst")
  726. TEST_CGPU_MATCH("TEST")
  727. TEST_CGPU_NOMATCH("TSF")
  728. TEST_CGPU_NOMATCH("TS")
  729. TEST_CGPU_NOMATCH("TSTF")
  730. TEST_CGPU_MATCH("TST1")
  731. TEST_CGPU_MATCH("test1")
  732. TEST_CGPU_MATCH("TST0-1")
  733. TEST_CGPU_MATCH("TST 1")
  734. TEST_CGPU_MATCH("TST 1-2")
  735. TEST_CGPU_MATCH("TEST 1-2")
  736. TEST_CGPU_NOMATCH("TST2")
  737. TEST_CGPU_NOMATCH("TST2-3")
  738. TEST_CGPU_NOMATCH("TST0-0")
  739. TEST_CGPU_MATCH("TST1b")
  740. TEST_CGPU_MATCH("tst1b")
  741. TEST_CGPU_NOMATCH("TST1c")
  742. TEST_CGPU_NOMATCH("TST1bb")
  743. TEST_CGPU_MATCH("TST0-1b")
  744. TEST_CGPU_NOMATCH("TST0-1c")
  745. TEST_CGPU_MATCH("TST1a-d")
  746. TEST_CGPU_NOMATCH("TST1a-a")
  747. TEST_CGPU_NOMATCH("TST1-a")
  748. TEST_CGPU_NOMATCH("TST1c-z")
  749. TEST_CGPU_NOMATCH("TST1c-")
  750. TEST_CGPU_MATCH("@")
  751. TEST_CGPU_NOMATCH("@abc")
  752. TEST_CGPU_MATCH("@@b")
  753. TEST_CGPU_NOMATCH("@@c")
  754. TEST_CGPU_MATCH("TST@")
  755. TEST_CGPU_NOMATCH("TST@abc")
  756. TEST_CGPU_MATCH("TST@@b")
  757. TEST_CGPU_NOMATCH("TST@@c")
  758. TEST_CGPU_MATCH("TST@@b-f")
  759. TEST_CGPU_NOMATCH("TST@@c-f")
  760. TEST_CGPU_NOMATCH("TST@@-a")
  761. cgpu.device_path = "/dev/test";
  762. cgpu.dev_serial = "testy";
  763. TEST_CGPU_MATCH("TST@/dev/test")
  764. TEST_CGPU_MATCH("TST@testy")
  765. TEST_CGPU_NOMATCH("TST@")
  766. TEST_CGPU_NOMATCH("TST@/dev/test5@b")
  767. TEST_CGPU_NOMATCH("TST@testy3@b")
  768. TEST_CGPU_MATCH("TST@/dev/test@b")
  769. TEST_CGPU_MATCH("TST@testy@b")
  770. TEST_CGPU_NOMATCH("TST@/dev/test@c")
  771. TEST_CGPU_NOMATCH("TST@testy@c")
  772. cgpu.device_path = "usb:000:999";
  773. TEST_CGPU_MATCH("TST@usb:000:999")
  774. drv.dname = "test7";
  775. TEST_CGPU_MATCH("test7")
  776. TEST_CGPU_MATCH("TEST7")
  777. TEST_CGPU_NOMATCH("test&")
  778. TEST_CGPU_MATCH("test7 1-2")
  779. TEST_CGPU_MATCH("test7@testy@b")
  780. }
  781. static
  782. int cgpu_search(const char * const pattern, const int first)
  783. {
  784. int i;
  785. struct cgpu_info *cgpu;
  786. #define CHECK_CGPU_SEARCH do{ \
  787. cgpu = get_devices(i); \
  788. if (cgpu_match(pattern, cgpu)) \
  789. return i; \
  790. }while(0)
  791. for (i = first; i < total_devices; ++i)
  792. CHECK_CGPU_SEARCH;
  793. for (i = 0; i < first; ++i)
  794. CHECK_CGPU_SEARCH;
  795. #undef CHECK_CGPU_SEARCH
  796. return -1;
  797. }
  798. static pthread_mutex_t sharelog_lock;
  799. static FILE *sharelog_file = NULL;
  800. struct thr_info *get_thread(int thr_id)
  801. {
  802. struct thr_info *thr;
  803. rd_lock(&mining_thr_lock);
  804. thr = mining_thr[thr_id];
  805. rd_unlock(&mining_thr_lock);
  806. return thr;
  807. }
  808. static struct cgpu_info *get_thr_cgpu(int thr_id)
  809. {
  810. struct thr_info *thr = get_thread(thr_id);
  811. return thr->cgpu;
  812. }
  813. struct cgpu_info *get_devices(int id)
  814. {
  815. struct cgpu_info *cgpu;
  816. rd_lock(&devices_lock);
  817. cgpu = devices[id];
  818. rd_unlock(&devices_lock);
  819. return cgpu;
  820. }
  821. static pthread_mutex_t noncelog_lock = PTHREAD_MUTEX_INITIALIZER;
  822. static FILE *noncelog_file = NULL;
  823. static
  824. void noncelog(const struct work * const work)
  825. {
  826. const int thr_id = work->thr_id;
  827. const struct cgpu_info *proc = get_thr_cgpu(thr_id);
  828. char buf[0x200], hash[65], data[161], midstate[65];
  829. int rv;
  830. size_t ret;
  831. bin2hex(hash, work->hash, 32);
  832. bin2hex(data, work->data, 80);
  833. bin2hex(midstate, work->midstate, 32);
  834. // timestamp,proc,hash,data,midstate
  835. rv = snprintf(buf, sizeof(buf), "%lu,%s,%s,%s,%s\n",
  836. (unsigned long)time(NULL), proc->proc_repr_ns,
  837. hash, data, midstate);
  838. if (unlikely(rv < 1))
  839. {
  840. applog(LOG_ERR, "noncelog printf error");
  841. return;
  842. }
  843. mutex_lock(&noncelog_lock);
  844. ret = fwrite(buf, rv, 1, noncelog_file);
  845. fflush(noncelog_file);
  846. mutex_unlock(&noncelog_lock);
  847. if (ret != 1)
  848. applog(LOG_ERR, "noncelog fwrite error");
  849. }
  850. static void sharelog(const char*disposition, const struct work*work)
  851. {
  852. char target[(sizeof(work->target) * 2) + 1];
  853. char hash[(sizeof(work->hash) * 2) + 1];
  854. char data[(sizeof(work->data) * 2) + 1];
  855. struct cgpu_info *cgpu;
  856. unsigned long int t;
  857. struct pool *pool;
  858. int thr_id, rv;
  859. char s[1024];
  860. size_t ret;
  861. if (!sharelog_file)
  862. return;
  863. thr_id = work->thr_id;
  864. cgpu = get_thr_cgpu(thr_id);
  865. pool = work->pool;
  866. t = work->ts_getwork + timer_elapsed(&work->tv_getwork, &work->tv_work_found);
  867. bin2hex(target, work->target, sizeof(work->target));
  868. bin2hex(hash, work->hash, sizeof(work->hash));
  869. bin2hex(data, work->data, sizeof(work->data));
  870. // timestamp,disposition,target,pool,dev,thr,sharehash,sharedata
  871. 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);
  872. if (rv >= (int)(sizeof(s)))
  873. s[sizeof(s) - 1] = '\0';
  874. else if (rv < 0) {
  875. applog(LOG_ERR, "sharelog printf error");
  876. return;
  877. }
  878. mutex_lock(&sharelog_lock);
  879. ret = fwrite(s, rv, 1, sharelog_file);
  880. fflush(sharelog_file);
  881. mutex_unlock(&sharelog_lock);
  882. if (ret != 1)
  883. applog(LOG_ERR, "sharelog fwrite error");
  884. }
  885. #ifdef HAVE_CURSES
  886. static void switch_logsize(void);
  887. #endif
  888. static void hotplug_trigger();
  889. void goal_set_malgo(struct mining_goal_info * const goal, struct mining_algorithm * const malgo)
  890. {
  891. if (goal->malgo == malgo)
  892. return;
  893. if (goal->malgo)
  894. --goal->malgo->goal_refs;
  895. if (malgo->goal_refs++)
  896. // First time using a new mining algorithm may means we need to add mining hardware to support it
  897. // 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)
  898. if (opt_hotplug && api_thr_id)
  899. hotplug_trigger();
  900. goal->malgo = malgo;
  901. }
  902. struct mining_algorithm *mining_algorithm_by_alias(const char * const alias)
  903. {
  904. struct mining_algorithm *malgo;
  905. LL_FOREACH(mining_algorithms, malgo)
  906. {
  907. if (match_strtok(malgo->aliases, "|", alias))
  908. return malgo;
  909. }
  910. return NULL;
  911. }
  912. #ifdef USE_SCRYPT
  913. extern struct mining_algorithm malgo_scrypt;
  914. static
  915. const char *set_malgo_scrypt()
  916. {
  917. goal_set_malgo(get_mining_goal("default"), &malgo_scrypt);
  918. return NULL;
  919. }
  920. #endif
  921. static
  922. int mining_goals_name_cmp(const struct mining_goal_info * const a, const struct mining_goal_info * const b)
  923. {
  924. // default always goes first
  925. if (a->is_default)
  926. return -1;
  927. if (b->is_default)
  928. return 1;
  929. return strcmp(a->name, b->name);
  930. }
  931. static
  932. void blkchain_init_block(struct blockchain_info * const blkchain)
  933. {
  934. struct block_info * const dummy_block = calloc(sizeof(*dummy_block), 1);
  935. memset(dummy_block->prevblkhash, 0, 0x20);
  936. HASH_ADD(hh, blkchain->blocks, prevblkhash, sizeof(dummy_block->prevblkhash), dummy_block);
  937. blkchain->currentblk = dummy_block;
  938. }
  939. extern struct mining_algorithm malgo_sha256d;
  940. struct mining_goal_info *get_mining_goal(const char * const name)
  941. {
  942. static unsigned next_goal_id;
  943. struct mining_goal_info *goal;
  944. HASH_FIND_STR(mining_goals, name, goal);
  945. if (!goal)
  946. {
  947. struct blockchain_info * const blkchain = malloc(sizeof(*blkchain) + sizeof(*goal));
  948. goal = (void*)(&blkchain[1]);
  949. *blkchain = (struct blockchain_info){
  950. .currentblk = NULL,
  951. };
  952. blkchain_init_block(blkchain);
  953. *goal = (struct mining_goal_info){
  954. .id = next_goal_id++,
  955. .name = strdup(name),
  956. .is_default = !strcmp(name, "default"),
  957. .blkchain = blkchain,
  958. .current_diff = 0xFFFFFFFFFFFFFFFFULL,
  959. };
  960. #ifdef USE_SHA256D
  961. goal_set_malgo(goal, &malgo_sha256d);
  962. #else
  963. // NOTE: Basically random default
  964. goal_set_malgo(goal, mining_algorithms);
  965. #endif
  966. HASH_ADD_KEYPTR(hh, mining_goals, goal->name, strlen(goal->name), goal);
  967. HASH_SORT(mining_goals, mining_goals_name_cmp);
  968. #ifdef HAVE_CURSES
  969. devcursor = 7 + active_goals;
  970. switch_logsize();
  971. #endif
  972. }
  973. return goal;
  974. }
  975. void mining_goal_reset(struct mining_goal_info * const goal)
  976. {
  977. struct blockchain_info * const blkchain = goal->blkchain;
  978. struct block_info *blkinfo, *tmpblkinfo;
  979. HASH_ITER(hh, blkchain->blocks, blkinfo, tmpblkinfo)
  980. {
  981. HASH_DEL(blkchain->blocks, blkinfo);
  982. free(blkinfo);
  983. }
  984. blkchain_init_block(blkchain);
  985. }
  986. static char *getwork_req = "{\"method\": \"getwork\", \"params\": [], \"id\":0}\n";
  987. /* Adjust all the pools' quota to the greatest common denominator after a pool
  988. * has been added or the quotas changed. */
  989. void adjust_quota_gcd(void)
  990. {
  991. unsigned long gcd, lowest_quota = ~0UL, quota;
  992. struct pool *pool;
  993. int i;
  994. for (i = 0; i < total_pools; i++) {
  995. pool = pools[i];
  996. quota = pool->quota;
  997. if (!quota)
  998. continue;
  999. if (quota < lowest_quota)
  1000. lowest_quota = quota;
  1001. }
  1002. if (likely(lowest_quota < ~0UL)) {
  1003. gcd = lowest_quota;
  1004. for (i = 0; i < total_pools; i++) {
  1005. pool = pools[i];
  1006. quota = pool->quota;
  1007. if (!quota)
  1008. continue;
  1009. while (quota % gcd)
  1010. gcd--;
  1011. }
  1012. } else
  1013. gcd = 1;
  1014. for (i = 0; i < total_pools; i++) {
  1015. pool = pools[i];
  1016. pool->quota_used *= global_quota_gcd;
  1017. pool->quota_used /= gcd;
  1018. pool->quota_gcd = pool->quota / gcd;
  1019. }
  1020. global_quota_gcd = gcd;
  1021. applog(LOG_DEBUG, "Global quota greatest common denominator set to %lu", gcd);
  1022. }
  1023. /* Return value is ignored if not called from add_pool_details */
  1024. struct pool *add_pool2(struct mining_goal_info * const goal)
  1025. {
  1026. struct pool *pool;
  1027. pool = calloc(sizeof(struct pool), 1);
  1028. if (!pool)
  1029. quit(1, "Failed to malloc pool in add_pool");
  1030. pool->pool_no = pool->prio = total_pools;
  1031. mutex_init(&pool->last_work_lock);
  1032. mutex_init(&pool->pool_lock);
  1033. mutex_init(&pool->pool_test_lock);
  1034. if (unlikely(pthread_cond_init(&pool->cr_cond, bfg_condattr)))
  1035. quit(1, "Failed to pthread_cond_init in add_pool");
  1036. cglock_init(&pool->data_lock);
  1037. mutex_init(&pool->stratum_lock);
  1038. timer_unset(&pool->swork.tv_transparency);
  1039. pool->swork.pool = pool;
  1040. pool->goal = goal;
  1041. pool->idle = true;
  1042. /* Make sure the pool doesn't think we've been idle since time 0 */
  1043. pool->tv_idle.tv_sec = ~0UL;
  1044. cgtime(&pool->cgminer_stats.start_tv);
  1045. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  1046. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  1047. pool->rpc_proxy = NULL;
  1048. pool->quota = 1;
  1049. pool->sock = INVSOCK;
  1050. pool->lp_socket = CURL_SOCKET_BAD;
  1051. pools = realloc(pools, sizeof(struct pool *) * (total_pools + 2));
  1052. pools[total_pools++] = pool;
  1053. if (opt_benchmark)
  1054. {
  1055. // Immediately remove it
  1056. remove_pool(pool);
  1057. return pool;
  1058. }
  1059. adjust_quota_gcd();
  1060. if (!currentpool)
  1061. currentpool = pool;
  1062. enable_pool(pool);
  1063. return pool;
  1064. }
  1065. static
  1066. void pool_set_uri(struct pool * const pool, char * const uri)
  1067. {
  1068. pool->rpc_url = uri;
  1069. }
  1070. /* Pool variant of test and set */
  1071. static bool pool_tset(struct pool *pool, bool *var)
  1072. {
  1073. bool ret;
  1074. mutex_lock(&pool->pool_lock);
  1075. ret = *var;
  1076. *var = true;
  1077. mutex_unlock(&pool->pool_lock);
  1078. return ret;
  1079. }
  1080. bool pool_tclear(struct pool *pool, bool *var)
  1081. {
  1082. bool ret;
  1083. mutex_lock(&pool->pool_lock);
  1084. ret = *var;
  1085. *var = false;
  1086. mutex_unlock(&pool->pool_lock);
  1087. return ret;
  1088. }
  1089. struct pool *current_pool(void)
  1090. {
  1091. struct pool *pool;
  1092. cg_rlock(&control_lock);
  1093. pool = currentpool;
  1094. cg_runlock(&control_lock);
  1095. return pool;
  1096. }
  1097. #if defined(USE_CPUMINING) && !defined(USE_SHA256D)
  1098. static
  1099. char *arg_ignored(const char * const arg)
  1100. {
  1101. return NULL;
  1102. }
  1103. #endif
  1104. static
  1105. char *set_bool_ignore_arg(const char * const arg, bool * const b)
  1106. {
  1107. return opt_set_bool(b);
  1108. }
  1109. char *set_int_range(const char *arg, int *i, int min, int max)
  1110. {
  1111. char *err = opt_set_intval(arg, i);
  1112. if (err)
  1113. return err;
  1114. if (*i < min || *i > max)
  1115. return "Value out of range";
  1116. return NULL;
  1117. }
  1118. static char *set_int_0_to_9999(const char *arg, int *i)
  1119. {
  1120. return set_int_range(arg, i, 0, 9999);
  1121. }
  1122. static char *set_int_1_to_65535(const char *arg, int *i)
  1123. {
  1124. return set_int_range(arg, i, 1, 65535);
  1125. }
  1126. static char *set_int_0_to_10(const char *arg, int *i)
  1127. {
  1128. return set_int_range(arg, i, 0, 10);
  1129. }
  1130. static char *set_int_1_to_10(const char *arg, int *i)
  1131. {
  1132. return set_int_range(arg, i, 1, 10);
  1133. }
  1134. char *set_strdup(const char *arg, char **p)
  1135. {
  1136. *p = strdup((char *)arg);
  1137. return NULL;
  1138. }
  1139. #if BLKMAKER_VERSION > 1
  1140. static
  1141. char *set_b58addr(const char * const arg, bytes_t * const b)
  1142. {
  1143. size_t scriptsz = blkmk_address_to_script(NULL, 0, arg);
  1144. if (!scriptsz)
  1145. return "Invalid address";
  1146. char *script = malloc(scriptsz);
  1147. if (blkmk_address_to_script(script, scriptsz, arg) != scriptsz) {
  1148. free(script);
  1149. return "Failed to convert address to script";
  1150. }
  1151. bytes_assimilate_raw(b, script, scriptsz, scriptsz);
  1152. return NULL;
  1153. }
  1154. static char *set_generate_addr2(struct mining_goal_info *, const char *);
  1155. static
  1156. char *set_generate_addr(char *arg)
  1157. {
  1158. char * const colon = strchr(arg, ':');
  1159. struct mining_goal_info *goal;
  1160. if (colon)
  1161. {
  1162. colon[0] = '\0';
  1163. goal = get_mining_goal(arg);
  1164. arg = &colon[1];
  1165. }
  1166. else
  1167. goal = get_mining_goal("default");
  1168. return set_generate_addr2(goal, arg);
  1169. }
  1170. static
  1171. char *set_generate_addr2(struct mining_goal_info * const goal, const char * const arg)
  1172. {
  1173. bytes_t newscript = BYTES_INIT;
  1174. char *estr = set_b58addr(arg, &newscript);
  1175. if (estr)
  1176. {
  1177. bytes_free(&newscript);
  1178. return estr;
  1179. }
  1180. if (!goal->generation_script)
  1181. {
  1182. goal->generation_script = malloc(sizeof(*goal->generation_script));
  1183. bytes_init(goal->generation_script);
  1184. }
  1185. bytes_assimilate(goal->generation_script, &newscript);
  1186. bytes_free(&newscript);
  1187. return NULL;
  1188. }
  1189. #endif
  1190. static
  1191. char *set_quit_summary(const char * const arg)
  1192. {
  1193. if (!(strcasecmp(arg, "none") && strcasecmp(arg, "no")))
  1194. opt_quit_summary = BQS_NONE;
  1195. else
  1196. if (!(strcasecmp(arg, "devs") && strcasecmp(arg, "devices")))
  1197. opt_quit_summary = BQS_DEVS;
  1198. else
  1199. if (!(strcasecmp(arg, "procs") && strcasecmp(arg, "processors") && strcasecmp(arg, "chips") && strcasecmp(arg, "cores")))
  1200. opt_quit_summary = BQS_PROCS;
  1201. else
  1202. if (!(strcasecmp(arg, "detailed") && strcasecmp(arg, "detail") && strcasecmp(arg, "all")))
  1203. opt_quit_summary = BQS_DETAILED;
  1204. else
  1205. return "Quit summary must be one of none/devs/procs/detailed";
  1206. return NULL;
  1207. }
  1208. static void pdiff_target_leadzero(void *, double);
  1209. char *set_request_diff(const char *arg, float *p)
  1210. {
  1211. unsigned char target[32];
  1212. char *e = opt_set_floatval(arg, p);
  1213. if (e)
  1214. return e;
  1215. request_bdiff = (double)*p * 0.9999847412109375;
  1216. pdiff_target_leadzero(target, *p);
  1217. request_target_str = malloc(65);
  1218. bin2hex(request_target_str, target, 32);
  1219. return NULL;
  1220. }
  1221. #ifdef NEED_BFG_LOWL_VCOM
  1222. extern struct lowlevel_device_info *_vcom_devinfo_findorcreate(struct lowlevel_device_info **, const char *);
  1223. #ifdef WIN32
  1224. void _vcom_devinfo_scan_querydosdevice(struct lowlevel_device_info ** const devinfo_list)
  1225. {
  1226. char dev[PATH_MAX];
  1227. char *devp = dev;
  1228. size_t bufLen = 0x100;
  1229. tryagain: ;
  1230. char buf[bufLen];
  1231. if (!QueryDosDevice(NULL, buf, bufLen)) {
  1232. if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
  1233. bufLen *= 2;
  1234. applog(LOG_DEBUG, "QueryDosDevice returned insufficent buffer error; enlarging to %lx", (unsigned long)bufLen);
  1235. goto tryagain;
  1236. }
  1237. applogr(, LOG_WARNING, "Error occurred trying to enumerate COM ports with QueryDosDevice");
  1238. }
  1239. size_t tLen;
  1240. memcpy(devp, "\\\\.\\", 4);
  1241. devp = &devp[4];
  1242. for (char *t = buf; *t; t += tLen) {
  1243. tLen = strlen(t) + 1;
  1244. if (strncmp("COM", t, 3))
  1245. continue;
  1246. memcpy(devp, t, tLen);
  1247. // NOTE: We depend on _vcom_devinfo_findorcreate to further check that there's a number (and only a number) on the end
  1248. _vcom_devinfo_findorcreate(devinfo_list, dev);
  1249. }
  1250. }
  1251. #else
  1252. void _vcom_devinfo_scan_lsdev(struct lowlevel_device_info ** const devinfo_list)
  1253. {
  1254. char dev[PATH_MAX];
  1255. char *devp = dev;
  1256. DIR *D;
  1257. struct dirent *de;
  1258. const char devdir[] = "/dev";
  1259. const size_t devdirlen = sizeof(devdir) - 1;
  1260. char *devpath = devp;
  1261. char *devfile = devpath + devdirlen + 1;
  1262. D = opendir(devdir);
  1263. if (!D)
  1264. applogr(, LOG_DEBUG, "No /dev directory to look for VCOM devices in");
  1265. memcpy(devpath, devdir, devdirlen);
  1266. devpath[devdirlen] = '/';
  1267. while ( (de = readdir(D)) ) {
  1268. if (!strncmp(de->d_name, "cu.", 3)
  1269. //don't probe Bluetooth devices - causes bus errors and segfaults
  1270. && strncmp(de->d_name, "cu.Bluetooth", 12))
  1271. goto trydev;
  1272. if (strncmp(de->d_name, "tty", 3))
  1273. continue;
  1274. if (strncmp(&de->d_name[3], "USB", 3) && strncmp(&de->d_name[3], "ACM", 3))
  1275. continue;
  1276. trydev:
  1277. strcpy(devfile, de->d_name);
  1278. _vcom_devinfo_findorcreate(devinfo_list, dev);
  1279. }
  1280. closedir(D);
  1281. }
  1282. #endif
  1283. #endif
  1284. static char *add_serial(const char *arg)
  1285. {
  1286. string_elist_add(arg, &scan_devices);
  1287. return NULL;
  1288. }
  1289. static
  1290. char *opt_string_elist_add(const char *arg, struct string_elist **elist)
  1291. {
  1292. string_elist_add(arg, elist);
  1293. return NULL;
  1294. }
  1295. bool get_intrange(const char *arg, int *val1, int *val2)
  1296. {
  1297. // NOTE: This could be done with sscanf, but its %n is broken in strange ways on Windows
  1298. char *p, *p2;
  1299. *val1 = strtol(arg, &p, 0);
  1300. if (arg == p)
  1301. // Zero-length ending number, invalid
  1302. return false;
  1303. while (true)
  1304. {
  1305. if (!p[0])
  1306. {
  1307. *val2 = *val1;
  1308. return true;
  1309. }
  1310. if (p[0] == '-')
  1311. break;
  1312. if (!isspace(p[0]))
  1313. // Garbage, invalid
  1314. return false;
  1315. ++p;
  1316. }
  1317. p2 = &p[1];
  1318. *val2 = strtol(p2, &p, 0);
  1319. if (p2 == p)
  1320. // Zero-length ending number, invalid
  1321. return false;
  1322. while (true)
  1323. {
  1324. if (!p[0])
  1325. return true;
  1326. if (!isspace(p[0]))
  1327. // Garbage, invalid
  1328. return false;
  1329. ++p;
  1330. }
  1331. }
  1332. static
  1333. void _test_intrange(const char *s, const int v[2])
  1334. {
  1335. int a[2];
  1336. if (!get_intrange(s, &a[0], &a[1]))
  1337. {
  1338. ++unittest_failures;
  1339. applog(LOG_ERR, "Test \"%s\" failed: returned false", s);
  1340. }
  1341. for (int i = 0; i < 2; ++i)
  1342. if (unlikely(a[i] != v[i]))
  1343. {
  1344. ++unittest_failures;
  1345. applog(LOG_ERR, "Test \"%s\" failed: value %d should be %d but got %d", s, i, v[i], a[i]);
  1346. }
  1347. }
  1348. #define _test_intrange(s, ...) _test_intrange(s, (int[]){ __VA_ARGS__ })
  1349. static
  1350. void _test_intrange_fail(const char *s)
  1351. {
  1352. int a[2];
  1353. if (get_intrange(s, &a[0], &a[1]))
  1354. {
  1355. ++unittest_failures;
  1356. applog(LOG_ERR, "Test !\"%s\" failed: returned true with %d and %d", s, a[0], a[1]);
  1357. }
  1358. }
  1359. static
  1360. void test_intrange()
  1361. {
  1362. _test_intrange("-1--2", -1, -2);
  1363. _test_intrange("-1-2", -1, 2);
  1364. _test_intrange("1--2", 1, -2);
  1365. _test_intrange("1-2", 1, 2);
  1366. _test_intrange("111-222", 111, 222);
  1367. _test_intrange(" 11 - 22 ", 11, 22);
  1368. _test_intrange("+11-+22", 11, 22);
  1369. _test_intrange("-1", -1, -1);
  1370. _test_intrange_fail("all");
  1371. _test_intrange_fail("1-");
  1372. _test_intrange_fail("");
  1373. _test_intrange_fail("1-54x");
  1374. }
  1375. static char *set_devices(char *arg)
  1376. {
  1377. if (*arg) {
  1378. if (*arg == '?') {
  1379. opt_display_devs = true;
  1380. return NULL;
  1381. }
  1382. } else
  1383. return "Invalid device parameters";
  1384. string_elist_add(arg, &opt_devices_enabled_list);
  1385. return NULL;
  1386. }
  1387. static char *set_balance(enum pool_strategy *strategy)
  1388. {
  1389. *strategy = POOL_BALANCE;
  1390. return NULL;
  1391. }
  1392. static char *set_loadbalance(enum pool_strategy *strategy)
  1393. {
  1394. *strategy = POOL_LOADBALANCE;
  1395. return NULL;
  1396. }
  1397. static char *set_rotate(const char *arg, int *i)
  1398. {
  1399. pool_strategy = POOL_ROTATE;
  1400. return set_int_range(arg, i, 0, 9999);
  1401. }
  1402. static char *set_rr(enum pool_strategy *strategy)
  1403. {
  1404. *strategy = POOL_ROUNDROBIN;
  1405. return NULL;
  1406. }
  1407. static
  1408. char *set_benchmark_intense()
  1409. {
  1410. opt_benchmark = true;
  1411. opt_benchmark_intense = true;
  1412. return NULL;
  1413. }
  1414. /* Detect that url is for a stratum protocol either via the presence of
  1415. * stratum+tcp or by detecting a stratum server response */
  1416. bool detect_stratum(struct pool *pool, char *url)
  1417. {
  1418. if (!extract_sockaddr(url, &pool->sockaddr_url, &pool->stratum_port))
  1419. return false;
  1420. if (!strncasecmp(url, "stratum+tcp://", 14)) {
  1421. pool_set_uri(pool, strdup(url));
  1422. pool->has_stratum = true;
  1423. pool->stratum_url = pool->sockaddr_url;
  1424. return true;
  1425. }
  1426. return false;
  1427. }
  1428. static struct pool *add_url(void)
  1429. {
  1430. total_urls++;
  1431. if (total_urls > total_pools)
  1432. add_pool();
  1433. return pools[total_urls - 1];
  1434. }
  1435. static void setup_url(struct pool *pool, char *arg)
  1436. {
  1437. if (detect_stratum(pool, arg))
  1438. return;
  1439. opt_set_charp(arg, &pool->rpc_url);
  1440. if (strncmp(arg, "http://", 7) &&
  1441. strncmp(arg, "https://", 8)) {
  1442. const size_t L = strlen(arg);
  1443. char *httpinput;
  1444. httpinput = malloc(8 + L);
  1445. if (!httpinput)
  1446. quit(1, "Failed to malloc httpinput");
  1447. sprintf(httpinput, "http://%s", arg);
  1448. pool_set_uri(pool, httpinput);
  1449. }
  1450. }
  1451. static char *set_url(char *arg)
  1452. {
  1453. struct pool *pool = add_url();
  1454. setup_url(pool, arg);
  1455. return NULL;
  1456. }
  1457. static char *set_quota(char *arg)
  1458. {
  1459. char *semicolon = strchr(arg, ';'), *url;
  1460. int len, qlen, quota;
  1461. struct pool *pool;
  1462. if (!semicolon)
  1463. return "No semicolon separated quota;URL pair found";
  1464. len = strlen(arg);
  1465. *semicolon = '\0';
  1466. qlen = strlen(arg);
  1467. if (!qlen)
  1468. return "No parameter for quota found";
  1469. len -= qlen + 1;
  1470. if (len < 1)
  1471. return "No parameter for URL found";
  1472. quota = atoi(arg);
  1473. if (quota < 0)
  1474. return "Invalid negative parameter for quota set";
  1475. url = arg + qlen + 1;
  1476. pool = add_url();
  1477. setup_url(pool, url);
  1478. pool->quota = quota;
  1479. applog(LOG_INFO, "Setting pool %d to quota %d", pool->pool_no, pool->quota);
  1480. adjust_quota_gcd();
  1481. return NULL;
  1482. }
  1483. static char *set_user(const char *arg)
  1484. {
  1485. struct pool *pool;
  1486. total_users++;
  1487. if (total_users > total_pools)
  1488. add_pool();
  1489. pool = pools[total_users - 1];
  1490. opt_set_charp(arg, &pool->rpc_user);
  1491. return NULL;
  1492. }
  1493. static char *set_pass(const char *arg)
  1494. {
  1495. struct pool *pool;
  1496. total_passes++;
  1497. if (total_passes > total_pools)
  1498. add_pool();
  1499. pool = pools[total_passes - 1];
  1500. opt_set_charp(arg, &pool->rpc_pass);
  1501. return NULL;
  1502. }
  1503. static char *set_userpass(const char *arg)
  1504. {
  1505. struct pool *pool;
  1506. char *updup;
  1507. if (total_users != total_passes)
  1508. return "User + pass options must be balanced before userpass";
  1509. ++total_users;
  1510. ++total_passes;
  1511. if (total_users > total_pools)
  1512. add_pool();
  1513. pool = pools[total_users - 1];
  1514. updup = strdup(arg);
  1515. opt_set_charp(arg, &pool->rpc_userpass);
  1516. pool->rpc_user = updup;
  1517. pool->rpc_pass = strchr(updup, ':');
  1518. if (pool->rpc_pass)
  1519. pool->rpc_pass++[0] = '\0';
  1520. else
  1521. pool->rpc_pass = &updup[strlen(updup)];
  1522. return NULL;
  1523. }
  1524. static char *set_cbcaddr(char *arg)
  1525. {
  1526. struct pool *pool;
  1527. char *p, *addr;
  1528. bytes_t target_script = BYTES_INIT;
  1529. if (!total_pools)
  1530. return "Define pool first, then the --coinbase-check-addr list";
  1531. pool = pools[total_pools - 1];
  1532. /* NOTE: 'x' is a new prefix which leads both mainnet and testnet address, we would
  1533. * need support it later, but now leave the code just so.
  1534. *
  1535. * Regarding details of address prefix 'x', check the below URL:
  1536. * https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#Serialization_format
  1537. */
  1538. pool->cb_param.testnet = (arg[0] != '1' && arg[0] != '3' && arg[0] != 'x');
  1539. for (; (addr = strtok_r(arg, ",", &p)); arg = NULL)
  1540. {
  1541. struct bytes_hashtbl *ah;
  1542. if (set_b58addr(addr, &target_script))
  1543. /* No bother to free memory since we are going to exit anyway */
  1544. return "Invalid address in --coinbase-check-address list";
  1545. HASH_FIND(hh, pool->cb_param.scripts, bytes_buf(&target_script), bytes_len(&target_script), ah);
  1546. if (!ah)
  1547. {
  1548. /* Note: for the below allocated memory we have good way to release its memory
  1549. * since we can't be sure there are no reference to the pool struct when remove_pool()
  1550. * get called.
  1551. *
  1552. * We just hope the remove_pool() would not be called many many times during
  1553. * the whole running life of this program.
  1554. */
  1555. ah = malloc(sizeof(*ah));
  1556. bytes_init(&ah->b);
  1557. bytes_assimilate(&ah->b, &target_script);
  1558. HASH_ADD(hh, pool->cb_param.scripts, b.buf, bytes_len(&ah->b), ah);
  1559. }
  1560. }
  1561. bytes_free(&target_script);
  1562. return NULL;
  1563. }
  1564. static char *set_cbctotal(const char *arg)
  1565. {
  1566. struct pool *pool;
  1567. if (!total_pools)
  1568. return "Define pool first, then the --coinbase-check-total argument";
  1569. pool = pools[total_pools - 1];
  1570. pool->cb_param.total = atoll(arg);
  1571. if (pool->cb_param.total < 0)
  1572. return "The total payout amount in coinbase should be greater than 0";
  1573. return NULL;
  1574. }
  1575. static char *set_cbcperc(const char *arg)
  1576. {
  1577. struct pool *pool;
  1578. if (!total_pools)
  1579. return "Define pool first, then the --coinbase-check-percent argument";
  1580. pool = pools[total_pools - 1];
  1581. if (!pool->cb_param.scripts)
  1582. return "Define --coinbase-check-addr list first, then the --coinbase-check-total argument";
  1583. pool->cb_param.perc = atof(arg) / 100;
  1584. if (pool->cb_param.perc < 0.0 || pool->cb_param.perc > 1.0)
  1585. return "The percentage should be between 0 and 100";
  1586. return NULL;
  1587. }
  1588. static
  1589. 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)
  1590. {
  1591. *out_success = SDR_ERR;
  1592. if (!(strcasecmp(optname, "malgo") && strcasecmp(optname, "algo")))
  1593. {
  1594. if (!newvalue)
  1595. return "Goal option 'malgo' requires a value (eg, SHA256d)";
  1596. struct mining_algorithm * const new_malgo = mining_algorithm_by_alias(newvalue);
  1597. if (!new_malgo)
  1598. return "Unrecognised mining algorithm";
  1599. goal_set_malgo(goal, new_malgo);
  1600. goto success;
  1601. }
  1602. #if BLKMAKER_VERSION > 1
  1603. 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))
  1604. {
  1605. if (!newvalue)
  1606. return "Missing value for 'generate-to' goal option";
  1607. const char * const emsg = set_generate_addr2(goal, newvalue);
  1608. if (emsg)
  1609. return emsg;
  1610. goto success;
  1611. }
  1612. #endif
  1613. *out_success = SDR_UNKNOWN;
  1614. return "Unknown goal option";
  1615. success:
  1616. *out_success = SDR_OK;
  1617. return NULL;
  1618. }
  1619. // May leak replybuf if returning an error
  1620. static
  1621. const char *set_goal_params(struct mining_goal_info * const goal, char *arg)
  1622. {
  1623. bytes_t replybuf = BYTES_INIT;
  1624. for (char *param, *nextptr; (param = strtok_r(arg, ",", &nextptr)); arg = NULL)
  1625. {
  1626. char *val = strchr(param, '=');
  1627. if (val)
  1628. val++[0] = '\0';
  1629. enum bfg_set_device_replytype success;
  1630. const char * const emsg = goal_set(goal, param, val, &replybuf, &success);
  1631. if (success != SDR_OK)
  1632. return emsg ?: "Error setting goal param";
  1633. }
  1634. bytes_free(&replybuf);
  1635. return NULL;
  1636. }
  1637. static
  1638. const char *set_pool_goal(const char * const arg)
  1639. {
  1640. struct pool *pool;
  1641. if (!total_pools)
  1642. return "Usage of --pool-goal before pools are defined does not make sense";
  1643. pool = pools[total_pools - 1];
  1644. char *param = strchr(arg, ':');
  1645. if (param)
  1646. param++[0] = '\0';
  1647. pool->goal = get_mining_goal(arg);
  1648. if (param)
  1649. return set_goal_params(pool->goal, param);
  1650. return NULL;
  1651. }
  1652. static char *set_pool_priority(const char *arg)
  1653. {
  1654. struct pool *pool;
  1655. if (!total_pools)
  1656. return "Usage of --pool-priority before pools are defined does not make sense";
  1657. pool = pools[total_pools - 1];
  1658. opt_set_intval(arg, &pool->prio);
  1659. return NULL;
  1660. }
  1661. static char *set_pool_proxy(const char *arg)
  1662. {
  1663. struct pool *pool;
  1664. if (!total_pools)
  1665. return "Usage of --pool-proxy before pools are defined does not make sense";
  1666. if (!our_curl_supports_proxy_uris())
  1667. return "Your installed cURL library does not support proxy URIs. At least version 7.21.7 is required.";
  1668. pool = pools[total_pools - 1];
  1669. opt_set_charp(arg, &pool->rpc_proxy);
  1670. return NULL;
  1671. }
  1672. static char *set_pool_force_rollntime(const char *arg)
  1673. {
  1674. struct pool *pool;
  1675. if (!total_pools)
  1676. return "Usage of --force-rollntime before pools are defined does not make sense";
  1677. pool = pools[total_pools - 1];
  1678. opt_set_intval(arg, &pool->force_rollntime);
  1679. return NULL;
  1680. }
  1681. static char *enable_debug(bool *flag)
  1682. {
  1683. *flag = true;
  1684. opt_debug_console = true;
  1685. /* Turn on verbose output, too. */
  1686. opt_log_output = true;
  1687. return NULL;
  1688. }
  1689. static char *set_schedtime(const char *arg, struct schedtime *st)
  1690. {
  1691. if (sscanf(arg, "%d:%d", &st->tm.tm_hour, &st->tm.tm_min) != 2)
  1692. {
  1693. if (strcasecmp(arg, "now"))
  1694. return "Invalid time set, should be HH:MM";
  1695. } else
  1696. schedstop.tm.tm_sec = 0;
  1697. if (st->tm.tm_hour > 23 || st->tm.tm_min > 59 || st->tm.tm_hour < 0 || st->tm.tm_min < 0)
  1698. return "Invalid time set.";
  1699. st->enable = true;
  1700. return NULL;
  1701. }
  1702. static
  1703. char *set_log_file(char *arg)
  1704. {
  1705. char *r = "";
  1706. long int i = strtol(arg, &r, 10);
  1707. int fd, stderr_fd = fileno(stderr);
  1708. if ((!*r) && i >= 0 && i <= INT_MAX)
  1709. fd = i;
  1710. else
  1711. if (!strcmp(arg, "-"))
  1712. {
  1713. fd = fileno(stdout);
  1714. if (unlikely(fd == -1))
  1715. return "Standard output missing for log-file";
  1716. }
  1717. else
  1718. {
  1719. fd = open(arg, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR);
  1720. if (unlikely(fd == -1))
  1721. return "Failed to open log-file";
  1722. }
  1723. close(stderr_fd);
  1724. if (unlikely(-1 == dup2(fd, stderr_fd)))
  1725. return "Failed to dup2 for log-file";
  1726. close(fd);
  1727. return NULL;
  1728. }
  1729. static
  1730. char *_bfgopt_set_file(const char *arg, FILE **F, const char *mode, const char *purpose)
  1731. {
  1732. char *r = "";
  1733. long int i = strtol(arg, &r, 10);
  1734. static char *err = NULL;
  1735. const size_t errbufsz = 0x100;
  1736. free(err);
  1737. err = NULL;
  1738. if ((!*r) && i >= 0 && i <= INT_MAX) {
  1739. *F = fdopen((int)i, mode);
  1740. if (!*F)
  1741. {
  1742. err = malloc(errbufsz);
  1743. snprintf(err, errbufsz, "Failed to open fd %d for %s",
  1744. (int)i, purpose);
  1745. return err;
  1746. }
  1747. } else if (!strcmp(arg, "-")) {
  1748. *F = (mode[0] == 'a') ? stdout : stdin;
  1749. if (!*F)
  1750. {
  1751. err = malloc(errbufsz);
  1752. snprintf(err, errbufsz, "Standard %sput missing for %s",
  1753. (mode[0] == 'a') ? "out" : "in", purpose);
  1754. return err;
  1755. }
  1756. } else {
  1757. *F = fopen(arg, mode);
  1758. if (!*F)
  1759. {
  1760. err = malloc(errbufsz);
  1761. snprintf(err, errbufsz, "Failed to open %s for %s",
  1762. arg, purpose);
  1763. return err;
  1764. }
  1765. }
  1766. return NULL;
  1767. }
  1768. static char *set_noncelog(char *arg)
  1769. {
  1770. return _bfgopt_set_file(arg, &noncelog_file, "a", "nonce log");
  1771. }
  1772. static char *set_sharelog(char *arg)
  1773. {
  1774. return _bfgopt_set_file(arg, &sharelog_file, "a", "share log");
  1775. }
  1776. static
  1777. void _add_set_device_option(const char * const func, const char * const buf)
  1778. {
  1779. applog(LOG_DEBUG, "%s: Using --set-device %s", func, buf);
  1780. string_elist_add(buf, &opt_set_device_list);
  1781. }
  1782. #define add_set_device_option(...) do{ \
  1783. char _tmp1718[0x100]; \
  1784. snprintf(_tmp1718, sizeof(_tmp1718), __VA_ARGS__); \
  1785. _add_set_device_option(__func__, _tmp1718); \
  1786. }while(0)
  1787. char *set_temp_cutoff(char *arg)
  1788. {
  1789. if (strchr(arg, ','))
  1790. return "temp-cutoff no longer supports comma-delimited syntax, use --set-device for better control";
  1791. applog(LOG_WARNING, "temp-cutoff is deprecated! Use --set-device for better control");
  1792. add_set_device_option("all:temp-cutoff=%s", arg);
  1793. return NULL;
  1794. }
  1795. char *set_temp_target(char *arg)
  1796. {
  1797. if (strchr(arg, ','))
  1798. return "temp-target no longer supports comma-delimited syntax, use --set-device for better control";
  1799. applog(LOG_WARNING, "temp-target is deprecated! Use --set-device for better control");
  1800. add_set_device_option("all:temp-target=%s", arg);
  1801. return NULL;
  1802. }
  1803. #ifdef USE_OPENCL
  1804. static
  1805. char *set_no_opencl_binaries(__maybe_unused void * const dummy)
  1806. {
  1807. applog(LOG_WARNING, "The --no-opencl-binaries option is deprecated! Use --set-device OCL:binary=no");
  1808. add_set_device_option("OCL:binary=no");
  1809. return NULL;
  1810. }
  1811. #endif
  1812. static
  1813. char *disable_pool_redirect(__maybe_unused void * const dummy)
  1814. {
  1815. opt_disable_client_reconnect = true;
  1816. want_stratum = false;
  1817. return NULL;
  1818. }
  1819. static char *set_api_allow(const char *arg)
  1820. {
  1821. opt_set_charp(arg, &opt_api_allow);
  1822. return NULL;
  1823. }
  1824. static char *set_api_groups(const char *arg)
  1825. {
  1826. opt_set_charp(arg, &opt_api_groups);
  1827. return NULL;
  1828. }
  1829. static char *set_api_description(const char *arg)
  1830. {
  1831. opt_set_charp(arg, &opt_api_description);
  1832. return NULL;
  1833. }
  1834. static char *set_api_mcast_des(const char *arg)
  1835. {
  1836. opt_set_charp(arg, &opt_api_mcast_des);
  1837. return NULL;
  1838. }
  1839. #ifdef USE_ICARUS
  1840. extern const struct bfg_set_device_definition icarus_set_device_funcs[];
  1841. static char *set_icarus_options(const char *arg)
  1842. {
  1843. if (strchr(arg, ','))
  1844. return "icarus-options no longer supports comma-delimited syntax, see README.FPGA for better control";
  1845. applog(LOG_WARNING, "icarus-options is deprecated! See README.FPGA for better control");
  1846. char *opts = strdup(arg), *argdup;
  1847. argdup = opts;
  1848. const struct bfg_set_device_definition *sdf = icarus_set_device_funcs;
  1849. const char *drivers[] = {"antminer", "cairnsmore", "erupter", "icarus"};
  1850. char *saveptr, *opt;
  1851. for (int i = 0; i < 4; ++i, ++sdf)
  1852. {
  1853. opt = strtok_r(opts, ":", &saveptr);
  1854. opts = NULL;
  1855. if (!opt)
  1856. break;
  1857. if (!opt[0])
  1858. continue;
  1859. for (int j = 0; j < 4; ++j)
  1860. add_set_device_option("%s:%s=%s", drivers[j], sdf->optname, opt);
  1861. }
  1862. free(argdup);
  1863. return NULL;
  1864. }
  1865. static char *set_icarus_timing(const char *arg)
  1866. {
  1867. if (strchr(arg, ','))
  1868. return "icarus-timing no longer supports comma-delimited syntax, see README.FPGA for better control";
  1869. applog(LOG_WARNING, "icarus-timing is deprecated! See README.FPGA for better control");
  1870. const char *drivers[] = {"antminer", "cairnsmore", "erupter", "icarus"};
  1871. for (int j = 0; j < 4; ++j)
  1872. add_set_device_option("%s:timing=%s", drivers[j], arg);
  1873. return NULL;
  1874. }
  1875. #endif
  1876. #ifdef USE_AVALON
  1877. extern const struct bfg_set_device_definition avalon_set_device_funcs[];
  1878. static char *set_avalon_options(const char *arg)
  1879. {
  1880. if (strchr(arg, ','))
  1881. return "avalon-options no longer supports comma-delimited syntax, see README.FPGA for better control";
  1882. applog(LOG_WARNING, "avalon-options is deprecated! See README.FPGA for better control");
  1883. char *opts = strdup(arg), *argdup;
  1884. argdup = opts;
  1885. const struct bfg_set_device_definition *sdf = avalon_set_device_funcs;
  1886. char *saveptr, *opt;
  1887. for (int i = 0; i < 5; ++i, ++sdf)
  1888. {
  1889. opt = strtok_r(opts, ":", &saveptr);
  1890. opts = NULL;
  1891. if (!opt)
  1892. break;
  1893. if (!opt[0])
  1894. continue;
  1895. add_set_device_option("avalon:%s=%s", sdf->optname, opt);
  1896. }
  1897. free(argdup);
  1898. return NULL;
  1899. }
  1900. #endif
  1901. #ifdef USE_KLONDIKE
  1902. static char *set_klondike_options(const char *arg)
  1903. {
  1904. int hashclock;
  1905. double temptarget;
  1906. switch (sscanf(arg, "%d:%lf", &hashclock, &temptarget))
  1907. {
  1908. default:
  1909. return "Unrecognised --klondike-options";
  1910. case 2:
  1911. add_set_device_option("klondike:temp-target=%lf", temptarget);
  1912. // fallthru
  1913. case 1:
  1914. add_set_device_option("klondike:clock=%d", hashclock);
  1915. }
  1916. applog(LOG_WARNING, "klondike-options is deprecated! Use --set-device for better control");
  1917. return NULL;
  1918. }
  1919. #endif
  1920. __maybe_unused
  1921. static char *set_null(const char __maybe_unused *arg)
  1922. {
  1923. return NULL;
  1924. }
  1925. /* These options are available from config file or commandline */
  1926. static struct opt_table opt_config_table[] = {
  1927. #ifdef USE_CPUMINING
  1928. #ifdef USE_SHA256D
  1929. OPT_WITH_ARG("--algo",
  1930. set_algo, show_algo, &opt_algo,
  1931. "Specify sha256 implementation for CPU mining:\n"
  1932. "\tfastauto*\tQuick benchmark at startup to pick a working algorithm\n"
  1933. "\tauto\t\tBenchmark at startup and pick fastest algorithm"
  1934. "\n\tc\t\tLinux kernel sha256, implemented in C"
  1935. #ifdef WANT_SSE2_4WAY
  1936. "\n\t4way\t\ttcatm's 4-way SSE2 implementation"
  1937. #endif
  1938. #ifdef WANT_VIA_PADLOCK
  1939. "\n\tvia\t\tVIA padlock implementation"
  1940. #endif
  1941. "\n\tcryptopp\tCrypto++ C/C++ implementation"
  1942. #ifdef WANT_CRYPTOPP_ASM32
  1943. "\n\tcryptopp_asm32\tCrypto++ 32-bit assembler implementation"
  1944. #endif
  1945. #ifdef WANT_X8632_SSE2
  1946. "\n\tsse2_32\t\tSSE2 32 bit implementation for i386 machines"
  1947. #endif
  1948. #ifdef WANT_X8664_SSE2
  1949. "\n\tsse2_64\t\tSSE2 64 bit implementation for x86_64 machines"
  1950. #endif
  1951. #ifdef WANT_X8664_SSE4
  1952. "\n\tsse4_64\t\tSSE4.1 64 bit implementation for x86_64 machines"
  1953. #endif
  1954. #ifdef WANT_ALTIVEC_4WAY
  1955. "\n\taltivec_4way\tAltivec implementation for PowerPC G4 and G5 machines"
  1956. #endif
  1957. ),
  1958. OPT_WITH_ARG("-a",
  1959. set_algo, show_algo, &opt_algo,
  1960. opt_hidden),
  1961. #else
  1962. // NOTE: Silently ignoring option, since it is plausable a non-SHA256d miner was using it just to skip benchmarking
  1963. OPT_WITH_ARG("--algo|-a", arg_ignored, NULL, NULL, opt_hidden),
  1964. #endif /* USE_SHA256D */
  1965. #endif /* USE_CPUMINING */
  1966. OPT_WITH_ARG("--api-allow",
  1967. set_api_allow, NULL, NULL,
  1968. "Allow API access only to the given list of [G:]IP[/Prefix] addresses[/subnets]"),
  1969. OPT_WITH_ARG("--api-description",
  1970. set_api_description, NULL, NULL,
  1971. "Description placed in the API status header, default: BFGMiner version"),
  1972. OPT_WITH_ARG("--api-groups",
  1973. set_api_groups, NULL, NULL,
  1974. "API one letter groups G:cmd:cmd[,P:cmd:*...] defining the cmds a groups can use"),
  1975. OPT_WITHOUT_ARG("--api-listen",
  1976. opt_set_bool, &opt_api_listen,
  1977. "Enable API, default: disabled"),
  1978. OPT_WITHOUT_ARG("--api-mcast",
  1979. opt_set_bool, &opt_api_mcast,
  1980. "Enable API Multicast listener, default: disabled"),
  1981. OPT_WITH_ARG("--api-mcast-addr",
  1982. opt_set_charp, opt_show_charp, &opt_api_mcast_addr,
  1983. "API Multicast listen address"),
  1984. OPT_WITH_ARG("--api-mcast-code",
  1985. opt_set_charp, opt_show_charp, &opt_api_mcast_code,
  1986. "Code expected in the API Multicast message, don't use '-'"),
  1987. OPT_WITH_ARG("--api-mcast-des",
  1988. set_api_mcast_des, NULL, NULL,
  1989. "Description appended to the API Multicast reply, default: ''"),
  1990. OPT_WITH_ARG("--api-mcast-port",
  1991. set_int_1_to_65535, opt_show_intval, &opt_api_mcast_port,
  1992. "API Multicast listen port"),
  1993. OPT_WITHOUT_ARG("--api-network",
  1994. opt_set_bool, &opt_api_network,
  1995. "Allow API (if enabled) to listen on/for any address, default: only 127.0.0.1"),
  1996. OPT_WITH_ARG("--api-port",
  1997. set_int_1_to_65535, opt_show_intval, &opt_api_port,
  1998. "Port number of miner API"),
  1999. #ifdef HAVE_ADL
  2000. OPT_WITHOUT_ARG("--auto-fan",
  2001. opt_set_bool, &opt_autofan,
  2002. opt_hidden),
  2003. OPT_WITHOUT_ARG("--auto-gpu",
  2004. opt_set_bool, &opt_autoengine,
  2005. opt_hidden),
  2006. #endif
  2007. OPT_WITHOUT_ARG("--balance",
  2008. set_balance, &pool_strategy,
  2009. "Change multipool strategy from failover to even share balance"),
  2010. OPT_WITHOUT_ARG("--benchmark",
  2011. opt_set_bool, &opt_benchmark,
  2012. "Run BFGMiner in benchmark mode - produces no shares"),
  2013. OPT_WITHOUT_ARG("--benchmark-intense",
  2014. set_benchmark_intense, &opt_benchmark_intense,
  2015. "Run BFGMiner in intensive benchmark mode - produces no shares"),
  2016. #if defined(USE_BITFORCE)
  2017. OPT_WITHOUT_ARG("--bfl-range",
  2018. opt_set_bool, &opt_bfl_noncerange,
  2019. "Use nonce range on bitforce devices if supported"),
  2020. #endif
  2021. #ifdef HAVE_CHROOT
  2022. OPT_WITH_ARG("--chroot-dir",
  2023. opt_set_charp, NULL, &chroot_dir,
  2024. "Chroot to a directory right after startup"),
  2025. #endif
  2026. OPT_WITH_ARG("--cmd-idle",
  2027. opt_set_charp, NULL, &cmd_idle,
  2028. "Execute a command when a device is allowed to be idle (rest or wait)"),
  2029. OPT_WITH_ARG("--cmd-sick",
  2030. opt_set_charp, NULL, &cmd_sick,
  2031. "Execute a command when a device is declared sick"),
  2032. OPT_WITH_ARG("--cmd-dead",
  2033. opt_set_charp, NULL, &cmd_dead,
  2034. "Execute a command when a device is declared dead"),
  2035. #if BLKMAKER_VERSION > 0
  2036. OPT_WITH_ARG("--coinbase-sig",
  2037. set_strdup, NULL, &opt_coinbase_sig,
  2038. "Set coinbase signature when possible"),
  2039. OPT_WITH_ARG("--coinbase|--cbsig|--cb-sig|--cb|--prayer",
  2040. set_strdup, NULL, &opt_coinbase_sig,
  2041. opt_hidden),
  2042. #endif
  2043. #ifdef HAVE_CURSES
  2044. OPT_WITHOUT_ARG("--compact",
  2045. opt_set_bool, &opt_compact,
  2046. "Use compact display without per device statistics"),
  2047. #endif
  2048. #ifdef USE_CPUMINING
  2049. OPT_WITH_ARG("--cpu-threads",
  2050. force_nthreads_int, opt_show_intval, &opt_n_threads,
  2051. "Number of miner CPU threads"),
  2052. OPT_WITH_ARG("-t",
  2053. force_nthreads_int, opt_show_intval, &opt_n_threads,
  2054. opt_hidden),
  2055. #endif
  2056. OPT_WITHOUT_ARG("--debug|-D",
  2057. enable_debug, &opt_debug,
  2058. "Enable debug output"),
  2059. OPT_WITHOUT_ARG("--debuglog",
  2060. opt_set_bool, &opt_debug,
  2061. "Enable debug logging"),
  2062. OPT_WITHOUT_ARG("--device-protocol-dump",
  2063. opt_set_bool, &opt_dev_protocol,
  2064. "Verbose dump of device protocol-level activities"),
  2065. OPT_WITH_ARG("--device|-d",
  2066. set_devices, NULL, NULL,
  2067. "Enable only devices matching pattern (default: all)"),
  2068. OPT_WITHOUT_ARG("--disable-rejecting",
  2069. opt_set_bool, &opt_disable_pool,
  2070. "Automatically disable pools that continually reject shares"),
  2071. #ifdef USE_LIBMICROHTTPD
  2072. OPT_WITH_ARG("--http-port",
  2073. opt_set_intval, opt_show_intval, &httpsrv_port,
  2074. "Port number to listen on for HTTP getwork miners (-1 means disabled)"),
  2075. #endif
  2076. OPT_WITH_ARG("--expiry",
  2077. set_int_0_to_9999, opt_show_intval, &opt_expiry,
  2078. "Upper bound on how many seconds after getting work we consider a share from it stale (w/o longpoll active)"),
  2079. OPT_WITH_ARG("-E",
  2080. set_int_0_to_9999, opt_show_intval, &opt_expiry,
  2081. opt_hidden),
  2082. OPT_WITH_ARG("--expiry-lp",
  2083. set_int_0_to_9999, opt_show_intval, &opt_expiry_lp,
  2084. "Upper bound on how many seconds after getting work we consider a share from it stale (with longpoll active)"),
  2085. OPT_WITHOUT_ARG("--failover-only",
  2086. opt_set_bool, &opt_fail_only,
  2087. "Don't leak work to backup pools when primary pool is lagging"),
  2088. OPT_WITH_ARG("--failover-switch-delay",
  2089. set_int_1_to_65535, opt_show_intval, &opt_fail_switch_delay,
  2090. "Delay in seconds before switching back to a failed pool"),
  2091. #ifdef USE_FPGA
  2092. OPT_WITHOUT_ARG("--force-dev-init",
  2093. opt_set_bool, &opt_force_dev_init,
  2094. "Always initialize devices when possible (such as bitstream uploads to some FPGAs)"),
  2095. #endif
  2096. #if BLKMAKER_VERSION > 1
  2097. OPT_WITH_ARG("--generate-to",
  2098. set_generate_addr, NULL, NULL,
  2099. "Set an address to generate to for solo mining"),
  2100. 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",
  2101. set_generate_addr, NULL, NULL,
  2102. opt_hidden),
  2103. #endif
  2104. #ifdef USE_OPENCL
  2105. OPT_WITH_ARG("--gpu-dyninterval",
  2106. set_int_1_to_65535, opt_show_intval, &opt_dynamic_interval,
  2107. opt_hidden),
  2108. OPT_WITH_ARG("--gpu-platform",
  2109. set_int_0_to_9999, opt_show_intval, &opt_platform_id,
  2110. "Select OpenCL platform ID to use for GPU mining"),
  2111. OPT_WITH_ARG("--gpu-threads|-g",
  2112. set_gpu_threads, opt_show_intval, &opt_g_threads,
  2113. opt_hidden),
  2114. #ifdef HAVE_ADL
  2115. OPT_WITH_ARG("--gpu-engine",
  2116. set_gpu_engine, NULL, NULL,
  2117. opt_hidden),
  2118. OPT_WITH_ARG("--gpu-fan",
  2119. set_gpu_fan, NULL, NULL,
  2120. opt_hidden),
  2121. OPT_WITH_ARG("--gpu-map",
  2122. set_gpu_map, NULL, NULL,
  2123. "Map OpenCL to ADL device order manually, paired CSV (e.g. 1:0,2:1 maps OpenCL 1 to ADL 0, 2 to 1)"),
  2124. OPT_WITH_ARG("--gpu-memclock",
  2125. set_gpu_memclock, NULL, NULL,
  2126. opt_hidden),
  2127. OPT_WITH_ARG("--gpu-memdiff",
  2128. set_gpu_memdiff, NULL, NULL,
  2129. opt_hidden),
  2130. OPT_WITH_ARG("--gpu-powertune",
  2131. set_gpu_powertune, NULL, NULL,
  2132. opt_hidden),
  2133. OPT_WITHOUT_ARG("--gpu-reorder",
  2134. opt_set_bool, &opt_reorder,
  2135. "Attempt to reorder GPU devices according to PCI Bus ID"),
  2136. OPT_WITH_ARG("--gpu-vddc",
  2137. set_gpu_vddc, NULL, NULL,
  2138. opt_hidden),
  2139. #endif
  2140. #ifdef USE_SCRYPT
  2141. OPT_WITH_ARG("--lookup-gap",
  2142. set_lookup_gap, NULL, NULL,
  2143. opt_hidden),
  2144. #endif
  2145. OPT_WITH_ARG("--intensity|-I",
  2146. set_intensity, NULL, NULL,
  2147. opt_hidden),
  2148. #endif
  2149. #if defined(USE_OPENCL) || defined(USE_MODMINER) || defined(USE_X6500) || defined(USE_ZTEX)
  2150. OPT_WITH_ARG("--kernel-path",
  2151. opt_set_charp, opt_show_charp, &opt_kernel_path,
  2152. "Specify a path to where bitstream and kernel files are"),
  2153. OPT_WITH_ARG("-K",
  2154. opt_set_charp, opt_show_charp, &opt_kernel_path,
  2155. opt_hidden),
  2156. #endif
  2157. #ifdef USE_OPENCL
  2158. OPT_WITH_ARG("--kernel|-k",
  2159. set_kernel, NULL, NULL,
  2160. opt_hidden),
  2161. #endif
  2162. #ifdef USE_ICARUS
  2163. OPT_WITH_ARG("--icarus-options",
  2164. set_icarus_options, NULL, NULL,
  2165. opt_hidden),
  2166. OPT_WITH_ARG("--icarus-timing",
  2167. set_icarus_timing, NULL, NULL,
  2168. opt_hidden),
  2169. #endif
  2170. #ifdef USE_AVALON
  2171. OPT_WITH_ARG("--avalon-options",
  2172. set_avalon_options, NULL, NULL,
  2173. opt_hidden),
  2174. #endif
  2175. #ifdef USE_KLONDIKE
  2176. OPT_WITH_ARG("--klondike-options",
  2177. set_klondike_options, NULL, NULL,
  2178. "Set klondike options clock:temptarget"),
  2179. #endif
  2180. OPT_WITHOUT_ARG("--load-balance",
  2181. set_loadbalance, &pool_strategy,
  2182. "Change multipool strategy from failover to quota based balance"),
  2183. OPT_WITH_ARG("--log|-l",
  2184. set_int_0_to_9999, opt_show_intval, &opt_log_interval,
  2185. "Interval in seconds between log output"),
  2186. OPT_WITH_ARG("--log-file|-L",
  2187. set_log_file, NULL, NULL,
  2188. "Append log file for output messages"),
  2189. OPT_WITH_ARG("--logfile",
  2190. set_log_file, NULL, NULL,
  2191. opt_hidden),
  2192. OPT_WITHOUT_ARG("--log-microseconds",
  2193. opt_set_bool, &opt_log_microseconds,
  2194. "Include microseconds in log output"),
  2195. #if defined(unix) || defined(__APPLE__)
  2196. OPT_WITH_ARG("--monitor|-m",
  2197. opt_set_charp, NULL, &opt_stderr_cmd,
  2198. "Use custom pipe cmd for output messages"),
  2199. #endif // defined(unix)
  2200. OPT_WITHOUT_ARG("--net-delay",
  2201. opt_set_bool, &opt_delaynet,
  2202. "Impose small delays in networking to avoid overloading slow routers"),
  2203. OPT_WITHOUT_ARG("--no-adl",
  2204. opt_set_bool, &opt_noadl,
  2205. #ifdef HAVE_ADL
  2206. "Disable the ATI display library used for monitoring and setting GPU parameters"
  2207. #else
  2208. opt_hidden
  2209. #endif
  2210. ),
  2211. OPT_WITHOUT_ARG("--no-gbt",
  2212. opt_set_invbool, &want_gbt,
  2213. "Disable getblocktemplate support"),
  2214. OPT_WITHOUT_ARG("--no-getwork",
  2215. opt_set_invbool, &want_getwork,
  2216. "Disable getwork support"),
  2217. OPT_WITHOUT_ARG("--no-hotplug",
  2218. #ifdef HAVE_BFG_HOTPLUG
  2219. opt_set_invbool, &opt_hotplug,
  2220. "Disable hotplug detection"
  2221. #else
  2222. set_null, &opt_hotplug,
  2223. opt_hidden
  2224. #endif
  2225. ),
  2226. OPT_WITHOUT_ARG("--no-local-bitcoin",
  2227. #if BLKMAKER_VERSION > 1
  2228. opt_set_invbool, &opt_load_bitcoin_conf,
  2229. "Disable adding pools for local bitcoin RPC servers"),
  2230. #else
  2231. set_null, NULL, opt_hidden),
  2232. #endif
  2233. OPT_WITHOUT_ARG("--no-longpoll",
  2234. opt_set_invbool, &want_longpoll,
  2235. "Disable X-Long-Polling support"),
  2236. OPT_WITHOUT_ARG("--no-pool-disable",
  2237. opt_set_invbool, &opt_disable_pool,
  2238. opt_hidden),
  2239. OPT_WITHOUT_ARG("--no-client-reconnect",
  2240. opt_set_invbool, &opt_disable_client_reconnect,
  2241. opt_hidden),
  2242. OPT_WITHOUT_ARG("--no-pool-redirect",
  2243. disable_pool_redirect, NULL,
  2244. "Ignore pool requests to redirect to another server"),
  2245. OPT_WITHOUT_ARG("--no-restart",
  2246. opt_set_invbool, &opt_restart,
  2247. "Do not attempt to restart devices that hang"
  2248. ),
  2249. OPT_WITHOUT_ARG("--no-show-processors",
  2250. opt_set_invbool, &opt_show_procs,
  2251. opt_hidden),
  2252. OPT_WITHOUT_ARG("--no-show-procs",
  2253. opt_set_invbool, &opt_show_procs,
  2254. opt_hidden),
  2255. OPT_WITHOUT_ARG("--no-stratum",
  2256. opt_set_invbool, &want_stratum,
  2257. "Disable Stratum detection"),
  2258. OPT_WITHOUT_ARG("--no-submit-stale",
  2259. opt_set_invbool, &opt_submit_stale,
  2260. "Don't submit shares if they are detected as stale"),
  2261. #ifdef USE_OPENCL
  2262. OPT_WITHOUT_ARG("--no-opencl-binaries",
  2263. set_no_opencl_binaries, NULL,
  2264. opt_hidden),
  2265. #endif
  2266. OPT_WITHOUT_ARG("--no-unicode",
  2267. #ifdef USE_UNICODE
  2268. opt_set_invbool, &use_unicode,
  2269. "Don't use Unicode characters in TUI"
  2270. #else
  2271. set_null, &use_unicode,
  2272. opt_hidden
  2273. #endif
  2274. ),
  2275. OPT_WITH_ARG("--noncelog",
  2276. set_noncelog, NULL, NULL,
  2277. "Create log of all nonces found"),
  2278. OPT_WITH_ARG("--pass|-p",
  2279. set_pass, NULL, NULL,
  2280. "Password for bitcoin JSON-RPC server"),
  2281. OPT_WITHOUT_ARG("--per-device-stats",
  2282. opt_set_bool, &want_per_device_stats,
  2283. "Force verbose mode and output per-device statistics"),
  2284. OPT_WITH_ARG("--userpass|-O",
  2285. set_userpass, NULL, NULL,
  2286. "Username:Password pair for bitcoin JSON-RPC server"),
  2287. OPT_WITH_ARG("--pool-goal",
  2288. set_pool_goal, NULL, NULL,
  2289. "Named goal for the previous-defined pool"),
  2290. OPT_WITH_ARG("--pool-priority",
  2291. set_pool_priority, NULL, NULL,
  2292. "Priority for just the previous-defined pool"),
  2293. OPT_WITH_ARG("--pool-proxy|-x",
  2294. set_pool_proxy, NULL, NULL,
  2295. "Proxy URI to use for connecting to just the previous-defined pool"),
  2296. OPT_WITH_ARG("--force-rollntime", // NOTE: must be after --pass for config file ordering
  2297. set_pool_force_rollntime, NULL, NULL,
  2298. opt_hidden),
  2299. OPT_WITHOUT_ARG("--protocol-dump|-P",
  2300. opt_set_bool, &opt_protocol,
  2301. "Verbose dump of protocol-level activities"),
  2302. OPT_WITH_ARG("--queue|-Q",
  2303. set_int_0_to_9999, opt_show_intval, &opt_queue,
  2304. "Minimum number of work items to have queued (0+)"),
  2305. OPT_WITHOUT_ARG("--quiet|-q",
  2306. opt_set_bool, &opt_quiet,
  2307. "Disable logging output, display status and errors"),
  2308. OPT_WITHOUT_ARG("--quiet-work-updates|--quiet-work-update",
  2309. opt_set_bool, &opt_quiet_work_updates,
  2310. opt_hidden),
  2311. OPT_WITH_ARG("--quit-summary",
  2312. set_quit_summary, NULL, NULL,
  2313. "Summary printed when you quit: none/devs/procs/detailed"),
  2314. OPT_WITH_ARG("--quota|-U",
  2315. set_quota, NULL, NULL,
  2316. "quota;URL combination for server with load-balance strategy quotas"),
  2317. OPT_WITHOUT_ARG("--real-quiet",
  2318. opt_set_bool, &opt_realquiet,
  2319. "Disable all output"),
  2320. OPT_WITH_ARG("--request-diff",
  2321. set_request_diff, opt_show_floatval, &request_pdiff,
  2322. "Request a specific difficulty from pools"),
  2323. OPT_WITH_ARG("--retries",
  2324. opt_set_intval, opt_show_intval, &opt_retries,
  2325. "Number of times to retry failed submissions before giving up (-1 means never)"),
  2326. OPT_WITH_ARG("--retry-pause",
  2327. set_null, NULL, NULL,
  2328. opt_hidden),
  2329. OPT_WITH_ARG("--rotate",
  2330. set_rotate, opt_show_intval, &opt_rotate_period,
  2331. "Change multipool strategy from failover to regularly rotate at N minutes"),
  2332. OPT_WITHOUT_ARG("--round-robin",
  2333. set_rr, &pool_strategy,
  2334. "Change multipool strategy from failover to round robin on failure"),
  2335. OPT_WITH_ARG("--scan|-S",
  2336. add_serial, NULL, NULL,
  2337. "Configure how to scan for mining devices"),
  2338. OPT_WITH_ARG("--scan-device|--scan-serial|--devscan",
  2339. add_serial, NULL, NULL,
  2340. opt_hidden),
  2341. OPT_WITH_ARG("--scan-time",
  2342. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  2343. "Upper bound on time spent scanning current work, in seconds"),
  2344. OPT_WITH_ARG("-s",
  2345. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  2346. opt_hidden),
  2347. OPT_WITH_ARG("--scantime",
  2348. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  2349. opt_hidden),
  2350. OPT_WITH_ARG("--sched-start",
  2351. set_schedtime, NULL, &schedstart,
  2352. "Set a time of day in HH:MM to start mining (a once off without a stop time)"),
  2353. OPT_WITH_ARG("--sched-stop",
  2354. set_schedtime, NULL, &schedstop,
  2355. "Set a time of day in HH:MM to stop mining (will quit without a start time)"),
  2356. #ifdef USE_SCRYPT
  2357. OPT_WITHOUT_ARG("--scrypt",
  2358. set_malgo_scrypt, NULL,
  2359. "Use the scrypt algorithm for mining (non-bitcoin)"),
  2360. #endif
  2361. OPT_WITH_ARG("--set-device|--set",
  2362. opt_string_elist_add, NULL, &opt_set_device_list,
  2363. "Set default parameters on devices; eg, NFY:osc6_bits=50"),
  2364. #if defined(USE_SCRYPT) && defined(USE_OPENCL)
  2365. OPT_WITH_ARG("--shaders",
  2366. set_shaders, NULL, NULL,
  2367. opt_hidden),
  2368. #endif
  2369. #ifdef HAVE_PWD_H
  2370. OPT_WITH_ARG("--setuid",
  2371. opt_set_charp, NULL, &opt_setuid,
  2372. "Username of an unprivileged user to run as"),
  2373. #endif
  2374. OPT_WITH_ARG("--sharelog",
  2375. set_sharelog, NULL, NULL,
  2376. "Append share log to file"),
  2377. OPT_WITH_ARG("--shares",
  2378. opt_set_floatval, NULL, &opt_shares,
  2379. "Quit after mining 2^32 * N hashes worth of shares (default: unlimited)"),
  2380. OPT_WITHOUT_ARG("--show-processors",
  2381. opt_set_bool, &opt_show_procs,
  2382. "Show per processor statistics in summary"),
  2383. OPT_WITHOUT_ARG("--show-procs",
  2384. opt_set_bool, &opt_show_procs,
  2385. opt_hidden),
  2386. OPT_WITH_ARG("--skip-security-checks",
  2387. set_int_0_to_9999, NULL, &opt_skip_checks,
  2388. "Skip security checks sometimes to save bandwidth; only check 1/<arg>th of the time (default: never skip)"),
  2389. OPT_WITH_ARG("--socks-proxy",
  2390. opt_set_charp, NULL, &opt_socks_proxy,
  2391. "Set socks proxy (host:port)"),
  2392. #ifdef USE_LIBEVENT
  2393. OPT_WITH_ARG("--stratum-port",
  2394. opt_set_intval, opt_show_intval, &stratumsrv_port,
  2395. "Port number to listen on for stratum miners (-1 means disabled)"),
  2396. #endif
  2397. OPT_WITHOUT_ARG("--submit-stale",
  2398. opt_set_bool, &opt_submit_stale,
  2399. opt_hidden),
  2400. OPT_WITH_ARG("--submit-threads",
  2401. opt_set_intval, opt_show_intval, &opt_submit_threads,
  2402. "Minimum number of concurrent share submissions (default: 64)"),
  2403. #ifdef HAVE_SYSLOG_H
  2404. OPT_WITHOUT_ARG("--syslog",
  2405. opt_set_bool, &use_syslog,
  2406. "Use system log for output messages (default: standard error)"),
  2407. #endif
  2408. OPT_WITH_ARG("--temp-cutoff",
  2409. set_temp_cutoff, NULL, &opt_cutofftemp,
  2410. opt_hidden),
  2411. OPT_WITH_ARG("--temp-hysteresis",
  2412. set_int_1_to_10, opt_show_intval, &opt_hysteresis,
  2413. "Set how much the temperature can fluctuate outside limits when automanaging speeds"),
  2414. #ifdef HAVE_ADL
  2415. OPT_WITH_ARG("--temp-overheat",
  2416. set_temp_overheat, opt_show_intval, &opt_overheattemp,
  2417. opt_hidden),
  2418. #endif
  2419. OPT_WITH_ARG("--temp-target",
  2420. set_temp_target, NULL, NULL,
  2421. opt_hidden),
  2422. OPT_WITHOUT_ARG("--text-only|-T",
  2423. opt_set_invbool, &use_curses,
  2424. #ifdef HAVE_CURSES
  2425. "Disable ncurses formatted screen output"
  2426. #else
  2427. opt_hidden
  2428. #endif
  2429. ),
  2430. #if defined(USE_SCRYPT) && defined(USE_OPENCL)
  2431. OPT_WITH_ARG("--thread-concurrency",
  2432. set_thread_concurrency, NULL, NULL,
  2433. opt_hidden),
  2434. #endif
  2435. #ifdef USE_UNICODE
  2436. OPT_WITHOUT_ARG("--unicode",
  2437. opt_set_bool, &use_unicode,
  2438. "Use Unicode characters in TUI"),
  2439. #endif
  2440. OPT_WITH_ARG("--url|-o",
  2441. set_url, NULL, NULL,
  2442. "URL for bitcoin JSON-RPC server"),
  2443. OPT_WITH_ARG("--user|-u",
  2444. set_user, NULL, NULL,
  2445. "Username for bitcoin JSON-RPC server"),
  2446. #ifdef USE_OPENCL
  2447. OPT_WITH_ARG("--vectors|-v",
  2448. set_vector, NULL, NULL,
  2449. opt_hidden),
  2450. #endif
  2451. OPT_WITHOUT_ARG("--verbose",
  2452. opt_set_bool, &opt_log_output,
  2453. "Log verbose output to stderr as well as status output"),
  2454. OPT_WITHOUT_ARG("--verbose-work-updates|--verbose-work-update",
  2455. opt_set_invbool, &opt_quiet_work_updates,
  2456. opt_hidden),
  2457. OPT_WITHOUT_ARG("--weighed-stats",
  2458. opt_set_bool, &opt_weighed_stats,
  2459. "Display statistics weighed to difficulty 1"),
  2460. #ifdef USE_OPENCL
  2461. OPT_WITH_ARG("--worksize|-w",
  2462. set_worksize, NULL, NULL,
  2463. opt_hidden),
  2464. #endif
  2465. OPT_WITHOUT_ARG("--unittest",
  2466. opt_set_bool, &opt_unittest, opt_hidden),
  2467. OPT_WITH_ARG("--coinbase-check-addr",
  2468. set_cbcaddr, NULL, NULL,
  2469. "A list of address to check against in coinbase payout list received from the previous-defined pool, separated by ','"),
  2470. OPT_WITH_ARG("--cbcheck-addr|--cbc-addr|--cbcaddr",
  2471. set_cbcaddr, NULL, NULL,
  2472. opt_hidden),
  2473. OPT_WITH_ARG("--coinbase-check-total",
  2474. set_cbctotal, NULL, NULL,
  2475. "The least total payout amount expected in coinbase received from the previous-defined pool"),
  2476. OPT_WITH_ARG("--cbcheck-total|--cbc-total|--cbctotal",
  2477. set_cbctotal, NULL, NULL,
  2478. opt_hidden),
  2479. OPT_WITH_ARG("--coinbase-check-percent",
  2480. set_cbcperc, NULL, NULL,
  2481. "The least benefit percentage expected for the sum of addr(s) listed in --cbaddr argument for previous-defined pool"),
  2482. OPT_WITH_ARG("--cbcheck-percent|--cbc-percent|--cbcpercent|--cbcperc",
  2483. set_cbcperc, NULL, NULL,
  2484. opt_hidden),
  2485. OPT_WITHOUT_ARG("--worktime",
  2486. opt_set_bool, &opt_worktime,
  2487. "Display extra work time debug information"),
  2488. OPT_WITH_ARG("--pools",
  2489. opt_set_bool, NULL, NULL, opt_hidden),
  2490. OPT_ENDTABLE
  2491. };
  2492. static char *load_config(const char *arg, void __maybe_unused *unused);
  2493. static char *parse_config(json_t *config, bool fileconf, int * const fileconf_load_p)
  2494. {
  2495. static char err_buf[200];
  2496. struct opt_table *opt;
  2497. json_t *val;
  2498. if (fileconf && !*fileconf_load_p)
  2499. *fileconf_load_p = 1;
  2500. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  2501. char *p, *name, *sp;
  2502. /* We don't handle subtables. */
  2503. assert(!(opt->type & OPT_SUBTABLE));
  2504. if (!opt->names)
  2505. continue;
  2506. /* Pull apart the option name(s). */
  2507. name = strdup(opt->names);
  2508. for (p = strtok_r(name, "|", &sp); p; p = strtok_r(NULL, "|", &sp)) {
  2509. char *err = "Invalid value";
  2510. /* Ignore short options. */
  2511. if (p[1] != '-')
  2512. continue;
  2513. val = json_object_get(config, p+2);
  2514. if (!val)
  2515. continue;
  2516. if (opt->type & OPT_HASARG) {
  2517. if (json_is_string(val)) {
  2518. err = opt->cb_arg(json_string_value(val),
  2519. opt->u.arg);
  2520. } else if (json_is_number(val)) {
  2521. char buf[256], *p, *q;
  2522. snprintf(buf, 256, "%f", json_number_value(val));
  2523. if ( (p = strchr(buf, '.')) ) {
  2524. // Trim /\.0*$/ to work properly with integer-only arguments
  2525. q = p;
  2526. while (*(++q) == '0') {}
  2527. if (*q == '\0')
  2528. *p = '\0';
  2529. }
  2530. err = opt->cb_arg(buf, opt->u.arg);
  2531. } else if (json_is_array(val)) {
  2532. int n, size = json_array_size(val);
  2533. err = NULL;
  2534. for (n = 0; n < size && !err; n++) {
  2535. if (json_is_string(json_array_get(val, n)))
  2536. err = opt->cb_arg(json_string_value(json_array_get(val, n)), opt->u.arg);
  2537. else if (json_is_object(json_array_get(val, n)))
  2538. err = parse_config(json_array_get(val, n), false, fileconf_load_p);
  2539. }
  2540. }
  2541. } else if (opt->type & OPT_NOARG) {
  2542. if (json_is_true(val))
  2543. err = opt->cb(opt->u.arg);
  2544. else if (json_is_boolean(val)) {
  2545. if (opt->cb == (void*)opt_set_bool)
  2546. err = opt_set_invbool(opt->u.arg);
  2547. else if (opt->cb == (void*)opt_set_invbool)
  2548. err = opt_set_bool(opt->u.arg);
  2549. }
  2550. }
  2551. if (err) {
  2552. /* Allow invalid values to be in configuration
  2553. * file, just skipping over them provided the
  2554. * JSON is still valid after that. */
  2555. if (fileconf) {
  2556. applog(LOG_ERR, "Invalid config option %s: %s", p, err);
  2557. *fileconf_load_p = -1;
  2558. } else {
  2559. snprintf(err_buf, sizeof(err_buf), "Parsing JSON option %s: %s",
  2560. p, err);
  2561. free(name);
  2562. return err_buf;
  2563. }
  2564. }
  2565. }
  2566. free(name);
  2567. }
  2568. val = json_object_get(config, JSON_INCLUDE_CONF);
  2569. if (val && json_is_string(val))
  2570. return load_config(json_string_value(val), NULL);
  2571. return NULL;
  2572. }
  2573. struct bfg_loaded_configfile *bfg_loaded_configfiles;
  2574. static char *load_config(const char *arg, void __maybe_unused *unused)
  2575. {
  2576. json_error_t err;
  2577. json_t *config;
  2578. char *json_error;
  2579. size_t siz;
  2580. struct bfg_loaded_configfile *cfginfo;
  2581. cfginfo = malloc(sizeof(*cfginfo));
  2582. *cfginfo = (struct bfg_loaded_configfile){
  2583. .filename = strdup(arg),
  2584. };
  2585. LL_APPEND(bfg_loaded_configfiles, cfginfo);
  2586. if (++include_count > JSON_MAX_DEPTH)
  2587. return JSON_MAX_DEPTH_ERR;
  2588. #if JANSSON_MAJOR_VERSION > 1
  2589. config = json_load_file(arg, 0, &err);
  2590. #else
  2591. config = json_load_file(arg, &err);
  2592. #endif
  2593. if (!json_is_object(config)) {
  2594. siz = JSON_LOAD_ERROR_LEN + strlen(arg) + strlen(err.text);
  2595. json_error = malloc(siz);
  2596. if (!json_error)
  2597. quit(1, "Malloc failure in json error");
  2598. snprintf(json_error, siz, JSON_LOAD_ERROR, arg, err.text);
  2599. return json_error;
  2600. }
  2601. config_loaded = true;
  2602. /* Parse the config now, so we can override it. That can keep pointers
  2603. * so don't free config object. */
  2604. return parse_config(config, true, &cfginfo->fileconf_load);
  2605. }
  2606. static
  2607. bool _load_default_configs(const char * const filepath, void * __maybe_unused userp)
  2608. {
  2609. bool * const found_defcfg_p = userp;
  2610. *found_defcfg_p = true;
  2611. load_config(filepath, NULL);
  2612. // Regardless of status of loading the config file, we should continue loading other defaults
  2613. return false;
  2614. }
  2615. static void load_default_config(void)
  2616. {
  2617. bool found_defcfg = false;
  2618. appdata_file_call("BFGMiner", def_conf, _load_default_configs, &found_defcfg);
  2619. if (!found_defcfg)
  2620. {
  2621. // No BFGMiner config, try Cgminer's...
  2622. appdata_file_call("cgminer", "cgminer.conf", _load_default_configs, &found_defcfg);
  2623. }
  2624. }
  2625. extern const char *opt_argv0;
  2626. static
  2627. void bfg_versioninfo(void)
  2628. {
  2629. puts(packagename);
  2630. printf(" Lowlevel:%s\n", BFG_LOWLLIST);
  2631. printf(" Drivers:%s\n", BFG_DRIVERLIST);
  2632. printf(" Algorithms:%s\n", BFG_ALGOLIST);
  2633. printf(" Options:%s\n", BFG_OPTLIST);
  2634. }
  2635. static char *opt_verusage_and_exit(const char *extra)
  2636. {
  2637. bfg_versioninfo();
  2638. printf("%s", opt_usage(opt_argv0, extra));
  2639. fflush(stdout);
  2640. exit(0);
  2641. }
  2642. static
  2643. const char *my_opt_version_and_exit(void)
  2644. {
  2645. bfg_versioninfo();
  2646. fflush(stdout);
  2647. exit(0);
  2648. }
  2649. /* These options are parsed before anything else */
  2650. static struct opt_table opt_early_table[] = {
  2651. // Default config is loaded in command line order, like a regular config
  2652. OPT_EARLY_WITH_ARG("--config|-c|--default-config",
  2653. set_bool_ignore_arg, NULL, &config_loaded,
  2654. opt_hidden),
  2655. OPT_EARLY_WITHOUT_ARG("--no-config|--no-default-config",
  2656. opt_set_bool, &config_loaded,
  2657. "Inhibit loading default config file"),
  2658. OPT_ENDTABLE
  2659. };
  2660. /* These options are available from commandline only */
  2661. static struct opt_table opt_cmdline_table[] = {
  2662. OPT_WITH_ARG("--config|-c",
  2663. load_config, NULL, NULL,
  2664. "Load a JSON-format configuration file\n"
  2665. "See example.conf for an example configuration."),
  2666. OPT_EARLY_WITHOUT_ARG("--no-config",
  2667. opt_set_bool, &config_loaded,
  2668. opt_hidden),
  2669. OPT_EARLY_WITHOUT_ARG("--no-default-config",
  2670. opt_set_bool, &config_loaded,
  2671. "Inhibit loading default config file"),
  2672. OPT_WITHOUT_ARG("--default-config",
  2673. load_default_config, NULL,
  2674. "Always load the default config file"),
  2675. OPT_WITHOUT_ARG("--help|-h",
  2676. opt_verusage_and_exit, NULL,
  2677. "Print this message"),
  2678. #ifdef USE_OPENCL
  2679. OPT_WITHOUT_ARG("--ndevs|-n",
  2680. print_ndevs_and_exit, &nDevs,
  2681. opt_hidden),
  2682. #endif
  2683. OPT_WITHOUT_ARG("--version|-V",
  2684. my_opt_version_and_exit, NULL,
  2685. "Display version and exit"),
  2686. OPT_ENDTABLE
  2687. };
  2688. static bool jobj_binary(const json_t *obj, const char *key,
  2689. void *buf, size_t buflen, bool required)
  2690. {
  2691. const char *hexstr;
  2692. json_t *tmp;
  2693. tmp = json_object_get(obj, key);
  2694. if (unlikely(!tmp)) {
  2695. if (unlikely(required))
  2696. applog(LOG_ERR, "JSON key '%s' not found", key);
  2697. return false;
  2698. }
  2699. hexstr = json_string_value(tmp);
  2700. if (unlikely(!hexstr)) {
  2701. applog(LOG_ERR, "JSON key '%s' is not a string", key);
  2702. return false;
  2703. }
  2704. if (!hex2bin(buf, hexstr, buflen))
  2705. return false;
  2706. return true;
  2707. }
  2708. static void calc_midstate(struct work *work)
  2709. {
  2710. union {
  2711. unsigned char c[64];
  2712. uint32_t i[16];
  2713. } data;
  2714. swap32yes(&data.i[0], work->data, 16);
  2715. sha256_ctx ctx;
  2716. sha256_init(&ctx);
  2717. sha256_update(&ctx, data.c, 64);
  2718. memcpy(work->midstate, ctx.h, sizeof(work->midstate));
  2719. swap32tole(work->midstate, work->midstate, 8);
  2720. }
  2721. static
  2722. struct bfg_tmpl_ref *tmpl_makeref(blktemplate_t * const tmpl)
  2723. {
  2724. struct bfg_tmpl_ref * const tr = malloc(sizeof(*tr));
  2725. *tr = (struct bfg_tmpl_ref){
  2726. .tmpl = tmpl,
  2727. .refcount = 1,
  2728. };
  2729. mutex_init(&tr->mutex);
  2730. return tr;
  2731. }
  2732. static
  2733. void tmpl_incref(struct bfg_tmpl_ref * const tr)
  2734. {
  2735. mutex_lock(&tr->mutex);
  2736. ++tr->refcount;
  2737. mutex_unlock(&tr->mutex);
  2738. }
  2739. void tmpl_decref(struct bfg_tmpl_ref * const tr)
  2740. {
  2741. mutex_lock(&tr->mutex);
  2742. bool free_tmpl = !--tr->refcount;
  2743. mutex_unlock(&tr->mutex);
  2744. if (free_tmpl)
  2745. {
  2746. blktmpl_free(tr->tmpl);
  2747. mutex_destroy(&tr->mutex);
  2748. free(tr);
  2749. }
  2750. }
  2751. static struct work *make_work(void)
  2752. {
  2753. struct work *work = calloc(1, sizeof(struct work));
  2754. if (unlikely(!work))
  2755. quit(1, "Failed to calloc work in make_work");
  2756. cg_wlock(&control_lock);
  2757. work->id = total_work++;
  2758. cg_wunlock(&control_lock);
  2759. return work;
  2760. }
  2761. /* This is the central place all work that is about to be retired should be
  2762. * cleaned to remove any dynamically allocated arrays within the struct */
  2763. void clean_work(struct work *work)
  2764. {
  2765. free(work->job_id);
  2766. bytes_free(&work->nonce2);
  2767. free(work->nonce1);
  2768. if (work->device_data_free_func)
  2769. work->device_data_free_func(work);
  2770. if (work->tr)
  2771. tmpl_decref(work->tr);
  2772. memset(work, 0, sizeof(struct work));
  2773. }
  2774. /* All dynamically allocated work structs should be freed here to not leak any
  2775. * ram from arrays allocated within the work struct */
  2776. void free_work(struct work *work)
  2777. {
  2778. clean_work(work);
  2779. free(work);
  2780. }
  2781. 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";
  2782. #define workpadding_bin bfg_workpadding_bin
  2783. static const size_t block_info_str_sz = 3 /* ... */ + 16 /* block hash segment */ + 1;
  2784. static
  2785. void block_info_str(char * const out, const struct block_info * const blkinfo)
  2786. {
  2787. unsigned char hash_swap[32];
  2788. swap256(hash_swap, blkinfo->prevblkhash);
  2789. swap32tole(hash_swap, hash_swap, 32 / 4);
  2790. memset(out, '.', 3);
  2791. // FIXME: The block number will overflow this sometime around AD 2025-2027
  2792. if (blkinfo->height > 0 && blkinfo->height < 1000000)
  2793. {
  2794. bin2hex(&out[3], &hash_swap[0x1c], 4);
  2795. snprintf(&out[11], block_info_str_sz-11, " #%6u", blkinfo->height);
  2796. }
  2797. else
  2798. bin2hex(&out[3], &hash_swap[0x18], 8);
  2799. }
  2800. #ifdef HAVE_CURSES
  2801. static void update_block_display(void);
  2802. #endif
  2803. // Must only be called with ch_lock held!
  2804. static
  2805. void __update_block_title(struct mining_goal_info * const goal)
  2806. {
  2807. struct blockchain_info * const blkchain = goal->blkchain;
  2808. if (!goal->current_goal_detail)
  2809. goal->current_goal_detail = malloc(block_info_str_sz);
  2810. block_info_str(goal->current_goal_detail, blkchain->currentblk);
  2811. #ifdef HAVE_CURSES
  2812. update_block_display();
  2813. #endif
  2814. }
  2815. static struct block_info *block_exists(const struct blockchain_info *, const void *);
  2816. static
  2817. void have_block_height(struct mining_goal_info * const goal, const void * const prevblkhash, uint32_t blkheight)
  2818. {
  2819. struct blockchain_info * const blkchain = goal->blkchain;
  2820. struct block_info * const blkinfo = block_exists(blkchain, prevblkhash);
  2821. if ((!blkinfo) || blkinfo->height)
  2822. return;
  2823. uint32_t block_id = ((uint32_t*)prevblkhash)[0];
  2824. applog(LOG_DEBUG, "Learned that block id %08" PRIx32 " is height %" PRIu32, (uint32_t)be32toh(block_id), blkheight);
  2825. cg_wlock(&ch_lock);
  2826. blkinfo->height = blkheight;
  2827. if (blkinfo == blkchain->currentblk)
  2828. {
  2829. blkchain->currentblk_subsidy = 5000000000LL >> (blkheight / 210000);
  2830. __update_block_title(goal);
  2831. }
  2832. cg_wunlock(&ch_lock);
  2833. }
  2834. static
  2835. void pool_set_opaque(struct pool *pool, bool opaque)
  2836. {
  2837. if (pool->swork.opaque == opaque)
  2838. return;
  2839. pool->swork.opaque = opaque;
  2840. if (opaque)
  2841. applog(LOG_WARNING, "Pool %u is hiding block contents from us",
  2842. pool->pool_no);
  2843. else
  2844. applog(LOG_NOTICE, "Pool %u now providing block contents to us",
  2845. pool->pool_no);
  2846. }
  2847. bool pool_may_redirect_to(struct pool * const pool, const char * const uri)
  2848. {
  2849. if (uri_get_param_bool(pool->rpc_url, "redirect", false))
  2850. return true;
  2851. return match_domains(pool->rpc_url, strlen(pool->rpc_url), uri, strlen(uri));
  2852. }
  2853. void pool_check_coinbase(struct pool * const pool, const uint8_t * const cbtxn, const size_t cbtxnsz)
  2854. {
  2855. if (uri_get_param_bool(pool->rpc_url, "skipcbcheck", false))
  2856. {}
  2857. else
  2858. if (!check_coinbase(cbtxn, cbtxnsz, &pool->cb_param))
  2859. {
  2860. if (pool->enabled == POOL_ENABLED)
  2861. {
  2862. applog(LOG_ERR, "Pool %d misbehaving (%s), disabling!", pool->pool_no, "coinbase check");
  2863. disable_pool(pool, POOL_MISBEHAVING);
  2864. }
  2865. }
  2866. else
  2867. if (pool->enabled == POOL_MISBEHAVING)
  2868. {
  2869. applog(LOG_NOTICE, "Pool %d no longer misbehaving, re-enabling!", pool->pool_no);
  2870. enable_pool(pool);
  2871. }
  2872. }
  2873. 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)
  2874. {
  2875. const int offsets = max(ntime_roll, 60);
  2876. *nrl = (struct ntime_roll_limits){
  2877. .min = ntime_base,
  2878. .max = ntime_base + ntime_roll,
  2879. .tv_ref = *tvp_ref,
  2880. .minoff = -offsets,
  2881. .maxoff = offsets,
  2882. };
  2883. }
  2884. void work_set_simple_ntime_roll_limit(struct work * const work, const int ntime_roll, const struct timeval * const tvp_ref)
  2885. {
  2886. set_simple_ntime_roll_limit(&work->ntime_roll_limits, upk_u32be(work->data, 0x44), ntime_roll, tvp_ref);
  2887. }
  2888. int work_ntime_range(struct work * const work, const struct timeval * const tvp_earliest, const struct timeval * const tvp_latest, const int desired_roll)
  2889. {
  2890. const struct ntime_roll_limits * const nrl = &work->ntime_roll_limits;
  2891. const uint32_t ref_ntime = work_get_ntime(work);
  2892. const int earliest_elapsed = timer_elapsed(&nrl->tv_ref, tvp_earliest);
  2893. const int latest_elapsed = timer_elapsed(&nrl->tv_ref, tvp_latest);
  2894. // minimum ntime is the latest possible result (add a second to spare) adjusted for minimum offset (or fixed minimum ntime)
  2895. uint32_t min_ntime = max(nrl->min, ref_ntime + latest_elapsed+1 + nrl->minoff);
  2896. // maximum ntime is the earliest possible result adjusted for maximum offset (or fixed maximum ntime)
  2897. uint32_t max_ntime = min(nrl->max, ref_ntime + earliest_elapsed + nrl->maxoff);
  2898. if (max_ntime < min_ntime)
  2899. return -1;
  2900. if (max_ntime - min_ntime > desired_roll)
  2901. {
  2902. // Adjust min_ntime upward for accuracy, when possible
  2903. const int mid_elapsed = ((latest_elapsed - earliest_elapsed) / 2) + earliest_elapsed;
  2904. uint32_t ideal_ntime = ref_ntime + mid_elapsed;
  2905. if (ideal_ntime > min_ntime)
  2906. min_ntime = min(ideal_ntime, max_ntime - desired_roll);
  2907. }
  2908. work_set_ntime(work, min_ntime);
  2909. return max_ntime - min_ntime;
  2910. }
  2911. #if BLKMAKER_VERSION > 1
  2912. static
  2913. bool goal_has_at_least_one_getcbaddr(const struct mining_goal_info * const goal)
  2914. {
  2915. for (int i = 0; i < total_pools; ++i)
  2916. {
  2917. struct pool * const pool = pools[i];
  2918. if (uri_get_param_bool(pool->rpc_url, "getcbaddr", false))
  2919. return true;
  2920. }
  2921. return false;
  2922. }
  2923. static
  2924. void refresh_bitcoind_address(struct mining_goal_info * const goal, const bool fresh)
  2925. {
  2926. struct blockchain_info * const blkchain = goal->blkchain;
  2927. if (!goal_has_at_least_one_getcbaddr(goal))
  2928. return;
  2929. char getcbaddr_req[60];
  2930. CURL *curl = NULL;
  2931. json_t *json, *j2;
  2932. const char *s, *s2;
  2933. bytes_t newscript = BYTES_INIT;
  2934. snprintf(getcbaddr_req, sizeof(getcbaddr_req), "{\"method\":\"get%saddress\",\"id\":0,\"params\":[\"BFGMiner\"]}", fresh ? "new" : "account");
  2935. for (int i = 0; i < total_pools; ++i)
  2936. {
  2937. struct pool * const pool = pools[i];
  2938. if (!uri_get_param_bool(pool->rpc_url, "getcbaddr", false))
  2939. continue;
  2940. if (pool->goal != goal)
  2941. continue;
  2942. applog(LOG_DEBUG, "Refreshing coinbase address from pool %d", pool->pool_no);
  2943. if (!curl)
  2944. {
  2945. curl = curl_easy_init();
  2946. if (unlikely(!curl))
  2947. {
  2948. applogfail(LOG_ERR, "curl_easy_init");
  2949. break;
  2950. }
  2951. }
  2952. json = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, getcbaddr_req, false, false, NULL, pool, true);
  2953. if (unlikely((!json) || !json_is_null( (j2 = json_object_get(json, "error")) )))
  2954. {
  2955. const char *estrc;
  2956. char *estr = NULL;
  2957. if (!(json && j2))
  2958. estrc = NULL;
  2959. else
  2960. {
  2961. estrc = json_string_value(j2);
  2962. if (!estrc)
  2963. estrc = estr = json_dumps_ANY(j2, JSON_ENSURE_ASCII | JSON_SORT_KEYS);
  2964. }
  2965. applog(LOG_WARNING, "Error %cetting coinbase address from pool %d: %s", 'g', pool->pool_no, estrc);
  2966. free(estr);
  2967. continue;
  2968. }
  2969. s = bfg_json_obj_string(json, "result", NULL);
  2970. if (unlikely(!s))
  2971. {
  2972. applog(LOG_WARNING, "Error %cetting coinbase address from pool %d: %s", 'g', pool->pool_no, "(return value was not a String)");
  2973. continue;
  2974. }
  2975. s2 = set_b58addr(s, &newscript);
  2976. if (unlikely(s2))
  2977. {
  2978. applog(LOG_WARNING, "Error %cetting coinbase address from pool %d: %s", 's', pool->pool_no, s2);
  2979. continue;
  2980. }
  2981. if (goal->generation_script)
  2982. {
  2983. if (bytes_eq(&newscript, goal->generation_script))
  2984. {
  2985. applog(LOG_DEBUG, "Pool %d returned coinbase address already in use (%s)", pool->pool_no, s);
  2986. break;
  2987. }
  2988. }
  2989. else
  2990. {
  2991. goal->generation_script = malloc(sizeof(*goal->generation_script));
  2992. bytes_init(goal->generation_script);
  2993. }
  2994. bytes_assimilate(goal->generation_script, &newscript);
  2995. coinbase_script_block_id = blkchain->currentblk->block_id;
  2996. applog(LOG_NOTICE, "Now using coinbase address %s, provided by pool %d", s, pool->pool_no);
  2997. break;
  2998. }
  2999. bytes_free(&newscript);
  3000. if (curl)
  3001. curl_easy_cleanup(curl);
  3002. }
  3003. #endif
  3004. #define GBT_XNONCESZ (sizeof(uint32_t))
  3005. #if BLKMAKER_VERSION > 4
  3006. #define blkmk_append_coinbase_safe(tmpl, append, appendsz) \
  3007. blkmk_append_coinbase_safe2(tmpl, append, appendsz, GBT_XNONCESZ, false)
  3008. #endif
  3009. static bool work_decode(struct pool *pool, struct work *work, json_t *val)
  3010. {
  3011. json_t *res_val = json_object_get(val, "result");
  3012. json_t *tmp_val;
  3013. bool ret = false;
  3014. struct timeval tv_now;
  3015. if (unlikely(detect_algo == 1)) {
  3016. json_t *tmp = json_object_get(res_val, "algorithm");
  3017. const char *v = tmp ? json_string_value(tmp) : "";
  3018. if (strncasecmp(v, "scrypt", 6))
  3019. detect_algo = 2;
  3020. }
  3021. timer_set_now(&tv_now);
  3022. if (work->tr)
  3023. {
  3024. blktemplate_t * const tmpl = work->tr->tmpl;
  3025. const char *err = blktmpl_add_jansson(tmpl, res_val, tv_now.tv_sec);
  3026. if (err) {
  3027. applog(LOG_ERR, "blktmpl error: %s", err);
  3028. return false;
  3029. }
  3030. work->rolltime = blkmk_time_left(tmpl, tv_now.tv_sec);
  3031. #if BLKMAKER_VERSION > 1
  3032. struct mining_goal_info * const goal = pool->goal;
  3033. const uint32_t tmpl_block_id = ((uint32_t*)tmpl->prevblk)[0];
  3034. if ((!tmpl->cbtxn) && coinbase_script_block_id != tmpl_block_id)
  3035. refresh_bitcoind_address(goal, false);
  3036. if (goal->generation_script)
  3037. {
  3038. bool newcb;
  3039. #if BLKMAKER_VERSION > 2
  3040. blkmk_init_generation2(tmpl, bytes_buf(goal->generation_script), bytes_len(goal->generation_script), &newcb);
  3041. #else
  3042. newcb = !tmpl->cbtxn;
  3043. blkmk_init_generation(tmpl, bytes_buf(goal->generation_script), bytes_len(goal->generation_script));
  3044. #endif
  3045. if (newcb)
  3046. {
  3047. ssize_t ae = blkmk_append_coinbase_safe(tmpl, &template_nonce, sizeof(template_nonce));
  3048. if (ae < (ssize_t)sizeof(template_nonce))
  3049. 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);
  3050. ++template_nonce;
  3051. }
  3052. }
  3053. #endif
  3054. #if BLKMAKER_VERSION > 0
  3055. {
  3056. ssize_t ae = blkmk_append_coinbase_safe(tmpl, opt_coinbase_sig, 101);
  3057. static bool appenderr = false;
  3058. if (ae <= 0) {
  3059. if (opt_coinbase_sig) {
  3060. applog((appenderr ? LOG_DEBUG : LOG_WARNING), "Cannot append coinbase signature at all on pool %u (%"PRId64")", pool->pool_no, (int64_t)ae);
  3061. appenderr = true;
  3062. }
  3063. } else if (ae >= 3 || opt_coinbase_sig) {
  3064. const char *cbappend = opt_coinbase_sig;
  3065. const char * const full = bfgminer_name_space_ver;
  3066. char *need_free = NULL;
  3067. if (!cbappend) {
  3068. if ((size_t)ae >= sizeof(full) - 1)
  3069. cbappend = full;
  3070. else if ((size_t)ae >= sizeof(PACKAGE) - 1)
  3071. {
  3072. const char *pos = strchr(full, '-');
  3073. size_t sz = (pos - full);
  3074. if (pos && ae > sz)
  3075. {
  3076. cbappend = need_free = malloc(sz + 1);
  3077. memcpy(need_free, full, sz);
  3078. need_free[sz] = '\0';
  3079. }
  3080. else
  3081. cbappend = PACKAGE;
  3082. }
  3083. else
  3084. cbappend = "BFG";
  3085. }
  3086. size_t cbappendsz = strlen(cbappend);
  3087. static bool truncatewarning = false;
  3088. if (cbappendsz <= (size_t)ae) {
  3089. if (cbappendsz < (size_t)ae)
  3090. // If we have space, include the trailing \0
  3091. ++cbappendsz;
  3092. ae = cbappendsz;
  3093. truncatewarning = false;
  3094. } else {
  3095. char *tmp = malloc(ae + 1);
  3096. memcpy(tmp, opt_coinbase_sig, ae);
  3097. tmp[ae] = '\0';
  3098. applog((truncatewarning ? LOG_DEBUG : LOG_WARNING),
  3099. "Pool %u truncating appended coinbase signature at %"PRId64" bytes: %s(%s)",
  3100. pool->pool_no, (int64_t)ae, tmp, &opt_coinbase_sig[ae]);
  3101. free(tmp);
  3102. truncatewarning = true;
  3103. }
  3104. ae = blkmk_append_coinbase_safe(tmpl, cbappend, ae);
  3105. free(need_free);
  3106. if (ae <= 0) {
  3107. applog((appenderr ? LOG_DEBUG : LOG_WARNING), "Error appending coinbase signature (%"PRId64")", (int64_t)ae);
  3108. appenderr = true;
  3109. } else
  3110. appenderr = false;
  3111. }
  3112. }
  3113. #endif
  3114. if (blkmk_get_data(tmpl, work->data, 80, tv_now.tv_sec, NULL, &work->dataid) < 76)
  3115. return false;
  3116. swap32yes(work->data, work->data, 80 / 4);
  3117. memcpy(&work->data[80], workpadding_bin, 48);
  3118. work->ntime_roll_limits = (struct ntime_roll_limits){
  3119. .min = tmpl->mintime,
  3120. .max = tmpl->maxtime,
  3121. .tv_ref = tv_now,
  3122. .minoff = tmpl->mintimeoff,
  3123. .maxoff = tmpl->maxtimeoff,
  3124. };
  3125. const struct blktmpl_longpoll_req *lp;
  3126. if ((lp = blktmpl_get_longpoll(tmpl)) && ((!pool->lp_id) || strcmp(lp->id, pool->lp_id))) {
  3127. free(pool->lp_id);
  3128. pool->lp_id = strdup(lp->id);
  3129. #if 0 /* This just doesn't work :( */
  3130. curl_socket_t sock = pool->lp_socket;
  3131. if (sock != CURL_SOCKET_BAD) {
  3132. pool->lp_socket = CURL_SOCKET_BAD;
  3133. applog(LOG_WARNING, "Pool %u long poll request hanging, reconnecting", pool->pool_no);
  3134. shutdown(sock, SHUT_RDWR);
  3135. }
  3136. #endif
  3137. }
  3138. }
  3139. else
  3140. if (unlikely(!jobj_binary(res_val, "data", work->data, sizeof(work->data), true))) {
  3141. applog(LOG_ERR, "JSON inval data");
  3142. return false;
  3143. }
  3144. else
  3145. work_set_simple_ntime_roll_limit(work, 0, &tv_now);
  3146. if (!jobj_binary(res_val, "midstate", work->midstate, sizeof(work->midstate), false)) {
  3147. // Calculate it ourselves
  3148. applog(LOG_DEBUG, "Calculating midstate locally");
  3149. calc_midstate(work);
  3150. }
  3151. if (unlikely(!jobj_binary(res_val, "target", work->target, sizeof(work->target), true))) {
  3152. applog(LOG_ERR, "JSON inval target");
  3153. return false;
  3154. }
  3155. if (work->tr)
  3156. {
  3157. for (size_t i = 0; i < sizeof(work->target) / 2; ++i)
  3158. {
  3159. int p = (sizeof(work->target) - 1) - i;
  3160. unsigned char c = work->target[i];
  3161. work->target[i] = work->target[p];
  3162. work->target[p] = c;
  3163. }
  3164. }
  3165. if ( (tmp_val = json_object_get(res_val, "height")) ) {
  3166. struct mining_goal_info * const goal = pool->goal;
  3167. uint32_t blkheight = json_number_value(tmp_val);
  3168. const void * const prevblkhash = &work->data[4];
  3169. have_block_height(goal, prevblkhash, blkheight);
  3170. }
  3171. memset(work->hash, 0, sizeof(work->hash));
  3172. work->tv_staged = tv_now;
  3173. #if BLKMAKER_VERSION > 4
  3174. if (work->tr)
  3175. {
  3176. blktemplate_t * const tmpl = work->tr->tmpl;
  3177. uint8_t buf[80];
  3178. int16_t expire;
  3179. uint8_t *cbtxn;
  3180. size_t cbtxnsz;
  3181. size_t cbextranonceoffset;
  3182. int branchcount;
  3183. libblkmaker_hash_t *branches;
  3184. if (blkmk_get_mdata(tmpl, buf, sizeof(buf), tv_now.tv_sec, &expire, &cbtxn, &cbtxnsz, &cbextranonceoffset, &branchcount, &branches, GBT_XNONCESZ, false))
  3185. {
  3186. struct stratum_work * const swork = &pool->swork;
  3187. const size_t branchdatasz = branchcount * 0x20;
  3188. pool_check_coinbase(pool, cbtxn, cbtxnsz);
  3189. cg_wlock(&pool->data_lock);
  3190. swork->tr = work->tr;
  3191. bytes_assimilate_raw(&swork->coinbase, cbtxn, cbtxnsz, cbtxnsz);
  3192. swork->nonce2_offset = cbextranonceoffset;
  3193. bytes_assimilate_raw(&swork->merkle_bin, branches, branchdatasz, branchdatasz);
  3194. swork->merkles = branchcount;
  3195. memcpy(swork->header1, &buf[0], 36);
  3196. swork->ntime = le32toh(*(uint32_t *)(&buf[68]));
  3197. swork->tv_received = tv_now;
  3198. memcpy(swork->diffbits, &buf[72], 4);
  3199. memcpy(swork->target, work->target, sizeof(swork->target));
  3200. free(swork->job_id);
  3201. swork->job_id = NULL;
  3202. swork->clean = true;
  3203. swork->work_restart_id = pool->work_restart_id;
  3204. // FIXME: Do something with expire
  3205. pool->nonce2sz = swork->n2size = GBT_XNONCESZ;
  3206. pool->nonce2 = 0;
  3207. cg_wunlock(&pool->data_lock);
  3208. }
  3209. else
  3210. applog(LOG_DEBUG, "blkmk_get_mdata failed for pool %u", pool->pool_no);
  3211. }
  3212. #endif // BLKMAKER_VERSION > 4
  3213. pool_set_opaque(pool, !work->tr);
  3214. ret = true;
  3215. return ret;
  3216. }
  3217. /* Returns whether the pool supports local work generation or not. */
  3218. static bool pool_localgen(struct pool *pool)
  3219. {
  3220. return (pool->last_work_copy || pool->has_stratum);
  3221. }
  3222. int dev_from_id(int thr_id)
  3223. {
  3224. struct cgpu_info *cgpu = get_thr_cgpu(thr_id);
  3225. return cgpu->device_id;
  3226. }
  3227. /* Create an exponentially decaying average over the opt_log_interval */
  3228. void decay_time(double *f, double fadd, double fsecs)
  3229. {
  3230. double ftotal, fprop;
  3231. fprop = 1.0 - 1 / (exp(fsecs / (double)opt_log_interval));
  3232. ftotal = 1.0 + fprop;
  3233. *f += (fadd * fprop);
  3234. *f /= ftotal;
  3235. }
  3236. static
  3237. int __total_staged(const bool include_spares)
  3238. {
  3239. int tot = HASH_COUNT(staged_work);
  3240. if (!include_spares)
  3241. tot -= staged_spare;
  3242. return tot;
  3243. }
  3244. static int total_staged(const bool include_spares)
  3245. {
  3246. int ret;
  3247. mutex_lock(stgd_lock);
  3248. ret = __total_staged(include_spares);
  3249. mutex_unlock(stgd_lock);
  3250. return ret;
  3251. }
  3252. #ifdef HAVE_CURSES
  3253. WINDOW *mainwin, *statuswin, *logwin;
  3254. #endif
  3255. double total_secs = 1.0;
  3256. #ifdef HAVE_CURSES
  3257. static char statusline[256];
  3258. /* statusy is where the status window goes up to in cases where it won't fit at startup */
  3259. static int statusy;
  3260. static int devsummaryYOffset;
  3261. static int total_lines;
  3262. #endif
  3263. #ifdef USE_OPENCL
  3264. struct cgpu_info gpus[MAX_GPUDEVICES]; /* Maximum number apparently possible */
  3265. #endif
  3266. struct cgpu_info *cpus;
  3267. bool _bfg_console_cancel_disabled;
  3268. int _bfg_console_prev_cancelstate;
  3269. #ifdef HAVE_CURSES
  3270. #define lock_curses() bfg_console_lock()
  3271. #define unlock_curses() bfg_console_unlock()
  3272. static bool curses_active_locked(void)
  3273. {
  3274. bool ret;
  3275. lock_curses();
  3276. ret = curses_active;
  3277. if (!ret)
  3278. unlock_curses();
  3279. return ret;
  3280. }
  3281. // Cancellable getch
  3282. int my_cancellable_getch(void)
  3283. {
  3284. // This only works because the macro only hits direct getch() calls
  3285. typedef int (*real_getch_t)(void);
  3286. const real_getch_t real_getch = __real_getch;
  3287. int type, rv;
  3288. bool sct;
  3289. sct = !pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &type);
  3290. rv = real_getch();
  3291. if (sct)
  3292. pthread_setcanceltype(type, &type);
  3293. return rv;
  3294. }
  3295. #ifdef PDCURSES
  3296. static
  3297. int bfg_wresize(WINDOW *win, int lines, int columns)
  3298. {
  3299. int rv = wresize(win, lines, columns);
  3300. int x, y;
  3301. getyx(win, y, x);
  3302. if (unlikely(y >= lines || x >= columns))
  3303. {
  3304. if (y >= lines)
  3305. y = lines - 1;
  3306. if (x >= columns)
  3307. x = columns - 1;
  3308. wmove(win, y, x);
  3309. }
  3310. return rv;
  3311. }
  3312. #else
  3313. # define bfg_wresize wresize
  3314. #endif
  3315. #endif
  3316. void tailsprintf(char *buf, size_t bufsz, const char *fmt, ...)
  3317. {
  3318. va_list ap;
  3319. size_t presz = strlen(buf);
  3320. va_start(ap, fmt);
  3321. vsnprintf(&buf[presz], bufsz - presz, fmt, ap);
  3322. va_end(ap);
  3323. }
  3324. double stats_elapsed(struct cgminer_stats *stats)
  3325. {
  3326. struct timeval now;
  3327. double elapsed;
  3328. if (stats->start_tv.tv_sec == 0)
  3329. elapsed = total_secs;
  3330. else {
  3331. cgtime(&now);
  3332. elapsed = tdiff(&now, &stats->start_tv);
  3333. }
  3334. if (elapsed < 1.0)
  3335. elapsed = 1.0;
  3336. return elapsed;
  3337. }
  3338. bool drv_ready(struct cgpu_info *cgpu)
  3339. {
  3340. switch (cgpu->status) {
  3341. case LIFE_INIT:
  3342. case LIFE_DEAD2:
  3343. return false;
  3344. default:
  3345. return true;
  3346. }
  3347. }
  3348. double cgpu_utility(struct cgpu_info *cgpu)
  3349. {
  3350. double dev_runtime = cgpu_runtime(cgpu);
  3351. return cgpu->utility = cgpu->accepted / dev_runtime * 60;
  3352. }
  3353. #define suffix_string(val, buf, bufsiz, sigdigits) do{ \
  3354. _Static_assert(sigdigits == 0, "suffix_string only supported with sigdigits==0"); \
  3355. format_unit3(buf, bufsiz, FUP_DIFF, "", H2B_SHORTV, val, -1); \
  3356. }while(0)
  3357. static float
  3358. utility_to_hashrate(double utility)
  3359. {
  3360. return utility * 0x4444444;
  3361. }
  3362. static const char*_unitchar = "pn\xb5m kMGTPEZY?";
  3363. static const int _unitbase = 4;
  3364. static
  3365. void pick_unit(float hashrate, unsigned char *unit)
  3366. {
  3367. unsigned char i;
  3368. if (hashrate == 0 || !isfinite(hashrate))
  3369. {
  3370. if (*unit < _unitbase)
  3371. *unit = _unitbase;
  3372. return;
  3373. }
  3374. hashrate *= 1e12;
  3375. for (i = 0; i < *unit; ++i)
  3376. hashrate /= 1e3;
  3377. // 1000 but with tolerance for floating-point rounding, avoid showing "1000.0"
  3378. while (hashrate >= 999.95)
  3379. {
  3380. hashrate /= 1e3;
  3381. if (likely(_unitchar[*unit] != '?'))
  3382. ++*unit;
  3383. }
  3384. }
  3385. #define hashrate_pick_unit(hashrate, unit) pick_unit(hashrate, unit)
  3386. enum h2bs_fmt {
  3387. H2B_NOUNIT, // "xxx.x"
  3388. H2B_SHORT, // "xxx.xMH/s"
  3389. H2B_SPACED, // "xxx.x MH/s"
  3390. H2B_SHORTV, // Like H2B_SHORT, but omit space for base unit
  3391. };
  3392. enum bfu_floatprec {
  3393. FUP_INTEGER,
  3394. FUP_HASHES,
  3395. FUP_BTC,
  3396. FUP_DIFF,
  3397. };
  3398. static
  3399. int format_unit3(char *buf, size_t sz, enum bfu_floatprec fprec, const char *measurement, enum h2bs_fmt fmt, float hashrate, signed char unitin)
  3400. {
  3401. char *s = buf;
  3402. unsigned char prec, i, unit;
  3403. int rv = 0;
  3404. if (unitin == -1)
  3405. {
  3406. unit = 0;
  3407. hashrate_pick_unit(hashrate, &unit);
  3408. }
  3409. else
  3410. unit = unitin;
  3411. hashrate *= 1e12;
  3412. for (i = 0; i < unit; ++i)
  3413. hashrate /= 1000;
  3414. switch (fprec)
  3415. {
  3416. case FUP_HASHES:
  3417. // 100 but with tolerance for floating-point rounding, max "99.99" then "100.0"
  3418. if (hashrate >= 99.995 || unit < 6)
  3419. prec = 1;
  3420. else
  3421. prec = 2;
  3422. _SNP("%5.*f", prec, hashrate);
  3423. break;
  3424. case FUP_INTEGER:
  3425. _SNP("%3d", (int)hashrate);
  3426. break;
  3427. case FUP_BTC:
  3428. if (hashrate >= 99.995)
  3429. prec = 0;
  3430. else
  3431. prec = 2;
  3432. _SNP("%5.*f", prec, hashrate);
  3433. break;
  3434. case FUP_DIFF:
  3435. if (unit > _unitbase)
  3436. _SNP("%.3g", hashrate);
  3437. else
  3438. _SNP("%u", (unsigned int)hashrate);
  3439. }
  3440. if (fmt != H2B_NOUNIT)
  3441. {
  3442. char uc[3] = {_unitchar[unit], '\0'};
  3443. switch (fmt) {
  3444. case H2B_SPACED:
  3445. _SNP(" ");
  3446. default:
  3447. break;
  3448. case H2B_SHORTV:
  3449. if (isspace(uc[0]))
  3450. uc[0] = '\0';
  3451. }
  3452. if (uc[0] == '\xb5')
  3453. // Convert to UTF-8
  3454. snprintf(uc, sizeof(uc), "%s", U8_MICRO);
  3455. _SNP("%s%s", uc, measurement);
  3456. }
  3457. return rv;
  3458. }
  3459. #define format_unit2(buf, sz, floatprec, measurement, fmt, n, unit) \
  3460. format_unit3(buf, sz, floatprec ? FUP_HASHES : FUP_INTEGER, measurement, fmt, n, unit)
  3461. static
  3462. 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)
  3463. {
  3464. unsigned char unit = 0;
  3465. bool allzero = true;
  3466. int i;
  3467. size_t delimsz = 0;
  3468. char *buf = buflist[0];
  3469. size_t bufsz = bufszlist[0];
  3470. size_t itemwidth = (floatprec ? 5 : 3);
  3471. if (!isarray)
  3472. delimsz = strlen(delim);
  3473. for (i = 0; i < count; ++i)
  3474. if (numbers[i] != 0)
  3475. {
  3476. pick_unit(numbers[i], &unit);
  3477. allzero = false;
  3478. }
  3479. if (allzero)
  3480. unit = _unitbase;
  3481. --count;
  3482. for (i = 0; i < count; ++i)
  3483. {
  3484. format_unit2(buf, bufsz, floatprec, NULL, H2B_NOUNIT, numbers[i], unit);
  3485. if (isarray)
  3486. {
  3487. buf = buflist[i + 1];
  3488. bufsz = bufszlist[i + 1];
  3489. }
  3490. else
  3491. {
  3492. buf += itemwidth;
  3493. bufsz -= itemwidth;
  3494. if (delimsz > bufsz)
  3495. delimsz = bufsz;
  3496. memcpy(buf, delim, delimsz);
  3497. buf += delimsz;
  3498. bufsz -= delimsz;
  3499. }
  3500. }
  3501. // Last entry has the unit
  3502. format_unit2(buf, bufsz, floatprec, measurement, fmt, numbers[count], unit);
  3503. return buflist[0];
  3504. }
  3505. #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)
  3506. #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)
  3507. static
  3508. int percentf3(char * const buf, size_t sz, double p, const double t)
  3509. {
  3510. char *s = buf;
  3511. int rv = 0;
  3512. if (!p)
  3513. _SNP("none");
  3514. else
  3515. if (t <= p)
  3516. _SNP("100%%");
  3517. else
  3518. {
  3519. p /= t;
  3520. if (p < 0.00995) // 0.01 but with tolerance for floating-point rounding, max ".99%"
  3521. _SNP(".%02.0f%%", p * 10000); // ".01%"
  3522. else
  3523. if (p < 0.0995) // 0.1 but with tolerance for floating-point rounding, max "9.9%"
  3524. _SNP("%.1f%%", p * 100); // "9.1%"
  3525. else
  3526. _SNP("%3.0f%%", p * 100); // " 99%"
  3527. }
  3528. return rv;
  3529. }
  3530. #define percentf4(buf, bufsz, p, t) percentf3(buf, bufsz, p, p + t)
  3531. static
  3532. void test_decimal_width()
  3533. {
  3534. // The pipe character at end of each line should perfectly line up
  3535. char printbuf[512];
  3536. char testbuf1[64];
  3537. char testbuf2[64];
  3538. char testbuf3[64];
  3539. char testbuf4[64];
  3540. double testn;
  3541. int width;
  3542. int saved;
  3543. // Hotspots around 0.1 and 0.01
  3544. saved = -1;
  3545. for (testn = 0.09; testn <= 0.11; testn += 0.000001) {
  3546. percentf3(testbuf1, sizeof(testbuf1), testn, 1.0);
  3547. percentf3(testbuf2, sizeof(testbuf2), testn, 10.0);
  3548. width = snprintf(printbuf, sizeof(printbuf), "%10g %s %s |", testn, testbuf1, testbuf2);
  3549. if (unlikely((saved != -1) && (width != saved))) {
  3550. ++unittest_failures;
  3551. applog(LOG_ERR, "Test width mismatch in percentf3! %d not %d at %10g", width, saved, testn);
  3552. applog(LOG_ERR, "%s", printbuf);
  3553. }
  3554. saved = width;
  3555. }
  3556. // Hotspot around 100 (but test this in several units because format_unit2 also has unit<2 check)
  3557. saved = -1;
  3558. for (testn = 99.0; testn <= 101.0; testn += 0.0001) {
  3559. format_unit2(testbuf1, sizeof(testbuf1), true, "x", H2B_SHORT, testn , -1);
  3560. format_unit2(testbuf2, sizeof(testbuf2), true, "x", H2B_SHORT, testn * 1e3, -1);
  3561. format_unit2(testbuf3, sizeof(testbuf3), true, "x", H2B_SHORT, testn * 1e6, -1);
  3562. snprintf(printbuf, sizeof(printbuf), "%10g %s %s %s |", testn, testbuf1, testbuf2, testbuf3);
  3563. width = utf8_strlen(printbuf);
  3564. if (unlikely((saved != -1) && (width != saved))) {
  3565. ++unittest_failures;
  3566. applog(LOG_ERR, "Test width mismatch in format_unit2! %d not %d at %10g", width, saved, testn);
  3567. applog(LOG_ERR, "%s", printbuf);
  3568. }
  3569. saved = width;
  3570. }
  3571. // Hotspot around unit transition boundary in pick_unit
  3572. saved = -1;
  3573. for (testn = 999.0; testn <= 1001.0; testn += 0.0001) {
  3574. format_unit2(testbuf1, sizeof(testbuf1), true, "x", H2B_SHORT, testn , -1);
  3575. format_unit2(testbuf2, sizeof(testbuf2), true, "x", H2B_SHORT, testn * 1e3, -1);
  3576. format_unit2(testbuf3, sizeof(testbuf3), true, "x", H2B_SHORT, testn * 1e6, -1);
  3577. format_unit2(testbuf4, sizeof(testbuf4), true, "x", H2B_SHORT, testn * 1e9, -1);
  3578. snprintf(printbuf, sizeof(printbuf), "%10g %s %s %s %s |", testn, testbuf1, testbuf2, testbuf3, testbuf4);
  3579. width = utf8_strlen(printbuf);
  3580. if (unlikely((saved != -1) && (width != saved))) {
  3581. ++unittest_failures;
  3582. applog(LOG_ERR, "Test width mismatch in pick_unit! %d not %d at %10g", width, saved, testn);
  3583. applog(LOG_ERR, "%s", printbuf);
  3584. }
  3585. saved = width;
  3586. }
  3587. }
  3588. #ifdef HAVE_CURSES
  3589. static void adj_width(int var, int *length);
  3590. #endif
  3591. #ifdef HAVE_CURSES
  3592. static int awidth = 1, rwidth = 1, swidth = 1, hwwidth = 1;
  3593. static
  3594. 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)
  3595. {
  3596. char rejpcbuf[6];
  3597. char bnbuf[6];
  3598. adj_width(accepted, &awidth);
  3599. adj_width(rejected, &rwidth);
  3600. adj_width(stale, &swidth);
  3601. adj_width(hwerrs, &hwwidth);
  3602. percentf4(rejpcbuf, sizeof(rejpcbuf), wnotaccepted, waccepted);
  3603. percentf3(bnbuf, sizeof(bnbuf), bad_diff1, allnonces);
  3604. tailsprintf(buf, bufsz, "%s/%s/%s | A:%*d R:%*d+%*d(%s) HW:%*d/%s",
  3605. cHr, aHr, uHr,
  3606. awidth, accepted,
  3607. rwidth, rejected,
  3608. swidth, stale,
  3609. rejpcbuf,
  3610. hwwidth, hwerrs,
  3611. bnbuf
  3612. );
  3613. }
  3614. static
  3615. const char *pool_proto_str(const struct pool * const pool)
  3616. {
  3617. if (pool->idle)
  3618. return "Dead ";
  3619. if (pool->has_stratum)
  3620. return "Strtm";
  3621. if (pool->lp_url && pool->proto != pool->lp_proto)
  3622. return "Mixed";
  3623. switch (pool->proto)
  3624. {
  3625. case PLP_GETBLOCKTEMPLATE:
  3626. return " GBT ";
  3627. case PLP_GETWORK:
  3628. return "GWork";
  3629. default:
  3630. return "Alive";
  3631. }
  3632. }
  3633. #endif
  3634. static inline
  3635. void temperature_column(char *buf, size_t bufsz, bool maybe_unicode, const float * const temp)
  3636. {
  3637. if (!(use_unicode && have_unicode_degrees))
  3638. maybe_unicode = false;
  3639. if (temp && *temp > 0.)
  3640. if (maybe_unicode)
  3641. snprintf(buf, bufsz, "%4.1f"U8_DEGREE"C", *temp);
  3642. else
  3643. snprintf(buf, bufsz, "%4.1fC", *temp);
  3644. else
  3645. {
  3646. if (temp)
  3647. snprintf(buf, bufsz, " ");
  3648. if (maybe_unicode)
  3649. tailsprintf(buf, bufsz, " ");
  3650. }
  3651. tailsprintf(buf, bufsz, " | ");
  3652. }
  3653. void get_statline3(char *buf, size_t bufsz, struct cgpu_info *cgpu, bool for_curses, bool opt_show_procs)
  3654. {
  3655. #ifndef HAVE_CURSES
  3656. assert(for_curses == false);
  3657. #endif
  3658. struct device_drv *drv = cgpu->drv;
  3659. enum h2bs_fmt hashrate_style = for_curses ? H2B_SHORT : H2B_SPACED;
  3660. char cHr[ALLOC_H2B_NOUNIT+1], aHr[ALLOC_H2B_NOUNIT+1], uHr[max(ALLOC_H2B_SHORT, ALLOC_H2B_SPACED)+3+1];
  3661. char rejpcbuf[6];
  3662. char bnbuf[6];
  3663. double dev_runtime;
  3664. if (!opt_show_procs)
  3665. cgpu = cgpu->device;
  3666. dev_runtime = cgpu_runtime(cgpu);
  3667. double rolling, mhashes;
  3668. int accepted, rejected, stale;
  3669. double waccepted;
  3670. double wnotaccepted;
  3671. int hwerrs;
  3672. double bad_diff1, good_diff1;
  3673. rolling = mhashes = waccepted = wnotaccepted = 0;
  3674. accepted = rejected = stale = hwerrs = bad_diff1 = good_diff1 = 0;
  3675. {
  3676. struct cgpu_info *slave = cgpu;
  3677. for (int i = 0; i < cgpu->procs; ++i, (slave = slave->next_proc))
  3678. {
  3679. slave->utility = slave->accepted / dev_runtime * 60;
  3680. slave->utility_diff1 = slave->diff_accepted / dev_runtime * 60;
  3681. rolling += slave->rolling;
  3682. mhashes += slave->total_mhashes;
  3683. if (opt_weighed_stats)
  3684. {
  3685. accepted += slave->diff_accepted;
  3686. rejected += slave->diff_rejected;
  3687. stale += slave->diff_stale;
  3688. }
  3689. else
  3690. {
  3691. accepted += slave->accepted;
  3692. rejected += slave->rejected;
  3693. stale += slave->stale;
  3694. }
  3695. waccepted += slave->diff_accepted;
  3696. wnotaccepted += slave->diff_rejected + slave->diff_stale;
  3697. hwerrs += slave->hw_errors;
  3698. bad_diff1 += slave->bad_diff1;
  3699. good_diff1 += slave->diff1;
  3700. if (opt_show_procs)
  3701. break;
  3702. }
  3703. }
  3704. if ((cgpu->device == cgpu) && (drv->get_master_rolling_hashrate))
  3705. rolling = drv->get_master_rolling_hashrate(cgpu);
  3706. double wtotal = (waccepted + wnotaccepted);
  3707. multi_format_unit_array2(
  3708. ((char*[]){cHr, aHr, uHr}),
  3709. ((size_t[]){sizeof(cHr), sizeof(aHr), sizeof(uHr)}),
  3710. true, "h/s", hashrate_style,
  3711. 3,
  3712. 1e6*rolling,
  3713. 1e6*mhashes / dev_runtime,
  3714. utility_to_hashrate(good_diff1 * (wtotal ? (waccepted / wtotal) : 1) * 60 / dev_runtime));
  3715. // Processor representation
  3716. #ifdef HAVE_CURSES
  3717. if (for_curses)
  3718. {
  3719. if (opt_show_procs)
  3720. snprintf(buf, bufsz, " %*s: ", -(5 + max_lpdigits), cgpu->proc_repr);
  3721. else
  3722. snprintf(buf, bufsz, " %s: ", cgpu->dev_repr);
  3723. }
  3724. else
  3725. #endif
  3726. snprintf(buf, bufsz, "%s ", opt_show_procs ? cgpu->proc_repr_ns : cgpu->dev_repr_ns);
  3727. if (include_serial_in_statline && cgpu->dev_serial)
  3728. tailsprintf(buf, bufsz, "[serial=%s] ", cgpu->dev_serial);
  3729. if (unlikely(cgpu->status == LIFE_INIT))
  3730. {
  3731. tailsprintf(buf, bufsz, "Initializing...");
  3732. return;
  3733. }
  3734. {
  3735. const size_t bufln = strlen(buf);
  3736. const size_t abufsz = (bufln >= bufsz) ? 0 : (bufsz - bufln);
  3737. if (likely(cgpu->status != LIFE_DEAD2) && drv->override_statline_temp2 && drv->override_statline_temp2(buf, bufsz, cgpu, opt_show_procs))
  3738. temperature_column(&buf[bufln], abufsz, for_curses, NULL);
  3739. else
  3740. {
  3741. float temp = cgpu->temp;
  3742. if (!opt_show_procs)
  3743. {
  3744. // Find the highest temperature of all processors
  3745. struct cgpu_info *proc = cgpu;
  3746. for (int i = 0; i < cgpu->procs; ++i, (proc = proc->next_proc))
  3747. if (proc->temp > temp)
  3748. temp = proc->temp;
  3749. }
  3750. temperature_column(&buf[bufln], abufsz, for_curses, &temp);
  3751. }
  3752. }
  3753. #ifdef HAVE_CURSES
  3754. if (for_curses)
  3755. {
  3756. const char *cHrStatsOpt[] = {AS_BAD("DEAD "), AS_BAD("SICK "), "OFF ", AS_BAD("REST "), AS_BAD(" ERR "), AS_BAD("WAIT "), cHr};
  3757. const char *cHrStats;
  3758. int cHrStatsI = (sizeof(cHrStatsOpt) / sizeof(*cHrStatsOpt)) - 1;
  3759. bool all_dead = true, all_off = true, all_rdrv = true;
  3760. struct cgpu_info *proc = cgpu;
  3761. for (int i = 0; i < cgpu->procs; ++i, (proc = proc->next_proc))
  3762. {
  3763. switch (cHrStatsI) {
  3764. default:
  3765. if (proc->status == LIFE_WAIT)
  3766. cHrStatsI = 5;
  3767. case 5:
  3768. if (proc->deven == DEV_RECOVER_ERR)
  3769. cHrStatsI = 4;
  3770. case 4:
  3771. if (proc->deven == DEV_RECOVER)
  3772. cHrStatsI = 3;
  3773. case 3:
  3774. if (proc->status == LIFE_SICK || proc->status == LIFE_DEAD || proc->status == LIFE_DEAD2)
  3775. {
  3776. cHrStatsI = 1;
  3777. all_off = false;
  3778. }
  3779. else
  3780. {
  3781. if (likely(proc->deven == DEV_ENABLED))
  3782. all_off = false;
  3783. if (proc->deven != DEV_RECOVER_DRV)
  3784. all_rdrv = false;
  3785. }
  3786. case 1:
  3787. break;
  3788. }
  3789. if (likely(proc->status != LIFE_DEAD && proc->status != LIFE_DEAD2))
  3790. all_dead = false;
  3791. if (opt_show_procs)
  3792. break;
  3793. }
  3794. if (unlikely(all_dead))
  3795. cHrStatsI = 0;
  3796. else
  3797. if (unlikely(all_off))
  3798. cHrStatsI = 2;
  3799. cHrStats = cHrStatsOpt[cHrStatsI];
  3800. if (cHrStatsI == 2 && all_rdrv)
  3801. cHrStats = " RST ";
  3802. format_statline(buf, bufsz,
  3803. cHrStats,
  3804. aHr, uHr,
  3805. accepted, rejected, stale,
  3806. wnotaccepted, waccepted,
  3807. hwerrs,
  3808. bad_diff1, bad_diff1 + good_diff1);
  3809. }
  3810. else
  3811. #endif
  3812. {
  3813. percentf4(rejpcbuf, sizeof(rejpcbuf), wnotaccepted, waccepted);
  3814. percentf4(bnbuf, sizeof(bnbuf), bad_diff1, good_diff1);
  3815. tailsprintf(buf, bufsz, "%ds:%s avg:%s u:%s | A:%d R:%d+%d(%s) HW:%d/%s",
  3816. opt_log_interval,
  3817. cHr, aHr, uHr,
  3818. accepted,
  3819. rejected,
  3820. stale,
  3821. rejpcbuf,
  3822. hwerrs,
  3823. bnbuf
  3824. );
  3825. }
  3826. }
  3827. #define get_statline(buf, bufsz, cgpu) get_statline3(buf, bufsz, cgpu, false, opt_show_procs)
  3828. #define get_statline2(buf, bufsz, cgpu, for_curses) get_statline3(buf, bufsz, cgpu, for_curses, opt_show_procs)
  3829. static void text_print_status(int thr_id)
  3830. {
  3831. struct cgpu_info *cgpu;
  3832. char logline[256];
  3833. cgpu = get_thr_cgpu(thr_id);
  3834. if (cgpu) {
  3835. get_statline(logline, sizeof(logline), cgpu);
  3836. printf("\n%s\r", logline);
  3837. fflush(stdout);
  3838. }
  3839. }
  3840. #ifdef HAVE_CURSES
  3841. static int attr_bad = A_BOLD;
  3842. #ifdef WIN32
  3843. #define swprintf snwprintf
  3844. #endif
  3845. static
  3846. void bfg_waddstr(WINDOW *win, const char *s)
  3847. {
  3848. const char *p = s;
  3849. int32_t w;
  3850. int wlen;
  3851. unsigned char stop_ascii = (use_unicode ? '|' : 0x80);
  3852. while (true)
  3853. {
  3854. while (likely(p[0] == '\n' || (p[0] >= 0x20 && p[0] < stop_ascii)))
  3855. {
  3856. // Printable ASCII
  3857. ++p;
  3858. }
  3859. if (p != s)
  3860. waddnstr(win, s, p - s);
  3861. w = utf8_decode(p, &wlen);
  3862. s = p += wlen;
  3863. switch(w)
  3864. {
  3865. // NOTE: U+F000-U+F7FF are reserved for font hacks
  3866. case '\0':
  3867. return;
  3868. case 0xb5: // micro symbol
  3869. w = unicode_micro;
  3870. goto default_addch;
  3871. case 0xf000: // "bad" off
  3872. wattroff(win, attr_bad);
  3873. break;
  3874. case 0xf001: // "bad" on
  3875. wattron(win, attr_bad);
  3876. break;
  3877. #ifdef USE_UNICODE
  3878. case '|':
  3879. wadd_wch(win, WACS_VLINE);
  3880. break;
  3881. #endif
  3882. case 0x2500: // BOX DRAWINGS LIGHT HORIZONTAL
  3883. case 0x2534: // BOX DRAWINGS LIGHT UP AND HORIZONTAL
  3884. if (!use_unicode)
  3885. {
  3886. waddch(win, '-');
  3887. break;
  3888. }
  3889. #ifdef USE_UNICODE
  3890. wadd_wch(win, (w == 0x2500) ? WACS_HLINE : WACS_BTEE);
  3891. break;
  3892. #endif
  3893. case 0x2022:
  3894. if (w > WCHAR_MAX || !iswprint(w))
  3895. w = '*';
  3896. default:
  3897. default_addch:
  3898. if (w > WCHAR_MAX || !(iswprint(w) || w == '\n'))
  3899. {
  3900. #if REPLACEMENT_CHAR <= WCHAR_MAX
  3901. if (iswprint(REPLACEMENT_CHAR))
  3902. w = REPLACEMENT_CHAR;
  3903. else
  3904. #endif
  3905. w = '?';
  3906. }
  3907. {
  3908. #ifdef USE_UNICODE
  3909. wchar_t wbuf[0x10];
  3910. int wbuflen = sizeof(wbuf) / sizeof(*wbuf);
  3911. wbuflen = swprintf(wbuf, wbuflen, L"%lc", (wint_t)w);
  3912. waddnwstr(win, wbuf, wbuflen);
  3913. #else
  3914. wprintw(win, "%lc", (wint_t)w);
  3915. #endif
  3916. }
  3917. }
  3918. }
  3919. }
  3920. static inline
  3921. void bfg_hline(WINDOW *win, int y)
  3922. {
  3923. int maxx, __maybe_unused maxy;
  3924. getmaxyx(win, maxy, maxx);
  3925. #ifdef USE_UNICODE
  3926. if (use_unicode)
  3927. mvwhline_set(win, y, 0, WACS_HLINE, maxx);
  3928. else
  3929. #endif
  3930. mvwhline(win, y, 0, '-', maxx);
  3931. }
  3932. static
  3933. int bfg_win_linelen(WINDOW * const win)
  3934. {
  3935. int maxx;
  3936. int __maybe_unused y;
  3937. getmaxyx(win, y, maxx);
  3938. return maxx;
  3939. }
  3940. // Spaces until end of line, using current attributes (ie, not completely clear)
  3941. static
  3942. void bfg_wspctoeol(WINDOW * const win, const int offset)
  3943. {
  3944. int x, maxx;
  3945. int __maybe_unused y;
  3946. getmaxyx(win, y, maxx);
  3947. getyx(win, y, x);
  3948. const int space_count = (maxx - x) - offset;
  3949. // Check for negative - terminal too narrow
  3950. if (space_count <= 0)
  3951. return;
  3952. char buf[space_count];
  3953. memset(buf, ' ', space_count);
  3954. waddnstr(win, buf, space_count);
  3955. }
  3956. static int menu_attr = A_REVERSE;
  3957. #define CURBUFSIZ 256
  3958. #define cg_mvwprintw(win, y, x, fmt, ...) do { \
  3959. char tmp42[CURBUFSIZ]; \
  3960. snprintf(tmp42, sizeof(tmp42), fmt, ##__VA_ARGS__); \
  3961. wmove(win, y, x); \
  3962. bfg_waddstr(win, tmp42); \
  3963. } while (0)
  3964. #define cg_wprintw(win, fmt, ...) do { \
  3965. char tmp42[CURBUFSIZ]; \
  3966. snprintf(tmp42, sizeof(tmp42), fmt, ##__VA_ARGS__); \
  3967. bfg_waddstr(win, tmp42); \
  3968. } while (0)
  3969. static
  3970. void update_block_display_line(const int blky, struct mining_goal_info *goal)
  3971. {
  3972. struct blockchain_info * const blkchain = goal->blkchain;
  3973. struct block_info * const blkinfo = blkchain->currentblk;
  3974. double income;
  3975. char incomestr[ALLOC_H2B_SHORT+6+1];
  3976. if (blkinfo->height)
  3977. {
  3978. income = goal->diff_accepted * 3600 * blkchain->currentblk_subsidy / total_secs / goal->current_diff;
  3979. format_unit3(incomestr, sizeof(incomestr), FUP_BTC, "BTC/hr", H2B_SHORT, income/1e8, -1);
  3980. }
  3981. else
  3982. strcpy(incomestr, "?");
  3983. int linelen = bfg_win_linelen(statuswin);
  3984. wmove(statuswin, blky, 0);
  3985. bfg_waddstr(statuswin, " Block");
  3986. if (!goal->is_default)
  3987. linelen -= strlen(goal->name) + 1;
  3988. linelen -= 6; // " Block"
  3989. if (blkinfo->height && blkinfo->height < 1000000)
  3990. {
  3991. cg_wprintw(statuswin, " #%6u", blkinfo->height);
  3992. linelen -= 8;
  3993. }
  3994. bfg_waddstr(statuswin, ":");
  3995. if (linelen > 55)
  3996. bfg_waddstr(statuswin, " ");
  3997. if (linelen >= 65)
  3998. bfg_waddstr(statuswin, "...");
  3999. {
  4000. char hexpbh[0x11];
  4001. if (!(blkinfo->height && blkinfo->height < 1000000))
  4002. {
  4003. bin2hex(hexpbh, &blkinfo->prevblkhash[4], 4);
  4004. bfg_waddstr(statuswin, hexpbh);
  4005. }
  4006. bin2hex(hexpbh, &blkinfo->prevblkhash[0], 4);
  4007. bfg_waddstr(statuswin, hexpbh);
  4008. }
  4009. if (linelen >= 55)
  4010. bfg_waddstr(statuswin, " ");
  4011. cg_wprintw(statuswin, " Diff:%s", goal->current_diff_str);
  4012. if (linelen >= 69)
  4013. bfg_waddstr(statuswin, " ");
  4014. cg_wprintw(statuswin, "(%s) ", goal->net_hashrate);
  4015. if (linelen >= 62)
  4016. {
  4017. if (linelen >= 69)
  4018. bfg_waddstr(statuswin, " ");
  4019. bfg_waddstr(statuswin, "Started:");
  4020. }
  4021. else
  4022. bfg_waddstr(statuswin, "S:");
  4023. if (linelen >= 69)
  4024. bfg_waddstr(statuswin, " ");
  4025. bfg_waddstr(statuswin, blkchain->currentblk_first_seen_time_str);
  4026. if (linelen >= 69)
  4027. bfg_waddstr(statuswin, " ");
  4028. cg_wprintw(statuswin, " I:%s", incomestr);
  4029. if (!goal->is_default)
  4030. cg_wprintw(statuswin, " %s", goal->name);
  4031. wclrtoeol(statuswin);
  4032. }
  4033. static bool pool_actively_in_use(const struct pool *, const struct pool *);
  4034. static
  4035. void update_block_display(void)
  4036. {
  4037. struct mining_goal_info *goal, *tmpgoal;
  4038. int blky = 3, i, total_found_goals = 0;
  4039. HASH_ITER(hh, mining_goals, goal, tmpgoal)
  4040. {
  4041. for (i = 0; i < total_pools; ++i)
  4042. {
  4043. struct pool * const pool = pools[i];
  4044. if (pool->goal == goal && pool_actively_in_use(pool, NULL))
  4045. break;
  4046. }
  4047. if (i >= total_pools)
  4048. // no pools using this goal, so it's probably stale anyway
  4049. continue;
  4050. update_block_display_line(blky++, goal);
  4051. ++total_found_goals;
  4052. }
  4053. if (total_found_goals != active_goals)
  4054. {
  4055. active_goals = total_found_goals;
  4056. devcursor = 7 + active_goals;
  4057. switch_logsize();
  4058. }
  4059. }
  4060. static bool pool_unworkable(const struct pool *);
  4061. /* Must be called with curses mutex lock held and curses_active */
  4062. static void curses_print_status(const int ts)
  4063. {
  4064. struct pool *pool = currentpool;
  4065. struct timeval now, tv;
  4066. float efficiency;
  4067. int logdiv;
  4068. efficiency = total_bytes_xfer ? total_diff_accepted * 2048. / total_bytes_xfer : 0.0;
  4069. wattron(statuswin, attr_title);
  4070. const int linelen = bfg_win_linelen(statuswin);
  4071. int titlelen = 1 + strlen(PACKAGE) + 1 + strlen(bfgminer_ver) + 3 + 21 + 3 + 19;
  4072. cg_mvwprintw(statuswin, 0, 0, " " PACKAGE " ");
  4073. if (titlelen + 17 < linelen)
  4074. cg_wprintw(statuswin, "version ");
  4075. cg_wprintw(statuswin, "%s - ", bfgminer_ver);
  4076. if (titlelen + 9 < linelen)
  4077. cg_wprintw(statuswin, "Started: ");
  4078. else
  4079. if (titlelen + 7 <= linelen)
  4080. cg_wprintw(statuswin, "Start: ");
  4081. cg_wprintw(statuswin, "%s", datestamp);
  4082. timer_set_now(&now);
  4083. {
  4084. unsigned int days, hours;
  4085. div_t d;
  4086. timersub(&now, &miner_started, &tv);
  4087. d = div(tv.tv_sec, 86400);
  4088. days = d.quot;
  4089. d = div(d.rem, 3600);
  4090. hours = d.quot;
  4091. d = div(d.rem, 60);
  4092. cg_wprintw(statuswin, " - [%3u day%c %02d:%02d:%02d]"
  4093. , days
  4094. , (days == 1) ? ' ' : 's'
  4095. , hours
  4096. , d.quot
  4097. , d.rem
  4098. );
  4099. }
  4100. bfg_wspctoeol(statuswin, 0);
  4101. wattroff(statuswin, attr_title);
  4102. wattron(statuswin, menu_attr);
  4103. wmove(statuswin, 1, 0);
  4104. bfg_waddstr(statuswin, " [M]anage devices [P]ool management [S]ettings [D]isplay options ");
  4105. bfg_wspctoeol(statuswin, 14);
  4106. bfg_waddstr(statuswin, "[H]elp [Q]uit ");
  4107. wattroff(statuswin, menu_attr);
  4108. if ((pool_strategy == POOL_LOADBALANCE || pool_strategy == POOL_BALANCE) && enabled_pools > 1) {
  4109. char poolinfo[20], poolinfo2[20];
  4110. int poolinfooff = 0, poolinfo2off, workable_pools = 0;
  4111. double lowdiff = DBL_MAX, highdiff = -1;
  4112. struct pool *lowdiff_pool = pools[0], *highdiff_pool = pools[0];
  4113. time_t oldest_work_restart = time(NULL) + 1;
  4114. struct pool *oldest_work_restart_pool = pools[0];
  4115. for (int i = 0; i < total_pools; ++i)
  4116. {
  4117. if (pool_unworkable(pools[i]))
  4118. continue;
  4119. // NOTE: Only set pool var when it's workable; if only one is, it gets used by single-pool code
  4120. pool = pools[i];
  4121. ++workable_pools;
  4122. if (poolinfooff < sizeof(poolinfo))
  4123. poolinfooff += snprintf(&poolinfo[poolinfooff], sizeof(poolinfo) - poolinfooff, "%u,", pool->pool_no);
  4124. struct cgminer_pool_stats * const pool_stats = &pool->cgminer_pool_stats;
  4125. if (pool_stats->last_diff < lowdiff)
  4126. {
  4127. lowdiff = pool_stats->last_diff;
  4128. lowdiff_pool = pool;
  4129. }
  4130. if (pool_stats->last_diff > highdiff)
  4131. {
  4132. highdiff = pool_stats->last_diff;
  4133. highdiff_pool = pool;
  4134. }
  4135. if (oldest_work_restart >= pool->work_restart_time)
  4136. {
  4137. oldest_work_restart = pool->work_restart_time;
  4138. oldest_work_restart_pool = pool;
  4139. }
  4140. }
  4141. if (unlikely(!workable_pools))
  4142. goto no_workable_pools;
  4143. if (workable_pools == 1)
  4144. goto one_workable_pool;
  4145. poolinfo2off = snprintf(poolinfo2, sizeof(poolinfo2), "%u (", workable_pools);
  4146. if (poolinfooff > sizeof(poolinfo2) - poolinfo2off - 1)
  4147. snprintf(&poolinfo2[poolinfo2off], sizeof(poolinfo2) - poolinfo2off, "%.*s...)", (int)(sizeof(poolinfo2) - poolinfo2off - 5), poolinfo);
  4148. else
  4149. snprintf(&poolinfo2[poolinfo2off], sizeof(poolinfo2) - poolinfo2off, "%.*s)%*s", (int)(poolinfooff - 1), poolinfo, (int)(sizeof(poolinfo2)), "");
  4150. cg_mvwprintw(statuswin, 2, 0, " Pools: %s Diff:%s%s%s %c LU:%s",
  4151. poolinfo2,
  4152. lowdiff_pool->diff,
  4153. (lowdiff == highdiff) ? "" : "-",
  4154. (lowdiff == highdiff) ? "" : highdiff_pool->diff,
  4155. pool->goal->have_longpoll ? '+' : '-',
  4156. oldest_work_restart_pool->work_restart_timestamp);
  4157. }
  4158. else
  4159. if (pool_unworkable(pool))
  4160. {
  4161. no_workable_pools: ;
  4162. wattron(statuswin, attr_bad);
  4163. cg_mvwprintw(statuswin, 2, 0, " (all pools are dead) ");
  4164. wattroff(statuswin, attr_bad);
  4165. }
  4166. else
  4167. {
  4168. one_workable_pool: ;
  4169. char pooladdr[19];
  4170. {
  4171. const char *rawaddr = pool->sockaddr_url;
  4172. BFGINIT(rawaddr, pool->rpc_url);
  4173. size_t pooladdrlen = strlen(rawaddr);
  4174. if (pooladdrlen > 20)
  4175. snprintf(pooladdr, sizeof(pooladdr), "...%s", &rawaddr[pooladdrlen - (sizeof(pooladdr) - 4)]);
  4176. else
  4177. snprintf(pooladdr, sizeof(pooladdr), "%*s", -(int)(sizeof(pooladdr) - 1), rawaddr);
  4178. }
  4179. cg_mvwprintw(statuswin, 2, 0, " Pool%2u: %s Diff:%s %c%s LU:%s User:%s",
  4180. pool->pool_no, pooladdr, pool->diff,
  4181. pool->goal->have_longpoll ? '+' : '-', pool_proto_str(pool),
  4182. pool->work_restart_timestamp,
  4183. pool->rpc_user);
  4184. }
  4185. wclrtoeol(statuswin);
  4186. char bwstr[(ALLOC_H2B_SHORT*2)+3+1];
  4187. cg_mvwprintw(statuswin, devcursor - 4, 0, " ST:%d F:%d NB:%d AS:%d BW:[%s] E:%.2f BS:%s",
  4188. ts,
  4189. total_go + total_ro,
  4190. new_blocks,
  4191. total_submitting,
  4192. multi_format_unit2(bwstr, sizeof(bwstr),
  4193. false, "B/s", H2B_SHORT, "/", 2,
  4194. (float)(total_bytes_rcvd / total_secs),
  4195. (float)(total_bytes_sent / total_secs)),
  4196. efficiency,
  4197. best_share);
  4198. wclrtoeol(statuswin);
  4199. mvwaddstr(statuswin, devcursor - 3, 0, " ");
  4200. bfg_waddstr(statuswin, statusline);
  4201. wclrtoeol(statuswin);
  4202. int devdiv = devcursor - 2;
  4203. logdiv = statusy - 1;
  4204. bfg_hline(statuswin, devdiv);
  4205. bfg_hline(statuswin, logdiv);
  4206. #ifdef USE_UNICODE
  4207. if (use_unicode)
  4208. {
  4209. int offset = 8 /* device */ + 5 /* temperature */ + 1 /* padding space */;
  4210. if (opt_show_procs && !opt_compact)
  4211. offset += max_lpdigits; // proc letter(s)
  4212. if (have_unicode_degrees)
  4213. ++offset; // degrees symbol
  4214. mvwadd_wch(statuswin, devdiv, offset, WACS_PLUS);
  4215. mvwadd_wch(statuswin, logdiv, offset, WACS_BTEE);
  4216. offset += 24; // hashrates etc
  4217. mvwadd_wch(statuswin, devdiv, offset, WACS_PLUS);
  4218. mvwadd_wch(statuswin, logdiv, offset, WACS_BTEE);
  4219. }
  4220. #endif
  4221. }
  4222. static void adj_width(int var, int *length)
  4223. {
  4224. if ((int)(log10(var) + 1) > *length)
  4225. (*length)++;
  4226. }
  4227. static int dev_width;
  4228. static void curses_print_devstatus(struct cgpu_info *cgpu)
  4229. {
  4230. char logline[256];
  4231. int ypos;
  4232. if (opt_compact)
  4233. return;
  4234. /* Check this isn't out of the window size */
  4235. if (opt_show_procs)
  4236. ypos = cgpu->cgminer_id;
  4237. else
  4238. {
  4239. if (cgpu->proc_id)
  4240. return;
  4241. ypos = cgpu->device_line_id;
  4242. }
  4243. ypos += devsummaryYOffset;
  4244. if (ypos < 0)
  4245. return;
  4246. ypos += devcursor - 1;
  4247. if (ypos >= statusy - 1)
  4248. return;
  4249. if (wmove(statuswin, ypos, 0) == ERR)
  4250. return;
  4251. get_statline2(logline, sizeof(logline), cgpu, true);
  4252. if (selecting_device && (opt_show_procs ? (selected_device == cgpu->cgminer_id) : (devices[selected_device]->device == cgpu)))
  4253. wattron(statuswin, A_REVERSE);
  4254. bfg_waddstr(statuswin, logline);
  4255. wattroff(statuswin, A_REVERSE);
  4256. wclrtoeol(statuswin);
  4257. }
  4258. static
  4259. void _refresh_devstatus(const bool already_have_lock) {
  4260. if ((!opt_compact) && (already_have_lock || curses_active_locked())) {
  4261. int i;
  4262. if (unlikely(!total_devices))
  4263. {
  4264. const int ypos = devcursor - 1;
  4265. if (ypos < statusy - 1 && wmove(statuswin, ypos, 0) != ERR)
  4266. {
  4267. wattron(statuswin, attr_bad);
  4268. bfg_waddstr(statuswin, "NO DEVICES FOUND: Press 'M' and '+' to add");
  4269. wclrtoeol(statuswin);
  4270. wattroff(statuswin, attr_bad);
  4271. }
  4272. }
  4273. for (i = 0; i < total_devices; i++)
  4274. curses_print_devstatus(get_devices(i));
  4275. touchwin(statuswin);
  4276. wrefresh(statuswin);
  4277. if (!already_have_lock)
  4278. unlock_curses();
  4279. }
  4280. }
  4281. #define refresh_devstatus() _refresh_devstatus(false)
  4282. #endif
  4283. static void print_status(int thr_id)
  4284. {
  4285. if (!curses_active)
  4286. text_print_status(thr_id);
  4287. }
  4288. #ifdef HAVE_CURSES
  4289. static
  4290. bool set_statusy(int maxy)
  4291. {
  4292. if (loginput_size)
  4293. {
  4294. maxy -= loginput_size;
  4295. if (maxy < 0)
  4296. maxy = 0;
  4297. }
  4298. if (logstart < maxy)
  4299. maxy = logstart;
  4300. if (statusy == maxy)
  4301. return false;
  4302. statusy = maxy;
  4303. logcursor = statusy;
  4304. return true;
  4305. }
  4306. /* Check for window resize. Called with curses mutex locked */
  4307. static inline void change_logwinsize(void)
  4308. {
  4309. int x, y, logx, logy;
  4310. getmaxyx(mainwin, y, x);
  4311. if (x < 80 || y < 25)
  4312. return;
  4313. if (y > statusy + 2 && statusy < logstart) {
  4314. set_statusy(y - 2);
  4315. mvwin(logwin, logcursor, 0);
  4316. bfg_wresize(statuswin, statusy, x);
  4317. }
  4318. y -= logcursor;
  4319. getmaxyx(logwin, logy, logx);
  4320. /* Detect screen size change */
  4321. if (x != logx || y != logy)
  4322. bfg_wresize(logwin, y, x);
  4323. }
  4324. static void check_winsizes(void)
  4325. {
  4326. if (!use_curses)
  4327. return;
  4328. if (curses_active_locked()) {
  4329. int y, x;
  4330. x = getmaxx(statuswin);
  4331. if (set_statusy(LINES - 2))
  4332. {
  4333. erase();
  4334. bfg_wresize(statuswin, statusy, x);
  4335. getmaxyx(mainwin, y, x);
  4336. y -= logcursor;
  4337. bfg_wresize(logwin, y, x);
  4338. mvwin(logwin, logcursor, 0);
  4339. }
  4340. unlock_curses();
  4341. }
  4342. }
  4343. static int device_line_id_count;
  4344. static void switch_logsize(void)
  4345. {
  4346. if (curses_active_locked()) {
  4347. if (opt_compact) {
  4348. logstart = devcursor - 1;
  4349. logcursor = logstart + 1;
  4350. } else {
  4351. total_lines = (opt_show_procs ? total_devices : device_line_id_count) ?: 1;
  4352. logstart = devcursor + total_lines;
  4353. logcursor = logstart;
  4354. }
  4355. unlock_curses();
  4356. }
  4357. check_winsizes();
  4358. update_block_display();
  4359. }
  4360. /* For mandatory printing when mutex is already locked */
  4361. void _wlog(const char *str)
  4362. {
  4363. static bool newline;
  4364. size_t end = strlen(str) - 1;
  4365. if (newline)
  4366. bfg_waddstr(logwin, "\n");
  4367. if (str[end] == '\n')
  4368. {
  4369. char *s;
  4370. newline = true;
  4371. s = alloca(end + 1);
  4372. memcpy(s, str, end);
  4373. s[end] = '\0';
  4374. str = s;
  4375. }
  4376. else
  4377. newline = false;
  4378. bfg_waddstr(logwin, str);
  4379. }
  4380. /* Mandatory printing */
  4381. void _wlogprint(const char *str)
  4382. {
  4383. if (curses_active_locked()) {
  4384. _wlog(str);
  4385. unlock_curses();
  4386. }
  4387. }
  4388. #endif
  4389. #ifdef HAVE_CURSES
  4390. bool _log_curses_only(int prio, const char *datetime, const char *str)
  4391. {
  4392. bool high_prio;
  4393. high_prio = (prio == LOG_WARNING || prio == LOG_ERR);
  4394. if (curses_active)
  4395. {
  4396. if (!loginput_size || high_prio) {
  4397. wlog(" %s %s\n", datetime, str);
  4398. if (high_prio) {
  4399. touchwin(logwin);
  4400. wrefresh(logwin);
  4401. }
  4402. }
  4403. return true;
  4404. }
  4405. return false;
  4406. }
  4407. void clear_logwin(void)
  4408. {
  4409. if (curses_active_locked()) {
  4410. wclear(logwin);
  4411. unlock_curses();
  4412. }
  4413. }
  4414. void logwin_update(void)
  4415. {
  4416. if (curses_active_locked()) {
  4417. touchwin(logwin);
  4418. wrefresh(logwin);
  4419. unlock_curses();
  4420. }
  4421. }
  4422. #endif
  4423. void enable_pool(struct pool * const pool)
  4424. {
  4425. if (pool->enabled != POOL_ENABLED) {
  4426. mutex_lock(&lp_lock);
  4427. enabled_pools++;
  4428. pool->enabled = POOL_ENABLED;
  4429. pthread_cond_broadcast(&lp_cond);
  4430. mutex_unlock(&lp_lock);
  4431. if (pool->prio < current_pool()->prio)
  4432. switch_pools(pool);
  4433. }
  4434. }
  4435. void manual_enable_pool(struct pool * const pool)
  4436. {
  4437. pool->failover_only = false;
  4438. BFGINIT(pool->quota, 1);
  4439. enable_pool(pool);
  4440. }
  4441. void disable_pool(struct pool * const pool, const enum pool_enable enable_status)
  4442. {
  4443. if (pool->enabled == POOL_DISABLED)
  4444. /* had been manually disabled before */
  4445. return;
  4446. if (pool->enabled != POOL_ENABLED)
  4447. {
  4448. /* has been programmatically disabled already, just change to the new status directly */
  4449. pool->enabled = enable_status;
  4450. return;
  4451. }
  4452. /* Fall into the lock area */
  4453. mutex_lock(&lp_lock);
  4454. --enabled_pools;
  4455. pool->enabled = enable_status;
  4456. mutex_unlock(&lp_lock);
  4457. if (pool == current_pool())
  4458. switch_pools(NULL);
  4459. }
  4460. static
  4461. void share_result_msg(const struct work *work, const char *disp, const char *reason, bool resubmit, const char *worktime) {
  4462. struct cgpu_info *cgpu;
  4463. const struct mining_algorithm * const malgo = work_mining_algorithm(work);
  4464. const unsigned char *hashpart = &work->hash[0x1c - malgo->ui_skip_hash_bytes];
  4465. char shrdiffdisp[ALLOC_H2B_SHORTV];
  4466. const double tgtdiff = work->work_difficulty;
  4467. char tgtdiffdisp[ALLOC_H2B_SHORTV];
  4468. char where[20];
  4469. cgpu = get_thr_cgpu(work->thr_id);
  4470. suffix_string(work->share_diff, shrdiffdisp, sizeof(shrdiffdisp), 0);
  4471. suffix_string(tgtdiff, tgtdiffdisp, sizeof(tgtdiffdisp), 0);
  4472. if (total_pools > 1)
  4473. snprintf(where, sizeof(where), " pool %d", work->pool->pool_no);
  4474. else
  4475. where[0] = '\0';
  4476. applog(LOG_NOTICE, "%s %02x%02x%02x%02x %"PRIprepr"%s Diff %s/%s%s %s%s",
  4477. disp,
  4478. (unsigned)hashpart[3], (unsigned)hashpart[2], (unsigned)hashpart[1], (unsigned)hashpart[0],
  4479. cgpu->proc_repr,
  4480. where,
  4481. shrdiffdisp, tgtdiffdisp,
  4482. reason,
  4483. resubmit ? "(resubmit)" : "",
  4484. worktime
  4485. );
  4486. }
  4487. static bool test_work_current(struct work *);
  4488. static void _submit_work_async(struct work *);
  4489. static
  4490. void maybe_local_submit(const struct work *work)
  4491. {
  4492. #if BLKMAKER_VERSION > 3
  4493. if (unlikely(work->block && work->tr))
  4494. {
  4495. // This is a block with a full template (GBT)
  4496. // Regardless of the result, submit to local bitcoind(s) as well
  4497. struct work *work_cp;
  4498. for (int i = 0; i < total_pools; ++i)
  4499. {
  4500. if (!uri_get_param_bool(pools[i]->rpc_url, "allblocks", false))
  4501. continue;
  4502. applog(LOG_DEBUG, "Attempting submission of full block to pool %d", pools[i]->pool_no);
  4503. work_cp = copy_work(work);
  4504. work_cp->pool = pools[i];
  4505. work_cp->do_foreign_submit = true;
  4506. _submit_work_async(work_cp);
  4507. }
  4508. }
  4509. #endif
  4510. }
  4511. static
  4512. json_t *extract_reject_reason_j(json_t * const val, json_t *res, json_t * const err, const struct work * const work)
  4513. {
  4514. if (json_is_string(res))
  4515. return res;
  4516. if ( (res = json_object_get(val, "reject-reason")) )
  4517. return res;
  4518. if (work->stratum && err && json_is_array(err) && json_array_size(err) >= 2 && (res = json_array_get(err, 1)) && json_is_string(res))
  4519. return res;
  4520. return NULL;
  4521. }
  4522. static
  4523. const char *extract_reject_reason(json_t * const val, json_t *res, json_t * const err, const struct work * const work)
  4524. {
  4525. json_t * const j = extract_reject_reason_j(val, res, err, work);
  4526. return j ? json_string_value(j) : NULL;
  4527. }
  4528. static
  4529. int put_in_parens(char * const buf, const size_t bufsz, const char * const s)
  4530. {
  4531. if (!s)
  4532. {
  4533. if (bufsz)
  4534. buf[0] = '\0';
  4535. return 0;
  4536. }
  4537. int p = snprintf(buf, bufsz, " (%s", s);
  4538. if (p >= bufsz - 1)
  4539. p = bufsz - 2;
  4540. strcpy(&buf[p], ")");
  4541. return p + 1;
  4542. }
  4543. /* Theoretically threads could race when modifying accepted and
  4544. * rejected values but the chance of two submits completing at the
  4545. * same time is zero so there is no point adding extra locking */
  4546. static void
  4547. share_result(json_t *val, json_t *res, json_t *err, const struct work *work,
  4548. /*char *hashshow,*/ bool resubmit, char *worktime)
  4549. {
  4550. struct pool *pool = work->pool;
  4551. struct cgpu_info *cgpu;
  4552. cgpu = get_thr_cgpu(work->thr_id);
  4553. if ((json_is_null(err) || !err) && (json_is_null(res) || json_is_true(res))) {
  4554. struct mining_goal_info * const goal = pool->goal;
  4555. mutex_lock(&stats_lock);
  4556. cgpu->accepted++;
  4557. total_accepted++;
  4558. pool->accepted++;
  4559. cgpu->diff_accepted += work->work_difficulty;
  4560. total_diff_accepted += work->work_difficulty;
  4561. pool->diff_accepted += work->work_difficulty;
  4562. goal->diff_accepted += work->work_difficulty;
  4563. mutex_unlock(&stats_lock);
  4564. pool->seq_rejects = 0;
  4565. cgpu->last_share_pool = pool->pool_no;
  4566. cgpu->last_share_pool_time = time(NULL);
  4567. cgpu->last_share_diff = work->work_difficulty;
  4568. pool->last_share_time = cgpu->last_share_pool_time;
  4569. pool->last_share_diff = work->work_difficulty;
  4570. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  4571. if (!QUIET) {
  4572. share_result_msg(work, "Accepted", "", resubmit, worktime);
  4573. }
  4574. sharelog("accept", work);
  4575. if (opt_shares && total_diff_accepted >= opt_shares) {
  4576. applog(LOG_WARNING, "Successfully mined %g accepted shares as requested and exiting.", opt_shares);
  4577. kill_work();
  4578. return;
  4579. }
  4580. /* Detect if a pool that has been temporarily disabled for
  4581. * continually rejecting shares has started accepting shares.
  4582. * This will only happen with the work returned from a
  4583. * longpoll */
  4584. if (unlikely(pool->enabled == POOL_REJECTING)) {
  4585. applog(LOG_WARNING, "Rejecting pool %d now accepting shares, re-enabling!", pool->pool_no);
  4586. enable_pool(pool);
  4587. }
  4588. if (unlikely(work->block)) {
  4589. // Force moving on to this new block :)
  4590. struct work fakework;
  4591. memset(&fakework, 0, sizeof(fakework));
  4592. fakework.pool = work->pool;
  4593. // Copy block version, bits, and time from share
  4594. memcpy(&fakework.data[ 0], &work->data[ 0], 4);
  4595. memcpy(&fakework.data[68], &work->data[68], 8);
  4596. // Set prevblock to winning hash (swap32'd)
  4597. swap32yes(&fakework.data[4], &work->hash[0], 32 / 4);
  4598. test_work_current(&fakework);
  4599. }
  4600. }
  4601. else
  4602. if (!hash_target_check(work->hash, work->target))
  4603. {
  4604. // This was submitted despite failing the proper target
  4605. // Quietly ignore the reject
  4606. char reason[32];
  4607. put_in_parens(reason, sizeof(reason), extract_reject_reason(val, res, err, work));
  4608. applog(LOG_DEBUG, "Share above target rejected%s by pool %u as expected, ignoring", reason, pool->pool_no);
  4609. } else {
  4610. mutex_lock(&stats_lock);
  4611. cgpu->rejected++;
  4612. total_rejected++;
  4613. pool->rejected++;
  4614. cgpu->diff_rejected += work->work_difficulty;
  4615. total_diff_rejected += work->work_difficulty;
  4616. pool->diff_rejected += work->work_difficulty;
  4617. pool->seq_rejects++;
  4618. mutex_unlock(&stats_lock);
  4619. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  4620. if (!QUIET) {
  4621. char disposition[36] = "reject";
  4622. char reason[32];
  4623. const char *reasontmp = extract_reject_reason(val, res, err, work);
  4624. int n = put_in_parens(reason, sizeof(reason), reasontmp);
  4625. if (reason[0])
  4626. snprintf(&disposition[6], sizeof(disposition) - 6, ":%.*s", n - 3, &reason[2]);
  4627. share_result_msg(work, "Rejected", reason, resubmit, worktime);
  4628. sharelog(disposition, work);
  4629. }
  4630. /* Once we have more than a nominal amount of sequential rejects,
  4631. * at least 10 and more than 3 mins at the current utility,
  4632. * disable the pool because some pool error is likely to have
  4633. * ensued. Do not do this if we know the share just happened to
  4634. * be stale due to networking delays.
  4635. */
  4636. if (pool->seq_rejects > 10 && !work->stale && opt_disable_pool && enabled_pools > 1) {
  4637. double utility = total_accepted / total_secs * 60;
  4638. if (pool->seq_rejects > utility * 3) {
  4639. applog(LOG_WARNING, "Pool %d rejected %d sequential shares, disabling!",
  4640. pool->pool_no, pool->seq_rejects);
  4641. disable_pool(pool, POOL_REJECTING);
  4642. pool->seq_rejects = 0;
  4643. }
  4644. }
  4645. }
  4646. maybe_local_submit(work);
  4647. }
  4648. static char *submit_upstream_work_request(struct work *work)
  4649. {
  4650. char *hexstr = NULL;
  4651. char *s, *sd;
  4652. struct pool *pool = work->pool;
  4653. if (work->tr)
  4654. {
  4655. blktemplate_t * const tmpl = work->tr->tmpl;
  4656. json_t *req;
  4657. unsigned char data[80];
  4658. swap32yes(data, work->data, 80 / 4);
  4659. #if BLKMAKER_VERSION > 3
  4660. if (work->do_foreign_submit)
  4661. req = blkmk_submit_foreign_jansson(tmpl, data, work->dataid, le32toh(*((uint32_t*)&work->data[76])));
  4662. else
  4663. #endif
  4664. req = blkmk_submit_jansson(tmpl, data, work->dataid, le32toh(*((uint32_t*)&work->data[76])));
  4665. s = json_dumps(req, 0);
  4666. json_decref(req);
  4667. sd = malloc(161);
  4668. bin2hex(sd, data, 80);
  4669. } else {
  4670. /* build hex string */
  4671. hexstr = malloc((sizeof(work->data) * 2) + 1);
  4672. bin2hex(hexstr, work->data, sizeof(work->data));
  4673. /* build JSON-RPC request */
  4674. s = strdup("{\"method\": \"getwork\", \"params\": [ \"");
  4675. s = realloc_strcat(s, hexstr);
  4676. s = realloc_strcat(s, "\" ], \"id\":1}");
  4677. free(hexstr);
  4678. sd = s;
  4679. }
  4680. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->rpc_url, sd);
  4681. if (work->tr)
  4682. free(sd);
  4683. else
  4684. s = realloc_strcat(s, "\n");
  4685. return s;
  4686. }
  4687. static bool submit_upstream_work_completed(struct work *work, bool resubmit, struct timeval *ptv_submit, json_t *val) {
  4688. json_t *res, *err;
  4689. bool rc = false;
  4690. int thr_id = work->thr_id;
  4691. struct pool *pool = work->pool;
  4692. struct timeval tv_submit_reply;
  4693. time_t ts_submit_reply;
  4694. char worktime[200] = "";
  4695. cgtime(&tv_submit_reply);
  4696. ts_submit_reply = time(NULL);
  4697. if (unlikely(!val)) {
  4698. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  4699. if (!pool_tset(pool, &pool->submit_fail)) {
  4700. total_ro++;
  4701. pool->remotefail_occasions++;
  4702. applog(LOG_WARNING, "Pool %d communication failure, caching submissions", pool->pool_no);
  4703. }
  4704. goto out;
  4705. } else if (pool_tclear(pool, &pool->submit_fail))
  4706. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  4707. res = json_object_get(val, "result");
  4708. err = json_object_get(val, "error");
  4709. if (!QUIET) {
  4710. if (opt_worktime) {
  4711. char workclone[20];
  4712. struct tm _tm;
  4713. struct tm *tm, tm_getwork, tm_submit_reply;
  4714. tm = &_tm;
  4715. double getwork_time = tdiff((struct timeval *)&(work->tv_getwork_reply),
  4716. (struct timeval *)&(work->tv_getwork));
  4717. double getwork_to_work = tdiff((struct timeval *)&(work->tv_work_start),
  4718. (struct timeval *)&(work->tv_getwork_reply));
  4719. double work_time = tdiff((struct timeval *)&(work->tv_work_found),
  4720. (struct timeval *)&(work->tv_work_start));
  4721. double work_to_submit = tdiff(ptv_submit,
  4722. (struct timeval *)&(work->tv_work_found));
  4723. double submit_time = tdiff(&tv_submit_reply, ptv_submit);
  4724. int diffplaces = 3;
  4725. localtime_r(&work->ts_getwork, tm);
  4726. memcpy(&tm_getwork, tm, sizeof(struct tm));
  4727. localtime_r(&ts_submit_reply, tm);
  4728. memcpy(&tm_submit_reply, tm, sizeof(struct tm));
  4729. if (work->clone) {
  4730. snprintf(workclone, sizeof(workclone), "C:%1.3f",
  4731. tdiff((struct timeval *)&(work->tv_cloned),
  4732. (struct timeval *)&(work->tv_getwork_reply)));
  4733. }
  4734. else
  4735. strcpy(workclone, "O");
  4736. if (work->work_difficulty < 1)
  4737. diffplaces = 6;
  4738. const struct mining_algorithm * const malgo = work_mining_algorithm(work);
  4739. const uint8_t * const prevblkhash = &work->data[4];
  4740. snprintf(worktime, sizeof(worktime),
  4741. " <-%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",
  4742. (unsigned long)be32toh(((uint32_t *)prevblkhash)[7 - malgo->worktime_skip_prevblk_u32]),
  4743. (unsigned long)be32toh(((uint32_t *)prevblkhash)[6 - malgo->worktime_skip_prevblk_u32]),
  4744. work->getwork_mode, diffplaces, work->work_difficulty,
  4745. tm_getwork.tm_hour, tm_getwork.tm_min,
  4746. tm_getwork.tm_sec, getwork_time, workclone,
  4747. getwork_to_work, work_time, work_to_submit, submit_time,
  4748. tm_submit_reply.tm_hour, tm_submit_reply.tm_min,
  4749. tm_submit_reply.tm_sec);
  4750. }
  4751. }
  4752. share_result(val, res, err, work, resubmit, worktime);
  4753. if (!opt_realquiet)
  4754. print_status(thr_id);
  4755. if (!want_per_device_stats) {
  4756. char logline[256];
  4757. struct cgpu_info *cgpu;
  4758. cgpu = get_thr_cgpu(thr_id);
  4759. get_statline(logline, sizeof(logline), cgpu);
  4760. applog(LOG_INFO, "%s", logline);
  4761. }
  4762. json_decref(val);
  4763. rc = true;
  4764. out:
  4765. return rc;
  4766. }
  4767. /* Specifies whether we can use this pool for work or not. */
  4768. static bool pool_unworkable(const struct pool * const pool)
  4769. {
  4770. if (pool->idle)
  4771. return true;
  4772. if (pool->enabled != POOL_ENABLED)
  4773. return true;
  4774. if (pool->has_stratum && !pool->stratum_active)
  4775. return true;
  4776. return false;
  4777. }
  4778. static struct pool *priority_pool(int);
  4779. static bool pool_unusable(struct pool *);
  4780. static
  4781. bool pool_actively_desired(const struct pool * const pool, const struct pool *cp)
  4782. {
  4783. if (pool->enabled != POOL_ENABLED)
  4784. return false;
  4785. if (pool_strategy == POOL_LOADBALANCE && pool->quota)
  4786. return true;
  4787. if (pool_strategy == POOL_BALANCE && !pool->failover_only)
  4788. return true;
  4789. if (!cp)
  4790. cp = current_pool();
  4791. if (pool == cp)
  4792. return true;
  4793. // If we are the highest priority, workable pool for a given algorithm, we are needed
  4794. struct mining_algorithm * const malgo = pool->goal->malgo;
  4795. for (int i = 0; i < total_pools; ++i)
  4796. {
  4797. struct pool * const other_pool = priority_pool(i);
  4798. if (other_pool == pool)
  4799. return true;
  4800. if (pool_unusable(other_pool))
  4801. continue;
  4802. if (other_pool->goal->malgo == malgo)
  4803. break;
  4804. }
  4805. return false;
  4806. }
  4807. static
  4808. bool pool_actively_in_use(const struct pool * const pool, const struct pool *cp)
  4809. {
  4810. return (!pool_unworkable(pool)) && pool_actively_desired(pool, cp);
  4811. }
  4812. static
  4813. bool pool_supports_block_change_notification(struct pool * const pool)
  4814. {
  4815. return pool->has_stratum || pool->lp_url;
  4816. }
  4817. static
  4818. bool pool_has_active_block_change_notification(struct pool * const pool)
  4819. {
  4820. return pool->stratum_active || pool->lp_active;
  4821. }
  4822. static struct pool *_select_longpoll_pool(struct pool *, bool(*)(struct pool *));
  4823. #define select_longpoll_pool(pool) _select_longpoll_pool(pool, pool_supports_block_change_notification)
  4824. #define pool_active_lp_pool(pool) _select_longpoll_pool(pool, pool_has_active_block_change_notification)
  4825. /* In balanced mode, the amount of diff1 solutions per pool is monitored as a
  4826. * rolling average per 10 minutes and if pools start getting more, it biases
  4827. * away from them to distribute work evenly. The share count is reset to the
  4828. * rolling average every 10 minutes to not send all work to one pool after it
  4829. * has been disabled/out for an extended period. */
  4830. static
  4831. struct pool *select_balanced(struct pool *cp, struct mining_algorithm * const malgo)
  4832. {
  4833. int i, lowest = cp->shares;
  4834. struct pool *ret = cp, *failover_pool = NULL;
  4835. for (i = 0; i < total_pools; i++) {
  4836. struct pool *pool = pools[i];
  4837. if (malgo && pool->goal->malgo != malgo)
  4838. continue;
  4839. if (pool_unworkable(pool))
  4840. continue;
  4841. if (pool->failover_only)
  4842. {
  4843. BFGINIT(failover_pool, pool);
  4844. continue;
  4845. }
  4846. if (pool->shares < lowest) {
  4847. lowest = pool->shares;
  4848. ret = pool;
  4849. }
  4850. }
  4851. if (malgo && ret->goal->malgo != malgo)
  4852. // Yes, we want failover_pool even if it's NULL
  4853. ret = failover_pool;
  4854. else
  4855. if (pool_unworkable(ret) && failover_pool)
  4856. ret = failover_pool;
  4857. if (ret)
  4858. ++ret->shares;
  4859. return ret;
  4860. }
  4861. static
  4862. struct pool *select_loadbalance(struct mining_algorithm * const malgo)
  4863. {
  4864. static int rotating_pool = 0;
  4865. struct pool *pool;
  4866. bool avail = false;
  4867. int tested, i, rpsave;
  4868. for (i = 0; i < total_pools; i++) {
  4869. struct pool *tp = pools[i];
  4870. if (tp->quota_used < tp->quota_gcd) {
  4871. avail = true;
  4872. break;
  4873. }
  4874. }
  4875. /* There are no pools with quota, so reset them. */
  4876. if (!avail) {
  4877. for (i = 0; i < total_pools; i++)
  4878. {
  4879. struct pool * const tp = pools[i];
  4880. tp->quota_used -= tp->quota_gcd;
  4881. }
  4882. if (++rotating_pool >= total_pools)
  4883. rotating_pool = 0;
  4884. }
  4885. /* Try to find the first pool in the rotation that is usable */
  4886. // Look for the lowest integer quota_used / quota_gcd in case we are imbalanced by algorithm demands
  4887. struct pool *pool_lowest = NULL;
  4888. int lowest = INT_MAX;
  4889. rpsave = rotating_pool;
  4890. for (tested = 0; tested < total_pools; ++tested)
  4891. {
  4892. pool = pools[rotating_pool];
  4893. if (malgo && pool->goal->malgo != malgo)
  4894. goto continue_tested;
  4895. if (pool->quota_used < pool->quota_gcd)
  4896. {
  4897. ++pool->quota_used;
  4898. if (!pool_unworkable(pool))
  4899. goto out;
  4900. /* Failover-only flag for load-balance means distribute
  4901. * unused quota to priority pool 0. */
  4902. if (opt_fail_only)
  4903. priority_pool(0)->quota_used--;
  4904. }
  4905. if (malgo)
  4906. {
  4907. const int count = pool->quota_used / pool->quota_gcd;
  4908. if (count < lowest)
  4909. {
  4910. pool_lowest = pool;
  4911. lowest = count;
  4912. }
  4913. }
  4914. continue_tested: ;
  4915. if (++rotating_pool >= total_pools)
  4916. rotating_pool = 0;
  4917. }
  4918. // Even if pool_lowest is NULL, we want to return that to indicate failure
  4919. // Note it isn't possible to get here if !malgo
  4920. pool = pool_lowest;
  4921. out: ;
  4922. // Restore rotating_pool static, so malgo searches don't affect the usual load balancing
  4923. if (malgo)
  4924. rotating_pool = rpsave;
  4925. return pool;
  4926. }
  4927. static
  4928. struct pool *select_failover(struct mining_algorithm * const malgo)
  4929. {
  4930. int i;
  4931. for (i = 0; i < total_pools; i++) {
  4932. struct pool *tp = priority_pool(i);
  4933. if (malgo && tp->goal->malgo != malgo)
  4934. continue;
  4935. if (!pool_unusable(tp)) {
  4936. return tp;
  4937. }
  4938. }
  4939. return NULL;
  4940. }
  4941. static bool pool_active(struct pool *, bool pinging);
  4942. static void pool_died(struct pool *);
  4943. /* Select any active pool in a rotating fashion when loadbalance is chosen if
  4944. * it has any quota left. */
  4945. static inline struct pool *select_pool(bool lagging, struct mining_algorithm * const malgo)
  4946. {
  4947. struct pool *pool = NULL, *cp;
  4948. retry:
  4949. cp = current_pool();
  4950. if (pool_strategy == POOL_BALANCE) {
  4951. pool = select_balanced(cp, malgo);
  4952. if ((!pool) || pool_unworkable(pool))
  4953. goto simple_failover;
  4954. goto out;
  4955. }
  4956. if (pool_strategy != POOL_LOADBALANCE && (!lagging || opt_fail_only)) {
  4957. if (malgo && cp->goal->malgo != malgo)
  4958. goto simple_failover;
  4959. pool = cp;
  4960. goto out;
  4961. } else
  4962. pool = select_loadbalance(malgo);
  4963. simple_failover:
  4964. /* If there are no alive pools with quota, choose according to
  4965. * priority. */
  4966. if (!pool) {
  4967. pool = select_failover(malgo);
  4968. }
  4969. /* If still nothing is usable, use the current pool */
  4970. if (!pool)
  4971. {
  4972. if (malgo && cp->goal->malgo != malgo)
  4973. {
  4974. applog(LOG_DEBUG, "Failed to select pool for specific mining algorithm '%s'", malgo->name);
  4975. return NULL;
  4976. }
  4977. pool = cp;
  4978. }
  4979. out:
  4980. if (!pool_actively_in_use(pool, cp))
  4981. {
  4982. if (!pool_active(pool, false))
  4983. {
  4984. pool_died(pool);
  4985. goto retry;
  4986. }
  4987. pool_tclear(pool, &pool->idle);
  4988. }
  4989. applog(LOG_DEBUG, "Selecting pool %d for %s%swork", pool->pool_no, malgo ? malgo->name : "", malgo ? " " : "");
  4990. return pool;
  4991. }
  4992. static double DIFFEXACTONE = 26959946667150639794667015087019630673637144422540572481103610249215.0;
  4993. double target_diff(const unsigned char *target)
  4994. {
  4995. double targ = 0;
  4996. signed int i;
  4997. for (i = 31; i >= 0; --i)
  4998. targ = (targ * 0x100) + target[i];
  4999. return DIFFEXACTONE / (targ ?: 1);
  5000. }
  5001. /*
  5002. * Calculate the work share difficulty
  5003. */
  5004. static void calc_diff(struct work *work, int known)
  5005. {
  5006. struct cgminer_pool_stats *pool_stats = &(work->pool->cgminer_pool_stats);
  5007. double difficulty;
  5008. if (!known) {
  5009. work->work_difficulty = target_diff(work->target);
  5010. } else
  5011. work->work_difficulty = known;
  5012. difficulty = work->work_difficulty;
  5013. pool_stats->last_diff = difficulty;
  5014. suffix_string(difficulty, work->pool->diff, sizeof(work->pool->diff), 0);
  5015. if (difficulty == pool_stats->min_diff)
  5016. pool_stats->min_diff_count++;
  5017. else if (difficulty < pool_stats->min_diff || pool_stats->min_diff == 0) {
  5018. pool_stats->min_diff = difficulty;
  5019. pool_stats->min_diff_count = 1;
  5020. }
  5021. if (difficulty == pool_stats->max_diff)
  5022. pool_stats->max_diff_count++;
  5023. else if (difficulty > pool_stats->max_diff) {
  5024. pool_stats->max_diff = difficulty;
  5025. pool_stats->max_diff_count = 1;
  5026. }
  5027. }
  5028. static void gen_stratum_work(struct pool *, struct work *);
  5029. static void pool_update_work_restart_time(struct pool *);
  5030. static void restart_threads(void);
  5031. static uint32_t benchmark_blkhdr[20];
  5032. static const int benchmark_update_interval = 1;
  5033. static
  5034. void *benchmark_intense_work_update_thread(void *userp)
  5035. {
  5036. pthread_detach(pthread_self());
  5037. RenameThread("benchmark-intense");
  5038. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  5039. struct pool * const pool = userp;
  5040. struct stratum_work * const swork = &pool->swork;
  5041. uint8_t * const blkhdr = swork->header1;
  5042. while (true)
  5043. {
  5044. sleep(benchmark_update_interval);
  5045. cg_wlock(&pool->data_lock);
  5046. for (int i = 36; --i >= 0; )
  5047. if (++blkhdr[i])
  5048. break;
  5049. cg_wunlock(&pool->data_lock);
  5050. struct work *work = make_work();
  5051. gen_stratum_work(pool, work);
  5052. pool->swork.work_restart_id = ++pool->work_restart_id;
  5053. pool_update_work_restart_time(pool);
  5054. test_work_current(work);
  5055. free_work(work);
  5056. restart_threads();
  5057. }
  5058. return NULL;
  5059. }
  5060. static
  5061. void setup_benchmark_pool()
  5062. {
  5063. struct pool *pool;
  5064. want_longpoll = false;
  5065. // Temporarily disable opt_benchmark to avoid auto-removal
  5066. opt_benchmark = false;
  5067. pool = add_pool();
  5068. opt_benchmark = true;
  5069. pool->rpc_url = malloc(255);
  5070. strcpy(pool->rpc_url, "Benchmark");
  5071. pool_set_uri(pool, pool->rpc_url);
  5072. pool->rpc_user = pool->rpc_url;
  5073. pool->rpc_pass = pool->rpc_url;
  5074. enable_pool(pool);
  5075. pool->idle = false;
  5076. successful_connect = true;
  5077. {
  5078. uint32_t * const blkhdr = benchmark_blkhdr;
  5079. blkhdr[2] = htobe32(1);
  5080. blkhdr[17] = htobe32(0x7fffffff); // timestamp
  5081. blkhdr[18] = htobe32(0x1700ffff); // "bits"
  5082. }
  5083. {
  5084. struct stratum_work * const swork = &pool->swork;
  5085. const int branchcount = 15; // 1 MB block
  5086. const size_t branchdatasz = branchcount * 0x20;
  5087. const size_t coinbase_sz = (opt_benchmark_intense ? 250 : 6) * 1024;
  5088. bytes_resize(&swork->coinbase, coinbase_sz);
  5089. memset(bytes_buf(&swork->coinbase), '\xff', coinbase_sz);
  5090. swork->nonce2_offset = 0;
  5091. bytes_resize(&swork->merkle_bin, branchdatasz);
  5092. memset(bytes_buf(&swork->merkle_bin), '\xff', branchdatasz);
  5093. swork->merkles = branchcount;
  5094. swork->header1[0] = '\xff';
  5095. memset(&swork->header1[1], '\0', 34);
  5096. swork->header1[35] = '\x01';
  5097. swork->ntime = 0x7fffffff;
  5098. timer_unset(&swork->tv_received);
  5099. memcpy(swork->diffbits, "\x17\0\xff\xff", 4);
  5100. const struct mining_goal_info * const goal = get_mining_goal("default");
  5101. const struct mining_algorithm * const malgo = goal->malgo;
  5102. set_target_to_pdiff(swork->target, malgo->reasonable_low_nonce_diff);
  5103. pool->nonce2sz = swork->n2size = GBT_XNONCESZ;
  5104. pool->nonce2 = 0;
  5105. }
  5106. if (opt_benchmark_intense)
  5107. {
  5108. pthread_t pth;
  5109. if (unlikely(pthread_create(&pth, NULL, benchmark_intense_work_update_thread, pool)))
  5110. applog(LOG_WARNING, "Failed to start benchmark intense work update thread");
  5111. }
  5112. }
  5113. void get_benchmark_work(struct work *work, bool use_swork)
  5114. {
  5115. if (use_swork)
  5116. {
  5117. struct timeval tv_now;
  5118. timer_set_now(&tv_now);
  5119. gen_stratum_work(pools[0], work);
  5120. work->getwork_mode = GETWORK_MODE_BENCHMARK;
  5121. work_set_simple_ntime_roll_limit(work, 0, &tv_now);
  5122. return;
  5123. }
  5124. struct pool * const pool = pools[0];
  5125. uint32_t * const blkhdr = benchmark_blkhdr;
  5126. for (int i = 16; i >= 0; --i)
  5127. if (++blkhdr[i])
  5128. break;
  5129. memcpy(&work->data[ 0], blkhdr, 80);
  5130. memcpy(&work->data[80], workpadding_bin, 48);
  5131. char hex[161];
  5132. bin2hex(hex, work->data, 80);
  5133. applog(LOG_DEBUG, "Generated benchmark header %s", hex);
  5134. calc_midstate(work);
  5135. memcpy(work->target, pool->swork.target, sizeof(work->target));
  5136. work->mandatory = true;
  5137. work->pool = pools[0];
  5138. cgtime(&work->tv_getwork);
  5139. copy_time(&work->tv_getwork_reply, &work->tv_getwork);
  5140. copy_time(&work->tv_staged, &work->tv_getwork);
  5141. work->getwork_mode = GETWORK_MODE_BENCHMARK;
  5142. calc_diff(work, 0);
  5143. work_set_simple_ntime_roll_limit(work, 60, &work->tv_getwork);
  5144. }
  5145. static void wake_gws(void);
  5146. static void update_last_work(struct work *work)
  5147. {
  5148. if (!work->tr)
  5149. // Only save GBT jobs, since rollntime isn't coordinated well yet
  5150. return;
  5151. struct pool *pool = work->pool;
  5152. mutex_lock(&pool->last_work_lock);
  5153. if (pool->last_work_copy)
  5154. free_work(pool->last_work_copy);
  5155. pool->last_work_copy = copy_work(work);
  5156. pool->last_work_copy->work_restart_id = pool->work_restart_id;
  5157. mutex_unlock(&pool->last_work_lock);
  5158. }
  5159. static
  5160. void gbt_req_target(json_t *req)
  5161. {
  5162. json_t *j;
  5163. json_t *n;
  5164. if (!request_target_str)
  5165. return;
  5166. j = json_object_get(req, "params");
  5167. if (!j)
  5168. {
  5169. n = json_array();
  5170. if (!n)
  5171. return;
  5172. if (json_object_set_new(req, "params", n))
  5173. goto erradd;
  5174. j = n;
  5175. }
  5176. n = json_array_get(j, 0);
  5177. if (!n)
  5178. {
  5179. n = json_object();
  5180. if (!n)
  5181. return;
  5182. if (json_array_append_new(j, n))
  5183. goto erradd;
  5184. }
  5185. j = n;
  5186. n = json_string(request_target_str);
  5187. if (!n)
  5188. return;
  5189. if (json_object_set_new(j, "target", n))
  5190. goto erradd;
  5191. return;
  5192. erradd:
  5193. json_decref(n);
  5194. }
  5195. static char *prepare_rpc_req2(struct work *work, enum pool_protocol proto, const char *lpid, bool probe, struct pool * const pool)
  5196. {
  5197. char *rpc_req;
  5198. clean_work(work);
  5199. switch (proto) {
  5200. case PLP_GETWORK:
  5201. work->getwork_mode = GETWORK_MODE_POOL;
  5202. return strdup(getwork_req);
  5203. case PLP_GETBLOCKTEMPLATE:
  5204. work->getwork_mode = GETWORK_MODE_GBT;
  5205. blktemplate_t * const tmpl = blktmpl_create();
  5206. if (!tmpl)
  5207. goto gbtfail2;
  5208. work->tr = tmpl_makeref(tmpl);
  5209. gbt_capabilities_t caps = blktmpl_addcaps(tmpl);
  5210. if (!caps)
  5211. goto gbtfail;
  5212. caps |= GBT_LONGPOLL;
  5213. #if BLKMAKER_VERSION > 1
  5214. const struct mining_goal_info * const goal = pool->goal;
  5215. if (goal->generation_script || goal_has_at_least_one_getcbaddr(goal))
  5216. caps |= GBT_CBVALUE;
  5217. #endif
  5218. json_t *req = blktmpl_request_jansson(caps, lpid);
  5219. if (!req)
  5220. goto gbtfail;
  5221. if (probe)
  5222. gbt_req_target(req);
  5223. rpc_req = json_dumps(req, 0);
  5224. if (!rpc_req)
  5225. goto gbtfail;
  5226. json_decref(req);
  5227. return rpc_req;
  5228. default:
  5229. return NULL;
  5230. }
  5231. return NULL;
  5232. gbtfail:
  5233. tmpl_decref(work->tr);
  5234. work->tr = NULL;
  5235. gbtfail2:
  5236. return NULL;
  5237. }
  5238. #define prepare_rpc_req(work, proto, lpid, pool) prepare_rpc_req2(work, proto, lpid, false, pool)
  5239. #define prepare_rpc_req_probe(work, proto, lpid, pool) prepare_rpc_req2(work, proto, lpid, true, pool)
  5240. static const char *pool_protocol_name(enum pool_protocol proto)
  5241. {
  5242. switch (proto) {
  5243. case PLP_GETBLOCKTEMPLATE:
  5244. return "getblocktemplate";
  5245. case PLP_GETWORK:
  5246. return "getwork";
  5247. default:
  5248. return "UNKNOWN";
  5249. }
  5250. }
  5251. static enum pool_protocol pool_protocol_fallback(enum pool_protocol proto)
  5252. {
  5253. switch (proto) {
  5254. case PLP_GETBLOCKTEMPLATE:
  5255. if (want_getwork)
  5256. return PLP_GETWORK;
  5257. default:
  5258. return PLP_NONE;
  5259. }
  5260. }
  5261. static bool get_upstream_work(struct work *work, CURL *curl)
  5262. {
  5263. struct pool *pool = work->pool;
  5264. struct cgminer_pool_stats *pool_stats = &(pool->cgminer_pool_stats);
  5265. struct timeval tv_elapsed;
  5266. json_t *val = NULL;
  5267. bool rc = false;
  5268. char *url;
  5269. enum pool_protocol proto;
  5270. char *rpc_req;
  5271. if (pool->proto == PLP_NONE)
  5272. pool->proto = PLP_GETBLOCKTEMPLATE;
  5273. tryagain:
  5274. rpc_req = prepare_rpc_req(work, pool->proto, NULL, pool);
  5275. work->pool = pool;
  5276. if (!rpc_req)
  5277. return false;
  5278. applog(LOG_DEBUG, "DBG: sending %s get RPC call: %s", pool->rpc_url, rpc_req);
  5279. url = pool->rpc_url;
  5280. cgtime(&work->tv_getwork);
  5281. val = json_rpc_call(curl, url, pool->rpc_userpass, rpc_req, false,
  5282. false, &work->rolltime, pool, false);
  5283. pool_stats->getwork_attempts++;
  5284. free(rpc_req);
  5285. if (likely(val)) {
  5286. rc = work_decode(pool, work, val);
  5287. if (unlikely(!rc))
  5288. applog(LOG_DEBUG, "Failed to decode work in get_upstream_work");
  5289. } else if (PLP_NONE != (proto = pool_protocol_fallback(pool->proto))) {
  5290. applog(LOG_WARNING, "Pool %u failed getblocktemplate request; falling back to getwork protocol", pool->pool_no);
  5291. pool->proto = proto;
  5292. goto tryagain;
  5293. } else
  5294. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  5295. cgtime(&work->tv_getwork_reply);
  5296. timersub(&(work->tv_getwork_reply), &(work->tv_getwork), &tv_elapsed);
  5297. pool_stats->getwork_wait_rolling += ((double)tv_elapsed.tv_sec + ((double)tv_elapsed.tv_usec / 1000000)) * 0.63;
  5298. pool_stats->getwork_wait_rolling /= 1.63;
  5299. timeradd(&tv_elapsed, &(pool_stats->getwork_wait), &(pool_stats->getwork_wait));
  5300. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_max), >)) {
  5301. pool_stats->getwork_wait_max.tv_sec = tv_elapsed.tv_sec;
  5302. pool_stats->getwork_wait_max.tv_usec = tv_elapsed.tv_usec;
  5303. }
  5304. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_min), <)) {
  5305. pool_stats->getwork_wait_min.tv_sec = tv_elapsed.tv_sec;
  5306. pool_stats->getwork_wait_min.tv_usec = tv_elapsed.tv_usec;
  5307. }
  5308. pool_stats->getwork_calls++;
  5309. work->pool = pool;
  5310. work->longpoll = false;
  5311. calc_diff(work, 0);
  5312. total_getworks++;
  5313. pool->getwork_requested++;
  5314. if (rc)
  5315. update_last_work(work);
  5316. if (likely(val))
  5317. json_decref(val);
  5318. return rc;
  5319. }
  5320. #ifdef HAVE_CURSES
  5321. static void disable_curses(void)
  5322. {
  5323. if (curses_active_locked()) {
  5324. use_curses = false;
  5325. curses_active = false;
  5326. leaveok(logwin, false);
  5327. leaveok(statuswin, false);
  5328. leaveok(mainwin, false);
  5329. nocbreak();
  5330. echo();
  5331. delwin(logwin);
  5332. delwin(statuswin);
  5333. delwin(mainwin);
  5334. endwin();
  5335. #ifdef WIN32
  5336. // Move the cursor to after curses output.
  5337. HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
  5338. CONSOLE_SCREEN_BUFFER_INFO csbi;
  5339. COORD coord;
  5340. if (GetConsoleScreenBufferInfo(hout, &csbi)) {
  5341. coord.X = 0;
  5342. coord.Y = csbi.dwSize.Y - 1;
  5343. SetConsoleCursorPosition(hout, coord);
  5344. }
  5345. #endif
  5346. unlock_curses();
  5347. }
  5348. }
  5349. #endif
  5350. static void __kill_work(void)
  5351. {
  5352. struct cgpu_info *cgpu;
  5353. struct thr_info *thr;
  5354. int i;
  5355. if (!successful_connect)
  5356. return;
  5357. applog(LOG_INFO, "Received kill message");
  5358. shutting_down = true;
  5359. applog(LOG_DEBUG, "Prompting submit_work thread to finish");
  5360. notifier_wake(submit_waiting_notifier);
  5361. #ifdef USE_LIBMICROHTTPD
  5362. httpsrv_stop();
  5363. #endif
  5364. applog(LOG_DEBUG, "Killing off watchpool thread");
  5365. /* Kill the watchpool thread */
  5366. thr = &control_thr[watchpool_thr_id];
  5367. thr_info_cancel(thr);
  5368. applog(LOG_DEBUG, "Killing off watchdog thread");
  5369. /* Kill the watchdog thread */
  5370. thr = &control_thr[watchdog_thr_id];
  5371. thr_info_cancel(thr);
  5372. applog(LOG_DEBUG, "Shutting down mining threads");
  5373. for (i = 0; i < mining_threads; i++) {
  5374. thr = get_thread(i);
  5375. if (!thr)
  5376. continue;
  5377. cgpu = thr->cgpu;
  5378. if (!cgpu)
  5379. continue;
  5380. if (!cgpu->threads)
  5381. continue;
  5382. cgpu->shutdown = true;
  5383. thr->work_restart = true;
  5384. notifier_wake(thr->notifier);
  5385. notifier_wake(thr->work_restart_notifier);
  5386. }
  5387. sleep(1);
  5388. applog(LOG_DEBUG, "Killing off mining threads");
  5389. /* Kill the mining threads*/
  5390. for (i = 0; i < mining_threads; i++) {
  5391. thr = get_thread(i);
  5392. if (!thr)
  5393. continue;
  5394. cgpu = thr->cgpu;
  5395. if (cgpu->threads)
  5396. {
  5397. applog(LOG_WARNING, "Killing %"PRIpreprv, thr->cgpu->proc_repr);
  5398. thr_info_cancel(thr);
  5399. }
  5400. cgpu->status = LIFE_DEAD2;
  5401. }
  5402. /* Stop the others */
  5403. applog(LOG_DEBUG, "Killing off API thread");
  5404. thr = &control_thr[api_thr_id];
  5405. thr_info_cancel(thr);
  5406. }
  5407. /* This should be the common exit path */
  5408. void kill_work(void)
  5409. {
  5410. __kill_work();
  5411. quit(0, "Shutdown signal received.");
  5412. }
  5413. static
  5414. #ifdef WIN32
  5415. #ifndef _WIN64
  5416. const
  5417. #endif
  5418. #endif
  5419. char **initial_args;
  5420. void _bfg_clean_up(bool);
  5421. void app_restart(void)
  5422. {
  5423. applog(LOG_WARNING, "Attempting to restart %s", packagename);
  5424. __kill_work();
  5425. _bfg_clean_up(true);
  5426. #if defined(unix) || defined(__APPLE__)
  5427. if (forkpid > 0) {
  5428. kill(forkpid, SIGTERM);
  5429. forkpid = 0;
  5430. }
  5431. #endif
  5432. execv(initial_args[0], initial_args);
  5433. applog(LOG_WARNING, "Failed to restart application");
  5434. }
  5435. static void sighandler(int __maybe_unused sig)
  5436. {
  5437. /* Restore signal handlers so we can still quit if kill_work fails */
  5438. sigaction(SIGTERM, &termhandler, NULL);
  5439. sigaction(SIGINT, &inthandler, NULL);
  5440. kill_work();
  5441. }
  5442. static void start_longpoll(void);
  5443. static void stop_longpoll(void);
  5444. /* Called with pool_lock held. Recruit an extra curl if none are available for
  5445. * this pool. */
  5446. static void recruit_curl(struct pool *pool)
  5447. {
  5448. struct curl_ent *ce = calloc(sizeof(struct curl_ent), 1);
  5449. if (unlikely(!ce))
  5450. quit(1, "Failed to calloc in recruit_curl");
  5451. ce->curl = curl_easy_init();
  5452. if (unlikely(!ce->curl))
  5453. quit(1, "Failed to init in recruit_curl");
  5454. LL_PREPEND(pool->curllist, ce);
  5455. pool->curls++;
  5456. }
  5457. /* Grab an available curl if there is one. If not, then recruit extra curls
  5458. * unless we are in a submit_fail situation, or we have opt_delaynet enabled
  5459. * and there are already 5 curls in circulation. Limit total number to the
  5460. * number of mining threads per pool as well to prevent blasting a pool during
  5461. * network delays/outages. */
  5462. static struct curl_ent *pop_curl_entry3(struct pool *pool, int blocking)
  5463. {
  5464. int curl_limit = opt_delaynet ? 5 : (mining_threads + opt_queue) * 2;
  5465. bool recruited = false;
  5466. struct curl_ent *ce;
  5467. mutex_lock(&pool->pool_lock);
  5468. retry:
  5469. if (!pool->curls) {
  5470. recruit_curl(pool);
  5471. recruited = true;
  5472. } else if (!pool->curllist) {
  5473. if (blocking < 2 && pool->curls >= curl_limit && (blocking || pool->curls >= opt_submit_threads)) {
  5474. if (!blocking) {
  5475. mutex_unlock(&pool->pool_lock);
  5476. return NULL;
  5477. }
  5478. pthread_cond_wait(&pool->cr_cond, &pool->pool_lock);
  5479. goto retry;
  5480. } else {
  5481. recruit_curl(pool);
  5482. recruited = true;
  5483. }
  5484. }
  5485. ce = pool->curllist;
  5486. LL_DELETE(pool->curllist, ce);
  5487. mutex_unlock(&pool->pool_lock);
  5488. if (recruited)
  5489. applog(LOG_DEBUG, "Recruited curl for pool %d", pool->pool_no);
  5490. return ce;
  5491. }
  5492. static struct curl_ent *pop_curl_entry2(struct pool *pool, bool blocking)
  5493. {
  5494. return pop_curl_entry3(pool, blocking ? 1 : 0);
  5495. }
  5496. __maybe_unused
  5497. static struct curl_ent *pop_curl_entry(struct pool *pool)
  5498. {
  5499. return pop_curl_entry3(pool, 1);
  5500. }
  5501. static void push_curl_entry(struct curl_ent *ce, struct pool *pool)
  5502. {
  5503. mutex_lock(&pool->pool_lock);
  5504. if (!ce || !ce->curl)
  5505. quithere(1, "Attempted to add NULL");
  5506. LL_PREPEND(pool->curllist, ce);
  5507. cgtime(&ce->tv);
  5508. pthread_cond_broadcast(&pool->cr_cond);
  5509. mutex_unlock(&pool->pool_lock);
  5510. }
  5511. bool stale_work(struct work *work, bool share);
  5512. static inline bool should_roll(struct work *work)
  5513. {
  5514. struct timeval now;
  5515. time_t expiry;
  5516. if (!pool_actively_in_use(work->pool, NULL))
  5517. return false;
  5518. if (stale_work(work, false))
  5519. return false;
  5520. if (work->rolltime > opt_scantime)
  5521. expiry = work->rolltime;
  5522. else
  5523. expiry = opt_scantime;
  5524. expiry = expiry * 2 / 3;
  5525. /* We shouldn't roll if we're unlikely to get one shares' duration
  5526. * work out of doing so */
  5527. cgtime(&now);
  5528. if (now.tv_sec - work->tv_staged.tv_sec > expiry)
  5529. return false;
  5530. return true;
  5531. }
  5532. /* Limit rolls to 7000 to not beyond 2 hours in the future where bitcoind will
  5533. * reject blocks as invalid. */
  5534. static inline bool can_roll(struct work *work)
  5535. {
  5536. if (work->stratum)
  5537. return false;
  5538. if (!(work->pool && !work->clone))
  5539. return false;
  5540. if (work->tr)
  5541. {
  5542. if (stale_work(work, false))
  5543. return false;
  5544. return blkmk_work_left(work->tr->tmpl);
  5545. }
  5546. return (work->rolltime &&
  5547. work->rolls < 7000 && !stale_work(work, false));
  5548. }
  5549. static void roll_work(struct work *work)
  5550. {
  5551. if (work->tr)
  5552. {
  5553. struct timeval tv_now;
  5554. cgtime(&tv_now);
  5555. if (blkmk_get_data(work->tr->tmpl, work->data, 80, tv_now.tv_sec, NULL, &work->dataid) < 76)
  5556. applog(LOG_ERR, "Failed to get next data from template; spinning wheels!");
  5557. swap32yes(work->data, work->data, 80 / 4);
  5558. calc_midstate(work);
  5559. applog(LOG_DEBUG, "Successfully rolled extranonce to dataid %u", work->dataid);
  5560. } else {
  5561. uint32_t *work_ntime;
  5562. uint32_t ntime;
  5563. work_ntime = (uint32_t *)(work->data + 68);
  5564. ntime = be32toh(*work_ntime);
  5565. ntime++;
  5566. *work_ntime = htobe32(ntime);
  5567. work_set_simple_ntime_roll_limit(work, 0, &work->ntime_roll_limits.tv_ref);
  5568. applog(LOG_DEBUG, "Successfully rolled time header in work");
  5569. }
  5570. local_work++;
  5571. work->rolls++;
  5572. work->blk.nonce = 0;
  5573. /* This is now a different work item so it needs a different ID for the
  5574. * hashtable */
  5575. work->id = total_work++;
  5576. }
  5577. /* Duplicates any dynamically allocated arrays within the work struct to
  5578. * prevent a copied work struct from freeing ram belonging to another struct */
  5579. static void _copy_work(struct work *work, const struct work *base_work, int noffset)
  5580. {
  5581. int id = work->id;
  5582. clean_work(work);
  5583. memcpy(work, base_work, sizeof(struct work));
  5584. /* Keep the unique new id assigned during make_work to prevent copied
  5585. * work from having the same id. */
  5586. work->id = id;
  5587. if (base_work->job_id)
  5588. work->job_id = strdup(base_work->job_id);
  5589. if (base_work->nonce1)
  5590. work->nonce1 = strdup(base_work->nonce1);
  5591. bytes_cpy(&work->nonce2, &base_work->nonce2);
  5592. if (base_work->tr)
  5593. tmpl_incref(base_work->tr);
  5594. if (noffset)
  5595. {
  5596. uint32_t *work_ntime = (uint32_t *)(work->data + 68);
  5597. uint32_t ntime = be32toh(*work_ntime);
  5598. ntime += noffset;
  5599. *work_ntime = htobe32(ntime);
  5600. }
  5601. if (work->device_data_dup_func)
  5602. work->device_data = work->device_data_dup_func(work);
  5603. }
  5604. /* Generates a copy of an existing work struct, creating fresh heap allocations
  5605. * for all dynamically allocated arrays within the struct. noffset is used for
  5606. * when a driver has internally rolled the ntime, noffset is a relative value.
  5607. * The macro copy_work() calls this function with an noffset of 0. */
  5608. struct work *copy_work_noffset(const struct work *base_work, int noffset)
  5609. {
  5610. struct work *work = make_work();
  5611. _copy_work(work, base_work, noffset);
  5612. return work;
  5613. }
  5614. void __copy_work(struct work *work, const struct work *base_work)
  5615. {
  5616. _copy_work(work, base_work, 0);
  5617. }
  5618. static struct work *make_clone(struct work *work)
  5619. {
  5620. struct work *work_clone = copy_work(work);
  5621. work_clone->clone = true;
  5622. cgtime((struct timeval *)&(work_clone->tv_cloned));
  5623. work_clone->longpoll = false;
  5624. work_clone->mandatory = false;
  5625. /* Make cloned work appear slightly older to bias towards keeping the
  5626. * master work item which can be further rolled */
  5627. work_clone->tv_staged.tv_sec -= 1;
  5628. return work_clone;
  5629. }
  5630. static void stage_work(struct work *work);
  5631. static bool clone_available(void)
  5632. {
  5633. struct work *work_clone = NULL, *work, *tmp;
  5634. bool cloned = false;
  5635. mutex_lock(stgd_lock);
  5636. if (!staged_rollable)
  5637. goto out_unlock;
  5638. HASH_ITER(hh, staged_work, work, tmp) {
  5639. if (can_roll(work) && should_roll(work)) {
  5640. roll_work(work);
  5641. work_clone = make_clone(work);
  5642. applog(LOG_DEBUG, "%s: Rolling work %d to %d", __func__, work->id, work_clone->id);
  5643. roll_work(work);
  5644. cloned = true;
  5645. break;
  5646. }
  5647. }
  5648. out_unlock:
  5649. mutex_unlock(stgd_lock);
  5650. if (cloned) {
  5651. applog(LOG_DEBUG, "Pushing cloned available work to stage thread");
  5652. stage_work(work_clone);
  5653. }
  5654. return cloned;
  5655. }
  5656. static void pool_died(struct pool *pool)
  5657. {
  5658. mutex_lock(&lp_lock);
  5659. if (!pool_tset(pool, &pool->idle)) {
  5660. cgtime(&pool->tv_idle);
  5661. pthread_cond_broadcast(&lp_cond);
  5662. mutex_unlock(&lp_lock);
  5663. if (pool == current_pool()) {
  5664. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  5665. switch_pools(NULL);
  5666. } else
  5667. applog(LOG_INFO, "Pool %d %s failed to return work", pool->pool_no, pool->rpc_url);
  5668. }
  5669. else
  5670. mutex_unlock(&lp_lock);
  5671. }
  5672. bool stale_work(struct work *work, bool share)
  5673. {
  5674. unsigned work_expiry;
  5675. struct pool *pool;
  5676. uint32_t block_id;
  5677. unsigned getwork_delay;
  5678. block_id = ((uint32_t*)work->data)[1];
  5679. pool = work->pool;
  5680. struct mining_goal_info * const goal = pool->goal;
  5681. struct blockchain_info * const blkchain = goal->blkchain;
  5682. /* Technically the rolltime should be correct but some pools
  5683. * advertise a broken expire= that is lower than a meaningful
  5684. * scantime */
  5685. if (work->rolltime >= opt_scantime || work->tr)
  5686. work_expiry = work->rolltime;
  5687. else
  5688. work_expiry = opt_expiry;
  5689. unsigned max_expiry = (goal->have_longpoll ? opt_expiry_lp : opt_expiry);
  5690. if (work_expiry > max_expiry)
  5691. work_expiry = max_expiry;
  5692. if (share) {
  5693. /* If the share isn't on this pool's latest block, it's stale */
  5694. if (pool->block_id && pool->block_id != block_id)
  5695. {
  5696. applog(LOG_DEBUG, "Share stale due to block mismatch (%08lx != %08lx)", (long)block_id, (long)pool->block_id);
  5697. return true;
  5698. }
  5699. /* If the pool doesn't want old shares, then any found in work before
  5700. * the most recent longpoll is stale */
  5701. if ((!pool->submit_old) && work->work_restart_id != pool->work_restart_id)
  5702. {
  5703. applog(LOG_DEBUG, "Share stale due to mandatory work update (%02x != %02x)", work->work_restart_id, pool->work_restart_id);
  5704. return true;
  5705. }
  5706. } else {
  5707. /* If this work isn't for the latest Bitcoin block, it's stale */
  5708. /* But only care about the current pool if failover-only */
  5709. if (enabled_pools <= 1 || opt_fail_only) {
  5710. if (pool->block_id && block_id != pool->block_id)
  5711. {
  5712. 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);
  5713. return true;
  5714. }
  5715. } else {
  5716. if (block_id != blkchain->currentblk->block_id)
  5717. {
  5718. 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);
  5719. return true;
  5720. }
  5721. }
  5722. /* If the pool has asked us to restart since this work, it's stale */
  5723. if (work->work_restart_id != pool->work_restart_id)
  5724. {
  5725. applog(LOG_DEBUG, "Work stale due to work update (%02x != %02x)", work->work_restart_id, pool->work_restart_id);
  5726. return true;
  5727. }
  5728. if (pool->has_stratum && work->job_id) {
  5729. bool same_job;
  5730. if (!pool->stratum_active || !pool->stratum_notify) {
  5731. applog(LOG_DEBUG, "Work stale due to stratum inactive");
  5732. return true;
  5733. }
  5734. same_job = true;
  5735. cg_rlock(&pool->data_lock);
  5736. if (strcmp(work->job_id, pool->swork.job_id))
  5737. same_job = false;
  5738. cg_runlock(&pool->data_lock);
  5739. if (!same_job) {
  5740. applog(LOG_DEBUG, "Work stale due to stratum job_id mismatch");
  5741. return true;
  5742. }
  5743. }
  5744. /* Factor in the average getwork delay of this pool, rounding it up to
  5745. * the nearest second */
  5746. getwork_delay = pool->cgminer_pool_stats.getwork_wait_rolling * 5 + 1;
  5747. if (unlikely(work_expiry <= getwork_delay + 5))
  5748. work_expiry = 5;
  5749. else
  5750. work_expiry -= getwork_delay;
  5751. }
  5752. int elapsed_since_staged = timer_elapsed(&work->tv_staged, NULL);
  5753. if (elapsed_since_staged > work_expiry) {
  5754. applog(LOG_DEBUG, "%s stale due to expiry (%d >= %u)", share?"Share":"Work", elapsed_since_staged, work_expiry);
  5755. return true;
  5756. }
  5757. /* If the user only wants strict failover, any work from a pool other than
  5758. * the current one is always considered stale */
  5759. if (opt_fail_only && !share && !work->mandatory && !pool_actively_in_use(pool, NULL))
  5760. {
  5761. applog(LOG_DEBUG, "Work stale due to fail only pool mismatch (pool %u vs %u)", pool->pool_no, current_pool()->pool_no);
  5762. return true;
  5763. }
  5764. return false;
  5765. }
  5766. double share_diff(const struct work *work)
  5767. {
  5768. double ret;
  5769. bool new_best = false;
  5770. ret = target_diff(work->hash);
  5771. cg_wlock(&control_lock);
  5772. if (unlikely(ret > best_diff)) {
  5773. new_best = true;
  5774. best_diff = ret;
  5775. suffix_string(best_diff, best_share, sizeof(best_share), 0);
  5776. }
  5777. if (unlikely(ret > work->pool->best_diff))
  5778. work->pool->best_diff = ret;
  5779. cg_wunlock(&control_lock);
  5780. if (unlikely(new_best))
  5781. applog(LOG_INFO, "New best share: %s", best_share);
  5782. return ret;
  5783. }
  5784. static
  5785. void work_check_for_block(struct work * const work)
  5786. {
  5787. struct pool * const pool = work->pool;
  5788. struct mining_goal_info * const goal = pool->goal;
  5789. work->share_diff = share_diff(work);
  5790. if (unlikely(work->share_diff >= goal->current_diff)) {
  5791. work->block = true;
  5792. work->pool->solved++;
  5793. found_blocks++;
  5794. work->mandatory = true;
  5795. applog(LOG_NOTICE, "Found block for pool %d!", work->pool->pool_no);
  5796. }
  5797. }
  5798. static void submit_discard_share2(const char *reason, struct work *work)
  5799. {
  5800. struct cgpu_info *cgpu = get_thr_cgpu(work->thr_id);
  5801. sharelog(reason, work);
  5802. mutex_lock(&stats_lock);
  5803. ++total_stale;
  5804. ++cgpu->stale;
  5805. ++(work->pool->stale_shares);
  5806. total_diff_stale += work->work_difficulty;
  5807. cgpu->diff_stale += work->work_difficulty;
  5808. work->pool->diff_stale += work->work_difficulty;
  5809. mutex_unlock(&stats_lock);
  5810. }
  5811. static void submit_discard_share(struct work *work)
  5812. {
  5813. submit_discard_share2("discard", work);
  5814. }
  5815. struct submit_work_state {
  5816. struct work *work;
  5817. bool resubmit;
  5818. struct curl_ent *ce;
  5819. int failures;
  5820. struct timeval tv_staleexpire;
  5821. char *s;
  5822. struct timeval tv_submit;
  5823. struct submit_work_state *next;
  5824. };
  5825. static int my_curl_timer_set(__maybe_unused CURLM *curlm, long timeout_ms, void *userp)
  5826. {
  5827. long *p_timeout_us = userp;
  5828. const long max_ms = LONG_MAX / 1000;
  5829. if (max_ms < timeout_ms)
  5830. timeout_ms = max_ms;
  5831. *p_timeout_us = timeout_ms * 1000;
  5832. return 0;
  5833. }
  5834. static void sws_has_ce(struct submit_work_state *sws)
  5835. {
  5836. struct pool *pool = sws->work->pool;
  5837. sws->s = submit_upstream_work_request(sws->work);
  5838. cgtime(&sws->tv_submit);
  5839. json_rpc_call_async(sws->ce->curl, pool->rpc_url, pool->rpc_userpass, sws->s, false, pool, true, sws);
  5840. }
  5841. static struct submit_work_state *begin_submission(struct work *work)
  5842. {
  5843. struct pool *pool;
  5844. struct submit_work_state *sws = NULL;
  5845. pool = work->pool;
  5846. sws = malloc(sizeof(*sws));
  5847. *sws = (struct submit_work_state){
  5848. .work = work,
  5849. };
  5850. work_check_for_block(work);
  5851. if (stale_work(work, true)) {
  5852. work->stale = true;
  5853. if (opt_submit_stale)
  5854. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as user requested", pool->pool_no);
  5855. else if (pool->submit_old)
  5856. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as pool requested", pool->pool_no);
  5857. else {
  5858. applog(LOG_NOTICE, "Pool %d stale share detected, discarding", pool->pool_no);
  5859. submit_discard_share(work);
  5860. goto out;
  5861. }
  5862. timer_set_delay_from_now(&sws->tv_staleexpire, 300000000);
  5863. }
  5864. if (work->stratum) {
  5865. char *s;
  5866. s = malloc(1024);
  5867. sws->s = s;
  5868. } else {
  5869. /* submit solution to bitcoin via JSON-RPC */
  5870. sws->ce = pop_curl_entry2(pool, false);
  5871. if (sws->ce) {
  5872. sws_has_ce(sws);
  5873. } else {
  5874. sws->next = pool->sws_waiting_on_curl;
  5875. pool->sws_waiting_on_curl = sws;
  5876. if (sws->next)
  5877. applog(LOG_DEBUG, "submit_thread queuing submission");
  5878. else
  5879. applog(LOG_WARNING, "submit_thread queuing submissions (see --submit-threads)");
  5880. }
  5881. }
  5882. return sws;
  5883. out:
  5884. free(sws);
  5885. return NULL;
  5886. }
  5887. static bool retry_submission(struct submit_work_state *sws)
  5888. {
  5889. struct work *work = sws->work;
  5890. struct pool *pool = work->pool;
  5891. sws->resubmit = true;
  5892. if ((!work->stale) && stale_work(work, true)) {
  5893. work->stale = true;
  5894. if (opt_submit_stale)
  5895. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, will retry as user requested", pool->pool_no);
  5896. else if (pool->submit_old)
  5897. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, will retry as pool requested", pool->pool_no);
  5898. else {
  5899. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, discarding", pool->pool_no);
  5900. submit_discard_share(work);
  5901. return false;
  5902. }
  5903. timer_set_delay_from_now(&sws->tv_staleexpire, 300000000);
  5904. }
  5905. if (unlikely((opt_retries >= 0) && (++sws->failures > opt_retries))) {
  5906. applog(LOG_ERR, "Pool %d failed %d submission retries, discarding", pool->pool_no, opt_retries);
  5907. submit_discard_share(work);
  5908. return false;
  5909. }
  5910. else if (work->stale) {
  5911. if (unlikely(opt_retries < 0 && timer_passed(&sws->tv_staleexpire, NULL)))
  5912. {
  5913. applog(LOG_NOTICE, "Pool %d stale share failed to submit for 5 minutes, discarding", pool->pool_no);
  5914. submit_discard_share(work);
  5915. return false;
  5916. }
  5917. }
  5918. /* pause, then restart work-request loop */
  5919. applog(LOG_INFO, "json_rpc_call failed on submit_work, retrying");
  5920. cgtime(&sws->tv_submit);
  5921. json_rpc_call_async(sws->ce->curl, pool->rpc_url, pool->rpc_userpass, sws->s, false, pool, true, sws);
  5922. return true;
  5923. }
  5924. static void free_sws(struct submit_work_state *sws)
  5925. {
  5926. free(sws->s);
  5927. free_work(sws->work);
  5928. free(sws);
  5929. }
  5930. static void *submit_work_thread(__maybe_unused void *userdata)
  5931. {
  5932. int wip = 0;
  5933. CURLM *curlm;
  5934. long curlm_timeout_us = -1;
  5935. struct timeval curlm_timer;
  5936. struct submit_work_state *sws, **swsp;
  5937. struct submit_work_state *write_sws = NULL;
  5938. unsigned tsreduce = 0;
  5939. pthread_detach(pthread_self());
  5940. RenameThread("submit_work");
  5941. applog(LOG_DEBUG, "Creating extra submit work thread");
  5942. curlm = curl_multi_init();
  5943. curlm_timeout_us = -1;
  5944. curl_multi_setopt(curlm, CURLMOPT_TIMERDATA, &curlm_timeout_us);
  5945. curl_multi_setopt(curlm, CURLMOPT_TIMERFUNCTION, my_curl_timer_set);
  5946. fd_set rfds, wfds, efds;
  5947. int maxfd;
  5948. struct timeval tv_timeout, tv_now;
  5949. int n;
  5950. CURLMsg *cm;
  5951. FD_ZERO(&rfds);
  5952. while (1) {
  5953. mutex_lock(&submitting_lock);
  5954. total_submitting -= tsreduce;
  5955. tsreduce = 0;
  5956. if (FD_ISSET(submit_waiting_notifier[0], &rfds)) {
  5957. notifier_read(submit_waiting_notifier);
  5958. }
  5959. // Receive any new submissions
  5960. while (submit_waiting) {
  5961. struct work *work = submit_waiting;
  5962. DL_DELETE(submit_waiting, work);
  5963. if ( (sws = begin_submission(work)) ) {
  5964. if (sws->ce)
  5965. curl_multi_add_handle(curlm, sws->ce->curl);
  5966. else if (sws->s) {
  5967. sws->next = write_sws;
  5968. write_sws = sws;
  5969. }
  5970. ++wip;
  5971. }
  5972. else {
  5973. --total_submitting;
  5974. free_work(work);
  5975. }
  5976. }
  5977. if (unlikely(shutting_down && !wip))
  5978. break;
  5979. mutex_unlock(&submitting_lock);
  5980. FD_ZERO(&rfds);
  5981. FD_ZERO(&wfds);
  5982. FD_ZERO(&efds);
  5983. tv_timeout.tv_sec = -1;
  5984. // Setup cURL with select
  5985. // Need to call perform to ensure the timeout gets updated
  5986. curl_multi_perform(curlm, &n);
  5987. curl_multi_fdset(curlm, &rfds, &wfds, &efds, &maxfd);
  5988. if (curlm_timeout_us >= 0)
  5989. {
  5990. timer_set_delay_from_now(&curlm_timer, curlm_timeout_us);
  5991. reduce_timeout_to(&tv_timeout, &curlm_timer);
  5992. }
  5993. // Setup waiting stratum submissions with select
  5994. for (sws = write_sws; sws; sws = sws->next)
  5995. {
  5996. struct pool *pool = sws->work->pool;
  5997. int fd = pool->sock;
  5998. if (fd == INVSOCK || (!pool->stratum_init) || !pool->stratum_notify)
  5999. continue;
  6000. FD_SET(fd, &wfds);
  6001. set_maxfd(&maxfd, fd);
  6002. }
  6003. // Setup "submit waiting" notifier with select
  6004. FD_SET(submit_waiting_notifier[0], &rfds);
  6005. set_maxfd(&maxfd, submit_waiting_notifier[0]);
  6006. // Wait for something interesting to happen :)
  6007. cgtime(&tv_now);
  6008. if (select(maxfd+1, &rfds, &wfds, &efds, select_timeout(&tv_timeout, &tv_now)) < 0) {
  6009. FD_ZERO(&rfds);
  6010. continue;
  6011. }
  6012. // Handle any stratum ready-to-write results
  6013. for (swsp = &write_sws; (sws = *swsp); ) {
  6014. struct work *work = sws->work;
  6015. struct pool *pool = work->pool;
  6016. int fd = pool->sock;
  6017. bool sessionid_match;
  6018. if (fd == INVSOCK || (!pool->stratum_init) || (!pool->stratum_notify) || !FD_ISSET(fd, &wfds)) {
  6019. next_write_sws:
  6020. // TODO: Check if stale, possibly discard etc
  6021. swsp = &sws->next;
  6022. continue;
  6023. }
  6024. cg_rlock(&pool->data_lock);
  6025. // 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
  6026. // NOTE: Worst case scenario for a false positive: the pool rejects it as H-not-zero
  6027. sessionid_match = (!pool->swork.nonce1) || !strcmp(work->nonce1, pool->swork.nonce1);
  6028. cg_runlock(&pool->data_lock);
  6029. if (!sessionid_match)
  6030. {
  6031. applog(LOG_DEBUG, "No matching session id for resubmitting stratum share");
  6032. submit_discard_share2("disconnect", work);
  6033. ++tsreduce;
  6034. next_write_sws_del:
  6035. // Clear the fd from wfds, to avoid potentially blocking on other submissions to the same socket
  6036. FD_CLR(fd, &wfds);
  6037. // Delete sws for this submission, since we're done with it
  6038. *swsp = sws->next;
  6039. free_sws(sws);
  6040. --wip;
  6041. continue;
  6042. }
  6043. char *s = sws->s;
  6044. struct stratum_share *sshare = calloc(sizeof(struct stratum_share), 1);
  6045. int sshare_id;
  6046. uint32_t nonce;
  6047. char nonce2hex[(bytes_len(&work->nonce2) * 2) + 1];
  6048. char noncehex[9];
  6049. char ntimehex[9];
  6050. sshare->work = copy_work(work);
  6051. bin2hex(nonce2hex, bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  6052. nonce = *((uint32_t *)(work->data + 76));
  6053. bin2hex(noncehex, (const unsigned char *)&nonce, 4);
  6054. bin2hex(ntimehex, (void *)&work->data[68], 4);
  6055. mutex_lock(&sshare_lock);
  6056. /* Give the stratum share a unique id */
  6057. sshare_id =
  6058. sshare->id = swork_id++;
  6059. HASH_ADD_INT(stratum_shares, id, sshare);
  6060. snprintf(s, 1024, "{\"params\": [\"%s\", \"%s\", \"%s\", \"%s\", \"%s\"], \"id\": %d, \"method\": \"mining.submit\"}",
  6061. pool->rpc_user, work->job_id, nonce2hex, ntimehex, noncehex, sshare->id);
  6062. mutex_unlock(&sshare_lock);
  6063. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->stratum_url, s);
  6064. if (likely(stratum_send(pool, s, strlen(s)))) {
  6065. if (pool_tclear(pool, &pool->submit_fail))
  6066. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  6067. applog(LOG_DEBUG, "Successfully submitted, adding to stratum_shares db");
  6068. goto next_write_sws_del;
  6069. } else if (!pool_tset(pool, &pool->submit_fail)) {
  6070. // Undo stuff
  6071. mutex_lock(&sshare_lock);
  6072. // NOTE: Need to find it again in case something else has consumed it already (like the stratum-disconnect resubmitter...)
  6073. HASH_FIND_INT(stratum_shares, &sshare_id, sshare);
  6074. if (sshare)
  6075. HASH_DEL(stratum_shares, sshare);
  6076. mutex_unlock(&sshare_lock);
  6077. if (sshare)
  6078. {
  6079. free_work(sshare->work);
  6080. free(sshare);
  6081. }
  6082. applog(LOG_WARNING, "Pool %d stratum share submission failure", pool->pool_no);
  6083. total_ro++;
  6084. pool->remotefail_occasions++;
  6085. if (!sshare)
  6086. goto next_write_sws_del;
  6087. goto next_write_sws;
  6088. }
  6089. }
  6090. // Handle any cURL activities
  6091. curl_multi_perform(curlm, &n);
  6092. while( (cm = curl_multi_info_read(curlm, &n)) ) {
  6093. if (cm->msg == CURLMSG_DONE)
  6094. {
  6095. bool finished;
  6096. json_t *val = json_rpc_call_completed(cm->easy_handle, cm->data.result, false, NULL, &sws);
  6097. curl_multi_remove_handle(curlm, cm->easy_handle);
  6098. finished = submit_upstream_work_completed(sws->work, sws->resubmit, &sws->tv_submit, val);
  6099. if (!finished) {
  6100. if (retry_submission(sws))
  6101. curl_multi_add_handle(curlm, sws->ce->curl);
  6102. else
  6103. finished = true;
  6104. }
  6105. if (finished) {
  6106. --wip;
  6107. ++tsreduce;
  6108. struct pool *pool = sws->work->pool;
  6109. if (pool->sws_waiting_on_curl) {
  6110. pool->sws_waiting_on_curl->ce = sws->ce;
  6111. sws_has_ce(pool->sws_waiting_on_curl);
  6112. pool->sws_waiting_on_curl = pool->sws_waiting_on_curl->next;
  6113. curl_multi_add_handle(curlm, sws->ce->curl);
  6114. } else {
  6115. push_curl_entry(sws->ce, sws->work->pool);
  6116. }
  6117. free_sws(sws);
  6118. }
  6119. }
  6120. }
  6121. }
  6122. assert(!write_sws);
  6123. mutex_unlock(&submitting_lock);
  6124. curl_multi_cleanup(curlm);
  6125. applog(LOG_DEBUG, "submit_work thread exiting");
  6126. return NULL;
  6127. }
  6128. /* Find the pool that currently has the highest priority */
  6129. static struct pool *priority_pool(int choice)
  6130. {
  6131. struct pool *ret = NULL;
  6132. int i;
  6133. for (i = 0; i < total_pools; i++) {
  6134. struct pool *pool = pools[i];
  6135. if (pool->prio == choice) {
  6136. ret = pool;
  6137. break;
  6138. }
  6139. }
  6140. if (unlikely(!ret)) {
  6141. applog(LOG_ERR, "WTF No pool %d found!", choice);
  6142. return pools[choice];
  6143. }
  6144. return ret;
  6145. }
  6146. int prioritize_pools(char *param, int *pid)
  6147. {
  6148. char *ptr, *next;
  6149. int i, pr, prio = 0;
  6150. if (total_pools == 0) {
  6151. return MSG_NOPOOL;
  6152. }
  6153. if (param == NULL || *param == '\0') {
  6154. return MSG_MISPID;
  6155. }
  6156. bool pools_changed[total_pools];
  6157. int new_prio[total_pools];
  6158. for (i = 0; i < total_pools; ++i)
  6159. pools_changed[i] = false;
  6160. next = param;
  6161. while (next && *next) {
  6162. ptr = next;
  6163. next = strchr(ptr, ',');
  6164. if (next)
  6165. *(next++) = '\0';
  6166. i = atoi(ptr);
  6167. if (i < 0 || i >= total_pools) {
  6168. *pid = i;
  6169. return MSG_INVPID;
  6170. }
  6171. if (pools_changed[i]) {
  6172. *pid = i;
  6173. return MSG_DUPPID;
  6174. }
  6175. pools_changed[i] = true;
  6176. new_prio[i] = prio++;
  6177. }
  6178. // Only change them if no errors
  6179. for (i = 0; i < total_pools; i++) {
  6180. if (pools_changed[i])
  6181. pools[i]->prio = new_prio[i];
  6182. }
  6183. // In priority order, cycle through the unchanged pools and append them
  6184. for (pr = 0; pr < total_pools; pr++)
  6185. for (i = 0; i < total_pools; i++) {
  6186. if (!pools_changed[i] && pools[i]->prio == pr) {
  6187. pools[i]->prio = prio++;
  6188. pools_changed[i] = true;
  6189. break;
  6190. }
  6191. }
  6192. if (current_pool()->prio)
  6193. switch_pools(NULL);
  6194. return MSG_POOLPRIO;
  6195. }
  6196. void validate_pool_priorities(void)
  6197. {
  6198. // TODO: this should probably do some sort of logging
  6199. int i, j;
  6200. bool used[total_pools];
  6201. bool valid[total_pools];
  6202. for (i = 0; i < total_pools; i++)
  6203. used[i] = valid[i] = false;
  6204. for (i = 0; i < total_pools; i++) {
  6205. if (pools[i]->prio >=0 && pools[i]->prio < total_pools) {
  6206. if (!used[pools[i]->prio]) {
  6207. valid[i] = true;
  6208. used[pools[i]->prio] = true;
  6209. }
  6210. }
  6211. }
  6212. for (i = 0; i < total_pools; i++) {
  6213. if (!valid[i]) {
  6214. for (j = 0; j < total_pools; j++) {
  6215. if (!used[j]) {
  6216. applog(LOG_WARNING, "Pool %d priority changed from %d to %d", i, pools[i]->prio, j);
  6217. pools[i]->prio = j;
  6218. used[j] = true;
  6219. break;
  6220. }
  6221. }
  6222. }
  6223. }
  6224. }
  6225. static void clear_pool_work(struct pool *pool);
  6226. /* Specifies whether we can switch to this pool or not. */
  6227. static bool pool_unusable(struct pool *pool)
  6228. {
  6229. if (pool->idle)
  6230. return true;
  6231. if (pool->enabled != POOL_ENABLED)
  6232. return true;
  6233. return false;
  6234. }
  6235. void switch_pools(struct pool *selected)
  6236. {
  6237. struct pool *pool, *last_pool, *failover_pool = NULL;
  6238. int i, pool_no, next_pool;
  6239. if (selected)
  6240. enable_pool(selected);
  6241. cg_wlock(&control_lock);
  6242. last_pool = currentpool;
  6243. pool_no = currentpool->pool_no;
  6244. /* Switch selected to pool number 0 and move the rest down */
  6245. if (selected) {
  6246. if (selected->prio != 0) {
  6247. for (i = 0; i < total_pools; i++) {
  6248. pool = pools[i];
  6249. if (pool->prio < selected->prio)
  6250. pool->prio++;
  6251. }
  6252. selected->prio = 0;
  6253. }
  6254. }
  6255. switch (pool_strategy) {
  6256. /* All of these set to the master pool */
  6257. case POOL_BALANCE:
  6258. case POOL_FAILOVER:
  6259. case POOL_LOADBALANCE:
  6260. for (i = 0; i < total_pools; i++) {
  6261. pool = priority_pool(i);
  6262. if (pool_unusable(pool))
  6263. continue;
  6264. pool_no = pool->pool_no;
  6265. break;
  6266. }
  6267. break;
  6268. /* Both of these simply increment and cycle */
  6269. case POOL_ROUNDROBIN:
  6270. case POOL_ROTATE:
  6271. if (selected && !selected->idle) {
  6272. pool_no = selected->pool_no;
  6273. break;
  6274. }
  6275. next_pool = pool_no;
  6276. /* Select the next alive pool */
  6277. for (i = 1; i < total_pools; i++) {
  6278. next_pool++;
  6279. if (next_pool >= total_pools)
  6280. next_pool = 0;
  6281. pool = pools[next_pool];
  6282. if (pool_unusable(pool))
  6283. continue;
  6284. if (pool->failover_only)
  6285. {
  6286. BFGINIT(failover_pool, pool);
  6287. continue;
  6288. }
  6289. pool_no = next_pool;
  6290. break;
  6291. }
  6292. break;
  6293. default:
  6294. break;
  6295. }
  6296. pool = pools[pool_no];
  6297. if (pool_unusable(pool) && failover_pool)
  6298. pool = failover_pool;
  6299. currentpool = pool;
  6300. cg_wunlock(&control_lock);
  6301. mutex_lock(&lp_lock);
  6302. pthread_cond_broadcast(&lp_cond);
  6303. mutex_unlock(&lp_lock);
  6304. /* Set the lagging flag to avoid pool not providing work fast enough
  6305. * messages in failover only mode since we have to get all fresh work
  6306. * as in restart_threads */
  6307. if (opt_fail_only)
  6308. pool_tset(pool, &pool->lagging);
  6309. if (pool != last_pool)
  6310. {
  6311. pool->block_id = 0;
  6312. if (pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  6313. applog(LOG_WARNING, "Switching to pool %d %s", pool->pool_no, pool->rpc_url);
  6314. if (pool_localgen(pool) || opt_fail_only)
  6315. clear_pool_work(last_pool);
  6316. }
  6317. }
  6318. mutex_lock(&lp_lock);
  6319. pthread_cond_broadcast(&lp_cond);
  6320. mutex_unlock(&lp_lock);
  6321. #ifdef HAVE_CURSES
  6322. update_block_display();
  6323. #endif
  6324. }
  6325. static void discard_work(struct work *work)
  6326. {
  6327. if (!work->clone && !work->rolls && !work->mined) {
  6328. if (work->pool) {
  6329. work->pool->discarded_work++;
  6330. work->pool->quota_used--;
  6331. work->pool->works--;
  6332. }
  6333. total_discarded++;
  6334. applog(LOG_DEBUG, "Discarded work");
  6335. } else
  6336. applog(LOG_DEBUG, "Discarded cloned or rolled work");
  6337. free_work(work);
  6338. }
  6339. static bool work_rollable(struct work *);
  6340. static
  6341. void unstage_work(struct work * const work)
  6342. {
  6343. HASH_DEL(staged_work, work);
  6344. --work_mining_algorithm(work)->staged;
  6345. if (work_rollable(work))
  6346. --staged_rollable;
  6347. if (work->spare)
  6348. --staged_spare;
  6349. staged_full = false;
  6350. }
  6351. static void wake_gws(void)
  6352. {
  6353. mutex_lock(stgd_lock);
  6354. pthread_cond_signal(&gws_cond);
  6355. mutex_unlock(stgd_lock);
  6356. }
  6357. static void discard_stale(void)
  6358. {
  6359. struct work *work, *tmp;
  6360. int stale = 0;
  6361. mutex_lock(stgd_lock);
  6362. HASH_ITER(hh, staged_work, work, tmp) {
  6363. if (stale_work(work, false)) {
  6364. unstage_work(work);
  6365. discard_work(work);
  6366. stale++;
  6367. }
  6368. }
  6369. pthread_cond_signal(&gws_cond);
  6370. mutex_unlock(stgd_lock);
  6371. if (stale)
  6372. applog(LOG_DEBUG, "Discarded %d stales that didn't match current hash", stale);
  6373. }
  6374. bool stale_work_future(struct work *work, bool share, unsigned long ustime)
  6375. {
  6376. bool rv;
  6377. struct timeval tv, orig;
  6378. ldiv_t d;
  6379. d = ldiv(ustime, 1000000);
  6380. tv = (struct timeval){
  6381. .tv_sec = d.quot,
  6382. .tv_usec = d.rem,
  6383. };
  6384. orig = work->tv_staged;
  6385. timersub(&orig, &tv, &work->tv_staged);
  6386. rv = stale_work(work, share);
  6387. work->tv_staged = orig;
  6388. return rv;
  6389. }
  6390. static
  6391. void pool_update_work_restart_time(struct pool * const pool)
  6392. {
  6393. pool->work_restart_time = time(NULL);
  6394. get_timestamp(pool->work_restart_timestamp, sizeof(pool->work_restart_timestamp), pool->work_restart_time);
  6395. }
  6396. static void restart_threads(void)
  6397. {
  6398. struct pool *cp = current_pool();
  6399. int i;
  6400. struct thr_info *thr;
  6401. /* Artificially set the lagging flag to avoid pool not providing work
  6402. * fast enough messages after every long poll */
  6403. pool_tset(cp, &cp->lagging);
  6404. /* Discard staged work that is now stale */
  6405. discard_stale();
  6406. rd_lock(&mining_thr_lock);
  6407. for (i = 0; i < mining_threads; i++)
  6408. {
  6409. thr = mining_thr[i];
  6410. thr->work_restart = true;
  6411. }
  6412. for (i = 0; i < mining_threads; i++)
  6413. {
  6414. thr = mining_thr[i];
  6415. notifier_wake(thr->work_restart_notifier);
  6416. }
  6417. rd_unlock(&mining_thr_lock);
  6418. }
  6419. void blkhashstr(char *rv, const unsigned char *hash)
  6420. {
  6421. unsigned char hash_swap[32];
  6422. swap256(hash_swap, hash);
  6423. swap32tole(hash_swap, hash_swap, 32 / 4);
  6424. bin2hex(rv, hash_swap, 32);
  6425. }
  6426. static
  6427. void set_curblock(struct mining_goal_info * const goal, struct block_info * const blkinfo)
  6428. {
  6429. struct blockchain_info * const blkchain = goal->blkchain;
  6430. blkchain->currentblk = blkinfo;
  6431. blkchain->currentblk_subsidy = 5000000000LL >> (blkinfo->height / 210000);
  6432. cg_wlock(&ch_lock);
  6433. __update_block_title(goal);
  6434. get_timestamp(blkchain->currentblk_first_seen_time_str, sizeof(blkchain->currentblk_first_seen_time_str), blkinfo->first_seen_time);
  6435. cg_wunlock(&ch_lock);
  6436. applog(LOG_INFO, "New block: %s diff %s (%s)", goal->current_goal_detail, goal->current_diff_str, goal->net_hashrate);
  6437. }
  6438. /* Search to see if this prevblkhash has been seen before */
  6439. static
  6440. struct block_info *block_exists(const struct blockchain_info * const blkchain, const void * const prevblkhash)
  6441. {
  6442. struct block_info *s;
  6443. rd_lock(&blk_lock);
  6444. HASH_FIND(hh, blkchain->blocks, prevblkhash, 0x20, s);
  6445. rd_unlock(&blk_lock);
  6446. return s;
  6447. }
  6448. static int block_sort(struct block_info * const blocka, struct block_info * const blockb)
  6449. {
  6450. return blocka->block_seen_order - blockb->block_seen_order;
  6451. }
  6452. static
  6453. void set_blockdiff(struct mining_goal_info * const goal, const struct work * const work)
  6454. {
  6455. unsigned char target[32];
  6456. double diff;
  6457. uint64_t diff64;
  6458. real_block_target(target, work->data);
  6459. diff = target_diff(target);
  6460. diff64 = diff;
  6461. suffix_string(diff64, goal->current_diff_str, sizeof(goal->current_diff_str), 0);
  6462. format_unit2(goal->net_hashrate, sizeof(goal->net_hashrate),
  6463. true, "h/s", H2B_SHORT, diff * 7158278, -1);
  6464. if (unlikely(goal->current_diff != diff))
  6465. applog(LOG_NOTICE, "Network difficulty changed to %s (%s)", goal->current_diff_str, goal->net_hashrate);
  6466. goal->current_diff = diff;
  6467. }
  6468. static bool test_work_current(struct work *work)
  6469. {
  6470. bool ret = true;
  6471. if (work->mandatory)
  6472. return ret;
  6473. uint32_t block_id = ((uint32_t*)(work->data))[1];
  6474. const uint8_t * const prevblkhash = &work->data[4];
  6475. {
  6476. /* Hack to work around dud work sneaking into test */
  6477. bool dudwork = true;
  6478. for (int i = 8; i < 26; ++i)
  6479. if (work->data[i])
  6480. {
  6481. dudwork = false;
  6482. break;
  6483. }
  6484. if (dudwork)
  6485. goto out_free;
  6486. }
  6487. struct pool * const pool = work->pool;
  6488. struct mining_goal_info * const goal = pool->goal;
  6489. struct blockchain_info * const blkchain = goal->blkchain;
  6490. /* Search to see if this block exists yet and if not, consider it a
  6491. * new block and set the current block details to this one */
  6492. if (!block_exists(blkchain, prevblkhash))
  6493. {
  6494. struct block_info * const s = calloc(sizeof(struct block_info), 1);
  6495. int deleted_block = 0;
  6496. ret = false;
  6497. if (unlikely(!s))
  6498. quit (1, "test_work_current OOM");
  6499. memcpy(s->prevblkhash, prevblkhash, sizeof(s->prevblkhash));
  6500. s->block_id = block_id;
  6501. s->block_seen_order = new_blocks++;
  6502. s->first_seen_time = time(NULL);
  6503. wr_lock(&blk_lock);
  6504. /* Only keep the last hour's worth of blocks in memory since
  6505. * work from blocks before this is virtually impossible and we
  6506. * want to prevent memory usage from continually rising */
  6507. if (HASH_COUNT(blkchain->blocks) > 6)
  6508. {
  6509. struct block_info *oldblock;
  6510. HASH_SORT(blkchain->blocks, block_sort);
  6511. oldblock = blkchain->blocks;
  6512. deleted_block = oldblock->block_seen_order;
  6513. HASH_DEL(blkchain->blocks, oldblock);
  6514. free(oldblock);
  6515. }
  6516. HASH_ADD(hh, blkchain->blocks, prevblkhash, sizeof(s->prevblkhash), s);
  6517. set_blockdiff(goal, work);
  6518. wr_unlock(&blk_lock);
  6519. pool->block_id = block_id;
  6520. pool_update_work_restart_time(pool);
  6521. if (deleted_block)
  6522. applog(LOG_DEBUG, "Deleted block %d from database", deleted_block);
  6523. #if BLKMAKER_VERSION > 1
  6524. template_nonce = 0;
  6525. #endif
  6526. set_curblock(goal, s);
  6527. if (unlikely(new_blocks == 1))
  6528. goto out_free;
  6529. if (!work->stratum)
  6530. {
  6531. if (work->longpoll)
  6532. {
  6533. applog(LOG_NOTICE, "Longpoll from pool %d detected new block",
  6534. pool->pool_no);
  6535. }
  6536. else
  6537. if (goal->have_longpoll)
  6538. applog(LOG_NOTICE, "New block detected on network before longpoll");
  6539. else
  6540. applog(LOG_NOTICE, "New block detected on network");
  6541. }
  6542. restart_threads();
  6543. }
  6544. else
  6545. {
  6546. bool restart = false;
  6547. if (unlikely(pool->block_id != block_id))
  6548. {
  6549. bool was_active = pool->block_id != 0;
  6550. pool->block_id = block_id;
  6551. pool_update_work_restart_time(pool);
  6552. if (!work->longpoll)
  6553. update_last_work(work);
  6554. if (was_active)
  6555. {
  6556. // Pool actively changed block
  6557. if (pool == current_pool())
  6558. restart = true;
  6559. if (block_id == blkchain->currentblk->block_id)
  6560. {
  6561. // Caught up, only announce if this pool is the one in use
  6562. if (restart)
  6563. applog(LOG_NOTICE, "%s %d caught up to new block",
  6564. work->longpoll ? "Longpoll from pool" : "Pool",
  6565. pool->pool_no);
  6566. }
  6567. else
  6568. {
  6569. // Switched to a block we know, but not the latest... why?
  6570. // This might detect pools trying to double-spend or 51%,
  6571. // but let's not make any accusations until it's had time
  6572. // in the real world.
  6573. char hexstr[65];
  6574. blkhashstr(hexstr, prevblkhash);
  6575. applog(LOG_WARNING, "%s %d is issuing work for an old block: %s",
  6576. work->longpoll ? "Longpoll from pool" : "Pool",
  6577. pool->pool_no,
  6578. hexstr);
  6579. }
  6580. }
  6581. }
  6582. if (work->longpoll)
  6583. {
  6584. struct pool * const cp = current_pool();
  6585. ++pool->work_restart_id;
  6586. if (work->tr && work->tr == pool->swork.tr)
  6587. pool->swork.work_restart_id = pool->work_restart_id;
  6588. update_last_work(work);
  6589. pool_update_work_restart_time(pool);
  6590. applog(
  6591. ((!opt_quiet_work_updates) && pool_actively_in_use(pool, cp) ? LOG_NOTICE : LOG_DEBUG),
  6592. "Longpoll from pool %d requested work update",
  6593. pool->pool_no);
  6594. if ((!restart) && pool == cp)
  6595. restart = true;
  6596. }
  6597. if (restart)
  6598. restart_threads();
  6599. }
  6600. work->longpoll = false;
  6601. out_free:
  6602. return ret;
  6603. }
  6604. static int tv_sort(struct work *worka, struct work *workb)
  6605. {
  6606. return worka->tv_staged.tv_sec - workb->tv_staged.tv_sec;
  6607. }
  6608. static bool work_rollable(struct work *work)
  6609. {
  6610. return (!work->clone && work->rolltime);
  6611. }
  6612. static bool hash_push(struct work *work)
  6613. {
  6614. bool rc = true;
  6615. mutex_lock(stgd_lock);
  6616. if (work_rollable(work))
  6617. staged_rollable++;
  6618. ++work_mining_algorithm(work)->staged;
  6619. if (work->spare)
  6620. ++staged_spare;
  6621. if (likely(!getq->frozen)) {
  6622. HASH_ADD_INT(staged_work, id, work);
  6623. HASH_SORT(staged_work, tv_sort);
  6624. } else
  6625. rc = false;
  6626. pthread_cond_broadcast(&getq->cond);
  6627. mutex_unlock(stgd_lock);
  6628. return rc;
  6629. }
  6630. static void stage_work(struct work *work)
  6631. {
  6632. applog(LOG_DEBUG, "Pushing work %d from pool %d to hash queue",
  6633. work->id, work->pool->pool_no);
  6634. work->work_restart_id = work->pool->work_restart_id;
  6635. work->pool->last_work_time = time(NULL);
  6636. cgtime(&work->pool->tv_last_work_time);
  6637. test_work_current(work);
  6638. work->pool->works++;
  6639. hash_push(work);
  6640. }
  6641. #ifdef HAVE_CURSES
  6642. int curses_int(const char *query)
  6643. {
  6644. int ret;
  6645. char *cvar;
  6646. cvar = curses_input(query);
  6647. if (unlikely(!cvar))
  6648. return -1;
  6649. ret = atoi(cvar);
  6650. free(cvar);
  6651. return ret;
  6652. }
  6653. #endif
  6654. #ifdef HAVE_CURSES
  6655. static bool input_pool(bool live);
  6656. #endif
  6657. #ifdef HAVE_CURSES
  6658. static void display_pool_summary(struct pool *pool)
  6659. {
  6660. double efficiency = 0.0;
  6661. char xfer[ALLOC_H2B_NOUNIT+ALLOC_H2B_SPACED+4+1], bw[ALLOC_H2B_NOUNIT+ALLOC_H2B_SPACED+6+1];
  6662. int pool_secs;
  6663. if (curses_active_locked()) {
  6664. wlog("Pool: %s Goal: %s\n", pool->rpc_url, pool->goal->name);
  6665. if (pool->solved)
  6666. wlog("SOLVED %d BLOCK%s!\n", pool->solved, pool->solved > 1 ? "S" : "");
  6667. if (!pool->has_stratum)
  6668. wlog("%s own long-poll support\n", pool->lp_url ? "Has" : "Does not have");
  6669. wlog(" Queued work requests: %d\n", pool->getwork_requested);
  6670. wlog(" Share submissions: %d\n", pool->accepted + pool->rejected);
  6671. wlog(" Accepted shares: %d\n", pool->accepted);
  6672. wlog(" Rejected shares: %d + %d stale (%.2f%%)\n",
  6673. pool->rejected, pool->stale_shares,
  6674. (float)(pool->rejected + pool->stale_shares) / (float)(pool->rejected + pool->stale_shares + pool->accepted)
  6675. );
  6676. wlog(" Accepted difficulty shares: %1.f\n", pool->diff_accepted);
  6677. wlog(" Rejected difficulty shares: %1.f\n", pool->diff_rejected);
  6678. pool_secs = timer_elapsed(&pool->cgminer_stats.start_tv, NULL);
  6679. wlog(" Network transfer: %s (%s)\n",
  6680. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  6681. (float)pool->cgminer_pool_stats.net_bytes_received,
  6682. (float)pool->cgminer_pool_stats.net_bytes_sent),
  6683. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  6684. (float)(pool->cgminer_pool_stats.net_bytes_received / pool_secs),
  6685. (float)(pool->cgminer_pool_stats.net_bytes_sent / pool_secs)));
  6686. uint64_t pool_bytes_xfer = pool->cgminer_pool_stats.net_bytes_received + pool->cgminer_pool_stats.net_bytes_sent;
  6687. efficiency = pool_bytes_xfer ? pool->diff_accepted * 2048. / pool_bytes_xfer : 0.0;
  6688. wlog(" Efficiency (accepted * difficulty / 2 KB): %.2f\n", efficiency);
  6689. wlog(" Items worked on: %d\n", pool->works);
  6690. wlog(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  6691. wlog(" Unable to get work from server occasions: %d\n", pool->getfail_occasions);
  6692. wlog(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  6693. unlock_curses();
  6694. }
  6695. }
  6696. #endif
  6697. /* We can't remove the memory used for this struct pool because there may
  6698. * still be work referencing it. We just remove it from the pools list */
  6699. void remove_pool(struct pool *pool)
  6700. {
  6701. int i, last_pool = total_pools - 1;
  6702. struct pool *other;
  6703. disable_pool(pool, POOL_DISABLED);
  6704. /* Boost priority of any lower prio than this one */
  6705. for (i = 0; i < total_pools; i++) {
  6706. other = pools[i];
  6707. if (other->prio > pool->prio)
  6708. other->prio--;
  6709. }
  6710. if (pool->pool_no < last_pool) {
  6711. /* Swap the last pool for this one */
  6712. (pools[last_pool])->pool_no = pool->pool_no;
  6713. pools[pool->pool_no] = pools[last_pool];
  6714. }
  6715. /* Give it an invalid number */
  6716. pool->pool_no = total_pools;
  6717. pool->removed = true;
  6718. pool->has_stratum = false;
  6719. total_pools--;
  6720. }
  6721. /* add a mutex if this needs to be thread safe in the future */
  6722. static struct JE {
  6723. char *buf;
  6724. struct JE *next;
  6725. } *jedata = NULL;
  6726. static void json_escape_free()
  6727. {
  6728. struct JE *jeptr = jedata;
  6729. struct JE *jenext;
  6730. jedata = NULL;
  6731. while (jeptr) {
  6732. jenext = jeptr->next;
  6733. free(jeptr->buf);
  6734. free(jeptr);
  6735. jeptr = jenext;
  6736. }
  6737. }
  6738. static
  6739. char *json_escape(const char *str)
  6740. {
  6741. struct JE *jeptr;
  6742. char *buf, *ptr;
  6743. /* 2x is the max, may as well just allocate that */
  6744. ptr = buf = malloc(strlen(str) * 2 + 1);
  6745. jeptr = malloc(sizeof(*jeptr));
  6746. jeptr->buf = buf;
  6747. jeptr->next = jedata;
  6748. jedata = jeptr;
  6749. while (*str) {
  6750. if (*str == '\\' || *str == '"')
  6751. *(ptr++) = '\\';
  6752. *(ptr++) = *(str++);
  6753. }
  6754. *ptr = '\0';
  6755. return buf;
  6756. }
  6757. static
  6758. void _write_config_string_elist(FILE *fcfg, const char *configname, struct string_elist * const elist)
  6759. {
  6760. if (!elist)
  6761. return;
  6762. static struct string_elist *entry;
  6763. fprintf(fcfg, ",\n\"%s\" : [", configname);
  6764. bool first = true;
  6765. DL_FOREACH(elist, entry)
  6766. {
  6767. const char * const s = entry->string;
  6768. fprintf(fcfg, "%s\n\t\"%s\"", first ? "" : ",", json_escape(s));
  6769. first = false;
  6770. }
  6771. fprintf(fcfg, "\n]");
  6772. }
  6773. void write_config(FILE *fcfg)
  6774. {
  6775. int i;
  6776. /* Write pool values */
  6777. fputs("{\n\"pools\" : [", fcfg);
  6778. for(i = 0; i < total_pools; i++) {
  6779. struct pool *pool = pools[i];
  6780. if (pool->failover_only)
  6781. // Don't write failover-only (automatically added) pools to the config file for now
  6782. continue;
  6783. if (pool->quota != 1) {
  6784. fprintf(fcfg, "%s\n\t{\n\t\t\"quota\" : \"%d;%s\",", i > 0 ? "," : "",
  6785. pool->quota,
  6786. json_escape(pool->rpc_url));
  6787. } else {
  6788. fprintf(fcfg, "%s\n\t{\n\t\t\"url\" : \"%s\",", i > 0 ? "," : "",
  6789. json_escape(pool->rpc_url));
  6790. }
  6791. if (pool->rpc_proxy)
  6792. fprintf(fcfg, "\n\t\t\"pool-proxy\" : \"%s\",", json_escape(pool->rpc_proxy));
  6793. fprintf(fcfg, "\n\t\t\"user\" : \"%s\",", json_escape(pool->rpc_user));
  6794. fprintf(fcfg, "\n\t\t\"pass\" : \"%s\",", json_escape(pool->rpc_pass));
  6795. if (strcmp(pool->goal->name, "default"))
  6796. fprintf(fcfg, "\n\t\t\"pool-goal\" : \"%s\",", pool->goal->name);
  6797. fprintf(fcfg, "\n\t\t\"pool-priority\" : \"%d\"", pool->prio);
  6798. if (pool->force_rollntime)
  6799. fprintf(fcfg, ",\n\t\t\"force-rollntime\" : %d", pool->force_rollntime);
  6800. fprintf(fcfg, "\n\t}");
  6801. }
  6802. fputs("\n]\n", fcfg);
  6803. #ifdef USE_OPENCL
  6804. write_config_opencl(fcfg);
  6805. #endif
  6806. #if defined(USE_CPUMINING) && defined(USE_SHA256D)
  6807. fprintf(fcfg, ",\n\"algo\" : \"%s\"", algo_names[opt_algo]);
  6808. #endif
  6809. /* Simple bool and int options */
  6810. struct opt_table *opt;
  6811. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  6812. char *p, *name = strdup(opt->names);
  6813. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  6814. if (p[1] != '-')
  6815. continue;
  6816. if (opt->type & OPT_NOARG &&
  6817. ((void *)opt->cb == (void *)opt_set_bool || (void *)opt->cb == (void *)opt_set_invbool) &&
  6818. (*(bool *)opt->u.arg == ((void *)opt->cb == (void *)opt_set_bool)))
  6819. fprintf(fcfg, ",\n\"%s\" : true", p+2);
  6820. if (opt->type & OPT_HASARG &&
  6821. ((void *)opt->cb_arg == (void *)set_int_0_to_9999 ||
  6822. (void *)opt->cb_arg == (void *)set_int_1_to_65535 ||
  6823. (void *)opt->cb_arg == (void *)set_int_0_to_10 ||
  6824. (void *)opt->cb_arg == (void *)set_int_1_to_10) &&
  6825. opt->desc != opt_hidden &&
  6826. 0 <= *(int *)opt->u.arg)
  6827. fprintf(fcfg, ",\n\"%s\" : \"%d\"", p+2, *(int *)opt->u.arg);
  6828. }
  6829. free(name);
  6830. }
  6831. /* Special case options */
  6832. if (request_target_str)
  6833. {
  6834. if (request_pdiff == (long)request_pdiff)
  6835. fprintf(fcfg, ",\n\"request-diff\" : %ld", (long)request_pdiff);
  6836. else
  6837. fprintf(fcfg, ",\n\"request-diff\" : %f", request_pdiff);
  6838. }
  6839. fprintf(fcfg, ",\n\"shares\" : %g", opt_shares);
  6840. if (pool_strategy == POOL_BALANCE)
  6841. fputs(",\n\"balance\" : true", fcfg);
  6842. if (pool_strategy == POOL_LOADBALANCE)
  6843. fputs(",\n\"load-balance\" : true", fcfg);
  6844. if (pool_strategy == POOL_ROUNDROBIN)
  6845. fputs(",\n\"round-robin\" : true", fcfg);
  6846. if (pool_strategy == POOL_ROTATE)
  6847. fprintf(fcfg, ",\n\"rotate\" : \"%d\"", opt_rotate_period);
  6848. #if defined(unix) || defined(__APPLE__)
  6849. if (opt_stderr_cmd && *opt_stderr_cmd)
  6850. fprintf(fcfg, ",\n\"monitor\" : \"%s\"", json_escape(opt_stderr_cmd));
  6851. #endif // defined(unix)
  6852. if (opt_kernel_path && *opt_kernel_path) {
  6853. char *kpath = strdup(opt_kernel_path);
  6854. if (kpath[strlen(kpath)-1] == '/')
  6855. kpath[strlen(kpath)-1] = 0;
  6856. fprintf(fcfg, ",\n\"kernel-path\" : \"%s\"", json_escape(kpath));
  6857. free(kpath);
  6858. }
  6859. if (schedstart.enable)
  6860. fprintf(fcfg, ",\n\"sched-time\" : \"%d:%d\"", schedstart.tm.tm_hour, schedstart.tm.tm_min);
  6861. if (schedstop.enable)
  6862. fprintf(fcfg, ",\n\"stop-time\" : \"%d:%d\"", schedstop.tm.tm_hour, schedstop.tm.tm_min);
  6863. if (opt_socks_proxy && *opt_socks_proxy)
  6864. fprintf(fcfg, ",\n\"socks-proxy\" : \"%s\"", json_escape(opt_socks_proxy));
  6865. _write_config_string_elist(fcfg, "scan", scan_devices);
  6866. #ifdef USE_LIBMICROHTTPD
  6867. if (httpsrv_port != -1)
  6868. fprintf(fcfg, ",\n\"http-port\" : %d", httpsrv_port);
  6869. #endif
  6870. #ifdef USE_LIBEVENT
  6871. if (stratumsrv_port != -1)
  6872. fprintf(fcfg, ",\n\"stratum-port\" : %d", stratumsrv_port);
  6873. #endif
  6874. _write_config_string_elist(fcfg, "device", opt_devices_enabled_list);
  6875. _write_config_string_elist(fcfg, "set-device", opt_set_device_list);
  6876. if (opt_api_allow)
  6877. fprintf(fcfg, ",\n\"api-allow\" : \"%s\"", json_escape(opt_api_allow));
  6878. if (strcmp(opt_api_mcast_addr, API_MCAST_ADDR) != 0)
  6879. fprintf(fcfg, ",\n\"api-mcast-addr\" : \"%s\"", json_escape(opt_api_mcast_addr));
  6880. if (strcmp(opt_api_mcast_code, API_MCAST_CODE) != 0)
  6881. fprintf(fcfg, ",\n\"api-mcast-code\" : \"%s\"", json_escape(opt_api_mcast_code));
  6882. if (*opt_api_mcast_des)
  6883. fprintf(fcfg, ",\n\"api-mcast-des\" : \"%s\"", json_escape(opt_api_mcast_des));
  6884. if (strcmp(opt_api_description, PACKAGE_STRING) != 0)
  6885. fprintf(fcfg, ",\n\"api-description\" : \"%s\"", json_escape(opt_api_description));
  6886. if (opt_api_groups)
  6887. fprintf(fcfg, ",\n\"api-groups\" : \"%s\"", json_escape(opt_api_groups));
  6888. fputs("\n}\n", fcfg);
  6889. json_escape_free();
  6890. }
  6891. void zero_bestshare(void)
  6892. {
  6893. int i;
  6894. best_diff = 0;
  6895. suffix_string(best_diff, best_share, sizeof(best_share), 0);
  6896. for (i = 0; i < total_pools; i++) {
  6897. struct pool *pool = pools[i];
  6898. pool->best_diff = 0;
  6899. }
  6900. }
  6901. void zero_stats(void)
  6902. {
  6903. int i;
  6904. applog(LOG_DEBUG, "Zeroing stats");
  6905. cgtime(&total_tv_start);
  6906. miner_started = total_tv_start;
  6907. total_rolling = 0;
  6908. total_mhashes_done = 0;
  6909. total_getworks = 0;
  6910. total_accepted = 0;
  6911. total_rejected = 0;
  6912. hw_errors = 0;
  6913. total_stale = 0;
  6914. total_discarded = 0;
  6915. total_bytes_rcvd = total_bytes_sent = 0;
  6916. new_blocks = 0;
  6917. local_work = 0;
  6918. total_go = 0;
  6919. total_ro = 0;
  6920. total_secs = 1.0;
  6921. total_diff1 = 0;
  6922. total_bad_diff1 = 0;
  6923. found_blocks = 0;
  6924. total_diff_accepted = 0;
  6925. total_diff_rejected = 0;
  6926. total_diff_stale = 0;
  6927. #ifdef HAVE_CURSES
  6928. awidth = rwidth = swidth = hwwidth = 1;
  6929. #endif
  6930. struct mining_goal_info *goal, *tmpgoal;
  6931. HASH_ITER(hh, mining_goals, goal, tmpgoal)
  6932. {
  6933. goal->diff_accepted = 0;
  6934. }
  6935. for (i = 0; i < total_pools; i++) {
  6936. struct pool *pool = pools[i];
  6937. pool->getwork_requested = 0;
  6938. pool->accepted = 0;
  6939. pool->rejected = 0;
  6940. pool->solved = 0;
  6941. pool->getwork_requested = 0;
  6942. pool->stale_shares = 0;
  6943. pool->discarded_work = 0;
  6944. pool->getfail_occasions = 0;
  6945. pool->remotefail_occasions = 0;
  6946. pool->last_share_time = 0;
  6947. pool->works = 0;
  6948. pool->diff1 = 0;
  6949. pool->diff_accepted = 0;
  6950. pool->diff_rejected = 0;
  6951. pool->diff_stale = 0;
  6952. pool->last_share_diff = 0;
  6953. pool->cgminer_stats.start_tv = total_tv_start;
  6954. pool->cgminer_stats.getwork_calls = 0;
  6955. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6956. pool->cgminer_stats.getwork_wait_max.tv_sec = 0;
  6957. pool->cgminer_stats.getwork_wait_max.tv_usec = 0;
  6958. pool->cgminer_pool_stats.getwork_calls = 0;
  6959. pool->cgminer_pool_stats.getwork_attempts = 0;
  6960. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6961. pool->cgminer_pool_stats.getwork_wait_max.tv_sec = 0;
  6962. pool->cgminer_pool_stats.getwork_wait_max.tv_usec = 0;
  6963. pool->cgminer_pool_stats.min_diff = 0;
  6964. pool->cgminer_pool_stats.max_diff = 0;
  6965. pool->cgminer_pool_stats.min_diff_count = 0;
  6966. pool->cgminer_pool_stats.max_diff_count = 0;
  6967. pool->cgminer_pool_stats.times_sent = 0;
  6968. pool->cgminer_pool_stats.bytes_sent = 0;
  6969. pool->cgminer_pool_stats.net_bytes_sent = 0;
  6970. pool->cgminer_pool_stats.times_received = 0;
  6971. pool->cgminer_pool_stats.bytes_received = 0;
  6972. pool->cgminer_pool_stats.net_bytes_received = 0;
  6973. }
  6974. zero_bestshare();
  6975. for (i = 0; i < total_devices; ++i) {
  6976. struct cgpu_info *cgpu = get_devices(i);
  6977. mutex_lock(&hash_lock);
  6978. cgpu->total_mhashes = 0;
  6979. cgpu->accepted = 0;
  6980. cgpu->rejected = 0;
  6981. cgpu->stale = 0;
  6982. cgpu->hw_errors = 0;
  6983. cgpu->utility = 0.0;
  6984. cgpu->utility_diff1 = 0;
  6985. cgpu->last_share_pool_time = 0;
  6986. cgpu->bad_diff1 = 0;
  6987. cgpu->diff1 = 0;
  6988. cgpu->diff_accepted = 0;
  6989. cgpu->diff_rejected = 0;
  6990. cgpu->diff_stale = 0;
  6991. cgpu->last_share_diff = 0;
  6992. cgpu->thread_fail_init_count = 0;
  6993. cgpu->thread_zero_hash_count = 0;
  6994. cgpu->thread_fail_queue_count = 0;
  6995. cgpu->dev_sick_idle_60_count = 0;
  6996. cgpu->dev_dead_idle_600_count = 0;
  6997. cgpu->dev_nostart_count = 0;
  6998. cgpu->dev_over_heat_count = 0;
  6999. cgpu->dev_thermal_cutoff_count = 0;
  7000. cgpu->dev_comms_error_count = 0;
  7001. cgpu->dev_throttle_count = 0;
  7002. cgpu->cgminer_stats.start_tv = total_tv_start;
  7003. cgpu->cgminer_stats.getwork_calls = 0;
  7004. cgpu->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  7005. cgpu->cgminer_stats.getwork_wait_max.tv_sec = 0;
  7006. cgpu->cgminer_stats.getwork_wait_max.tv_usec = 0;
  7007. mutex_unlock(&hash_lock);
  7008. if (cgpu->drv->zero_stats)
  7009. cgpu->drv->zero_stats(cgpu);
  7010. }
  7011. }
  7012. #ifdef HAVE_CURSES
  7013. static
  7014. void loginput_mode(const int size)
  7015. {
  7016. clear_logwin();
  7017. loginput_size = size;
  7018. check_winsizes();
  7019. }
  7020. static void display_pools(void)
  7021. {
  7022. struct pool *pool;
  7023. int selected, i, j;
  7024. char input;
  7025. loginput_mode(7 + total_pools);
  7026. immedok(logwin, true);
  7027. updated:
  7028. for (j = 0; j < total_pools; j++) {
  7029. for (i = 0; i < total_pools; i++) {
  7030. pool = pools[i];
  7031. if (pool->prio != j)
  7032. continue;
  7033. if (pool_actively_in_use(pool, NULL))
  7034. wattron(logwin, A_BOLD);
  7035. if (pool->enabled != POOL_ENABLED || pool->failover_only)
  7036. wattron(logwin, A_DIM);
  7037. wlogprint("%d: ", pool->prio);
  7038. switch (pool->enabled) {
  7039. case POOL_ENABLED:
  7040. if ((pool_strategy == POOL_LOADBALANCE) ? (!pool->quota)
  7041. : ((pool_strategy != POOL_FAILOVER) ? pool->failover_only : 0))
  7042. wlogprint("Failover ");
  7043. else
  7044. wlogprint("Enabled ");
  7045. break;
  7046. case POOL_DISABLED:
  7047. wlogprint("Disabled ");
  7048. break;
  7049. case POOL_REJECTING:
  7050. wlogprint("Rejectin ");
  7051. break;
  7052. case POOL_MISBEHAVING:
  7053. wlogprint("Misbehav ");
  7054. break;
  7055. }
  7056. _wlogprint(pool_proto_str(pool));
  7057. wlogprint(" Quota %d Pool %d: %s User:%s\n",
  7058. pool->quota,
  7059. pool->pool_no,
  7060. pool->rpc_url, pool->rpc_user);
  7061. wattroff(logwin, A_BOLD | A_DIM);
  7062. break; //for (i = 0; i < total_pools; i++)
  7063. }
  7064. }
  7065. retry:
  7066. wlogprint("\nCurrent pool management strategy: %s\n",
  7067. strategies[pool_strategy].s);
  7068. if (pool_strategy == POOL_ROTATE)
  7069. wlogprint("Set to rotate every %d minutes\n", opt_rotate_period);
  7070. wlogprint("[F]ailover only %s\n", opt_fail_only ? "enabled" : "disabled");
  7071. wlogprint("Pool [A]dd [R]emove [D]isable [E]nable [P]rioritize [Q]uota change\n");
  7072. wlogprint("[C]hange management strategy [S]witch pool [I]nformation\n");
  7073. wlogprint("Or press any other key to continue\n");
  7074. logwin_update();
  7075. input = getch();
  7076. if (!strncasecmp(&input, "a", 1)) {
  7077. if (opt_benchmark)
  7078. {
  7079. wlogprint("Cannot add pools in benchmark mode");
  7080. goto retry;
  7081. }
  7082. input_pool(true);
  7083. goto updated;
  7084. } else if (!strncasecmp(&input, "r", 1)) {
  7085. if (total_pools <= 1) {
  7086. wlogprint("Cannot remove last pool");
  7087. goto retry;
  7088. }
  7089. selected = curses_int("Select pool number");
  7090. if (selected < 0 || selected >= total_pools) {
  7091. wlogprint("Invalid selection\n");
  7092. goto retry;
  7093. }
  7094. pool = pools[selected];
  7095. if (pool == current_pool())
  7096. switch_pools(NULL);
  7097. if (pool == current_pool()) {
  7098. wlogprint("Unable to remove pool due to activity\n");
  7099. goto retry;
  7100. }
  7101. remove_pool(pool);
  7102. goto updated;
  7103. } else if (!strncasecmp(&input, "s", 1)) {
  7104. selected = curses_int("Select pool number");
  7105. if (selected < 0 || selected >= total_pools) {
  7106. wlogprint("Invalid selection\n");
  7107. goto retry;
  7108. }
  7109. pool = pools[selected];
  7110. manual_enable_pool(pool);
  7111. switch_pools(pool);
  7112. goto updated;
  7113. } else if (!strncasecmp(&input, "d", 1)) {
  7114. if (enabled_pools <= 1) {
  7115. wlogprint("Cannot disable last pool");
  7116. goto retry;
  7117. }
  7118. selected = curses_int("Select pool number");
  7119. if (selected < 0 || selected >= total_pools) {
  7120. wlogprint("Invalid selection\n");
  7121. goto retry;
  7122. }
  7123. pool = pools[selected];
  7124. disable_pool(pool, POOL_DISABLED);
  7125. goto updated;
  7126. } else if (!strncasecmp(&input, "e", 1)) {
  7127. selected = curses_int("Select pool number");
  7128. if (selected < 0 || selected >= total_pools) {
  7129. wlogprint("Invalid selection\n");
  7130. goto retry;
  7131. }
  7132. pool = pools[selected];
  7133. manual_enable_pool(pool);
  7134. goto updated;
  7135. } else if (!strncasecmp(&input, "c", 1)) {
  7136. for (i = 0; i <= TOP_STRATEGY; i++)
  7137. wlogprint("%d: %s\n", i, strategies[i].s);
  7138. selected = curses_int("Select strategy number type");
  7139. if (selected < 0 || selected > TOP_STRATEGY) {
  7140. wlogprint("Invalid selection\n");
  7141. goto retry;
  7142. }
  7143. if (selected == POOL_ROTATE) {
  7144. opt_rotate_period = curses_int("Select interval in minutes");
  7145. if (opt_rotate_period < 0 || opt_rotate_period > 9999) {
  7146. opt_rotate_period = 0;
  7147. wlogprint("Invalid selection\n");
  7148. goto retry;
  7149. }
  7150. }
  7151. mutex_lock(&lp_lock);
  7152. pool_strategy = selected;
  7153. pthread_cond_broadcast(&lp_cond);
  7154. mutex_unlock(&lp_lock);
  7155. switch_pools(NULL);
  7156. goto updated;
  7157. } else if (!strncasecmp(&input, "i", 1)) {
  7158. selected = curses_int("Select pool number");
  7159. if (selected < 0 || selected >= total_pools) {
  7160. wlogprint("Invalid selection\n");
  7161. goto retry;
  7162. }
  7163. pool = pools[selected];
  7164. display_pool_summary(pool);
  7165. goto retry;
  7166. } else if (!strncasecmp(&input, "q", 1)) {
  7167. selected = curses_int("Select pool number");
  7168. if (selected < 0 || selected >= total_pools) {
  7169. wlogprint("Invalid selection\n");
  7170. goto retry;
  7171. }
  7172. pool = pools[selected];
  7173. selected = curses_int("Set quota");
  7174. if (selected < 0) {
  7175. wlogprint("Invalid negative quota\n");
  7176. goto retry;
  7177. }
  7178. if (selected > 0)
  7179. pool->failover_only = false;
  7180. pool->quota = selected;
  7181. adjust_quota_gcd();
  7182. goto updated;
  7183. } else if (!strncasecmp(&input, "f", 1)) {
  7184. opt_fail_only ^= true;
  7185. goto updated;
  7186. } else if (!strncasecmp(&input, "p", 1)) {
  7187. char *prilist = curses_input("Enter new pool priority (comma separated list)");
  7188. if (!prilist)
  7189. {
  7190. wlogprint("Not changing priorities\n");
  7191. goto retry;
  7192. }
  7193. int res = prioritize_pools(prilist, &i);
  7194. free(prilist);
  7195. switch (res) {
  7196. case MSG_NOPOOL:
  7197. wlogprint("No pools\n");
  7198. goto retry;
  7199. case MSG_MISPID:
  7200. wlogprint("Missing pool id parameter\n");
  7201. goto retry;
  7202. case MSG_INVPID:
  7203. wlogprint("Invalid pool id %d - range is 0 - %d\n", i, total_pools - 1);
  7204. goto retry;
  7205. case MSG_DUPPID:
  7206. wlogprint("Duplicate pool specified %d\n", i);
  7207. goto retry;
  7208. case MSG_POOLPRIO:
  7209. default:
  7210. goto updated;
  7211. }
  7212. }
  7213. immedok(logwin, false);
  7214. loginput_mode(0);
  7215. }
  7216. static const char *summary_detail_level_str(void)
  7217. {
  7218. if (opt_compact)
  7219. return "compact";
  7220. if (opt_show_procs)
  7221. return "processors";
  7222. return "devices";
  7223. }
  7224. static void display_options(void)
  7225. {
  7226. int selected;
  7227. char input;
  7228. immedok(logwin, true);
  7229. loginput_mode(12);
  7230. retry:
  7231. clear_logwin();
  7232. wlogprint("[N]ormal [C]lear [S]ilent mode (disable all output)\n");
  7233. wlogprint("[D]ebug:%s\n[P]er-device:%s\n[Q]uiet:%s\n[V]erbose:%s\n"
  7234. "[R]PC debug:%s\n[W]orkTime details:%s\nsu[M]mary detail level:%s\n"
  7235. "[L]og interval:%d\nS[T]atistical counts: %s\n[Z]ero statistics\n",
  7236. opt_debug_console ? "on" : "off",
  7237. want_per_device_stats? "on" : "off",
  7238. opt_quiet ? "on" : "off",
  7239. opt_log_output ? "on" : "off",
  7240. opt_protocol ? "on" : "off",
  7241. opt_worktime ? "on" : "off",
  7242. summary_detail_level_str(),
  7243. opt_log_interval,
  7244. opt_weighed_stats ? "weighed" : "absolute");
  7245. wlogprint("Select an option or any other key to return\n");
  7246. logwin_update();
  7247. input = getch();
  7248. if (!strncasecmp(&input, "q", 1)) {
  7249. opt_quiet ^= true;
  7250. wlogprint("Quiet mode %s\n", opt_quiet ? "enabled" : "disabled");
  7251. goto retry;
  7252. } else if (!strncasecmp(&input, "v", 1)) {
  7253. opt_log_output ^= true;
  7254. if (opt_log_output)
  7255. opt_quiet = false;
  7256. wlogprint("Verbose mode %s\n", opt_log_output ? "enabled" : "disabled");
  7257. goto retry;
  7258. } else if (!strncasecmp(&input, "n", 1)) {
  7259. opt_log_output = false;
  7260. opt_debug_console = false;
  7261. opt_quiet = false;
  7262. opt_protocol = false;
  7263. opt_compact = false;
  7264. opt_show_procs = false;
  7265. devsummaryYOffset = 0;
  7266. want_per_device_stats = false;
  7267. wlogprint("Output mode reset to normal\n");
  7268. switch_logsize();
  7269. goto retry;
  7270. } else if (!strncasecmp(&input, "d", 1)) {
  7271. opt_debug = true;
  7272. opt_debug_console ^= true;
  7273. opt_log_output = opt_debug_console;
  7274. if (opt_debug_console)
  7275. opt_quiet = false;
  7276. wlogprint("Debug mode %s\n", opt_debug_console ? "enabled" : "disabled");
  7277. goto retry;
  7278. } else if (!strncasecmp(&input, "m", 1)) {
  7279. if (opt_compact)
  7280. opt_compact = false;
  7281. else
  7282. if (!opt_show_procs)
  7283. opt_show_procs = true;
  7284. else
  7285. {
  7286. opt_compact = true;
  7287. opt_show_procs = false;
  7288. devsummaryYOffset = 0;
  7289. }
  7290. wlogprint("su[M]mary detail level changed to: %s\n", summary_detail_level_str());
  7291. switch_logsize();
  7292. goto retry;
  7293. } else if (!strncasecmp(&input, "p", 1)) {
  7294. want_per_device_stats ^= true;
  7295. opt_log_output = want_per_device_stats;
  7296. wlogprint("Per-device stats %s\n", want_per_device_stats ? "enabled" : "disabled");
  7297. goto retry;
  7298. } else if (!strncasecmp(&input, "r", 1)) {
  7299. opt_protocol ^= true;
  7300. if (opt_protocol)
  7301. opt_quiet = false;
  7302. wlogprint("RPC protocol debugging %s\n", opt_protocol ? "enabled" : "disabled");
  7303. goto retry;
  7304. } else if (!strncasecmp(&input, "c", 1))
  7305. clear_logwin();
  7306. else if (!strncasecmp(&input, "l", 1)) {
  7307. selected = curses_int("Interval in seconds");
  7308. if (selected < 0 || selected > 9999) {
  7309. wlogprint("Invalid selection\n");
  7310. goto retry;
  7311. }
  7312. opt_log_interval = selected;
  7313. wlogprint("Log interval set to %d seconds\n", opt_log_interval);
  7314. goto retry;
  7315. } else if (!strncasecmp(&input, "s", 1)) {
  7316. opt_realquiet = true;
  7317. } else if (!strncasecmp(&input, "w", 1)) {
  7318. opt_worktime ^= true;
  7319. wlogprint("WorkTime details %s\n", opt_worktime ? "enabled" : "disabled");
  7320. goto retry;
  7321. } else if (!strncasecmp(&input, "t", 1)) {
  7322. opt_weighed_stats ^= true;
  7323. wlogprint("Now displaying %s statistics\n", opt_weighed_stats ? "weighed" : "absolute");
  7324. goto retry;
  7325. } else if (!strncasecmp(&input, "z", 1)) {
  7326. zero_stats();
  7327. goto retry;
  7328. }
  7329. immedok(logwin, false);
  7330. loginput_mode(0);
  7331. }
  7332. #endif
  7333. void default_save_file(char *filename)
  7334. {
  7335. #if defined(unix) || defined(__APPLE__)
  7336. if (getenv("HOME") && *getenv("HOME")) {
  7337. strcpy(filename, getenv("HOME"));
  7338. strcat(filename, "/");
  7339. }
  7340. else
  7341. strcpy(filename, "");
  7342. strcat(filename, ".bfgminer/");
  7343. mkdir(filename, 0777);
  7344. #else
  7345. strcpy(filename, "");
  7346. #endif
  7347. strcat(filename, def_conf);
  7348. }
  7349. #ifdef HAVE_CURSES
  7350. static void set_options(void)
  7351. {
  7352. int selected;
  7353. char input;
  7354. immedok(logwin, true);
  7355. loginput_mode(8);
  7356. retry:
  7357. wlogprint("\n[L]ongpoll: %s\n", want_longpoll ? "On" : "Off");
  7358. wlogprint("[Q]ueue: %d\n[S]cantime: %d\n[E]xpiry: %d\n[R]etries: %d\n"
  7359. "[W]rite config file\n[B]FGMiner restart\n",
  7360. opt_queue, opt_scantime, opt_expiry, opt_retries);
  7361. wlogprint("Select an option or any other key to return\n");
  7362. logwin_update();
  7363. input = getch();
  7364. if (!strncasecmp(&input, "q", 1)) {
  7365. selected = curses_int("Extra work items to queue");
  7366. if (selected < 0 || selected > 9999) {
  7367. wlogprint("Invalid selection\n");
  7368. goto retry;
  7369. }
  7370. opt_queue = selected;
  7371. goto retry;
  7372. } else if (!strncasecmp(&input, "l", 1)) {
  7373. if (want_longpoll)
  7374. stop_longpoll();
  7375. else
  7376. start_longpoll();
  7377. applog(LOG_WARNING, "Longpoll %s", want_longpoll ? "enabled" : "disabled");
  7378. goto retry;
  7379. } else if (!strncasecmp(&input, "s", 1)) {
  7380. selected = curses_int("Set scantime in seconds");
  7381. if (selected < 0 || selected > 9999) {
  7382. wlogprint("Invalid selection\n");
  7383. goto retry;
  7384. }
  7385. opt_scantime = selected;
  7386. goto retry;
  7387. } else if (!strncasecmp(&input, "e", 1)) {
  7388. selected = curses_int("Set expiry time in seconds");
  7389. if (selected < 0 || selected > 9999) {
  7390. wlogprint("Invalid selection\n");
  7391. goto retry;
  7392. }
  7393. opt_expiry = selected;
  7394. goto retry;
  7395. } else if (!strncasecmp(&input, "r", 1)) {
  7396. selected = curses_int("Retries before failing (-1 infinite)");
  7397. if (selected < -1 || selected > 9999) {
  7398. wlogprint("Invalid selection\n");
  7399. goto retry;
  7400. }
  7401. opt_retries = selected;
  7402. goto retry;
  7403. } else if (!strncasecmp(&input, "w", 1)) {
  7404. FILE *fcfg;
  7405. char *str, filename[PATH_MAX], prompt[PATH_MAX + 50];
  7406. default_save_file(filename);
  7407. snprintf(prompt, sizeof(prompt), "Config filename to write (Enter for default) [%s]", filename);
  7408. str = curses_input(prompt);
  7409. if (str) {
  7410. struct stat statbuf;
  7411. strcpy(filename, str);
  7412. free(str);
  7413. if (!stat(filename, &statbuf)) {
  7414. wlogprint("File exists, overwrite?\n");
  7415. input = getch();
  7416. if (strncasecmp(&input, "y", 1))
  7417. goto retry;
  7418. }
  7419. }
  7420. fcfg = fopen(filename, "w");
  7421. if (!fcfg) {
  7422. wlogprint("Cannot open or create file\n");
  7423. goto retry;
  7424. }
  7425. write_config(fcfg);
  7426. fclose(fcfg);
  7427. goto retry;
  7428. } else if (!strncasecmp(&input, "b", 1)) {
  7429. wlogprint("Are you sure?\n");
  7430. input = getch();
  7431. if (!strncasecmp(&input, "y", 1))
  7432. app_restart();
  7433. else
  7434. clear_logwin();
  7435. } else
  7436. clear_logwin();
  7437. loginput_mode(0);
  7438. immedok(logwin, false);
  7439. }
  7440. int scan_serial(const char *);
  7441. static
  7442. void _managetui_msg(const char *repr, const char **msg)
  7443. {
  7444. if (*msg)
  7445. {
  7446. applog(LOG_DEBUG, "ManageTUI: %"PRIpreprv": %s", repr, *msg);
  7447. wattron(logwin, A_BOLD);
  7448. wlogprint("%s", *msg);
  7449. wattroff(logwin, A_BOLD);
  7450. *msg = NULL;
  7451. }
  7452. logwin_update();
  7453. }
  7454. void manage_device(void)
  7455. {
  7456. char logline[256];
  7457. const char *msg = NULL;
  7458. struct cgpu_info *cgpu;
  7459. const struct device_drv *drv;
  7460. selecting_device = true;
  7461. immedok(logwin, true);
  7462. loginput_mode(12);
  7463. devchange:
  7464. if (unlikely(!total_devices))
  7465. {
  7466. clear_logwin();
  7467. wlogprint("(no devices)\n");
  7468. wlogprint("[Plus] Add device(s) [Enter] Close device manager\n");
  7469. _managetui_msg("(none)", &msg);
  7470. int input = getch();
  7471. switch (input)
  7472. {
  7473. case '+': case '=': // add new device
  7474. goto addnew;
  7475. default:
  7476. goto out;
  7477. }
  7478. }
  7479. cgpu = devices[selected_device];
  7480. drv = cgpu->drv;
  7481. refresh_devstatus();
  7482. refresh:
  7483. clear_logwin();
  7484. wlogprint("Select processor to manage using up/down arrow keys\n");
  7485. get_statline3(logline, sizeof(logline), cgpu, true, true);
  7486. wattron(logwin, A_BOLD);
  7487. wlogprint("%s", logline);
  7488. wattroff(logwin, A_BOLD);
  7489. wlogprint("\n");
  7490. if (cgpu->dev_manufacturer)
  7491. wlogprint(" %s from %s\n", (cgpu->dev_product ?: "Device"), cgpu->dev_manufacturer);
  7492. else
  7493. if (cgpu->dev_product)
  7494. wlogprint(" %s\n", cgpu->dev_product);
  7495. if (cgpu->dev_serial)
  7496. wlogprint("Serial: %s\n", cgpu->dev_serial);
  7497. if (cgpu->kname)
  7498. wlogprint("Kernel: %s\n", cgpu->kname);
  7499. if (drv->proc_wlogprint_status && likely(cgpu->status != LIFE_INIT))
  7500. drv->proc_wlogprint_status(cgpu);
  7501. wlogprint("\n");
  7502. // TODO: Last share at TIMESTAMP on pool N
  7503. // TODO: Custom device info/commands
  7504. if (cgpu->deven != DEV_ENABLED)
  7505. wlogprint("[E]nable ");
  7506. if (cgpu->deven != DEV_DISABLED)
  7507. wlogprint("[D]isable ");
  7508. if (drv->identify_device)
  7509. wlogprint("[I]dentify ");
  7510. if (drv->proc_tui_wlogprint_choices && likely(cgpu->status != LIFE_INIT))
  7511. drv->proc_tui_wlogprint_choices(cgpu);
  7512. wlogprint("\n");
  7513. wlogprint("[Slash] Find processor [Plus] Add device(s) [Enter] Close device manager\n");
  7514. _managetui_msg(cgpu->proc_repr, &msg);
  7515. while (true)
  7516. {
  7517. int input = getch();
  7518. applog(LOG_DEBUG, "ManageTUI: %"PRIpreprv": (choice %d)", cgpu->proc_repr, input);
  7519. switch (input) {
  7520. case 'd': case 'D':
  7521. if (cgpu->deven == DEV_DISABLED)
  7522. msg = "Processor already disabled\n";
  7523. else
  7524. {
  7525. cgpu->deven = DEV_DISABLED;
  7526. msg = "Processor being disabled\n";
  7527. }
  7528. goto refresh;
  7529. case 'e': case 'E':
  7530. if (cgpu->deven == DEV_ENABLED)
  7531. msg = "Processor already enabled\n";
  7532. else
  7533. {
  7534. proc_enable(cgpu);
  7535. msg = "Processor being enabled\n";
  7536. }
  7537. goto refresh;
  7538. case 'i': case 'I':
  7539. if (drv->identify_device && drv->identify_device(cgpu))
  7540. msg = "Identify command sent\n";
  7541. else
  7542. goto key_default;
  7543. goto refresh;
  7544. case KEY_DOWN:
  7545. if (selected_device >= total_devices - 1)
  7546. break;
  7547. ++selected_device;
  7548. goto devchange;
  7549. case KEY_UP:
  7550. if (selected_device <= 0)
  7551. break;
  7552. --selected_device;
  7553. goto devchange;
  7554. case KEY_NPAGE:
  7555. {
  7556. if (selected_device >= total_devices - 1)
  7557. break;
  7558. struct cgpu_info *mdev = devices[selected_device]->device;
  7559. do {
  7560. ++selected_device;
  7561. } while (devices[selected_device]->device == mdev && selected_device < total_devices - 1);
  7562. goto devchange;
  7563. }
  7564. case KEY_PPAGE:
  7565. {
  7566. if (selected_device <= 0)
  7567. break;
  7568. struct cgpu_info *mdev = devices[selected_device]->device;
  7569. do {
  7570. --selected_device;
  7571. } while (devices[selected_device]->device == mdev && selected_device > 0);
  7572. goto devchange;
  7573. }
  7574. case '/': case '?': // find device
  7575. {
  7576. static char *pattern = NULL;
  7577. char *newpattern = curses_input("Enter pattern");
  7578. if (newpattern)
  7579. {
  7580. free(pattern);
  7581. pattern = newpattern;
  7582. }
  7583. else
  7584. if (!pattern)
  7585. pattern = calloc(1, 1);
  7586. int match = cgpu_search(pattern, selected_device + 1);
  7587. if (match == -1)
  7588. {
  7589. msg = "Couldn't find device\n";
  7590. goto refresh;
  7591. }
  7592. selected_device = match;
  7593. goto devchange;
  7594. }
  7595. case '+': case '=': // add new device
  7596. {
  7597. addnew:
  7598. clear_logwin();
  7599. _wlogprint(
  7600. "Enter \"auto\", \"all\", or a serial port to probe for mining devices.\n"
  7601. "Prefix by a driver name and colon to only probe a specific driver.\n"
  7602. "For example: erupter:"
  7603. #ifdef WIN32
  7604. "\\\\.\\COM40"
  7605. #elif defined(__APPLE__)
  7606. "/dev/cu.SLAB_USBtoUART"
  7607. #else
  7608. "/dev/ttyUSB39"
  7609. #endif
  7610. "\n"
  7611. );
  7612. char *scanser = curses_input("Enter target");
  7613. if (scan_serial(scanser))
  7614. {
  7615. selected_device = total_devices - 1;
  7616. msg = "Device scan succeeded\n";
  7617. }
  7618. else
  7619. msg = "No new devices found\n";
  7620. goto devchange;
  7621. }
  7622. case 'Q': case 'q':
  7623. case KEY_BREAK: case KEY_BACKSPACE: case KEY_CANCEL: case KEY_CLOSE: case KEY_EXIT:
  7624. case '\x1b': // ESC
  7625. case KEY_ENTER:
  7626. case '\r': // Ctrl-M on Windows, with nonl
  7627. #ifdef PADENTER
  7628. case PADENTER: // pdcurses, used by Enter key on Windows with nonl
  7629. #endif
  7630. case '\n':
  7631. goto out;
  7632. default:
  7633. ;
  7634. key_default:
  7635. if (drv->proc_tui_handle_choice && likely(drv_ready(cgpu)))
  7636. {
  7637. msg = drv->proc_tui_handle_choice(cgpu, input);
  7638. if (msg)
  7639. goto refresh;
  7640. }
  7641. }
  7642. }
  7643. out:
  7644. selecting_device = false;
  7645. loginput_mode(0);
  7646. immedok(logwin, false);
  7647. }
  7648. void show_help(void)
  7649. {
  7650. loginput_mode(11);
  7651. // NOTE: wlogprint is a macro with a buffer limit
  7652. _wlogprint(
  7653. "LU: oldest explicit work update currently being used for new work\n"
  7654. "ST: work in queue | F: network fails | NB: new blocks detected\n"
  7655. "AS: shares being submitted | BW: bandwidth (up/down)\n"
  7656. "E: # shares * diff per 2kB bw | I: expected income | BS: best share ever found\n"
  7657. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7658. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7659. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7660. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_BTEE
  7661. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7662. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7663. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_BTEE U8_HLINE U8_HLINE U8_HLINE
  7664. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7665. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7666. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7667. "\n"
  7668. "devices/processors hashing (only for totals line), hottest temperature\n"
  7669. );
  7670. wlogprint(
  7671. "hashrates: %ds decaying / all-time average / all-time average (effective)\n"
  7672. , opt_log_interval);
  7673. _wlogprint(
  7674. "A: accepted shares | R: rejected+discarded(% of total)\n"
  7675. "HW: hardware errors / % nonces invalid\n"
  7676. "\n"
  7677. "Press any key to clear"
  7678. );
  7679. logwin_update();
  7680. getch();
  7681. loginput_mode(0);
  7682. }
  7683. static void *input_thread(void __maybe_unused *userdata)
  7684. {
  7685. RenameThread("input");
  7686. if (!curses_active)
  7687. return NULL;
  7688. while (1) {
  7689. int input;
  7690. input = getch();
  7691. switch (input) {
  7692. case 'h': case 'H': case '?':
  7693. case KEY_F(1):
  7694. show_help();
  7695. break;
  7696. case 'q': case 'Q':
  7697. kill_work();
  7698. return NULL;
  7699. case 'd': case 'D':
  7700. display_options();
  7701. break;
  7702. case 'm': case 'M':
  7703. manage_device();
  7704. break;
  7705. case 'p': case 'P':
  7706. display_pools();
  7707. break;
  7708. case 's': case 'S':
  7709. set_options();
  7710. break;
  7711. #ifdef HAVE_CURSES
  7712. case KEY_DOWN:
  7713. {
  7714. const int visible_lines = logcursor - devcursor;
  7715. const int invisible_lines = total_lines - visible_lines;
  7716. if (devsummaryYOffset <= -invisible_lines)
  7717. break;
  7718. devsummaryYOffset -= 2;
  7719. }
  7720. case KEY_UP:
  7721. if (devsummaryYOffset == 0)
  7722. break;
  7723. ++devsummaryYOffset;
  7724. refresh_devstatus();
  7725. break;
  7726. case KEY_NPAGE:
  7727. {
  7728. const int visible_lines = logcursor - devcursor;
  7729. const int invisible_lines = total_lines - visible_lines;
  7730. if (devsummaryYOffset - visible_lines <= -invisible_lines)
  7731. devsummaryYOffset = -invisible_lines;
  7732. else
  7733. devsummaryYOffset -= visible_lines;
  7734. refresh_devstatus();
  7735. break;
  7736. }
  7737. case KEY_PPAGE:
  7738. {
  7739. const int visible_lines = logcursor - devcursor;
  7740. if (devsummaryYOffset + visible_lines >= 0)
  7741. devsummaryYOffset = 0;
  7742. else
  7743. devsummaryYOffset += visible_lines;
  7744. refresh_devstatus();
  7745. break;
  7746. }
  7747. #endif
  7748. }
  7749. if (opt_realquiet) {
  7750. disable_curses();
  7751. break;
  7752. }
  7753. }
  7754. return NULL;
  7755. }
  7756. #endif
  7757. static void *api_thread(void *userdata)
  7758. {
  7759. struct thr_info *mythr = userdata;
  7760. pthread_detach(pthread_self());
  7761. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  7762. RenameThread("rpc");
  7763. api(api_thr_id);
  7764. mythr->has_pth = false;
  7765. return NULL;
  7766. }
  7767. void thread_reportin(struct thr_info *thr)
  7768. {
  7769. cgtime(&thr->last);
  7770. thr->cgpu->status = LIFE_WELL;
  7771. thr->getwork = 0;
  7772. thr->cgpu->device_last_well = time(NULL);
  7773. }
  7774. void thread_reportout(struct thr_info *thr)
  7775. {
  7776. thr->getwork = time(NULL);
  7777. }
  7778. static void hashmeter(int thr_id, struct timeval *diff,
  7779. uint64_t hashes_done)
  7780. {
  7781. char logstatusline[256];
  7782. struct timeval temp_tv_end, total_diff;
  7783. double secs;
  7784. double local_secs;
  7785. static double local_mhashes_done = 0;
  7786. double local_mhashes = (double)hashes_done / 1000000.0;
  7787. bool showlog = false;
  7788. char cHr[ALLOC_H2B_NOUNIT+1], aHr[ALLOC_H2B_NOUNIT+1], uHr[ALLOC_H2B_SPACED+3+1];
  7789. char rejpcbuf[6];
  7790. char bnbuf[6];
  7791. struct thr_info *thr;
  7792. /* Update the last time this thread reported in */
  7793. if (thr_id >= 0) {
  7794. thr = get_thread(thr_id);
  7795. cgtime(&(thr->last));
  7796. thr->cgpu->device_last_well = time(NULL);
  7797. }
  7798. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  7799. /* So we can call hashmeter from a non worker thread */
  7800. if (thr_id >= 0) {
  7801. struct cgpu_info *cgpu = thr->cgpu;
  7802. int threadobj = cgpu->threads ?: 1;
  7803. double thread_rolling = 0.0;
  7804. int i;
  7805. applog(LOG_DEBUG, "[thread %d: %"PRIu64" hashes, %.1f khash/sec]",
  7806. thr_id, hashes_done, hashes_done / 1000 / secs);
  7807. /* Rolling average for each thread and each device */
  7808. decay_time(&thr->rolling, local_mhashes / secs, secs);
  7809. for (i = 0; i < threadobj; i++)
  7810. thread_rolling += cgpu->thr[i]->rolling;
  7811. mutex_lock(&hash_lock);
  7812. decay_time(&cgpu->rolling, thread_rolling, secs);
  7813. cgpu->total_mhashes += local_mhashes;
  7814. mutex_unlock(&hash_lock);
  7815. // If needed, output detailed, per-device stats
  7816. if (want_per_device_stats) {
  7817. struct timeval now;
  7818. struct timeval elapsed;
  7819. struct timeval *last_msg_tv = opt_show_procs ? &thr->cgpu->last_message_tv : &thr->cgpu->device->last_message_tv;
  7820. cgtime(&now);
  7821. timersub(&now, last_msg_tv, &elapsed);
  7822. if (opt_log_interval <= elapsed.tv_sec) {
  7823. struct cgpu_info *cgpu = thr->cgpu;
  7824. char logline[255];
  7825. *last_msg_tv = now;
  7826. get_statline(logline, sizeof(logline), cgpu);
  7827. if (!curses_active) {
  7828. printf("\n%s\r", logline);
  7829. fflush(stdout);
  7830. } else
  7831. applog(LOG_INFO, "%s", logline);
  7832. }
  7833. }
  7834. }
  7835. /* Totals are updated by all threads so can race without locking */
  7836. mutex_lock(&hash_lock);
  7837. cgtime(&temp_tv_end);
  7838. timersub(&temp_tv_end, &total_tv_start, &total_diff);
  7839. total_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  7840. timersub(&temp_tv_end, &total_tv_end, &total_diff);
  7841. total_mhashes_done += local_mhashes;
  7842. local_mhashes_done += local_mhashes;
  7843. /* Only update with opt_log_interval */
  7844. if (total_diff.tv_sec < opt_log_interval)
  7845. goto out_unlock;
  7846. showlog = true;
  7847. cgtime(&total_tv_end);
  7848. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  7849. decay_time(&total_rolling, local_mhashes_done / local_secs, local_secs);
  7850. global_hashrate = ((unsigned long long)lround(total_rolling)) * 1000000;
  7851. double wtotal = (total_diff_accepted + total_diff_rejected + total_diff_stale);
  7852. multi_format_unit_array2(
  7853. ((char*[]){cHr, aHr, uHr}),
  7854. ((size_t[]){sizeof(cHr), sizeof(aHr), sizeof(uHr)}),
  7855. true, "h/s", H2B_SHORT,
  7856. 3,
  7857. 1e6*total_rolling,
  7858. 1e6*total_mhashes_done / total_secs,
  7859. utility_to_hashrate(total_diff1 * (wtotal ? (total_diff_accepted / wtotal) : 1) * 60 / total_secs));
  7860. int ui_accepted, ui_rejected, ui_stale;
  7861. if (opt_weighed_stats)
  7862. {
  7863. ui_accepted = total_diff_accepted;
  7864. ui_rejected = total_diff_rejected;
  7865. ui_stale = total_diff_stale;
  7866. }
  7867. else
  7868. {
  7869. ui_accepted = total_accepted;
  7870. ui_rejected = total_rejected;
  7871. ui_stale = total_stale;
  7872. }
  7873. #ifdef HAVE_CURSES
  7874. if (curses_active_locked()) {
  7875. float temp = 0;
  7876. struct cgpu_info *proc, *last_working_dev = NULL;
  7877. int i, working_devs = 0, working_procs = 0;
  7878. int divx;
  7879. bool bad = false;
  7880. // Find the highest temperature of all processors
  7881. for (i = 0; i < total_devices; ++i)
  7882. {
  7883. proc = get_devices(i);
  7884. if (proc->temp > temp)
  7885. temp = proc->temp;
  7886. if (unlikely(proc->deven == DEV_DISABLED))
  7887. ; // Just need to block it off from both conditions
  7888. else
  7889. if (likely(proc->status == LIFE_WELL && proc->deven == DEV_ENABLED))
  7890. {
  7891. if (proc->rolling > .1)
  7892. {
  7893. ++working_procs;
  7894. if (proc->device != last_working_dev)
  7895. {
  7896. ++working_devs;
  7897. last_working_dev = proc->device;
  7898. }
  7899. }
  7900. }
  7901. else
  7902. bad = true;
  7903. }
  7904. if (working_devs == working_procs)
  7905. snprintf(statusline, sizeof(statusline), "%s%d ", bad ? U8_BAD_START : "", working_devs);
  7906. else
  7907. snprintf(statusline, sizeof(statusline), "%s%d/%d ", bad ? U8_BAD_START : "", working_devs, working_procs);
  7908. divx = 7;
  7909. if (opt_show_procs && !opt_compact)
  7910. divx += max_lpdigits;
  7911. if (bad)
  7912. {
  7913. divx += sizeof(U8_BAD_START)-1;
  7914. strcpy(&statusline[divx], U8_BAD_END);
  7915. divx += sizeof(U8_BAD_END)-1;
  7916. }
  7917. temperature_column(&statusline[divx], sizeof(statusline)-divx, true, &temp);
  7918. format_statline(statusline, sizeof(statusline),
  7919. cHr, aHr,
  7920. uHr,
  7921. ui_accepted,
  7922. ui_rejected,
  7923. ui_stale,
  7924. total_diff_rejected + total_diff_stale, total_diff_accepted,
  7925. hw_errors,
  7926. total_bad_diff1, total_bad_diff1 + total_diff1);
  7927. unlock_curses();
  7928. }
  7929. #endif
  7930. // Add a space
  7931. memmove(&uHr[6], &uHr[5], strlen(&uHr[5]) + 1);
  7932. uHr[5] = ' ';
  7933. percentf4(rejpcbuf, sizeof(rejpcbuf), total_diff_rejected + total_diff_stale, total_diff_accepted);
  7934. percentf4(bnbuf, sizeof(bnbuf), total_bad_diff1, total_diff1);
  7935. snprintf(logstatusline, sizeof(logstatusline),
  7936. "%s%ds:%s avg:%s u:%s | A:%d R:%d+%d(%s) HW:%d/%s",
  7937. want_per_device_stats ? "ALL " : "",
  7938. opt_log_interval,
  7939. cHr, aHr,
  7940. uHr,
  7941. ui_accepted,
  7942. ui_rejected,
  7943. ui_stale,
  7944. rejpcbuf,
  7945. hw_errors,
  7946. bnbuf
  7947. );
  7948. local_mhashes_done = 0;
  7949. out_unlock:
  7950. mutex_unlock(&hash_lock);
  7951. if (showlog) {
  7952. if (!curses_active) {
  7953. if (want_per_device_stats)
  7954. printf("\n%s\r", logstatusline);
  7955. else
  7956. {
  7957. const int logstatusline_len = strlen(logstatusline);
  7958. int padding;
  7959. if (last_logstatusline_len > logstatusline_len)
  7960. padding = (last_logstatusline_len - logstatusline_len);
  7961. else
  7962. {
  7963. padding = 0;
  7964. if (last_logstatusline_len == -1)
  7965. puts("");
  7966. }
  7967. printf("%s%*s\r", logstatusline, padding, "");
  7968. last_logstatusline_len = logstatusline_len;
  7969. }
  7970. fflush(stdout);
  7971. } else
  7972. applog(LOG_INFO, "%s", logstatusline);
  7973. }
  7974. }
  7975. void hashmeter2(struct thr_info *thr)
  7976. {
  7977. struct timeval tv_now, tv_elapsed;
  7978. timerclear(&thr->tv_hashes_done);
  7979. cgtime(&tv_now);
  7980. timersub(&tv_now, &thr->tv_lastupdate, &tv_elapsed);
  7981. /* Update the hashmeter at most 5 times per second */
  7982. if ((thr->hashes_done && (tv_elapsed.tv_sec > 0 || tv_elapsed.tv_usec > 200000)) ||
  7983. tv_elapsed.tv_sec >= opt_log_interval) {
  7984. hashmeter(thr->id, &tv_elapsed, thr->hashes_done);
  7985. thr->hashes_done = 0;
  7986. thr->tv_lastupdate = tv_now;
  7987. }
  7988. }
  7989. static void stratum_share_result(json_t *val, json_t *res_val, json_t *err_val,
  7990. struct stratum_share *sshare)
  7991. {
  7992. struct work *work = sshare->work;
  7993. share_result(val, res_val, err_val, work, false, "");
  7994. }
  7995. /* Parses stratum json responses and tries to find the id that the request
  7996. * matched to and treat it accordingly. */
  7997. bool parse_stratum_response(struct pool *pool, char *s)
  7998. {
  7999. json_t *val = NULL, *err_val, *res_val, *id_val;
  8000. struct stratum_share *sshare;
  8001. json_error_t err;
  8002. bool ret = false;
  8003. int id;
  8004. val = JSON_LOADS(s, &err);
  8005. if (!val) {
  8006. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  8007. goto out;
  8008. }
  8009. res_val = json_object_get(val, "result");
  8010. err_val = json_object_get(val, "error");
  8011. id_val = json_object_get(val, "id");
  8012. if (json_is_null(id_val) || !id_val) {
  8013. char *ss;
  8014. if (err_val)
  8015. ss = json_dumps(err_val, JSON_INDENT(3));
  8016. else
  8017. ss = strdup("(unknown reason)");
  8018. applog(LOG_INFO, "JSON-RPC non method decode failed: %s", ss);
  8019. free(ss);
  8020. goto out;
  8021. }
  8022. if (!json_is_integer(id_val)) {
  8023. if (json_is_string(id_val)
  8024. && !strncmp(json_string_value(id_val), "txlist", 6))
  8025. {
  8026. const bool is_array = json_is_array(res_val);
  8027. applog(LOG_DEBUG, "Received %s for pool %u job %s",
  8028. is_array ? "transaction list" : "no-transaction-list response",
  8029. pool->pool_no, &json_string_value(id_val)[6]);
  8030. if (!is_array)
  8031. {
  8032. // No need to wait for a timeout
  8033. timer_unset(&pool->swork.tv_transparency);
  8034. pool_set_opaque(pool, true);
  8035. goto fishy;
  8036. }
  8037. if (strcmp(json_string_value(id_val) + 6, pool->swork.job_id))
  8038. // We only care about a transaction list for the current job id
  8039. goto fishy;
  8040. // Check that the transactions actually hash to the merkle links
  8041. {
  8042. unsigned maxtx = 1 << pool->swork.merkles;
  8043. unsigned mintx = maxtx >> 1;
  8044. --maxtx;
  8045. unsigned acttx = (unsigned)json_array_size(res_val);
  8046. if (acttx < mintx || acttx > maxtx) {
  8047. applog(LOG_WARNING, "Pool %u is sending mismatched block contents to us (%u is not %u-%u)",
  8048. pool->pool_no, acttx, mintx, maxtx);
  8049. goto fishy;
  8050. }
  8051. // TODO: Check hashes match actual merkle links
  8052. }
  8053. pool_set_opaque(pool, false);
  8054. timer_unset(&pool->swork.tv_transparency);
  8055. fishy:
  8056. ret = true;
  8057. }
  8058. goto out;
  8059. }
  8060. id = json_integer_value(id_val);
  8061. mutex_lock(&sshare_lock);
  8062. HASH_FIND_INT(stratum_shares, &id, sshare);
  8063. if (sshare)
  8064. HASH_DEL(stratum_shares, sshare);
  8065. mutex_unlock(&sshare_lock);
  8066. if (!sshare) {
  8067. double pool_diff;
  8068. /* Since the share is untracked, we can only guess at what the
  8069. * work difficulty is based on the current pool diff. */
  8070. cg_rlock(&pool->data_lock);
  8071. pool_diff = target_diff(pool->swork.target);
  8072. cg_runlock(&pool->data_lock);
  8073. if (json_is_true(res_val)) {
  8074. struct mining_goal_info * const goal = pool->goal;
  8075. applog(LOG_NOTICE, "Accepted untracked stratum share from pool %d", pool->pool_no);
  8076. /* We don't know what device this came from so we can't
  8077. * attribute the work to the relevant cgpu */
  8078. mutex_lock(&stats_lock);
  8079. total_accepted++;
  8080. pool->accepted++;
  8081. total_diff_accepted += pool_diff;
  8082. pool->diff_accepted += pool_diff;
  8083. goal->diff_accepted += pool_diff;
  8084. mutex_unlock(&stats_lock);
  8085. } else {
  8086. applog(LOG_NOTICE, "Rejected untracked stratum share from pool %d", pool->pool_no);
  8087. mutex_lock(&stats_lock);
  8088. total_rejected++;
  8089. pool->rejected++;
  8090. total_diff_rejected += pool_diff;
  8091. pool->diff_rejected += pool_diff;
  8092. mutex_unlock(&stats_lock);
  8093. }
  8094. goto out;
  8095. }
  8096. else {
  8097. mutex_lock(&submitting_lock);
  8098. --total_submitting;
  8099. mutex_unlock(&submitting_lock);
  8100. }
  8101. stratum_share_result(val, res_val, err_val, sshare);
  8102. free_work(sshare->work);
  8103. free(sshare);
  8104. ret = true;
  8105. out:
  8106. if (val)
  8107. json_decref(val);
  8108. return ret;
  8109. }
  8110. static void shutdown_stratum(struct pool *pool)
  8111. {
  8112. // Shut down Stratum as if we never had it
  8113. pool->stratum_active = false;
  8114. pool->stratum_init = false;
  8115. pool->has_stratum = false;
  8116. shutdown(pool->sock, SHUT_RDWR);
  8117. free(pool->stratum_url);
  8118. if (pool->sockaddr_url == pool->stratum_url)
  8119. pool->sockaddr_url = NULL;
  8120. pool->stratum_url = NULL;
  8121. }
  8122. void clear_stratum_shares(struct pool *pool)
  8123. {
  8124. int my_mining_threads = mining_threads; // Cached outside of locking
  8125. struct stratum_share *sshare, *tmpshare;
  8126. struct work *work;
  8127. struct cgpu_info *cgpu;
  8128. double diff_cleared = 0;
  8129. double thr_diff_cleared[my_mining_threads];
  8130. int cleared = 0;
  8131. int thr_cleared[my_mining_threads];
  8132. // NOTE: This is per-thread rather than per-device to avoid getting devices lock in stratum_shares loop
  8133. for (int i = 0; i < my_mining_threads; ++i)
  8134. {
  8135. thr_diff_cleared[i] = 0;
  8136. thr_cleared[i] = 0;
  8137. }
  8138. mutex_lock(&sshare_lock);
  8139. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  8140. work = sshare->work;
  8141. if (sshare->work->pool == pool && work->thr_id < my_mining_threads) {
  8142. HASH_DEL(stratum_shares, sshare);
  8143. sharelog("disconnect", work);
  8144. diff_cleared += sshare->work->work_difficulty;
  8145. thr_diff_cleared[work->thr_id] += work->work_difficulty;
  8146. ++thr_cleared[work->thr_id];
  8147. free_work(sshare->work);
  8148. free(sshare);
  8149. cleared++;
  8150. }
  8151. }
  8152. mutex_unlock(&sshare_lock);
  8153. if (cleared) {
  8154. applog(LOG_WARNING, "Lost %d shares due to stratum disconnect on pool %d", cleared, pool->pool_no);
  8155. mutex_lock(&stats_lock);
  8156. pool->stale_shares += cleared;
  8157. total_stale += cleared;
  8158. pool->diff_stale += diff_cleared;
  8159. total_diff_stale += diff_cleared;
  8160. for (int i = 0; i < my_mining_threads; ++i)
  8161. if (thr_cleared[i])
  8162. {
  8163. cgpu = get_thr_cgpu(i);
  8164. cgpu->diff_stale += thr_diff_cleared[i];
  8165. cgpu->stale += thr_cleared[i];
  8166. }
  8167. mutex_unlock(&stats_lock);
  8168. mutex_lock(&submitting_lock);
  8169. total_submitting -= cleared;
  8170. mutex_unlock(&submitting_lock);
  8171. }
  8172. }
  8173. static void resubmit_stratum_shares(struct pool *pool)
  8174. {
  8175. struct stratum_share *sshare, *tmpshare;
  8176. struct work *work;
  8177. unsigned resubmitted = 0;
  8178. mutex_lock(&sshare_lock);
  8179. mutex_lock(&submitting_lock);
  8180. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  8181. if (sshare->work->pool != pool)
  8182. continue;
  8183. HASH_DEL(stratum_shares, sshare);
  8184. work = sshare->work;
  8185. DL_APPEND(submit_waiting, work);
  8186. free(sshare);
  8187. ++resubmitted;
  8188. }
  8189. mutex_unlock(&submitting_lock);
  8190. mutex_unlock(&sshare_lock);
  8191. if (resubmitted) {
  8192. notifier_wake(submit_waiting_notifier);
  8193. applog(LOG_DEBUG, "Resubmitting %u shares due to stratum disconnect on pool %u", resubmitted, pool->pool_no);
  8194. }
  8195. }
  8196. static void clear_pool_work(struct pool *pool)
  8197. {
  8198. struct work *work, *tmp;
  8199. int cleared = 0;
  8200. mutex_lock(stgd_lock);
  8201. HASH_ITER(hh, staged_work, work, tmp) {
  8202. if (work->pool == pool) {
  8203. unstage_work(work);
  8204. free_work(work);
  8205. cleared++;
  8206. }
  8207. }
  8208. mutex_unlock(stgd_lock);
  8209. }
  8210. static int cp_prio(void)
  8211. {
  8212. int prio;
  8213. cg_rlock(&control_lock);
  8214. prio = currentpool->prio;
  8215. cg_runlock(&control_lock);
  8216. return prio;
  8217. }
  8218. /* We only need to maintain a secondary pool connection when we need the
  8219. * capacity to get work from the backup pools while still on the primary */
  8220. static bool cnx_needed(struct pool *pool)
  8221. {
  8222. struct pool *cp;
  8223. // We want to keep a connection open for rejecting or misbehaving pools, to detect when/if they change their tune
  8224. if (pool->enabled == POOL_DISABLED)
  8225. return false;
  8226. /* Idle stratum pool needs something to kick it alive again */
  8227. if (pool->has_stratum && pool->idle)
  8228. return true;
  8229. /* Getwork pools without opt_fail_only need backup pools up to be able
  8230. * to leak shares */
  8231. cp = current_pool();
  8232. if (pool_actively_desired(pool, cp))
  8233. return true;
  8234. if (!pool_localgen(cp) && (!opt_fail_only || !cp->hdr_path))
  8235. return true;
  8236. /* Keep the connection open to allow any stray shares to be submitted
  8237. * on switching pools for 2 minutes. */
  8238. if (timer_elapsed(&pool->tv_last_work_time, NULL) < 120)
  8239. return true;
  8240. /* If the pool has only just come to life and is higher priority than
  8241. * the current pool keep the connection open so we can fail back to
  8242. * it. */
  8243. if (pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  8244. return true;
  8245. if (pool_unworkable(cp))
  8246. return true;
  8247. /* We've run out of work, bring anything back to life. */
  8248. if (no_work)
  8249. return true;
  8250. // If the current pool lacks its own block change detection, see if we are needed for that
  8251. if (pool_active_lp_pool(cp) == pool)
  8252. return true;
  8253. return false;
  8254. }
  8255. static void wait_lpcurrent(struct pool *pool);
  8256. static void pool_resus(struct pool *pool);
  8257. static void stratum_resumed(struct pool *pool)
  8258. {
  8259. if (!pool->stratum_notify)
  8260. return;
  8261. if (pool_tclear(pool, &pool->idle)) {
  8262. applog(LOG_INFO, "Stratum connection to pool %d resumed", pool->pool_no);
  8263. pool_resus(pool);
  8264. }
  8265. }
  8266. static bool supports_resume(struct pool *pool)
  8267. {
  8268. bool ret;
  8269. cg_rlock(&pool->data_lock);
  8270. ret = (pool->sessionid != NULL);
  8271. cg_runlock(&pool->data_lock);
  8272. return ret;
  8273. }
  8274. static bool pools_active;
  8275. /* One stratum thread per pool that has stratum waits on the socket checking
  8276. * for new messages and for the integrity of the socket connection. We reset
  8277. * the connection based on the integrity of the receive side only as the send
  8278. * side will eventually expire data it fails to send. */
  8279. static void *stratum_thread(void *userdata)
  8280. {
  8281. struct pool *pool = (struct pool *)userdata;
  8282. pthread_detach(pthread_self());
  8283. char threadname[20];
  8284. snprintf(threadname, 20, "stratum%u", pool->pool_no);
  8285. RenameThread(threadname);
  8286. srand(time(NULL) + (intptr_t)userdata);
  8287. while (42) {
  8288. struct timeval timeout;
  8289. int sel_ret;
  8290. fd_set rd;
  8291. char *s;
  8292. int sock;
  8293. if (unlikely(!pool->has_stratum))
  8294. break;
  8295. /* Check to see whether we need to maintain this connection
  8296. * indefinitely or just bring it up when we switch to this
  8297. * pool */
  8298. while (true)
  8299. {
  8300. sock = pool->sock;
  8301. if (sock == INVSOCK)
  8302. applog(LOG_DEBUG, "Pool %u: Invalid socket, suspending",
  8303. pool->pool_no);
  8304. else
  8305. if (!sock_full(pool) && !cnx_needed(pool) && pools_active)
  8306. applog(LOG_DEBUG, "Pool %u: Connection not needed, suspending",
  8307. pool->pool_no);
  8308. else
  8309. break;
  8310. suspend_stratum(pool);
  8311. clear_stratum_shares(pool);
  8312. clear_pool_work(pool);
  8313. wait_lpcurrent(pool);
  8314. if (!restart_stratum(pool)) {
  8315. pool_died(pool);
  8316. while (!restart_stratum(pool)) {
  8317. if (pool->removed)
  8318. goto out;
  8319. cgsleep_ms(30000);
  8320. }
  8321. }
  8322. }
  8323. FD_ZERO(&rd);
  8324. FD_SET(sock, &rd);
  8325. timeout.tv_sec = 120;
  8326. timeout.tv_usec = 0;
  8327. /* If we fail to receive any notify messages for 2 minutes we
  8328. * assume the connection has been dropped and treat this pool
  8329. * as dead */
  8330. if (!sock_full(pool) && (sel_ret = select(sock + 1, &rd, NULL, NULL, &timeout)) < 1) {
  8331. applog(LOG_DEBUG, "Stratum select failed on pool %d with value %d", pool->pool_no, sel_ret);
  8332. s = NULL;
  8333. } else
  8334. s = recv_line(pool);
  8335. if (!s) {
  8336. if (!pool->has_stratum)
  8337. break;
  8338. applog(LOG_NOTICE, "Stratum connection to pool %d interrupted", pool->pool_no);
  8339. pool->getfail_occasions++;
  8340. total_go++;
  8341. mutex_lock(&pool->stratum_lock);
  8342. pool->stratum_active = pool->stratum_notify = false;
  8343. pool->sock = INVSOCK;
  8344. mutex_unlock(&pool->stratum_lock);
  8345. /* If the socket to our stratum pool disconnects, all
  8346. * submissions need to be discarded or resent. */
  8347. if (!supports_resume(pool))
  8348. clear_stratum_shares(pool);
  8349. else
  8350. resubmit_stratum_shares(pool);
  8351. clear_pool_work(pool);
  8352. if (pool == current_pool())
  8353. restart_threads();
  8354. if (restart_stratum(pool))
  8355. continue;
  8356. shutdown_stratum(pool);
  8357. pool_died(pool);
  8358. break;
  8359. }
  8360. /* Check this pool hasn't died while being a backup pool and
  8361. * has not had its idle flag cleared */
  8362. stratum_resumed(pool);
  8363. if (!parse_method(pool, s) && !parse_stratum_response(pool, s))
  8364. applog(LOG_INFO, "Unknown stratum msg: %s", s);
  8365. free(s);
  8366. if (pool->swork.clean) {
  8367. struct work *work = make_work();
  8368. /* Generate a single work item to update the current
  8369. * block database */
  8370. pool->swork.clean = false;
  8371. gen_stratum_work(pool, work);
  8372. /* Try to extract block height from coinbase scriptSig */
  8373. uint8_t *bin_height = &bytes_buf(&pool->swork.coinbase)[4 /*version*/ + 1 /*txin count*/ + 36 /*prevout*/ + 1 /*scriptSig len*/ + 1 /*push opcode*/];
  8374. unsigned char cb_height_sz;
  8375. cb_height_sz = bin_height[-1];
  8376. if (cb_height_sz == 3) {
  8377. // FIXME: The block number will overflow this by AD 2173
  8378. struct mining_goal_info * const goal = pool->goal;
  8379. const void * const prevblkhash = &work->data[4];
  8380. uint32_t height = 0;
  8381. memcpy(&height, bin_height, 3);
  8382. height = le32toh(height);
  8383. have_block_height(goal, prevblkhash, height);
  8384. }
  8385. pool->swork.work_restart_id =
  8386. ++pool->work_restart_id;
  8387. pool_update_work_restart_time(pool);
  8388. if (test_work_current(work)) {
  8389. /* Only accept a work update if this stratum
  8390. * connection is from the current pool */
  8391. struct pool * const cp = current_pool();
  8392. if (pool == cp)
  8393. restart_threads();
  8394. applog(
  8395. ((!opt_quiet_work_updates) && pool_actively_in_use(pool, cp) ? LOG_NOTICE : LOG_DEBUG),
  8396. "Stratum from pool %d requested work update", pool->pool_no);
  8397. } else
  8398. applog(LOG_NOTICE, "Stratum from pool %d detected new block", pool->pool_no);
  8399. free_work(work);
  8400. }
  8401. if (timer_passed(&pool->swork.tv_transparency, NULL)) {
  8402. // More than 4 timmills past since requested transactions
  8403. timer_unset(&pool->swork.tv_transparency);
  8404. pool_set_opaque(pool, true);
  8405. }
  8406. }
  8407. out:
  8408. return NULL;
  8409. }
  8410. static void init_stratum_thread(struct pool *pool)
  8411. {
  8412. struct mining_goal_info * const goal = pool->goal;
  8413. goal->have_longpoll = true;
  8414. if (unlikely(pthread_create(&pool->stratum_thread, NULL, stratum_thread, (void *)pool)))
  8415. quit(1, "Failed to create stratum thread");
  8416. }
  8417. static void *longpoll_thread(void *userdata);
  8418. static bool stratum_works(struct pool *pool)
  8419. {
  8420. applog(LOG_INFO, "Testing pool %d stratum %s", pool->pool_no, pool->stratum_url);
  8421. if (!extract_sockaddr(pool->stratum_url, &pool->sockaddr_url, &pool->stratum_port))
  8422. return false;
  8423. if (pool->stratum_active)
  8424. return true;
  8425. if (!initiate_stratum(pool))
  8426. return false;
  8427. return true;
  8428. }
  8429. static
  8430. bool pool_recently_got_work(struct pool * const pool, const struct timeval * const tvp_now)
  8431. {
  8432. return (timer_isset(&pool->tv_last_work_time) && timer_elapsed(&pool->tv_last_work_time, tvp_now) < 60);
  8433. }
  8434. static bool pool_active(struct pool *pool, bool pinging)
  8435. {
  8436. struct timeval tv_now, tv_getwork, tv_getwork_reply;
  8437. bool ret = false;
  8438. json_t *val;
  8439. CURL *curl = NULL;
  8440. int rolltime;
  8441. char *rpc_req;
  8442. struct work *work;
  8443. enum pool_protocol proto;
  8444. if (pool->stratum_init)
  8445. {
  8446. if (pool->stratum_active)
  8447. return true;
  8448. }
  8449. else
  8450. if (!pool->idle)
  8451. {
  8452. timer_set_now(&tv_now);
  8453. if (pool_recently_got_work(pool, &tv_now))
  8454. return true;
  8455. }
  8456. mutex_lock(&pool->pool_test_lock);
  8457. if (pool->stratum_init)
  8458. {
  8459. ret = pool->stratum_active;
  8460. goto out;
  8461. }
  8462. timer_set_now(&tv_now);
  8463. if (pool->idle)
  8464. {
  8465. if (timer_elapsed(&pool->tv_idle, &tv_now) < 30)
  8466. goto out;
  8467. }
  8468. else
  8469. if (pool_recently_got_work(pool, &tv_now))
  8470. {
  8471. ret = true;
  8472. goto out;
  8473. }
  8474. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  8475. /* This is the central point we activate stratum when we can */
  8476. curl = curl_easy_init();
  8477. if (unlikely(!curl)) {
  8478. applog(LOG_ERR, "CURL initialisation failed");
  8479. goto out;
  8480. }
  8481. if (!(want_gbt || want_getwork))
  8482. goto nohttp;
  8483. work = make_work();
  8484. /* Probe for GBT support on first pass */
  8485. proto = want_gbt ? PLP_GETBLOCKTEMPLATE : PLP_GETWORK;
  8486. tryagain:
  8487. rpc_req = prepare_rpc_req_probe(work, proto, NULL, pool);
  8488. work->pool = pool;
  8489. if (!rpc_req)
  8490. goto out;
  8491. pool->probed = false;
  8492. cgtime(&tv_getwork);
  8493. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  8494. true, false, &rolltime, pool, false);
  8495. cgtime(&tv_getwork_reply);
  8496. free(rpc_req);
  8497. /* Detect if a http getwork pool has an X-Stratum header at startup,
  8498. * and if so, switch to that in preference to getwork if it works */
  8499. if (pool->stratum_url && want_stratum && pool_may_redirect_to(pool, pool->stratum_url) && (pool->has_stratum || stratum_works(pool))) {
  8500. if (!pool->has_stratum) {
  8501. applog(LOG_NOTICE, "Switching pool %d %s to %s", pool->pool_no, pool->rpc_url, pool->stratum_url);
  8502. if (!pool->rpc_url)
  8503. pool_set_uri(pool, strdup(pool->stratum_url));
  8504. pool->has_stratum = true;
  8505. }
  8506. free_work(work);
  8507. if (val)
  8508. json_decref(val);
  8509. retry_stratum:
  8510. ;
  8511. /* We create the stratum thread for each pool just after
  8512. * successful authorisation. Once the init flag has been set
  8513. * we never unset it and the stratum thread is responsible for
  8514. * setting/unsetting the active flag */
  8515. bool init = pool_tset(pool, &pool->stratum_init);
  8516. if (!init) {
  8517. ret = initiate_stratum(pool) && auth_stratum(pool);
  8518. if (ret)
  8519. {
  8520. detect_algo = 2;
  8521. init_stratum_thread(pool);
  8522. }
  8523. else
  8524. {
  8525. pool_tclear(pool, &pool->stratum_init);
  8526. pool->tv_idle = tv_getwork_reply;
  8527. }
  8528. goto out;
  8529. }
  8530. ret = pool->stratum_active;
  8531. goto out;
  8532. }
  8533. else if (pool->has_stratum)
  8534. shutdown_stratum(pool);
  8535. if (val) {
  8536. bool rc;
  8537. json_t *res;
  8538. res = json_object_get(val, "result");
  8539. if ((!json_is_object(res)) || (proto == PLP_GETBLOCKTEMPLATE && !json_object_get(res, "bits")))
  8540. goto badwork;
  8541. work->rolltime = rolltime;
  8542. rc = work_decode(pool, work, val);
  8543. if (rc) {
  8544. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  8545. pool->pool_no, pool->rpc_url);
  8546. work->pool = pool;
  8547. copy_time(&work->tv_getwork, &tv_getwork);
  8548. copy_time(&work->tv_getwork_reply, &tv_getwork_reply);
  8549. work->getwork_mode = GETWORK_MODE_TESTPOOL;
  8550. calc_diff(work, 0);
  8551. update_last_work(work);
  8552. applog(LOG_DEBUG, "Pushing pooltest work to base pool");
  8553. stage_work(work);
  8554. total_getworks++;
  8555. pool->getwork_requested++;
  8556. ret = true;
  8557. pool->tv_idle = tv_getwork_reply;
  8558. } else {
  8559. badwork:
  8560. json_decref(val);
  8561. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher work from pool %u %s",
  8562. pool->pool_no, pool->rpc_url);
  8563. pool->proto = proto = pool_protocol_fallback(proto);
  8564. if (PLP_NONE != proto)
  8565. goto tryagain;
  8566. pool->tv_idle = tv_getwork_reply;
  8567. free_work(work);
  8568. goto out;
  8569. }
  8570. json_decref(val);
  8571. if (proto != pool->proto) {
  8572. pool->proto = proto;
  8573. applog(LOG_INFO, "Selected %s protocol for pool %u", pool_protocol_name(proto), pool->pool_no);
  8574. }
  8575. if (pool->lp_url)
  8576. goto out;
  8577. /* Decipher the longpoll URL, if any, and store it in ->lp_url */
  8578. const struct blktmpl_longpoll_req *lp;
  8579. if (work->tr && (lp = blktmpl_get_longpoll(work->tr->tmpl))) {
  8580. // NOTE: work_decode takes care of lp id
  8581. pool->lp_url = lp->uri ? absolute_uri(lp->uri, pool->rpc_url) : pool->rpc_url;
  8582. if (!pool->lp_url)
  8583. {
  8584. ret = false;
  8585. goto out;
  8586. }
  8587. pool->lp_proto = PLP_GETBLOCKTEMPLATE;
  8588. }
  8589. else
  8590. if (pool->hdr_path && want_getwork) {
  8591. pool->lp_url = absolute_uri(pool->hdr_path, pool->rpc_url);
  8592. if (!pool->lp_url)
  8593. {
  8594. ret = false;
  8595. goto out;
  8596. }
  8597. pool->lp_proto = PLP_GETWORK;
  8598. } else
  8599. pool->lp_url = NULL;
  8600. if (want_longpoll && !pool->lp_started) {
  8601. pool->lp_started = true;
  8602. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  8603. quit(1, "Failed to create pool longpoll thread");
  8604. }
  8605. } else if (PLP_NONE != (proto = pool_protocol_fallback(proto))) {
  8606. pool->proto = proto;
  8607. goto tryagain;
  8608. } else {
  8609. pool->tv_idle = tv_getwork_reply;
  8610. free_work(work);
  8611. nohttp:
  8612. /* If we failed to parse a getwork, this could be a stratum
  8613. * url without the prefix stratum+tcp:// so let's check it */
  8614. if (extract_sockaddr(pool->rpc_url, &pool->sockaddr_url, &pool->stratum_port) && initiate_stratum(pool)) {
  8615. pool->has_stratum = true;
  8616. goto retry_stratum;
  8617. }
  8618. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  8619. pool->pool_no, pool->rpc_url);
  8620. if (!pinging)
  8621. applog(LOG_WARNING, "Pool %u slow/down or URL or credentials invalid", pool->pool_no);
  8622. }
  8623. out:
  8624. if (curl)
  8625. curl_easy_cleanup(curl);
  8626. mutex_unlock(&pool->pool_test_lock);
  8627. return ret;
  8628. }
  8629. static void pool_resus(struct pool *pool)
  8630. {
  8631. if (pool->enabled == POOL_ENABLED && pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  8632. applog(LOG_WARNING, "Pool %d %s alive, testing stability", pool->pool_no, pool->rpc_url);
  8633. else
  8634. applog(LOG_INFO, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  8635. }
  8636. static
  8637. void *cmd_idle_thread(void * const __maybe_unused userp)
  8638. {
  8639. pthread_detach(pthread_self());
  8640. RenameThread("cmd-idle");
  8641. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  8642. sleep(opt_log_interval);
  8643. pthread_testcancel();
  8644. run_cmd(cmd_idle);
  8645. return NULL;
  8646. }
  8647. static struct work *hash_pop(struct cgpu_info * const proc)
  8648. {
  8649. int hc;
  8650. struct work *work, *work_found, *tmp;
  8651. enum {
  8652. HPWS_NONE,
  8653. HPWS_LOWDIFF,
  8654. HPWS_SPARE,
  8655. HPWS_ROLLABLE,
  8656. HPWS_PERFECT,
  8657. } work_score = HPWS_NONE;
  8658. bool did_cmd_idle = false;
  8659. pthread_t cmd_idle_thr;
  8660. retry:
  8661. mutex_lock(stgd_lock);
  8662. while (true)
  8663. {
  8664. work_found = NULL;
  8665. work_score = 0;
  8666. hc = HASH_COUNT(staged_work);
  8667. HASH_ITER(hh, staged_work, work, tmp)
  8668. {
  8669. const struct mining_algorithm * const work_malgo = work_mining_algorithm(work);
  8670. const float min_nonce_diff = drv_min_nonce_diff(proc->drv, proc, work_malgo);
  8671. #define FOUND_WORK(score) do{ \
  8672. if (work_score < score) \
  8673. { \
  8674. work_found = work; \
  8675. work_score = score; \
  8676. } \
  8677. continue; \
  8678. }while(0)
  8679. if (min_nonce_diff < work->work_difficulty)
  8680. {
  8681. if (min_nonce_diff < 0)
  8682. continue;
  8683. FOUND_WORK(HPWS_LOWDIFF);
  8684. }
  8685. if (work->spare)
  8686. FOUND_WORK(HPWS_SPARE);
  8687. if (work->rolltime && hc > staged_rollable)
  8688. FOUND_WORK(HPWS_ROLLABLE);
  8689. #undef FOUND_WORK
  8690. // Good match
  8691. work_found = work;
  8692. work_score = HPWS_PERFECT;
  8693. break;
  8694. }
  8695. if (work_found)
  8696. {
  8697. work = work_found;
  8698. break;
  8699. }
  8700. // Failed to get a usable work
  8701. if (unlikely(staged_full))
  8702. {
  8703. if (likely(opt_queue < 10 + mining_threads))
  8704. {
  8705. ++opt_queue;
  8706. applog(LOG_WARNING, "Staged work underrun; increasing queue minimum to %d", opt_queue);
  8707. }
  8708. else
  8709. applog(LOG_WARNING, "Staged work underrun; not automatically increasing above %d", opt_queue);
  8710. staged_full = false; // Let it fill up before triggering an underrun again
  8711. no_work = true;
  8712. }
  8713. pthread_cond_signal(&gws_cond);
  8714. if (cmd_idle && !did_cmd_idle)
  8715. {
  8716. if (likely(!pthread_create(&cmd_idle_thr, NULL, cmd_idle_thread, NULL)))
  8717. did_cmd_idle = true;
  8718. }
  8719. pthread_cond_wait(&getq->cond, stgd_lock);
  8720. }
  8721. if (did_cmd_idle)
  8722. pthread_cancel(cmd_idle_thr);
  8723. no_work = false;
  8724. if (can_roll(work) && should_roll(work))
  8725. {
  8726. // Instead of consuming it, force it to be cloned and grab the clone
  8727. mutex_unlock(stgd_lock);
  8728. clone_available();
  8729. goto retry;
  8730. }
  8731. unstage_work(work);
  8732. /* Signal the getwork scheduler to look for more work */
  8733. pthread_cond_signal(&gws_cond);
  8734. /* Signal hash_pop again in case there are mutliple hash_pop waiters */
  8735. pthread_cond_signal(&getq->cond);
  8736. mutex_unlock(stgd_lock);
  8737. work->pool->last_work_time = time(NULL);
  8738. cgtime(&work->pool->tv_last_work_time);
  8739. return work;
  8740. }
  8741. /* Clones work by rolling it if possible, and returning a clone instead of the
  8742. * original work item which gets staged again to possibly be rolled again in
  8743. * the future */
  8744. static struct work *clone_work(struct work *work)
  8745. {
  8746. int mrs = mining_threads + opt_queue - total_staged(false);
  8747. struct work *work_clone;
  8748. bool cloned;
  8749. if (mrs < 1)
  8750. return work;
  8751. cloned = false;
  8752. work_clone = make_clone(work);
  8753. while (mrs-- > 0 && can_roll(work) && should_roll(work)) {
  8754. applog(LOG_DEBUG, "Pushing rolled converted work to stage thread");
  8755. stage_work(work_clone);
  8756. roll_work(work);
  8757. work_clone = make_clone(work);
  8758. /* Roll it again to prevent duplicates should this be used
  8759. * directly later on */
  8760. roll_work(work);
  8761. cloned = true;
  8762. }
  8763. if (cloned) {
  8764. stage_work(work);
  8765. return work_clone;
  8766. }
  8767. free_work(work_clone);
  8768. return work;
  8769. }
  8770. void gen_hash(unsigned char *data, unsigned char *hash, int len)
  8771. {
  8772. unsigned char hash1[32];
  8773. sha256(data, len, hash1);
  8774. sha256(hash1, 32, hash);
  8775. }
  8776. /* PDiff 1 is a 256 bit unsigned integer of
  8777. * 0x00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff
  8778. * so we use a big endian 32 bit unsigned integer positioned at the Nth byte to
  8779. * cover a huge range of difficulty targets, though not all 256 bits' worth */
  8780. static void pdiff_target_leadzero(void * const target_p, double diff)
  8781. {
  8782. uint8_t *target = target_p;
  8783. diff *= 0x100000000;
  8784. int skip = log2(diff) / 8;
  8785. if (skip)
  8786. {
  8787. if (skip > 0x1c)
  8788. skip = 0x1c;
  8789. diff /= pow(0x100, skip);
  8790. memset(target, 0, skip);
  8791. }
  8792. uint32_t n = 0xffffffff;
  8793. n = (double)n / diff;
  8794. n = htobe32(n);
  8795. memcpy(&target[skip], &n, sizeof(n));
  8796. memset(&target[skip + sizeof(n)], 0xff, 32 - (skip + sizeof(n)));
  8797. }
  8798. void set_target_to_pdiff(void * const dest_target, const double pdiff)
  8799. {
  8800. unsigned char rtarget[32];
  8801. pdiff_target_leadzero(rtarget, pdiff);
  8802. swab256(dest_target, rtarget);
  8803. if (opt_debug) {
  8804. char htarget[65];
  8805. bin2hex(htarget, rtarget, 32);
  8806. applog(LOG_DEBUG, "Generated target %s", htarget);
  8807. }
  8808. }
  8809. void set_target_to_bdiff(void * const dest_target, const double bdiff)
  8810. {
  8811. set_target_to_pdiff(dest_target, bdiff_to_pdiff(bdiff));
  8812. }
  8813. void _test_target(void * const funcp, const char * const funcname, const bool little_endian, const void * const expectp, const double diff)
  8814. {
  8815. uint8_t bufr[32], buf[32], expectr[32], expect[32];
  8816. int off;
  8817. void (*func)(void *, double) = funcp;
  8818. func(little_endian ? bufr : buf, diff);
  8819. if (little_endian)
  8820. swab256(buf, bufr);
  8821. swap32tobe(expect, expectp, 256/32);
  8822. // Fuzzy comparison: the first 32 bits set must match, and the actual target must be >= the expected
  8823. for (off = 0; off < 28 && !buf[off]; ++off)
  8824. {}
  8825. if (memcmp(&buf[off], &expect[off], 4))
  8826. {
  8827. testfail: ;
  8828. ++unittest_failures;
  8829. char hexbuf[65], expectbuf[65];
  8830. bin2hex(hexbuf, buf, 32);
  8831. bin2hex(expectbuf, expect, 32);
  8832. applogr(, LOG_WARNING, "%s test failed: diff %g got %s (expected %s)",
  8833. funcname, diff, hexbuf, expectbuf);
  8834. }
  8835. if (!little_endian)
  8836. swab256(bufr, buf);
  8837. swab256(expectr, expect);
  8838. if (!hash_target_check(expectr, bufr))
  8839. goto testfail;
  8840. }
  8841. #define TEST_TARGET(func, le, expect, diff) \
  8842. _test_target(func, #func, le, expect, diff)
  8843. void test_target()
  8844. {
  8845. uint32_t expect[8] = {0};
  8846. // bdiff 1 should be exactly 00000000ffff0000000006f29cfd29510a6caee84634e86a57257cf03152537f due to floating-point imprecision (pdiff1 / 1.0000152590218966)
  8847. expect[0] = 0x0000ffff;
  8848. TEST_TARGET(set_target_to_bdiff, true, expect, 1./0x10000);
  8849. expect[0] = 0;
  8850. expect[1] = 0xffff0000;
  8851. TEST_TARGET(set_target_to_bdiff, true, expect, 1);
  8852. expect[1] >>= 1;
  8853. TEST_TARGET(set_target_to_bdiff, true, expect, 2);
  8854. expect[1] >>= 3;
  8855. TEST_TARGET(set_target_to_bdiff, true, expect, 0x10);
  8856. expect[1] >>= 4;
  8857. TEST_TARGET(set_target_to_bdiff, true, expect, 0x100);
  8858. memset(&expect[1], '\xff', 28);
  8859. expect[0] = 0x0000ffff;
  8860. TEST_TARGET(set_target_to_pdiff, true, expect, 1./0x10000);
  8861. expect[0] = 0;
  8862. TEST_TARGET(set_target_to_pdiff, true, expect, 1);
  8863. expect[1] >>= 1;
  8864. TEST_TARGET(set_target_to_pdiff, true, expect, 2);
  8865. expect[1] >>= 3;
  8866. TEST_TARGET(set_target_to_pdiff, true, expect, 0x10);
  8867. expect[1] >>= 4;
  8868. TEST_TARGET(set_target_to_pdiff, true, expect, 0x100);
  8869. }
  8870. void stratum_work_cpy(struct stratum_work * const dst, const struct stratum_work * const src)
  8871. {
  8872. *dst = *src;
  8873. if (dst->tr)
  8874. tmpl_incref(dst->tr);
  8875. dst->nonce1 = maybe_strdup(src->nonce1);
  8876. dst->job_id = maybe_strdup(src->job_id);
  8877. bytes_cpy(&dst->coinbase, &src->coinbase);
  8878. bytes_cpy(&dst->merkle_bin, &src->merkle_bin);
  8879. }
  8880. void stratum_work_clean(struct stratum_work * const swork)
  8881. {
  8882. if (swork->tr)
  8883. tmpl_decref(swork->tr);
  8884. free(swork->nonce1);
  8885. free(swork->job_id);
  8886. bytes_free(&swork->coinbase);
  8887. bytes_free(&swork->merkle_bin);
  8888. }
  8889. bool pool_has_usable_swork(const struct pool * const pool)
  8890. {
  8891. if (opt_benchmark)
  8892. return true;
  8893. if (pool->swork.tr)
  8894. {
  8895. // GBT
  8896. struct timeval tv_now;
  8897. timer_set_now(&tv_now);
  8898. return blkmk_time_left(pool->swork.tr->tmpl, tv_now.tv_sec);
  8899. }
  8900. return pool->stratum_notify;
  8901. }
  8902. /* Generates stratum based work based on the most recent notify information
  8903. * from the pool. This will keep generating work while a pool is down so we use
  8904. * other means to detect when the pool has died in stratum_thread */
  8905. static void gen_stratum_work(struct pool *pool, struct work *work)
  8906. {
  8907. clean_work(work);
  8908. cg_wlock(&pool->data_lock);
  8909. pool->swork.data_lock_p = &pool->data_lock;
  8910. const int n2size = pool->swork.n2size;
  8911. bytes_resize(&work->nonce2, n2size);
  8912. if (pool->nonce2sz < n2size)
  8913. memset(&bytes_buf(&work->nonce2)[pool->nonce2sz], 0, n2size - pool->nonce2sz);
  8914. memcpy(bytes_buf(&work->nonce2),
  8915. #ifdef WORDS_BIGENDIAN
  8916. // NOTE: On big endian, the most significant bits are stored at the end, so skip the LSBs
  8917. &((char*)&pool->nonce2)[pool->nonce2off],
  8918. #else
  8919. &pool->nonce2,
  8920. #endif
  8921. pool->nonce2sz);
  8922. pool->nonce2++;
  8923. work->pool = pool;
  8924. work->work_restart_id = pool->swork.work_restart_id;
  8925. gen_stratum_work2(work, &pool->swork);
  8926. cgtime(&work->tv_staged);
  8927. }
  8928. void gen_stratum_work2(struct work *work, struct stratum_work *swork)
  8929. {
  8930. unsigned char *coinbase, merkle_root[32], merkle_sha[64];
  8931. uint8_t *merkle_bin;
  8932. uint32_t *data32, *swap32;
  8933. int i;
  8934. /* Generate coinbase */
  8935. coinbase = bytes_buf(&swork->coinbase);
  8936. memcpy(&coinbase[swork->nonce2_offset], bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  8937. /* Downgrade to a read lock to read off the variables */
  8938. if (swork->data_lock_p)
  8939. cg_dwlock(swork->data_lock_p);
  8940. /* Generate merkle root */
  8941. gen_hash(coinbase, merkle_root, bytes_len(&swork->coinbase));
  8942. memcpy(merkle_sha, merkle_root, 32);
  8943. merkle_bin = bytes_buf(&swork->merkle_bin);
  8944. for (i = 0; i < swork->merkles; ++i, merkle_bin += 32) {
  8945. memcpy(merkle_sha + 32, merkle_bin, 32);
  8946. gen_hash(merkle_sha, merkle_root, 64);
  8947. memcpy(merkle_sha, merkle_root, 32);
  8948. }
  8949. data32 = (uint32_t *)merkle_sha;
  8950. swap32 = (uint32_t *)merkle_root;
  8951. flip32(swap32, data32);
  8952. memcpy(&work->data[0], swork->header1, 36);
  8953. memcpy(&work->data[36], merkle_root, 32);
  8954. *((uint32_t*)&work->data[68]) = htobe32(swork->ntime + timer_elapsed(&swork->tv_received, NULL));
  8955. memcpy(&work->data[72], swork->diffbits, 4);
  8956. memset(&work->data[76], 0, 4); // nonce
  8957. memcpy(&work->data[80], workpadding_bin, 48);
  8958. work->ntime_roll_limits = swork->ntime_roll_limits;
  8959. /* Copy parameters required for share submission */
  8960. memcpy(work->target, swork->target, sizeof(work->target));
  8961. work->job_id = maybe_strdup(swork->job_id);
  8962. work->nonce1 = maybe_strdup(swork->nonce1);
  8963. if (swork->data_lock_p)
  8964. cg_runlock(swork->data_lock_p);
  8965. if (opt_debug)
  8966. {
  8967. char header[161];
  8968. char nonce2hex[(bytes_len(&work->nonce2) * 2) + 1];
  8969. bin2hex(header, work->data, 80);
  8970. bin2hex(nonce2hex, bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  8971. applog(LOG_DEBUG, "Generated stratum header %s", header);
  8972. applog(LOG_DEBUG, "Work job_id %s nonce2 %s", work->job_id, nonce2hex);
  8973. }
  8974. calc_midstate(work);
  8975. local_work++;
  8976. work->stratum = true;
  8977. work->blk.nonce = 0;
  8978. work->id = total_work++;
  8979. work->longpoll = false;
  8980. work->getwork_mode = GETWORK_MODE_STRATUM;
  8981. calc_diff(work, 0);
  8982. }
  8983. void request_work(struct thr_info *thr)
  8984. {
  8985. struct cgpu_info *cgpu = thr->cgpu;
  8986. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  8987. /* Tell the watchdog thread this thread is waiting on getwork and
  8988. * should not be restarted */
  8989. thread_reportout(thr);
  8990. // HACK: Since get_work still blocks, reportout all processors dependent on this thread
  8991. for (struct cgpu_info *proc = thr->cgpu->next_proc; proc; proc = proc->next_proc)
  8992. {
  8993. if (proc->threads)
  8994. break;
  8995. thread_reportout(proc->thr[0]);
  8996. }
  8997. cgtime(&dev_stats->_get_start);
  8998. }
  8999. // FIXME: Make this non-blocking (and remove HACK above)
  9000. struct work *get_work(struct thr_info *thr)
  9001. {
  9002. const int thr_id = thr->id;
  9003. struct cgpu_info *cgpu = thr->cgpu;
  9004. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  9005. struct cgminer_stats *pool_stats;
  9006. struct timeval tv_get;
  9007. struct work *work = NULL;
  9008. applog(LOG_DEBUG, "%"PRIpreprv": Popping work from get queue to get work", cgpu->proc_repr);
  9009. while (!work) {
  9010. work = hash_pop(cgpu);
  9011. if (stale_work(work, false)) {
  9012. staged_full = false; // It wasn't really full, since it was stale :(
  9013. discard_work(work);
  9014. work = NULL;
  9015. wake_gws();
  9016. }
  9017. }
  9018. last_getwork = time(NULL);
  9019. applog(LOG_DEBUG, "%"PRIpreprv": Got work %d from get queue to get work for thread %d",
  9020. cgpu->proc_repr, work->id, thr_id);
  9021. work->thr_id = thr_id;
  9022. thread_reportin(thr);
  9023. // HACK: Since get_work still blocks, reportin all processors dependent on this thread
  9024. for (struct cgpu_info *proc = thr->cgpu->next_proc; proc; proc = proc->next_proc)
  9025. {
  9026. if (proc->threads)
  9027. break;
  9028. thread_reportin(proc->thr[0]);
  9029. }
  9030. work->mined = true;
  9031. work->blk.nonce = 0;
  9032. cgtime(&tv_get);
  9033. timersub(&tv_get, &dev_stats->_get_start, &tv_get);
  9034. timeradd(&tv_get, &dev_stats->getwork_wait, &dev_stats->getwork_wait);
  9035. if (timercmp(&tv_get, &dev_stats->getwork_wait_max, >))
  9036. dev_stats->getwork_wait_max = tv_get;
  9037. if (timercmp(&tv_get, &dev_stats->getwork_wait_min, <))
  9038. dev_stats->getwork_wait_min = tv_get;
  9039. ++dev_stats->getwork_calls;
  9040. pool_stats = &(work->pool->cgminer_stats);
  9041. timeradd(&tv_get, &pool_stats->getwork_wait, &pool_stats->getwork_wait);
  9042. if (timercmp(&tv_get, &pool_stats->getwork_wait_max, >))
  9043. pool_stats->getwork_wait_max = tv_get;
  9044. if (timercmp(&tv_get, &pool_stats->getwork_wait_min, <))
  9045. pool_stats->getwork_wait_min = tv_get;
  9046. ++pool_stats->getwork_calls;
  9047. if (work->work_difficulty < 1)
  9048. {
  9049. const float min_nonce_diff = drv_min_nonce_diff(cgpu->drv, cgpu, work_mining_algorithm(work));
  9050. if (unlikely(work->work_difficulty < min_nonce_diff))
  9051. {
  9052. if (min_nonce_diff - work->work_difficulty > 1./0x10000000)
  9053. applog(LOG_WARNING, "%"PRIpreprv": Using work with lower difficulty than device supports",
  9054. cgpu->proc_repr);
  9055. work->nonce_diff = min_nonce_diff;
  9056. }
  9057. else
  9058. work->nonce_diff = work->work_difficulty;
  9059. }
  9060. else
  9061. work->nonce_diff = 1;
  9062. return work;
  9063. }
  9064. struct dupe_hash_elem {
  9065. uint8_t hash[0x20];
  9066. struct timeval tv_prune;
  9067. UT_hash_handle hh;
  9068. };
  9069. static
  9070. void _submit_work_async(struct work *work)
  9071. {
  9072. applog(LOG_DEBUG, "Pushing submit work to work thread");
  9073. if (opt_benchmark)
  9074. {
  9075. json_t * const jn = json_null(), *result = NULL;
  9076. work_check_for_block(work);
  9077. {
  9078. static struct dupe_hash_elem *dupe_hashes;
  9079. struct dupe_hash_elem *dhe, *dhetmp;
  9080. HASH_FIND(hh, dupe_hashes, &work->hash, sizeof(dhe->hash), dhe);
  9081. if (dhe)
  9082. result = json_string("duplicate");
  9083. else
  9084. {
  9085. struct timeval tv_now;
  9086. timer_set_now(&tv_now);
  9087. // Prune old entries
  9088. HASH_ITER(hh, dupe_hashes, dhe, dhetmp)
  9089. {
  9090. if (!timer_passed(&dhe->tv_prune, &tv_now))
  9091. break;
  9092. HASH_DEL(dupe_hashes, dhe);
  9093. free(dhe);
  9094. }
  9095. dhe = malloc(sizeof(*dhe));
  9096. memcpy(dhe->hash, work->hash, sizeof(dhe->hash));
  9097. timer_set_delay(&dhe->tv_prune, &tv_now, 337500000);
  9098. HASH_ADD(hh, dupe_hashes, hash, sizeof(dhe->hash), dhe);
  9099. }
  9100. }
  9101. if (result)
  9102. {}
  9103. else
  9104. if (stale_work(work, true))
  9105. {
  9106. char stalemsg[0x10];
  9107. snprintf(stalemsg, sizeof(stalemsg), "stale %us", benchmark_update_interval * (work->pool->work_restart_id - work->work_restart_id));
  9108. result = json_string(stalemsg);
  9109. }
  9110. else
  9111. result = json_incref(jn);
  9112. share_result(jn, result, jn, work, false, "");
  9113. free_work(work);
  9114. json_decref(result);
  9115. json_decref(jn);
  9116. return;
  9117. }
  9118. mutex_lock(&submitting_lock);
  9119. ++total_submitting;
  9120. DL_APPEND(submit_waiting, work);
  9121. mutex_unlock(&submitting_lock);
  9122. notifier_wake(submit_waiting_notifier);
  9123. }
  9124. /* Submit a copy of the tested, statistic recorded work item asynchronously */
  9125. static void submit_work_async2(struct work *work, struct timeval *tv_work_found)
  9126. {
  9127. if (tv_work_found)
  9128. copy_time(&work->tv_work_found, tv_work_found);
  9129. _submit_work_async(work);
  9130. }
  9131. void inc_hw_errors3(struct thr_info *thr, const struct work *work, const uint32_t *bad_nonce_p, float nonce_diff)
  9132. {
  9133. struct cgpu_info * const cgpu = thr->cgpu;
  9134. if (bad_nonce_p)
  9135. {
  9136. if (bad_nonce_p == UNKNOWN_NONCE)
  9137. applog(LOG_DEBUG, "%"PRIpreprv": invalid nonce - HW error",
  9138. cgpu->proc_repr);
  9139. else
  9140. applog(LOG_DEBUG, "%"PRIpreprv": invalid nonce (%08lx) - HW error",
  9141. cgpu->proc_repr, (unsigned long)be32toh(*bad_nonce_p));
  9142. }
  9143. mutex_lock(&stats_lock);
  9144. hw_errors++;
  9145. ++cgpu->hw_errors;
  9146. if (bad_nonce_p)
  9147. {
  9148. total_bad_diff1 += nonce_diff;
  9149. cgpu->bad_diff1 += nonce_diff;
  9150. }
  9151. mutex_unlock(&stats_lock);
  9152. if (thr->cgpu->drv->hw_error)
  9153. thr->cgpu->drv->hw_error(thr);
  9154. }
  9155. void work_hash(struct work * const work)
  9156. {
  9157. const struct mining_algorithm * const malgo = work_mining_algorithm(work);
  9158. malgo->hash_data_f(work->hash, work->data);
  9159. }
  9160. static
  9161. bool test_hash(const void * const phash, const float diff)
  9162. {
  9163. const uint32_t * const hash = phash;
  9164. if (diff >= 1.)
  9165. // FIXME: > 1 should check more
  9166. return !hash[7];
  9167. const uint32_t Htarg = (uint32_t)ceil((1. / diff) - 1);
  9168. const uint32_t tmp_hash7 = le32toh(hash[7]);
  9169. applog(LOG_DEBUG, "htarget %08lx hash %08lx",
  9170. (long unsigned int)Htarg,
  9171. (long unsigned int)tmp_hash7);
  9172. return (tmp_hash7 <= Htarg);
  9173. }
  9174. enum test_nonce2_result _test_nonce2(struct work *work, uint32_t nonce, bool checktarget)
  9175. {
  9176. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  9177. *work_nonce = htole32(nonce);
  9178. work_hash(work);
  9179. if (!test_hash(work->hash, work->nonce_diff))
  9180. return TNR_BAD;
  9181. if (checktarget && !hash_target_check_v(work->hash, work->target))
  9182. {
  9183. bool high_hash = true;
  9184. struct pool * const pool = work->pool;
  9185. if (pool->stratum_active)
  9186. {
  9187. // 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
  9188. if (memcmp(pool->next_target, work->target, sizeof(work->target)))
  9189. {
  9190. applog(LOG_DEBUG, "Stratum pool %u target has changed since work job issued, checking that too",
  9191. pool->pool_no);
  9192. if (hash_target_check_v(work->hash, pool->next_target))
  9193. high_hash = false;
  9194. }
  9195. }
  9196. if (high_hash)
  9197. return TNR_HIGH;
  9198. }
  9199. return TNR_GOOD;
  9200. }
  9201. /* Returns true if nonce for work was a valid share */
  9202. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  9203. {
  9204. return submit_noffset_nonce(thr, work, nonce, 0);
  9205. }
  9206. /* Allows drivers to submit work items where the driver has changed the ntime
  9207. * value by noffset. Must be only used with a work protocol that does not ntime
  9208. * roll itself intrinsically to generate work (eg stratum). We do not touch
  9209. * the original work struct, but the copy of it only. */
  9210. bool submit_noffset_nonce(struct thr_info *thr, struct work *work_in, uint32_t nonce,
  9211. int noffset)
  9212. {
  9213. struct work *work = make_work();
  9214. _copy_work(work, work_in, noffset);
  9215. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  9216. struct timeval tv_work_found;
  9217. enum test_nonce2_result res;
  9218. bool ret = true;
  9219. thread_reportout(thr);
  9220. cgtime(&tv_work_found);
  9221. *work_nonce = htole32(nonce);
  9222. work->thr_id = thr->id;
  9223. /* Do one last check before attempting to submit the work */
  9224. /* Side effect: sets work->data and work->hash for us */
  9225. res = test_nonce2(work, nonce);
  9226. if (unlikely(res == TNR_BAD))
  9227. {
  9228. inc_hw_errors(thr, work, nonce);
  9229. ret = false;
  9230. goto out;
  9231. }
  9232. mutex_lock(&stats_lock);
  9233. total_diff1 += work->nonce_diff;
  9234. thr ->cgpu->diff1 += work->nonce_diff;
  9235. work->pool->diff1 += work->nonce_diff;
  9236. thr->cgpu->last_device_valid_work = time(NULL);
  9237. mutex_unlock(&stats_lock);
  9238. if (noncelog_file)
  9239. noncelog(work);
  9240. if (res == TNR_HIGH)
  9241. {
  9242. // Share above target, normal
  9243. /* Check the diff of the share, even if it didn't reach the
  9244. * target, just to set the best share value if it's higher. */
  9245. share_diff(work);
  9246. goto out;
  9247. }
  9248. submit_work_async2(work, &tv_work_found);
  9249. work = NULL; // Taken by submit_work_async2
  9250. out:
  9251. if (work)
  9252. free_work(work);
  9253. thread_reportin(thr);
  9254. return ret;
  9255. }
  9256. // return true of we should stop working on this piece of work
  9257. // returning false means we will keep scanning for a nonce
  9258. // assumptions: work->blk.nonce is the number of nonces completed in the work
  9259. // see minerloop_scanhash comments for more details & usage
  9260. bool abandon_work(struct work *work, struct timeval *wdiff, uint64_t max_hashes)
  9261. {
  9262. if (work->blk.nonce == 0xffffffff || // known we are scanning a full nonce range
  9263. wdiff->tv_sec > opt_scantime || // scan-time has elapsed (user specified, default 60s)
  9264. work->blk.nonce >= 0xfffffffe - max_hashes || // are there enough nonces left in the work
  9265. max_hashes >= 0xfffffffe || // assume we are scanning a full nonce range
  9266. stale_work(work, false)) // work is stale
  9267. return true;
  9268. return false;
  9269. }
  9270. void __thr_being_msg(int prio, struct thr_info *thr, const char *being)
  9271. {
  9272. struct cgpu_info *proc = thr->cgpu;
  9273. if (proc->threads > 1)
  9274. applog(prio, "%"PRIpreprv" (thread %d) %s", proc->proc_repr, thr->id, being);
  9275. else
  9276. applog(prio, "%"PRIpreprv" %s", proc->proc_repr, being);
  9277. }
  9278. // Called by asynchronous minerloops, when they find their processor should be disabled
  9279. void mt_disable_start(struct thr_info *mythr)
  9280. {
  9281. struct cgpu_info *cgpu = mythr->cgpu;
  9282. struct device_drv *drv = cgpu->drv;
  9283. if (drv->thread_disable)
  9284. drv->thread_disable(mythr);
  9285. hashmeter2(mythr);
  9286. __thr_being_msg(LOG_WARNING, mythr, "being disabled");
  9287. mythr->rolling = mythr->cgpu->rolling = 0;
  9288. thread_reportout(mythr);
  9289. mythr->_mt_disable_called = true;
  9290. }
  9291. /* Put a new unqueued work item in cgpu->unqueued_work under cgpu->qlock till
  9292. * the driver tells us it's full so that it may extract the work item using
  9293. * the get_queued() function which adds it to the hashtable on
  9294. * cgpu->queued_work. */
  9295. static void fill_queue(struct thr_info *mythr, struct cgpu_info *cgpu, struct device_drv *drv, const int thr_id)
  9296. {
  9297. thread_reportout(mythr);
  9298. do {
  9299. bool need_work;
  9300. /* Do this lockless just to know if we need more unqueued work. */
  9301. need_work = (!cgpu->unqueued_work);
  9302. /* get_work is a blocking function so do it outside of lock
  9303. * to prevent deadlocks with other locks. */
  9304. if (need_work) {
  9305. struct work *work = get_work(mythr);
  9306. wr_lock(&cgpu->qlock);
  9307. /* Check we haven't grabbed work somehow between
  9308. * checking and picking up the lock. */
  9309. if (likely(!cgpu->unqueued_work))
  9310. cgpu->unqueued_work = work;
  9311. else
  9312. need_work = false;
  9313. wr_unlock(&cgpu->qlock);
  9314. if (unlikely(!need_work))
  9315. discard_work(work);
  9316. }
  9317. /* The queue_full function should be used by the driver to
  9318. * actually place work items on the physical device if it
  9319. * does have a queue. */
  9320. } while (drv->queue_full && !drv->queue_full(cgpu));
  9321. }
  9322. /* Add a work item to a cgpu's queued hashlist */
  9323. void __add_queued(struct cgpu_info *cgpu, struct work *work)
  9324. {
  9325. cgpu->queued_count++;
  9326. HASH_ADD_INT(cgpu->queued_work, id, work);
  9327. }
  9328. /* This function is for retrieving one work item from the unqueued pointer and
  9329. * adding it to the hashtable of queued work. Code using this function must be
  9330. * able to handle NULL as a return which implies there is no work available. */
  9331. struct work *get_queued(struct cgpu_info *cgpu)
  9332. {
  9333. struct work *work = NULL;
  9334. wr_lock(&cgpu->qlock);
  9335. if (cgpu->unqueued_work) {
  9336. work = cgpu->unqueued_work;
  9337. if (unlikely(stale_work(work, false))) {
  9338. discard_work(work);
  9339. work = NULL;
  9340. wake_gws();
  9341. } else
  9342. __add_queued(cgpu, work);
  9343. cgpu->unqueued_work = NULL;
  9344. }
  9345. wr_unlock(&cgpu->qlock);
  9346. return work;
  9347. }
  9348. void add_queued(struct cgpu_info *cgpu, struct work *work)
  9349. {
  9350. wr_lock(&cgpu->qlock);
  9351. __add_queued(cgpu, work);
  9352. wr_unlock(&cgpu->qlock);
  9353. }
  9354. /* Get fresh work and add it to cgpu's queued hashlist */
  9355. struct work *get_queue_work(struct thr_info *thr, struct cgpu_info *cgpu, int thr_id)
  9356. {
  9357. struct work *work = get_work(thr);
  9358. add_queued(cgpu, work);
  9359. return work;
  9360. }
  9361. /* This function is for finding an already queued work item in the
  9362. * given que hashtable. Code using this function must be able
  9363. * to handle NULL as a return which implies there is no matching work.
  9364. * The calling function must lock access to the que if it is required.
  9365. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  9366. struct work *__find_work_bymidstate(struct work *que, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  9367. {
  9368. struct work *work, *tmp, *ret = NULL;
  9369. HASH_ITER(hh, que, work, tmp) {
  9370. if (memcmp(work->midstate, midstate, midstatelen) == 0 &&
  9371. memcmp(work->data + offset, data, datalen) == 0) {
  9372. ret = work;
  9373. break;
  9374. }
  9375. }
  9376. return ret;
  9377. }
  9378. /* This function is for finding an already queued work item in the
  9379. * device's queued_work hashtable. Code using this function must be able
  9380. * to handle NULL as a return which implies there is no matching work.
  9381. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  9382. struct work *find_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  9383. {
  9384. struct work *ret;
  9385. rd_lock(&cgpu->qlock);
  9386. ret = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  9387. rd_unlock(&cgpu->qlock);
  9388. return ret;
  9389. }
  9390. struct work *clone_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  9391. {
  9392. struct work *work, *ret = NULL;
  9393. rd_lock(&cgpu->qlock);
  9394. work = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  9395. if (work)
  9396. ret = copy_work(work);
  9397. rd_unlock(&cgpu->qlock);
  9398. return ret;
  9399. }
  9400. void __work_completed(struct cgpu_info *cgpu, struct work *work)
  9401. {
  9402. cgpu->queued_count--;
  9403. HASH_DEL(cgpu->queued_work, work);
  9404. }
  9405. /* This iterates over a queued hashlist finding work started more than secs
  9406. * seconds ago and discards the work as completed. The driver must set the
  9407. * work->tv_work_start value appropriately. Returns the number of items aged. */
  9408. int age_queued_work(struct cgpu_info *cgpu, double secs)
  9409. {
  9410. struct work *work, *tmp;
  9411. struct timeval tv_now;
  9412. int aged = 0;
  9413. cgtime(&tv_now);
  9414. wr_lock(&cgpu->qlock);
  9415. HASH_ITER(hh, cgpu->queued_work, work, tmp) {
  9416. if (tdiff(&tv_now, &work->tv_work_start) > secs) {
  9417. __work_completed(cgpu, work);
  9418. aged++;
  9419. }
  9420. }
  9421. wr_unlock(&cgpu->qlock);
  9422. return aged;
  9423. }
  9424. /* This function should be used by queued device drivers when they're sure
  9425. * the work struct is no longer in use. */
  9426. void work_completed(struct cgpu_info *cgpu, struct work *work)
  9427. {
  9428. wr_lock(&cgpu->qlock);
  9429. __work_completed(cgpu, work);
  9430. wr_unlock(&cgpu->qlock);
  9431. free_work(work);
  9432. }
  9433. /* Combines find_queued_work_bymidstate and work_completed in one function
  9434. * withOUT destroying the work so the driver must free it. */
  9435. struct work *take_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  9436. {
  9437. struct work *work;
  9438. wr_lock(&cgpu->qlock);
  9439. work = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  9440. if (work)
  9441. __work_completed(cgpu, work);
  9442. wr_unlock(&cgpu->qlock);
  9443. return work;
  9444. }
  9445. void flush_queue(struct cgpu_info *cgpu)
  9446. {
  9447. struct work *work = NULL;
  9448. wr_lock(&cgpu->qlock);
  9449. work = cgpu->unqueued_work;
  9450. cgpu->unqueued_work = NULL;
  9451. wr_unlock(&cgpu->qlock);
  9452. if (work) {
  9453. free_work(work);
  9454. applog(LOG_DEBUG, "Discarded queued work item");
  9455. }
  9456. }
  9457. /* This version of hash work is for devices that are fast enough to always
  9458. * perform a full nonce range and need a queue to maintain the device busy.
  9459. * Work creation and destruction is not done from within this function
  9460. * directly. */
  9461. void hash_queued_work(struct thr_info *mythr)
  9462. {
  9463. const long cycle = opt_log_interval / 5 ? : 1;
  9464. struct timeval tv_start = {0, 0}, tv_end;
  9465. struct cgpu_info *cgpu = mythr->cgpu;
  9466. struct device_drv *drv = cgpu->drv;
  9467. const int thr_id = mythr->id;
  9468. int64_t hashes_done = 0;
  9469. if (unlikely(cgpu->deven != DEV_ENABLED))
  9470. mt_disable(mythr);
  9471. while (likely(!cgpu->shutdown)) {
  9472. struct timeval diff;
  9473. int64_t hashes;
  9474. fill_queue(mythr, cgpu, drv, thr_id);
  9475. thread_reportin(mythr);
  9476. hashes = drv->scanwork(mythr);
  9477. /* Reset the bool here in case the driver looks for it
  9478. * synchronously in the scanwork loop. */
  9479. mythr->work_restart = false;
  9480. if (unlikely(hashes == -1 )) {
  9481. applog(LOG_ERR, "%s %d failure, disabling!", drv->name, cgpu->device_id);
  9482. cgpu->deven = DEV_DISABLED;
  9483. dev_error(cgpu, REASON_THREAD_ZERO_HASH);
  9484. mt_disable(mythr);
  9485. }
  9486. hashes_done += hashes;
  9487. cgtime(&tv_end);
  9488. timersub(&tv_end, &tv_start, &diff);
  9489. if (diff.tv_sec >= cycle) {
  9490. hashmeter(thr_id, &diff, hashes_done);
  9491. hashes_done = 0;
  9492. copy_time(&tv_start, &tv_end);
  9493. }
  9494. if (unlikely(mythr->pause || cgpu->deven != DEV_ENABLED))
  9495. mt_disable(mythr);
  9496. if (unlikely(mythr->work_restart)) {
  9497. flush_queue(cgpu);
  9498. if (drv->flush_work)
  9499. drv->flush_work(cgpu);
  9500. }
  9501. }
  9502. // cgpu->deven = DEV_DISABLED; set in miner_thread
  9503. }
  9504. // Called by minerloop, when it is re-enabling a processor
  9505. void mt_disable_finish(struct thr_info *mythr)
  9506. {
  9507. struct device_drv *drv = mythr->cgpu->drv;
  9508. thread_reportin(mythr);
  9509. __thr_being_msg(LOG_WARNING, mythr, "being re-enabled");
  9510. if (drv->thread_enable)
  9511. drv->thread_enable(mythr);
  9512. mythr->_mt_disable_called = false;
  9513. }
  9514. // Called by synchronous minerloops, when they find their processor should be disabled
  9515. // Calls mt_disable_start, waits until it's re-enabled, then calls mt_disable_finish
  9516. void mt_disable(struct thr_info *mythr)
  9517. {
  9518. const struct cgpu_info * const cgpu = mythr->cgpu;
  9519. mt_disable_start(mythr);
  9520. applog(LOG_DEBUG, "Waiting for wakeup notification in miner thread");
  9521. do {
  9522. notifier_read(mythr->notifier);
  9523. } while (mythr->pause || cgpu->deven != DEV_ENABLED);
  9524. mt_disable_finish(mythr);
  9525. }
  9526. enum {
  9527. STAT_SLEEP_INTERVAL = 1,
  9528. STAT_CTR_INTERVAL = 10000000,
  9529. FAILURE_INTERVAL = 30,
  9530. };
  9531. /* Stage another work item from the work returned in a longpoll */
  9532. 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)
  9533. {
  9534. bool rc;
  9535. work->rolltime = rolltime;
  9536. rc = work_decode(pool, work, val);
  9537. if (unlikely(!rc)) {
  9538. applog(LOG_ERR, "Could not convert longpoll data to work");
  9539. free_work(work);
  9540. return;
  9541. }
  9542. total_getworks++;
  9543. pool->getwork_requested++;
  9544. work->pool = pool;
  9545. copy_time(&work->tv_getwork, tv_lp);
  9546. copy_time(&work->tv_getwork_reply, tv_lp_reply);
  9547. calc_diff(work, 0);
  9548. if (pool->enabled == POOL_REJECTING)
  9549. work->mandatory = true;
  9550. work->longpoll = true;
  9551. work->getwork_mode = GETWORK_MODE_LP;
  9552. update_last_work(work);
  9553. /* We'll be checking this work item twice, but we already know it's
  9554. * from a new block so explicitly force the new block detection now
  9555. * rather than waiting for it to hit the stage thread. This also
  9556. * allows testwork to know whether LP discovered the block or not. */
  9557. test_work_current(work);
  9558. /* Don't use backup LPs as work if we have failover-only enabled. Use
  9559. * the longpoll work from a pool that has been rejecting shares as a
  9560. * way to detect when the pool has recovered.
  9561. */
  9562. if (pool != current_pool() && opt_fail_only && pool->enabled != POOL_REJECTING) {
  9563. free_work(work);
  9564. return;
  9565. }
  9566. work = clone_work(work);
  9567. applog(LOG_DEBUG, "Pushing converted work to stage thread");
  9568. stage_work(work);
  9569. applog(LOG_DEBUG, "Converted longpoll data to work");
  9570. }
  9571. /* If we want longpoll, enable it for the chosen default pool, or, if
  9572. * the pool does not support longpoll, find the first one that does
  9573. * and use its longpoll support */
  9574. static
  9575. struct pool *_select_longpoll_pool(struct pool *cp, bool(*func)(struct pool *))
  9576. {
  9577. int i;
  9578. if (func(cp))
  9579. return cp;
  9580. for (i = 0; i < total_pools; i++) {
  9581. struct pool *pool = pools[i];
  9582. if (cp->goal != pool->goal)
  9583. continue;
  9584. if (func(pool))
  9585. return pool;
  9586. }
  9587. return NULL;
  9588. }
  9589. /* This will make the longpoll thread wait till it's the current pool, or it
  9590. * has been flagged as rejecting, before attempting to open any connections.
  9591. */
  9592. static void wait_lpcurrent(struct pool *pool)
  9593. {
  9594. mutex_lock(&lp_lock);
  9595. while (!cnx_needed(pool))
  9596. {
  9597. pool->lp_active = false;
  9598. pthread_cond_wait(&lp_cond, &lp_lock);
  9599. }
  9600. mutex_unlock(&lp_lock);
  9601. }
  9602. static curl_socket_t save_curl_socket(void *vpool, __maybe_unused curlsocktype purpose, struct curl_sockaddr *addr) {
  9603. struct pool *pool = vpool;
  9604. curl_socket_t sock = bfg_socket(addr->family, addr->socktype, addr->protocol);
  9605. pool->lp_socket = sock;
  9606. return sock;
  9607. }
  9608. static void *longpoll_thread(void *userdata)
  9609. {
  9610. struct pool *cp = (struct pool *)userdata;
  9611. /* This *pool is the source of the actual longpoll, not the pool we've
  9612. * tied it to */
  9613. struct timeval start, reply, end;
  9614. struct pool *pool = NULL;
  9615. char threadname[20];
  9616. CURL *curl = NULL;
  9617. int failures = 0;
  9618. char *lp_url;
  9619. int rolltime;
  9620. #ifndef HAVE_PTHREAD_CANCEL
  9621. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  9622. #endif
  9623. snprintf(threadname, 20, "longpoll%u", cp->pool_no);
  9624. RenameThread(threadname);
  9625. curl = curl_easy_init();
  9626. if (unlikely(!curl)) {
  9627. applog(LOG_ERR, "CURL initialisation failed");
  9628. return NULL;
  9629. }
  9630. retry_pool:
  9631. pool = select_longpoll_pool(cp);
  9632. if (!pool) {
  9633. applog(LOG_WARNING, "No suitable long-poll found for %s", cp->rpc_url);
  9634. while (!pool) {
  9635. cgsleep_ms(60000);
  9636. pool = select_longpoll_pool(cp);
  9637. }
  9638. }
  9639. if (pool->has_stratum) {
  9640. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  9641. cp->rpc_url, pool->rpc_url);
  9642. goto out;
  9643. }
  9644. /* Any longpoll from any pool is enough for this to be true */
  9645. pool->goal->have_longpoll = true;
  9646. wait_lpcurrent(cp);
  9647. {
  9648. lp_url = pool->lp_url;
  9649. if (cp == pool)
  9650. applog(LOG_WARNING, "Long-polling activated for %s (%s)", lp_url, pool_protocol_name(pool->lp_proto));
  9651. else
  9652. applog(LOG_WARNING, "Long-polling activated for %s via %s (%s)", cp->rpc_url, lp_url, pool_protocol_name(pool->lp_proto));
  9653. }
  9654. while (42) {
  9655. json_t *val, *soval;
  9656. struct work *work = make_work();
  9657. char *lpreq;
  9658. lpreq = prepare_rpc_req(work, pool->lp_proto, pool->lp_id, pool);
  9659. work->pool = pool;
  9660. if (!lpreq)
  9661. {
  9662. free_work(work);
  9663. goto lpfail;
  9664. }
  9665. wait_lpcurrent(cp);
  9666. cgtime(&start);
  9667. /* Longpoll connections can be persistent for a very long time
  9668. * and any number of issues could have come up in the meantime
  9669. * so always establish a fresh connection instead of relying on
  9670. * a persistent one. */
  9671. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  9672. curl_easy_setopt(curl, CURLOPT_FORBID_REUSE, 1);
  9673. curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, save_curl_socket);
  9674. curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, pool);
  9675. val = json_rpc_call(curl, lp_url, pool->rpc_userpass,
  9676. lpreq, false, true, &rolltime, pool, false);
  9677. pool->lp_socket = CURL_SOCKET_BAD;
  9678. cgtime(&reply);
  9679. free(lpreq);
  9680. if (likely(val)) {
  9681. soval = json_object_get(json_object_get(val, "result"), "submitold");
  9682. if (soval)
  9683. pool->submit_old = json_is_true(soval);
  9684. else
  9685. pool->submit_old = false;
  9686. convert_to_work(val, rolltime, pool, work, &start, &reply);
  9687. failures = 0;
  9688. json_decref(val);
  9689. } else {
  9690. /* Some pools regularly drop the longpoll request so
  9691. * only see this as longpoll failure if it happens
  9692. * immediately and just restart it the rest of the
  9693. * time. */
  9694. cgtime(&end);
  9695. free_work(work);
  9696. if (end.tv_sec - start.tv_sec <= 30)
  9697. {
  9698. if (failures == 1)
  9699. applog(LOG_WARNING, "longpoll failed for %s, retrying every 30s", lp_url);
  9700. lpfail:
  9701. cgsleep_ms(30000);
  9702. }
  9703. }
  9704. if (pool != cp) {
  9705. pool = select_longpoll_pool(cp);
  9706. if (pool->has_stratum) {
  9707. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  9708. cp->rpc_url, pool->rpc_url);
  9709. break;
  9710. }
  9711. if (unlikely(!pool))
  9712. goto retry_pool;
  9713. }
  9714. if (unlikely(pool->removed))
  9715. break;
  9716. }
  9717. out:
  9718. pool->lp_active = false;
  9719. curl_easy_cleanup(curl);
  9720. return NULL;
  9721. }
  9722. static void stop_longpoll(void)
  9723. {
  9724. int i;
  9725. want_longpoll = false;
  9726. for (i = 0; i < total_pools; ++i)
  9727. {
  9728. struct pool *pool = pools[i];
  9729. if (unlikely(!pool->lp_started))
  9730. continue;
  9731. pool->lp_started = false;
  9732. pthread_cancel(pool->longpoll_thread);
  9733. }
  9734. struct mining_goal_info *goal, *tmpgoal;
  9735. HASH_ITER(hh, mining_goals, goal, tmpgoal)
  9736. {
  9737. goal->have_longpoll = false;
  9738. }
  9739. }
  9740. static void start_longpoll(void)
  9741. {
  9742. int i;
  9743. want_longpoll = true;
  9744. for (i = 0; i < total_pools; ++i)
  9745. {
  9746. struct pool *pool = pools[i];
  9747. if (unlikely(pool->removed || pool->lp_started || !pool->lp_url))
  9748. continue;
  9749. pool->lp_started = true;
  9750. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  9751. quit(1, "Failed to create pool longpoll thread");
  9752. }
  9753. }
  9754. void reinit_device(struct cgpu_info *cgpu)
  9755. {
  9756. if (cgpu->drv->reinit_device)
  9757. cgpu->drv->reinit_device(cgpu);
  9758. }
  9759. static struct timeval rotate_tv;
  9760. /* We reap curls if they are unused for over a minute */
  9761. static void reap_curl(struct pool *pool)
  9762. {
  9763. struct curl_ent *ent, *iter;
  9764. struct timeval now;
  9765. int reaped = 0;
  9766. cgtime(&now);
  9767. mutex_lock(&pool->pool_lock);
  9768. LL_FOREACH_SAFE(pool->curllist, ent, iter) {
  9769. if (pool->curls < 2)
  9770. break;
  9771. if (now.tv_sec - ent->tv.tv_sec > 300) {
  9772. reaped++;
  9773. pool->curls--;
  9774. LL_DELETE(pool->curllist, ent);
  9775. curl_easy_cleanup(ent->curl);
  9776. free(ent);
  9777. }
  9778. }
  9779. mutex_unlock(&pool->pool_lock);
  9780. if (reaped)
  9781. applog(LOG_DEBUG, "Reaped %d curl%s from pool %d", reaped, reaped > 1 ? "s" : "", pool->pool_no);
  9782. }
  9783. static void *watchpool_thread(void __maybe_unused *userdata)
  9784. {
  9785. int intervals = 0;
  9786. #ifndef HAVE_PTHREAD_CANCEL
  9787. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  9788. #endif
  9789. RenameThread("watchpool");
  9790. while (42) {
  9791. struct timeval now;
  9792. int i;
  9793. if (++intervals > 20)
  9794. intervals = 0;
  9795. cgtime(&now);
  9796. for (i = 0; i < total_pools; i++) {
  9797. struct pool *pool = pools[i];
  9798. if (!opt_benchmark)
  9799. reap_curl(pool);
  9800. /* Get a rolling utility per pool over 10 mins */
  9801. if (intervals > 19) {
  9802. int shares = pool->diff1 - pool->last_shares;
  9803. pool->last_shares = pool->diff1;
  9804. pool->utility = (pool->utility + (double)shares * 0.63) / 1.63;
  9805. pool->shares = pool->utility;
  9806. }
  9807. if (pool->enabled == POOL_DISABLED)
  9808. continue;
  9809. /* Don't start testing any pools if the test threads
  9810. * from startup are still doing their first attempt. */
  9811. if (unlikely(pool->testing)) {
  9812. pthread_join(pool->test_thread, NULL);
  9813. }
  9814. /* Test pool is idle once every minute */
  9815. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 30) {
  9816. if (pool_active(pool, true) && pool_tclear(pool, &pool->idle))
  9817. pool_resus(pool);
  9818. }
  9819. /* Only switch pools if the failback pool has been
  9820. * alive for more than 5 minutes (default) to prevent
  9821. * intermittently failing pools from being used. */
  9822. 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)
  9823. {
  9824. if (opt_fail_switch_delay % 60)
  9825. applog(LOG_WARNING, "Pool %d %s stable for %d second%s",
  9826. pool->pool_no, pool->rpc_url,
  9827. opt_fail_switch_delay,
  9828. (opt_fail_switch_delay == 1 ? "" : "s"));
  9829. else
  9830. applog(LOG_WARNING, "Pool %d %s stable for %d minute%s",
  9831. pool->pool_no, pool->rpc_url,
  9832. opt_fail_switch_delay / 60,
  9833. (opt_fail_switch_delay == 60 ? "" : "s"));
  9834. switch_pools(NULL);
  9835. }
  9836. }
  9837. if (current_pool()->idle)
  9838. switch_pools(NULL);
  9839. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  9840. cgtime(&rotate_tv);
  9841. switch_pools(NULL);
  9842. }
  9843. cgsleep_ms(30000);
  9844. }
  9845. return NULL;
  9846. }
  9847. void mt_enable(struct thr_info *thr)
  9848. {
  9849. applog(LOG_DEBUG, "Waking up thread %d", thr->id);
  9850. notifier_wake(thr->notifier);
  9851. }
  9852. void proc_enable(struct cgpu_info *cgpu)
  9853. {
  9854. int j;
  9855. cgpu->deven = DEV_ENABLED;
  9856. for (j = cgpu->threads ?: 1; j--; )
  9857. mt_enable(cgpu->thr[j]);
  9858. }
  9859. #define device_recovered(cgpu) proc_enable(cgpu)
  9860. void cgpu_set_defaults(struct cgpu_info * const cgpu)
  9861. {
  9862. struct string_elist *setstr_elist;
  9863. const char *p, *p2;
  9864. char replybuf[0x2000];
  9865. size_t L;
  9866. DL_FOREACH(opt_set_device_list, setstr_elist)
  9867. {
  9868. const char * const setstr = setstr_elist->string;
  9869. p = strchr(setstr, ':');
  9870. if (!p)
  9871. p = setstr;
  9872. {
  9873. L = p - setstr;
  9874. char pattern[L + 1];
  9875. if (L)
  9876. memcpy(pattern, setstr, L);
  9877. pattern[L] = '\0';
  9878. if (!cgpu_match(pattern, cgpu))
  9879. continue;
  9880. }
  9881. applog(LOG_DEBUG, "%"PRIpreprv": %s: Matched with set default: %s",
  9882. cgpu->proc_repr, __func__, setstr);
  9883. if (p[0] == ':')
  9884. ++p;
  9885. p2 = strchr(p, '=');
  9886. if (!p2)
  9887. {
  9888. L = strlen(p);
  9889. p2 = "";
  9890. }
  9891. else
  9892. {
  9893. L = p2 - p;
  9894. ++p2;
  9895. }
  9896. char opt[L + 1];
  9897. if (L)
  9898. memcpy(opt, p, L);
  9899. opt[L] = '\0';
  9900. L = strlen(p2);
  9901. char setval[L + 1];
  9902. if (L)
  9903. memcpy(setval, p2, L);
  9904. setval[L] = '\0';
  9905. enum bfg_set_device_replytype success;
  9906. p = proc_set_device(cgpu, opt, setval, replybuf, &success);
  9907. switch (success)
  9908. {
  9909. case SDR_OK:
  9910. applog(LOG_DEBUG, "%"PRIpreprv": Applied rule %s%s%s",
  9911. cgpu->proc_repr, setstr,
  9912. p ? ": " : "", p ?: "");
  9913. break;
  9914. case SDR_ERR:
  9915. case SDR_HELP:
  9916. case SDR_UNKNOWN:
  9917. applog(LOG_DEBUG, "%"PRIpreprv": Applying rule %s: %s",
  9918. cgpu->proc_repr, setstr, p);
  9919. break;
  9920. case SDR_AUTO:
  9921. case SDR_NOSUPP:
  9922. applog(LOG_DEBUG, "%"PRIpreprv": set_device is not implemented (trying to apply rule: %s)",
  9923. cgpu->proc_repr, setstr);
  9924. }
  9925. }
  9926. cgpu->already_set_defaults = true;
  9927. }
  9928. 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)
  9929. {
  9930. struct device_drv dummy_drv = *drv;
  9931. struct cgpu_info dummy_cgpu = {
  9932. .drv = &dummy_drv,
  9933. .device = &dummy_cgpu,
  9934. .device_id = -1,
  9935. .proc_id = -1,
  9936. .device_data = userp,
  9937. .device_path = devpath,
  9938. .dev_serial = serial,
  9939. };
  9940. strcpy(dummy_cgpu.proc_repr, drv->name);
  9941. switch (mode)
  9942. {
  9943. case 0:
  9944. dummy_drv.set_device = datap;
  9945. break;
  9946. case 1:
  9947. dummy_drv.set_device = NULL;
  9948. dummy_cgpu.set_device_funcs = datap;
  9949. break;
  9950. }
  9951. cgpu_set_defaults(&dummy_cgpu);
  9952. }
  9953. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  9954. * the screen at regular intervals, and restarts threads if they appear to have
  9955. * died. */
  9956. #define WATCHDOG_SICK_TIME 60
  9957. #define WATCHDOG_DEAD_TIME 600
  9958. #define WATCHDOG_SICK_COUNT (WATCHDOG_SICK_TIME/WATCHDOG_INTERVAL)
  9959. #define WATCHDOG_DEAD_COUNT (WATCHDOG_DEAD_TIME/WATCHDOG_INTERVAL)
  9960. static void *watchdog_thread(void __maybe_unused *userdata)
  9961. {
  9962. const unsigned int interval = WATCHDOG_INTERVAL;
  9963. struct timeval zero_tv;
  9964. #ifndef HAVE_PTHREAD_CANCEL
  9965. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  9966. #endif
  9967. RenameThread("watchdog");
  9968. memset(&zero_tv, 0, sizeof(struct timeval));
  9969. cgtime(&rotate_tv);
  9970. while (1) {
  9971. int i;
  9972. struct timeval now;
  9973. sleep(interval);
  9974. discard_stale();
  9975. hashmeter(-1, &zero_tv, 0);
  9976. #ifdef HAVE_CURSES
  9977. const int ts = total_staged(true);
  9978. if (curses_active_locked()) {
  9979. change_logwinsize();
  9980. curses_print_status(ts);
  9981. _refresh_devstatus(true);
  9982. touchwin(logwin);
  9983. wrefresh(logwin);
  9984. unlock_curses();
  9985. }
  9986. #endif
  9987. cgtime(&now);
  9988. if (!sched_paused && !should_run()) {
  9989. applog(LOG_WARNING, "Pausing execution as per stop time %02d:%02d scheduled",
  9990. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  9991. if (!schedstart.enable) {
  9992. quit(0, "Terminating execution as planned");
  9993. break;
  9994. }
  9995. applog(LOG_WARNING, "Will restart execution as scheduled at %02d:%02d",
  9996. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  9997. sched_paused = true;
  9998. rd_lock(&mining_thr_lock);
  9999. for (i = 0; i < mining_threads; i++)
  10000. mining_thr[i]->pause = true;
  10001. rd_unlock(&mining_thr_lock);
  10002. } else if (sched_paused && should_run()) {
  10003. applog(LOG_WARNING, "Restarting execution as per start time %02d:%02d scheduled",
  10004. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  10005. if (schedstop.enable)
  10006. applog(LOG_WARNING, "Will pause execution as scheduled at %02d:%02d",
  10007. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  10008. sched_paused = false;
  10009. for (i = 0; i < mining_threads; i++) {
  10010. struct thr_info *thr;
  10011. thr = get_thread(i);
  10012. thr->pause = false;
  10013. }
  10014. for (i = 0; i < total_devices; ++i)
  10015. {
  10016. struct cgpu_info *cgpu = get_devices(i);
  10017. /* Don't touch disabled devices */
  10018. if (cgpu->deven == DEV_DISABLED)
  10019. continue;
  10020. proc_enable(cgpu);
  10021. }
  10022. }
  10023. for (i = 0; i < total_devices; ++i) {
  10024. struct cgpu_info *cgpu = get_devices(i);
  10025. if (!cgpu->disable_watchdog)
  10026. bfg_watchdog(cgpu, &now);
  10027. }
  10028. }
  10029. return NULL;
  10030. }
  10031. void bfg_watchdog(struct cgpu_info * const cgpu, struct timeval * const tvp_now)
  10032. {
  10033. struct thr_info *thr = cgpu->thr[0];
  10034. enum dev_enable *denable;
  10035. char *dev_str = cgpu->proc_repr;
  10036. if (likely(drv_ready(cgpu)))
  10037. {
  10038. if (unlikely(!cgpu->already_set_defaults))
  10039. cgpu_set_defaults(cgpu);
  10040. if (cgpu->drv->get_stats)
  10041. cgpu->drv->get_stats(cgpu);
  10042. }
  10043. denable = &cgpu->deven;
  10044. if (cgpu->drv->watchdog)
  10045. cgpu->drv->watchdog(cgpu, tvp_now);
  10046. /* Thread is disabled */
  10047. if (*denable == DEV_DISABLED)
  10048. return;
  10049. else
  10050. if (*denable == DEV_RECOVER_ERR) {
  10051. if (opt_restart && timer_elapsed(&cgpu->tv_device_last_not_well, NULL) > cgpu->reinit_backoff) {
  10052. applog(LOG_NOTICE, "Attempting to reinitialize %s",
  10053. dev_str);
  10054. if (cgpu->reinit_backoff < 300)
  10055. cgpu->reinit_backoff *= 2;
  10056. device_recovered(cgpu);
  10057. }
  10058. return;
  10059. }
  10060. else
  10061. if (*denable == DEV_RECOVER) {
  10062. if (opt_restart && cgpu->temp < cgpu->targettemp) {
  10063. applog(LOG_NOTICE, "%s recovered to temperature below target, re-enabling",
  10064. dev_str);
  10065. device_recovered(cgpu);
  10066. }
  10067. dev_error_update(cgpu, REASON_DEV_THERMAL_CUTOFF);
  10068. return;
  10069. }
  10070. else
  10071. if (cgpu->temp > cgpu->cutofftemp)
  10072. {
  10073. applog(LOG_WARNING, "%s hit thermal cutoff limit at %dC, disabling!",
  10074. dev_str, (int)cgpu->temp);
  10075. *denable = DEV_RECOVER;
  10076. dev_error(cgpu, REASON_DEV_THERMAL_CUTOFF);
  10077. run_cmd(cmd_idle);
  10078. }
  10079. if (thr->getwork) {
  10080. if (cgpu->status == LIFE_WELL && thr->getwork < tvp_now->tv_sec - opt_log_interval) {
  10081. int thrid;
  10082. bool cgpu_idle = true;
  10083. thr->rolling = 0;
  10084. for (thrid = 0; thrid < cgpu->threads; ++thrid)
  10085. if (!cgpu->thr[thrid]->getwork)
  10086. cgpu_idle = false;
  10087. if (cgpu_idle) {
  10088. cgpu->rolling = 0;
  10089. cgpu->status = LIFE_WAIT;
  10090. }
  10091. }
  10092. return;
  10093. }
  10094. else if (cgpu->status == LIFE_WAIT)
  10095. cgpu->status = LIFE_WELL;
  10096. #ifdef USE_CPUMINING
  10097. if (!strcmp(cgpu->drv->dname, "cpu"))
  10098. return;
  10099. #endif
  10100. if (cgpu->status != LIFE_WELL && (tvp_now->tv_sec - thr->last.tv_sec < WATCHDOG_SICK_TIME)) {
  10101. if (likely(cgpu->status != LIFE_INIT && cgpu->status != LIFE_INIT2))
  10102. applog(LOG_ERR, "%s: Recovered, declaring WELL!", dev_str);
  10103. cgpu->status = LIFE_WELL;
  10104. cgpu->device_last_well = time(NULL);
  10105. } else if (cgpu->status == LIFE_WELL && (tvp_now->tv_sec - thr->last.tv_sec > WATCHDOG_SICK_TIME)) {
  10106. thr->rolling = cgpu->rolling = 0;
  10107. cgpu->status = LIFE_SICK;
  10108. applog(LOG_ERR, "%s: Idle for more than 60 seconds, declaring SICK!", dev_str);
  10109. cgtime(&thr->sick);
  10110. dev_error(cgpu, REASON_DEV_SICK_IDLE_60);
  10111. run_cmd(cmd_sick);
  10112. if (opt_restart && cgpu->drv->reinit_device) {
  10113. applog(LOG_ERR, "%s: Attempting to restart", dev_str);
  10114. reinit_device(cgpu);
  10115. }
  10116. } else if (cgpu->status == LIFE_SICK && (tvp_now->tv_sec - thr->last.tv_sec > WATCHDOG_DEAD_TIME)) {
  10117. cgpu->status = LIFE_DEAD;
  10118. applog(LOG_ERR, "%s: Not responded for more than 10 minutes, declaring DEAD!", dev_str);
  10119. cgtime(&thr->sick);
  10120. dev_error(cgpu, REASON_DEV_DEAD_IDLE_600);
  10121. run_cmd(cmd_dead);
  10122. } else if (tvp_now->tv_sec - thr->sick.tv_sec > 60 &&
  10123. (cgpu->status == LIFE_SICK || cgpu->status == LIFE_DEAD)) {
  10124. /* Attempt to restart a GPU that's sick or dead once every minute */
  10125. cgtime(&thr->sick);
  10126. if (opt_restart)
  10127. reinit_device(cgpu);
  10128. }
  10129. }
  10130. static void log_print_status(struct cgpu_info *cgpu)
  10131. {
  10132. char logline[255];
  10133. get_statline(logline, sizeof(logline), cgpu);
  10134. applog(LOG_WARNING, "%s", logline);
  10135. }
  10136. void print_summary(void)
  10137. {
  10138. struct timeval diff;
  10139. int hours, mins, secs, i;
  10140. double utility, efficiency = 0.0;
  10141. char xfer[(ALLOC_H2B_SPACED*2)+4+1], bw[(ALLOC_H2B_SPACED*2)+6+1];
  10142. int pool_secs;
  10143. timersub(&total_tv_end, &total_tv_start, &diff);
  10144. hours = diff.tv_sec / 3600;
  10145. mins = (diff.tv_sec % 3600) / 60;
  10146. secs = diff.tv_sec % 60;
  10147. utility = total_accepted / total_secs * 60;
  10148. efficiency = total_bytes_xfer ? total_diff_accepted * 2048. / total_bytes_xfer : 0.0;
  10149. applog(LOG_WARNING, "\nSummary of runtime statistics:\n");
  10150. applog(LOG_WARNING, "Started at %s", datestamp);
  10151. if (total_pools == 1)
  10152. applog(LOG_WARNING, "Pool: %s", pools[0]->rpc_url);
  10153. #if defined(USE_CPUMINING) && defined(USE_SHA256D)
  10154. if (opt_n_threads > 0)
  10155. applog(LOG_WARNING, "CPU hasher algorithm used: %s", algo_names[opt_algo]);
  10156. #endif
  10157. applog(LOG_WARNING, "Runtime: %d hrs : %d mins : %d secs", hours, mins, secs);
  10158. applog(LOG_WARNING, "Average hashrate: %.1f Megahash/s", total_mhashes_done / total_secs);
  10159. applog(LOG_WARNING, "Solved blocks: %d", found_blocks);
  10160. applog(LOG_WARNING, "Best share difficulty: %s", best_share);
  10161. applog(LOG_WARNING, "Share submissions: %d", total_accepted + total_rejected);
  10162. applog(LOG_WARNING, "Accepted shares: %d", total_accepted);
  10163. applog(LOG_WARNING, "Rejected shares: %d + %d stale (%.2f%%)",
  10164. total_rejected, total_stale,
  10165. (float)(total_rejected + total_stale) / (float)(total_rejected + total_stale + total_accepted)
  10166. );
  10167. applog(LOG_WARNING, "Accepted difficulty shares: %1.f", total_diff_accepted);
  10168. applog(LOG_WARNING, "Rejected difficulty shares: %1.f", total_diff_rejected);
  10169. applog(LOG_WARNING, "Hardware errors: %d", hw_errors);
  10170. applog(LOG_WARNING, "Network transfer: %s (%s)",
  10171. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  10172. (float)total_bytes_rcvd,
  10173. (float)total_bytes_sent),
  10174. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  10175. (float)(total_bytes_rcvd / total_secs),
  10176. (float)(total_bytes_sent / total_secs)));
  10177. applog(LOG_WARNING, "Efficiency (accepted shares * difficulty / 2 KB): %.2f", efficiency);
  10178. applog(LOG_WARNING, "Utility (accepted shares / min): %.2f/min\n", utility);
  10179. applog(LOG_WARNING, "Unable to get work from server occasions: %d", total_go);
  10180. applog(LOG_WARNING, "Work items generated locally: %d", local_work);
  10181. applog(LOG_WARNING, "Submitting work remotely delay occasions: %d", total_ro);
  10182. applog(LOG_WARNING, "New blocks detected on network: %d\n", new_blocks);
  10183. if (total_pools > 1) {
  10184. for (i = 0; i < total_pools; i++) {
  10185. struct pool *pool = pools[i];
  10186. applog(LOG_WARNING, "Pool: %s", pool->rpc_url);
  10187. if (pool->solved)
  10188. applog(LOG_WARNING, "SOLVED %d BLOCK%s!", pool->solved, pool->solved > 1 ? "S" : "");
  10189. applog(LOG_WARNING, " Share submissions: %d", pool->accepted + pool->rejected);
  10190. applog(LOG_WARNING, " Accepted shares: %d", pool->accepted);
  10191. applog(LOG_WARNING, " Rejected shares: %d + %d stale (%.2f%%)",
  10192. pool->rejected, pool->stale_shares,
  10193. (float)(pool->rejected + pool->stale_shares) / (float)(pool->rejected + pool->stale_shares + pool->accepted)
  10194. );
  10195. applog(LOG_WARNING, " Accepted difficulty shares: %1.f", pool->diff_accepted);
  10196. applog(LOG_WARNING, " Rejected difficulty shares: %1.f", pool->diff_rejected);
  10197. pool_secs = timer_elapsed(&pool->cgminer_stats.start_tv, NULL);
  10198. applog(LOG_WARNING, " Network transfer: %s (%s)",
  10199. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  10200. (float)pool->cgminer_pool_stats.net_bytes_received,
  10201. (float)pool->cgminer_pool_stats.net_bytes_sent),
  10202. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  10203. (float)(pool->cgminer_pool_stats.net_bytes_received / pool_secs),
  10204. (float)(pool->cgminer_pool_stats.net_bytes_sent / pool_secs)));
  10205. uint64_t pool_bytes_xfer = pool->cgminer_pool_stats.net_bytes_received + pool->cgminer_pool_stats.net_bytes_sent;
  10206. efficiency = pool_bytes_xfer ? pool->diff_accepted * 2048. / pool_bytes_xfer : 0.0;
  10207. applog(LOG_WARNING, " Efficiency (accepted * difficulty / 2 KB): %.2f", efficiency);
  10208. applog(LOG_WARNING, " Items worked on: %d", pool->works);
  10209. applog(LOG_WARNING, " Unable to get work from server occasions: %d", pool->getfail_occasions);
  10210. applog(LOG_WARNING, " Submitting work remotely delay occasions: %d\n", pool->remotefail_occasions);
  10211. }
  10212. }
  10213. if (opt_quit_summary != BQS_NONE)
  10214. {
  10215. if (opt_quit_summary == BQS_DEFAULT)
  10216. {
  10217. if (total_devices < 25)
  10218. opt_quit_summary = BQS_PROCS;
  10219. else
  10220. opt_quit_summary = BQS_DEVS;
  10221. }
  10222. if (opt_quit_summary == BQS_DETAILED)
  10223. include_serial_in_statline = true;
  10224. applog(LOG_WARNING, "Summary of per device statistics:\n");
  10225. for (i = 0; i < total_devices; ++i) {
  10226. struct cgpu_info *cgpu = get_devices(i);
  10227. if (!cgpu->proc_id)
  10228. {
  10229. // Device summary line
  10230. opt_show_procs = false;
  10231. log_print_status(cgpu);
  10232. opt_show_procs = true;
  10233. }
  10234. if ((opt_quit_summary == BQS_PROCS || opt_quit_summary == BQS_DETAILED) && cgpu->procs > 1)
  10235. log_print_status(cgpu);
  10236. }
  10237. }
  10238. if (opt_shares) {
  10239. applog(LOG_WARNING, "Mined %g accepted shares of %g requested\n", total_diff_accepted, opt_shares);
  10240. if (opt_shares > total_diff_accepted)
  10241. applog(LOG_WARNING, "WARNING - Mined only %g shares of %g requested.", total_diff_accepted, opt_shares);
  10242. }
  10243. applog(LOG_WARNING, " ");
  10244. fflush(stderr);
  10245. fflush(stdout);
  10246. }
  10247. void _bfg_clean_up(bool restarting)
  10248. {
  10249. #ifdef USE_OPENCL
  10250. clear_adl(nDevs);
  10251. #endif
  10252. #ifdef HAVE_LIBUSB
  10253. if (likely(have_libusb))
  10254. libusb_exit(NULL);
  10255. #endif
  10256. cgtime(&total_tv_end);
  10257. #ifdef WIN32
  10258. timeEndPeriod(1);
  10259. #endif
  10260. if (!restarting) {
  10261. /* Attempting to disable curses or print a summary during a
  10262. * restart can lead to a deadlock. */
  10263. #ifdef HAVE_CURSES
  10264. disable_curses();
  10265. #endif
  10266. if (!opt_realquiet && successful_connect)
  10267. print_summary();
  10268. }
  10269. if (opt_n_threads > 0)
  10270. free(cpus);
  10271. curl_global_cleanup();
  10272. #ifdef WIN32
  10273. WSACleanup();
  10274. #endif
  10275. }
  10276. void _quit(int status)
  10277. {
  10278. if (status) {
  10279. const char *ev = getenv("__BFGMINER_SEGFAULT_ERRQUIT");
  10280. if (unlikely(ev && ev[0] && ev[0] != '0')) {
  10281. int *p = NULL;
  10282. // NOTE debugger can bypass with: p = &p
  10283. *p = status; // Segfault, hopefully dumping core
  10284. }
  10285. }
  10286. #if defined(unix) || defined(__APPLE__)
  10287. if (forkpid > 0) {
  10288. kill(forkpid, SIGTERM);
  10289. forkpid = 0;
  10290. }
  10291. #endif
  10292. exit(status);
  10293. }
  10294. #ifdef HAVE_CURSES
  10295. char *curses_input(const char *query)
  10296. {
  10297. char *input;
  10298. echo();
  10299. input = malloc(255);
  10300. if (!input)
  10301. quit(1, "Failed to malloc input");
  10302. leaveok(logwin, false);
  10303. wlogprint("%s:\n", query);
  10304. wgetnstr(logwin, input, 255);
  10305. if (!strlen(input))
  10306. {
  10307. free(input);
  10308. input = NULL;
  10309. }
  10310. leaveok(logwin, true);
  10311. noecho();
  10312. return input;
  10313. }
  10314. #endif
  10315. static void *test_pool_thread(void *arg)
  10316. {
  10317. struct pool *pool = (struct pool *)arg;
  10318. if (pool_active(pool, false)) {
  10319. pool_tset(pool, &pool->lagging);
  10320. pool_tclear(pool, &pool->idle);
  10321. bool first_pool = false;
  10322. cg_wlock(&control_lock);
  10323. if (!pools_active) {
  10324. currentpool = pool;
  10325. if (pool->pool_no != 0)
  10326. first_pool = true;
  10327. pools_active = true;
  10328. }
  10329. cg_wunlock(&control_lock);
  10330. if (unlikely(first_pool))
  10331. applog(LOG_NOTICE, "Switching to pool %d %s - first alive pool", pool->pool_no, pool->rpc_url);
  10332. else
  10333. applog(LOG_NOTICE, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  10334. switch_pools(NULL);
  10335. } else
  10336. pool_died(pool);
  10337. pool->testing = false;
  10338. return NULL;
  10339. }
  10340. /* Always returns true that the pool details were added unless we are not
  10341. * live, implying this is the only pool being added, so if no pools are
  10342. * active it returns false. */
  10343. bool add_pool_details(struct pool *pool, bool live, char *url, char *user, char *pass)
  10344. {
  10345. size_t siz;
  10346. pool_set_uri(pool, url);
  10347. pool->rpc_user = user;
  10348. pool->rpc_pass = pass;
  10349. siz = strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2;
  10350. pool->rpc_userpass = malloc(siz);
  10351. if (!pool->rpc_userpass)
  10352. quit(1, "Failed to malloc userpass");
  10353. snprintf(pool->rpc_userpass, siz, "%s:%s", pool->rpc_user, pool->rpc_pass);
  10354. pool->testing = true;
  10355. pool->idle = true;
  10356. enable_pool(pool);
  10357. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  10358. if (!live) {
  10359. pthread_join(pool->test_thread, NULL);
  10360. return pools_active;
  10361. }
  10362. return true;
  10363. }
  10364. #ifdef HAVE_CURSES
  10365. static bool input_pool(bool live)
  10366. {
  10367. char *url = NULL, *user = NULL, *pass = NULL;
  10368. struct pool *pool;
  10369. bool ret = false;
  10370. immedok(logwin, true);
  10371. wlogprint("Input server details.\n");
  10372. url = curses_input("URL");
  10373. if (!url)
  10374. goto out;
  10375. user = curses_input("Username");
  10376. if (!user)
  10377. goto out;
  10378. pass = curses_input("Password");
  10379. if (!pass)
  10380. pass = calloc(1, 1);
  10381. pool = add_pool();
  10382. if (!detect_stratum(pool, url) && strncmp(url, "http://", 7) &&
  10383. strncmp(url, "https://", 8)) {
  10384. char *httpinput;
  10385. httpinput = malloc(256);
  10386. if (!httpinput)
  10387. quit(1, "Failed to malloc httpinput");
  10388. strcpy(httpinput, "http://");
  10389. strncat(httpinput, url, 248);
  10390. free(url);
  10391. url = httpinput;
  10392. }
  10393. ret = add_pool_details(pool, live, url, user, pass);
  10394. out:
  10395. immedok(logwin, false);
  10396. if (!ret) {
  10397. if (url)
  10398. free(url);
  10399. if (user)
  10400. free(user);
  10401. if (pass)
  10402. free(pass);
  10403. }
  10404. return ret;
  10405. }
  10406. #endif
  10407. #if BLKMAKER_VERSION > 1 && defined(USE_SHA256D)
  10408. static
  10409. bool _add_local_gbt(const char * const filepath, void *userp)
  10410. {
  10411. const bool * const live_p = userp;
  10412. struct pool *pool;
  10413. char buf[0x100];
  10414. char *rpcuser = NULL, *rpcpass = NULL, *rpcconnect = NULL;
  10415. int rpcport = 0, rpcssl = -101;
  10416. FILE * const F = fopen(filepath, "r");
  10417. if (!F)
  10418. applogr(false, LOG_WARNING, "%s: Failed to open %s for reading", "add_local_gbt", filepath);
  10419. while (fgets(buf, sizeof(buf), F))
  10420. {
  10421. if (!strncasecmp(buf, "rpcuser=", 8))
  10422. rpcuser = trimmed_strdup(&buf[8]);
  10423. else
  10424. if (!strncasecmp(buf, "rpcpassword=", 12))
  10425. rpcpass = trimmed_strdup(&buf[12]);
  10426. else
  10427. if (!strncasecmp(buf, "rpcport=", 8))
  10428. rpcport = atoi(&buf[8]);
  10429. else
  10430. if (!strncasecmp(buf, "rpcssl=", 7))
  10431. rpcssl = atoi(&buf[7]);
  10432. else
  10433. if (!strncasecmp(buf, "rpcconnect=", 11))
  10434. rpcconnect = trimmed_strdup(&buf[11]);
  10435. else
  10436. continue;
  10437. if (rpcuser && rpcpass && rpcport && rpcssl != -101 && rpcconnect)
  10438. break;
  10439. }
  10440. fclose(F);
  10441. if (!rpcpass)
  10442. {
  10443. applog(LOG_DEBUG, "%s: Did not find rpcpassword in %s", "add_local_gbt", filepath);
  10444. err:
  10445. free(rpcuser);
  10446. free(rpcpass);
  10447. goto out;
  10448. }
  10449. if (!rpcport)
  10450. rpcport = 8332;
  10451. if (rpcssl == -101)
  10452. rpcssl = 0;
  10453. const bool have_cbaddr = get_mining_goal("default")->generation_script;
  10454. const int uri_sz = 0x30;
  10455. char * const uri = malloc(uri_sz);
  10456. snprintf(uri, uri_sz, "http%s://%s:%d/%s#allblocks", rpcssl ? "s" : "", rpcconnect ?: "localhost", rpcport, have_cbaddr ? "" : "#getcbaddr");
  10457. char hfuri[0x40];
  10458. if (rpcconnect)
  10459. snprintf(hfuri, sizeof(hfuri), "%s:%d", rpcconnect, rpcport);
  10460. else
  10461. snprintf(hfuri, sizeof(hfuri), "port %d", rpcport);
  10462. applog(LOG_DEBUG, "Local bitcoin RPC server on %s found in %s", hfuri, filepath);
  10463. for (int i = 0; i < total_pools; ++i)
  10464. {
  10465. struct pool *pool = pools[i];
  10466. if (!(strcmp(pool->rpc_url, uri) || strcmp(pool->rpc_pass, rpcpass)))
  10467. {
  10468. applog(LOG_DEBUG, "Server on %s is already configured, not adding as failover", hfuri);
  10469. free(uri);
  10470. goto err;
  10471. }
  10472. }
  10473. pool = add_pool();
  10474. if (!pool)
  10475. {
  10476. applog(LOG_ERR, "%s: Error adding pool for bitcoin configured in %s", "add_local_gbt", filepath);
  10477. goto err;
  10478. }
  10479. if (!rpcuser)
  10480. rpcuser = "";
  10481. pool->quota = 0;
  10482. adjust_quota_gcd();
  10483. pool->failover_only = true;
  10484. add_pool_details(pool, *live_p, uri, rpcuser, rpcpass);
  10485. applog(LOG_NOTICE, "Added local bitcoin RPC server on %s as pool %d", hfuri, pool->pool_no);
  10486. out:
  10487. return false;
  10488. }
  10489. static
  10490. void add_local_gbt(bool live)
  10491. {
  10492. appdata_file_call("Bitcoin", "bitcoin.conf", _add_local_gbt, &live);
  10493. }
  10494. #endif
  10495. #if defined(unix) || defined(__APPLE__)
  10496. static void fork_monitor()
  10497. {
  10498. // Make a pipe: [readFD, writeFD]
  10499. int pfd[2];
  10500. int r = pipe(pfd);
  10501. if (r < 0) {
  10502. perror("pipe - failed to create pipe for --monitor");
  10503. exit(1);
  10504. }
  10505. // Make stderr write end of pipe
  10506. fflush(stderr);
  10507. r = dup2(pfd[1], 2);
  10508. if (r < 0) {
  10509. perror("dup2 - failed to alias stderr to write end of pipe for --monitor");
  10510. exit(1);
  10511. }
  10512. r = close(pfd[1]);
  10513. if (r < 0) {
  10514. perror("close - failed to close write end of pipe for --monitor");
  10515. exit(1);
  10516. }
  10517. // Don't allow a dying monitor to kill the main process
  10518. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  10519. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  10520. if (SIG_ERR == sr0 || SIG_ERR == sr1) {
  10521. perror("signal - failed to edit signal mask for --monitor");
  10522. exit(1);
  10523. }
  10524. // Fork a child process
  10525. forkpid = fork();
  10526. if (forkpid < 0) {
  10527. perror("fork - failed to fork child process for --monitor");
  10528. exit(1);
  10529. }
  10530. // Child: launch monitor command
  10531. if (0 == forkpid) {
  10532. // Make stdin read end of pipe
  10533. r = dup2(pfd[0], 0);
  10534. if (r < 0) {
  10535. perror("dup2 - in child, failed to alias read end of pipe to stdin for --monitor");
  10536. exit(1);
  10537. }
  10538. close(pfd[0]);
  10539. if (r < 0) {
  10540. perror("close - in child, failed to close read end of pipe for --monitor");
  10541. exit(1);
  10542. }
  10543. // Launch user specified command
  10544. execl("/bin/bash", "/bin/bash", "-c", opt_stderr_cmd, (char*)NULL);
  10545. perror("execl - in child failed to exec user specified command for --monitor");
  10546. exit(1);
  10547. }
  10548. // Parent: clean up unused fds and bail
  10549. r = close(pfd[0]);
  10550. if (r < 0) {
  10551. perror("close - failed to close read end of pipe for --monitor");
  10552. exit(1);
  10553. }
  10554. }
  10555. #endif // defined(unix)
  10556. #ifdef HAVE_CURSES
  10557. #ifdef USE_UNICODE
  10558. static
  10559. wchar_t select_unicode_char(const wchar_t *opt)
  10560. {
  10561. for ( ; *opt; ++opt)
  10562. if (iswprint(*opt))
  10563. return *opt;
  10564. return '?';
  10565. }
  10566. #endif
  10567. void enable_curses(void) {
  10568. int x;
  10569. __maybe_unused int y;
  10570. lock_curses();
  10571. if (curses_active) {
  10572. unlock_curses();
  10573. return;
  10574. }
  10575. #ifdef USE_UNICODE
  10576. if (use_unicode)
  10577. {
  10578. setlocale(LC_CTYPE, "");
  10579. if (iswprint(0xb0))
  10580. have_unicode_degrees = true;
  10581. unicode_micro = select_unicode_char(L"\xb5\u03bcu");
  10582. }
  10583. #endif
  10584. mainwin = initscr();
  10585. start_color();
  10586. #if defined(PDCURSES) || defined(NCURSES_VERSION)
  10587. if (ERR != use_default_colors())
  10588. default_bgcolor = -1;
  10589. #endif
  10590. if (has_colors() && ERR != init_pair(1, COLOR_WHITE, COLOR_BLUE))
  10591. {
  10592. menu_attr = COLOR_PAIR(1);
  10593. if (ERR != init_pair(2, COLOR_RED, default_bgcolor))
  10594. attr_bad |= COLOR_PAIR(2);
  10595. }
  10596. keypad(mainwin, true);
  10597. getmaxyx(mainwin, y, x);
  10598. statuswin = newwin(logstart, x, 0, 0);
  10599. leaveok(statuswin, true);
  10600. // For whatever reason, PDCurses crashes if the logwin is initialized to height y-logcursor
  10601. // We resize the window later anyway, so just start it off at 1 :)
  10602. logwin = newwin(1, 0, logcursor, 0);
  10603. idlok(logwin, true);
  10604. scrollok(logwin, true);
  10605. leaveok(logwin, true);
  10606. cbreak();
  10607. noecho();
  10608. nonl();
  10609. curses_active = true;
  10610. statusy = logstart;
  10611. unlock_curses();
  10612. }
  10613. #endif
  10614. /* TODO: fix need a dummy CPU device_drv even if no support for CPU mining */
  10615. #ifndef USE_CPUMINING
  10616. struct device_drv cpu_drv;
  10617. struct device_drv cpu_drv = {
  10618. .name = "CPU",
  10619. };
  10620. #endif
  10621. static int cgminer_id_count = 0;
  10622. static int device_line_id_count;
  10623. void register_device(struct cgpu_info *cgpu)
  10624. {
  10625. cgpu->deven = DEV_ENABLED;
  10626. wr_lock(&devices_lock);
  10627. devices[cgpu->cgminer_id = cgminer_id_count++] = cgpu;
  10628. wr_unlock(&devices_lock);
  10629. if (!cgpu->proc_id)
  10630. cgpu->device_line_id = device_line_id_count++;
  10631. int thr_objs = cgpu->threads ?: 1;
  10632. mining_threads += thr_objs;
  10633. base_queue += thr_objs + cgpu->extra_work_queue;
  10634. {
  10635. const struct device_drv * const drv = cgpu->drv;
  10636. struct mining_algorithm *malgo;
  10637. LL_FOREACH(mining_algorithms, malgo)
  10638. {
  10639. if (drv_min_nonce_diff(drv, cgpu, malgo) < 0)
  10640. continue;
  10641. malgo->base_queue += thr_objs + cgpu->extra_work_queue;
  10642. }
  10643. }
  10644. #ifdef HAVE_CURSES
  10645. adj_width(mining_threads, &dev_width);
  10646. #endif
  10647. rwlock_init(&cgpu->qlock);
  10648. cgpu->queued_work = NULL;
  10649. }
  10650. struct _cgpu_devid_counter {
  10651. char name[4];
  10652. int lastid;
  10653. UT_hash_handle hh;
  10654. };
  10655. void renumber_cgpu(struct cgpu_info *cgpu)
  10656. {
  10657. static struct _cgpu_devid_counter *devids = NULL;
  10658. struct _cgpu_devid_counter *d;
  10659. HASH_FIND_STR(devids, cgpu->drv->name, d);
  10660. if (d)
  10661. cgpu->device_id = ++d->lastid;
  10662. else {
  10663. d = malloc(sizeof(*d));
  10664. memcpy(d->name, cgpu->drv->name, sizeof(d->name));
  10665. cgpu->device_id = d->lastid = 0;
  10666. HASH_ADD_STR(devids, name, d);
  10667. }
  10668. // Build repr strings
  10669. sprintf(cgpu->dev_repr, "%s%2u", cgpu->drv->name, cgpu->device_id % 100);
  10670. sprintf(cgpu->dev_repr_ns, "%s%u", cgpu->drv->name, cgpu->device_id % 100);
  10671. strcpy(cgpu->proc_repr, cgpu->dev_repr);
  10672. sprintf(cgpu->proc_repr_ns, "%s%u", cgpu->drv->name, cgpu->device_id);
  10673. const int lpcount = cgpu->procs;
  10674. if (lpcount > 1)
  10675. {
  10676. int ns;
  10677. struct cgpu_info *slave;
  10678. int lpdigits = 1;
  10679. for (int i = lpcount; i > 26 && lpdigits < 3; i /= 26)
  10680. ++lpdigits;
  10681. if (lpdigits > max_lpdigits)
  10682. max_lpdigits = lpdigits;
  10683. memset(&cgpu->proc_repr[5], 'a', lpdigits);
  10684. cgpu->proc_repr[5 + lpdigits] = '\0';
  10685. ns = strlen(cgpu->proc_repr_ns);
  10686. strcpy(&cgpu->proc_repr_ns[ns], &cgpu->proc_repr[5]);
  10687. slave = cgpu;
  10688. for (int i = 1; i < lpcount; ++i)
  10689. {
  10690. slave = slave->next_proc;
  10691. strcpy(slave->proc_repr, cgpu->proc_repr);
  10692. strcpy(slave->proc_repr_ns, cgpu->proc_repr_ns);
  10693. for (int x = i, y = lpdigits; --y, x; x /= 26)
  10694. {
  10695. slave->proc_repr_ns[ns + y] =
  10696. slave->proc_repr[5 + y] += (x % 26);
  10697. }
  10698. }
  10699. }
  10700. }
  10701. static bool my_blkmaker_sha256_callback(void *digest, const void *buffer, size_t length)
  10702. {
  10703. sha256(buffer, length, digest);
  10704. return true;
  10705. }
  10706. static
  10707. bool drv_algo_check(const struct device_drv * const drv)
  10708. {
  10709. struct mining_goal_info *goal, *tmpgoal;
  10710. HASH_ITER(hh, mining_goals, goal, tmpgoal)
  10711. {
  10712. if (drv_min_nonce_diff(drv, NULL, goal->malgo) >= 0)
  10713. return true;
  10714. }
  10715. return false;
  10716. }
  10717. #ifndef HAVE_PTHREAD_CANCEL
  10718. extern void setup_pthread_cancel_workaround();
  10719. extern struct sigaction pcwm_orig_term_handler;
  10720. #endif
  10721. bool bfg_need_detect_rescan;
  10722. extern void probe_device(struct lowlevel_device_info *);
  10723. static void schedule_rescan(const struct timeval *);
  10724. static
  10725. void drv_detect_all()
  10726. {
  10727. bool rescanning = false;
  10728. rescan:
  10729. bfg_need_detect_rescan = false;
  10730. #ifdef HAVE_BFG_LOWLEVEL
  10731. struct lowlevel_device_info * const infolist = lowlevel_scan(), *info, *infotmp;
  10732. LL_FOREACH_SAFE(infolist, info, infotmp)
  10733. probe_device(info);
  10734. LL_FOREACH_SAFE(infolist, info, infotmp)
  10735. pthread_join(info->probe_pth, NULL);
  10736. #endif
  10737. struct driver_registration *reg, *tmp;
  10738. BFG_FOREACH_DRIVER_BY_PRIORITY(reg, tmp)
  10739. {
  10740. const struct device_drv * const drv = reg->drv;
  10741. if (!(drv_algo_check(drv) && drv->drv_detect))
  10742. continue;
  10743. drv->drv_detect();
  10744. }
  10745. #ifdef HAVE_BFG_LOWLEVEL
  10746. lowlevel_scan_free();
  10747. #endif
  10748. if (bfg_need_detect_rescan)
  10749. {
  10750. if (rescanning)
  10751. {
  10752. applog(LOG_DEBUG, "Device rescan requested a second time, delaying");
  10753. struct timeval tv_when;
  10754. timer_set_delay_from_now(&tv_when, rescan_delay_ms * 1000);
  10755. schedule_rescan(&tv_when);
  10756. }
  10757. else
  10758. {
  10759. rescanning = true;
  10760. applog(LOG_DEBUG, "Device rescan requested");
  10761. goto rescan;
  10762. }
  10763. }
  10764. }
  10765. static
  10766. void allocate_cgpu(struct cgpu_info *cgpu, unsigned int *kp)
  10767. {
  10768. struct thr_info *thr;
  10769. int j;
  10770. struct device_drv *api = cgpu->drv;
  10771. cgpu->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  10772. int threadobj = cgpu->threads;
  10773. if (!threadobj)
  10774. // Create a fake thread object to handle hashmeter etc
  10775. threadobj = 1;
  10776. cgpu->thr = calloc(threadobj + 1, sizeof(*cgpu->thr));
  10777. cgpu->thr[threadobj] = NULL;
  10778. cgpu->status = LIFE_INIT;
  10779. if (opt_devices_enabled_list)
  10780. {
  10781. struct string_elist *enablestr_elist;
  10782. cgpu->deven = DEV_DISABLED;
  10783. DL_FOREACH(opt_devices_enabled_list, enablestr_elist)
  10784. {
  10785. const char * const enablestr = enablestr_elist->string;
  10786. if (cgpu_match(enablestr, cgpu))
  10787. {
  10788. cgpu->deven = DEV_ENABLED;
  10789. break;
  10790. }
  10791. }
  10792. }
  10793. cgpu->max_hashes = 0;
  10794. BFGINIT(cgpu->cutofftemp, opt_cutofftemp);
  10795. BFGINIT(cgpu->targettemp, cgpu->cutofftemp - 6);
  10796. // Setup thread structs before starting any of the threads, in case they try to interact
  10797. for (j = 0; j < threadobj; ++j, ++*kp) {
  10798. thr = get_thread(*kp);
  10799. thr->id = *kp;
  10800. thr->cgpu = cgpu;
  10801. thr->device_thread = j;
  10802. thr->work_restart_notifier[1] = INVSOCK;
  10803. thr->mutex_request[1] = INVSOCK;
  10804. thr->_job_transition_in_progress = true;
  10805. timerclear(&thr->tv_morework);
  10806. thr->scanhash_working = true;
  10807. thr->hashes_done = 0;
  10808. timerclear(&thr->tv_hashes_done);
  10809. cgtime(&thr->tv_lastupdate);
  10810. thr->tv_poll.tv_sec = -1;
  10811. thr->_max_nonce = api->can_limit_work ? api->can_limit_work(thr) : 0xffffffff;
  10812. cgpu->thr[j] = thr;
  10813. }
  10814. if (!cgpu->device->threads)
  10815. notifier_init_invalid(cgpu->thr[0]->notifier);
  10816. else
  10817. if (!cgpu->threads)
  10818. memcpy(&cgpu->thr[0]->notifier, &cgpu->device->thr[0]->notifier, sizeof(cgpu->thr[0]->notifier));
  10819. else
  10820. for (j = 0; j < cgpu->threads; ++j)
  10821. {
  10822. thr = cgpu->thr[j];
  10823. notifier_init(thr->notifier);
  10824. }
  10825. }
  10826. static
  10827. void start_cgpu(struct cgpu_info *cgpu)
  10828. {
  10829. struct thr_info *thr;
  10830. int j;
  10831. for (j = 0; j < cgpu->threads; ++j) {
  10832. thr = cgpu->thr[j];
  10833. /* Enable threads for devices set not to mine but disable
  10834. * their queue in case we wish to enable them later */
  10835. if (cgpu->drv->thread_prepare && !cgpu->drv->thread_prepare(thr))
  10836. continue;
  10837. thread_reportout(thr);
  10838. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  10839. quit(1, "thread %d create failed", thr->id);
  10840. notifier_wake(thr->notifier);
  10841. }
  10842. if (cgpu->deven == DEV_ENABLED)
  10843. proc_enable(cgpu);
  10844. }
  10845. static
  10846. void _scan_serial(void *p)
  10847. {
  10848. const char *s = p;
  10849. struct string_elist *iter, *tmp;
  10850. struct string_elist *orig_scan_devices = scan_devices;
  10851. if (s)
  10852. {
  10853. // Make temporary scan_devices list
  10854. scan_devices = NULL;
  10855. string_elist_add("noauto", &scan_devices);
  10856. add_serial(s);
  10857. }
  10858. drv_detect_all();
  10859. if (s)
  10860. {
  10861. DL_FOREACH_SAFE(scan_devices, iter, tmp)
  10862. {
  10863. string_elist_del(&scan_devices, iter);
  10864. }
  10865. scan_devices = orig_scan_devices;
  10866. }
  10867. }
  10868. #ifdef HAVE_BFG_LOWLEVEL
  10869. static
  10870. bool _probe_device_match(const struct lowlevel_device_info * const info, const char * const ser)
  10871. {
  10872. if (!(false
  10873. || (info->serial && !strcasecmp(ser, info->serial))
  10874. || (info->path && !strcasecmp(ser, info->path ))
  10875. || (info->devid && !strcasecmp(ser, info->devid ))
  10876. ))
  10877. {
  10878. char *devid = devpath_to_devid(ser);
  10879. if (!devid)
  10880. return false;
  10881. const bool different = strcmp(info->devid, devid);
  10882. free(devid);
  10883. if (different)
  10884. return false;
  10885. }
  10886. return true;
  10887. }
  10888. static
  10889. const struct device_drv *_probe_device_find_drv(const char * const _dname, const size_t dnamelen)
  10890. {
  10891. struct driver_registration *dreg;
  10892. char dname[dnamelen];
  10893. int i;
  10894. for (i = 0; i < dnamelen; ++i)
  10895. dname[i] = tolower(_dname[i]);
  10896. BFG_FIND_DRV_BY_DNAME(dreg, dname, dnamelen);
  10897. if (!dreg)
  10898. {
  10899. for (i = 0; i < dnamelen; ++i)
  10900. dname[i] = toupper(_dname[i]);
  10901. BFG_FIND_DRV_BY_NAME(dreg, dname, dnamelen);
  10902. if (!dreg)
  10903. return NULL;
  10904. }
  10905. if (!drv_algo_check(dreg->drv))
  10906. return NULL;
  10907. return dreg->drv;
  10908. }
  10909. static
  10910. bool _probe_device_do_probe(const struct device_drv * const drv, const struct lowlevel_device_info * const info, bool * const request_rescan_p)
  10911. {
  10912. bfg_probe_result_flags = 0;
  10913. if (drv->lowl_probe(info))
  10914. {
  10915. if (!(bfg_probe_result_flags & BPR_CONTINUE_PROBES))
  10916. return true;
  10917. }
  10918. else
  10919. if (request_rescan_p && opt_hotplug && !(bfg_probe_result_flags & BPR_DONT_RESCAN))
  10920. *request_rescan_p = true;
  10921. return false;
  10922. }
  10923. bool dummy_check_never_true = false;
  10924. static
  10925. void *probe_device_thread(void *p)
  10926. {
  10927. struct lowlevel_device_info * const infolist = p;
  10928. struct lowlevel_device_info *info = infolist;
  10929. bool request_rescan = false;
  10930. {
  10931. char threadname[5 + strlen(info->devid) + 1];
  10932. sprintf(threadname, "probe_%s", info->devid);
  10933. RenameThread(threadname);
  10934. }
  10935. // If already in use, ignore
  10936. if (bfg_claim_any(NULL, NULL, info->devid))
  10937. applogr(NULL, LOG_DEBUG, "%s: \"%s\" already in use",
  10938. __func__, info->product);
  10939. // if lowlevel device matches specific user assignment, probe requested driver(s)
  10940. struct string_elist *sd_iter, *sd_tmp;
  10941. struct driver_registration *dreg, *dreg_tmp;
  10942. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  10943. {
  10944. const char * const dname = sd_iter->string;
  10945. const char * const colon = strpbrk(dname, ":@");
  10946. if (!(colon && colon != dname))
  10947. continue;
  10948. const char * const ser = &colon[1];
  10949. LL_FOREACH2(infolist, info, same_devid_next)
  10950. {
  10951. if (!_probe_device_match(info, ser))
  10952. continue;
  10953. const size_t dnamelen = (colon - dname);
  10954. const struct device_drv * const drv = _probe_device_find_drv(dname, dnamelen);
  10955. if (!(drv && drv->lowl_probe && drv_algo_check(drv)))
  10956. continue;
  10957. if (_probe_device_do_probe(drv, info, &request_rescan))
  10958. return NULL;
  10959. }
  10960. }
  10961. // probe driver(s) with auto enabled and matching VID/PID/Product/etc of device
  10962. BFG_FOREACH_DRIVER_BY_PRIORITY(dreg, dreg_tmp)
  10963. {
  10964. const struct device_drv * const drv = dreg->drv;
  10965. if (!drv_algo_check(drv))
  10966. continue;
  10967. // Check for "noauto" flag
  10968. // NOTE: driver-specific configuration overrides general
  10969. bool doauto = true;
  10970. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  10971. {
  10972. const char * const dname = sd_iter->string;
  10973. // NOTE: Only checking flags here, NOT path/serial, so @ is unacceptable
  10974. const char *colon = strchr(dname, ':');
  10975. if (!colon)
  10976. colon = &dname[-1];
  10977. if (strcasecmp("noauto", &colon[1]) && strcasecmp("auto", &colon[1]))
  10978. continue;
  10979. const ssize_t dnamelen = (colon - dname);
  10980. if (dnamelen >= 0 && _probe_device_find_drv(dname, dnamelen) != drv)
  10981. continue;
  10982. doauto = (tolower(colon[1]) == 'a');
  10983. if (dnamelen != -1)
  10984. break;
  10985. }
  10986. if (doauto && drv->lowl_match)
  10987. {
  10988. LL_FOREACH2(infolist, info, same_devid_next)
  10989. {
  10990. /*
  10991. The below call to applog is absolutely necessary
  10992. Starting with commit 76d0cc183b1c9ddcc0ef34d2e43bc696ef9de92e installing BFGMiner on
  10993. Mac OS X using Homebrew results in a binary that segfaults on startup
  10994. There are two unresolved issues:
  10995. 1) The BFGMiner authors cannot find a way to install BFGMiner with Homebrew that results
  10996. in debug symbols being available to help troubleshoot the issue
  10997. 2) The issue disappears when unrelated code changes are made, such as adding the following
  10998. call to applog with infolist and / or p
  10999. We would encourage revisiting this in the future to come up with a more concrete solution
  11000. Reproducing should only require commenting / removing the following line and installing
  11001. BFGMiner using "brew install bfgminer --HEAD"
  11002. */
  11003. if (dummy_check_never_true)
  11004. applog(LOG_DEBUG, "lowl_match: %p(%s) %p %p %p", drv, drv->dname, info, infolist, p);
  11005. if (!drv->lowl_match(info))
  11006. continue;
  11007. if (_probe_device_do_probe(drv, info, &request_rescan))
  11008. return NULL;
  11009. }
  11010. }
  11011. }
  11012. // probe driver(s) with 'all' enabled
  11013. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  11014. {
  11015. const char * const dname = sd_iter->string;
  11016. // NOTE: Only checking flags here, NOT path/serial, so @ is unacceptable
  11017. const char * const colon = strchr(dname, ':');
  11018. if (!colon)
  11019. {
  11020. LL_FOREACH2(infolist, info, same_devid_next)
  11021. {
  11022. if (
  11023. #ifdef NEED_BFG_LOWL_VCOM
  11024. (info->lowl == &lowl_vcom && !strcasecmp(dname, "all")) ||
  11025. #endif
  11026. _probe_device_match(info, (dname[0] == '@') ? &dname[1] : dname))
  11027. {
  11028. bool dont_rescan = false;
  11029. BFG_FOREACH_DRIVER_BY_PRIORITY(dreg, dreg_tmp)
  11030. {
  11031. const struct device_drv * const drv = dreg->drv;
  11032. if (!drv_algo_check(drv))
  11033. continue;
  11034. if (drv->lowl_probe_by_name_only)
  11035. continue;
  11036. if (!drv->lowl_probe)
  11037. continue;
  11038. if (_probe_device_do_probe(drv, info, NULL))
  11039. return NULL;
  11040. if (bfg_probe_result_flags & BPR_DONT_RESCAN)
  11041. dont_rescan = true;
  11042. }
  11043. if (opt_hotplug && !dont_rescan)
  11044. request_rescan = true;
  11045. break;
  11046. }
  11047. }
  11048. continue;
  11049. }
  11050. if (strcasecmp(&colon[1], "all"))
  11051. continue;
  11052. const size_t dnamelen = (colon - dname);
  11053. const struct device_drv * const drv = _probe_device_find_drv(dname, dnamelen);
  11054. if (!(drv && drv->lowl_probe && drv_algo_check(drv)))
  11055. continue;
  11056. LL_FOREACH2(infolist, info, same_devid_next)
  11057. {
  11058. if (info->lowl->exclude_from_all)
  11059. continue;
  11060. if (_probe_device_do_probe(drv, info, NULL))
  11061. return NULL;
  11062. }
  11063. }
  11064. // Only actually request a rescan if we never found any cgpu
  11065. if (request_rescan)
  11066. bfg_need_detect_rescan = true;
  11067. return NULL;
  11068. }
  11069. void probe_device(struct lowlevel_device_info * const info)
  11070. {
  11071. pthread_create(&info->probe_pth, NULL, probe_device_thread, info);
  11072. }
  11073. #endif
  11074. int create_new_cgpus(void (*addfunc)(void*), void *arg)
  11075. {
  11076. static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  11077. int devcount, i, mining_threads_new = 0;
  11078. unsigned int k;
  11079. struct cgpu_info *cgpu;
  11080. struct thr_info *thr;
  11081. void *p;
  11082. mutex_lock(&mutex);
  11083. devcount = total_devices;
  11084. addfunc(arg);
  11085. if (!total_devices_new)
  11086. goto out;
  11087. wr_lock(&devices_lock);
  11088. p = realloc(devices, sizeof(struct cgpu_info *) * (total_devices + total_devices_new + 1));
  11089. if (unlikely(!p))
  11090. {
  11091. wr_unlock(&devices_lock);
  11092. applog(LOG_ERR, "scan_serial: realloc failed trying to grow devices array");
  11093. goto out;
  11094. }
  11095. devices = p;
  11096. wr_unlock(&devices_lock);
  11097. for (i = 0; i < total_devices_new; ++i)
  11098. {
  11099. cgpu = devices_new[i];
  11100. mining_threads_new += cgpu->threads ?: 1;
  11101. }
  11102. wr_lock(&mining_thr_lock);
  11103. mining_threads_new += mining_threads;
  11104. p = realloc(mining_thr, sizeof(struct thr_info *) * mining_threads_new);
  11105. if (unlikely(!p))
  11106. {
  11107. wr_unlock(&mining_thr_lock);
  11108. applog(LOG_ERR, "scan_serial: realloc failed trying to grow mining_thr");
  11109. goto out;
  11110. }
  11111. mining_thr = p;
  11112. wr_unlock(&mining_thr_lock);
  11113. for (i = mining_threads; i < mining_threads_new; ++i) {
  11114. mining_thr[i] = calloc(1, sizeof(*thr));
  11115. if (!mining_thr[i])
  11116. {
  11117. applog(LOG_ERR, "scan_serial: Failed to calloc mining_thr[%d]", i);
  11118. for ( ; --i >= mining_threads; )
  11119. free(mining_thr[i]);
  11120. goto out;
  11121. }
  11122. }
  11123. k = mining_threads;
  11124. for (i = 0; i < total_devices_new; ++i)
  11125. {
  11126. cgpu = devices_new[i];
  11127. allocate_cgpu(cgpu, &k);
  11128. }
  11129. for (i = 0; i < total_devices_new; ++i)
  11130. {
  11131. cgpu = devices_new[i];
  11132. start_cgpu(cgpu);
  11133. register_device(cgpu);
  11134. ++total_devices;
  11135. }
  11136. #ifdef HAVE_CURSES
  11137. switch_logsize();
  11138. #endif
  11139. out:
  11140. total_devices_new = 0;
  11141. devcount = total_devices - devcount;
  11142. mutex_unlock(&mutex);
  11143. return devcount;
  11144. }
  11145. int scan_serial(const char *s)
  11146. {
  11147. return create_new_cgpus(_scan_serial, (void*)s);
  11148. }
  11149. static pthread_mutex_t rescan_mutex = PTHREAD_MUTEX_INITIALIZER;
  11150. static bool rescan_active;
  11151. static struct timeval tv_rescan;
  11152. static notifier_t rescan_notifier;
  11153. static
  11154. void *rescan_thread(__maybe_unused void *p)
  11155. {
  11156. pthread_detach(pthread_self());
  11157. RenameThread("rescan");
  11158. struct timeval tv_timeout, tv_now;
  11159. fd_set rfds;
  11160. while (true)
  11161. {
  11162. mutex_lock(&rescan_mutex);
  11163. tv_timeout = tv_rescan;
  11164. if (!timer_isset(&tv_timeout))
  11165. {
  11166. rescan_active = false;
  11167. mutex_unlock(&rescan_mutex);
  11168. break;
  11169. }
  11170. mutex_unlock(&rescan_mutex);
  11171. FD_ZERO(&rfds);
  11172. FD_SET(rescan_notifier[0], &rfds);
  11173. const int maxfd = rescan_notifier[0];
  11174. timer_set_now(&tv_now);
  11175. if (select(maxfd+1, &rfds, NULL, NULL, select_timeout(&tv_timeout, &tv_now)) > 0)
  11176. notifier_read(rescan_notifier);
  11177. mutex_lock(&rescan_mutex);
  11178. if (timer_passed(&tv_rescan, NULL))
  11179. {
  11180. timer_unset(&tv_rescan);
  11181. mutex_unlock(&rescan_mutex);
  11182. applog(LOG_DEBUG, "Rescan timer expired, triggering");
  11183. scan_serial(NULL);
  11184. }
  11185. else
  11186. mutex_unlock(&rescan_mutex);
  11187. }
  11188. return NULL;
  11189. }
  11190. static
  11191. void _schedule_rescan(const struct timeval * const tvp_when)
  11192. {
  11193. if (rescan_active)
  11194. {
  11195. if (timercmp(tvp_when, &tv_rescan, <))
  11196. applog(LOG_DEBUG, "schedule_rescan: New schedule is before current, waiting it out");
  11197. else
  11198. {
  11199. applog(LOG_DEBUG, "schedule_rescan: New schedule is after current, delaying rescan");
  11200. tv_rescan = *tvp_when;
  11201. }
  11202. return;
  11203. }
  11204. applog(LOG_DEBUG, "schedule_rescan: Scheduling rescan (no rescans currently pending)");
  11205. tv_rescan = *tvp_when;
  11206. rescan_active = true;
  11207. static pthread_t pth;
  11208. if (unlikely(pthread_create(&pth, NULL, rescan_thread, NULL)))
  11209. applog(LOG_ERR, "Failed to start rescan thread");
  11210. }
  11211. static
  11212. void schedule_rescan(const struct timeval * const tvp_when)
  11213. {
  11214. mutex_lock(&rescan_mutex);
  11215. _schedule_rescan(tvp_when);
  11216. mutex_unlock(&rescan_mutex);
  11217. }
  11218. static
  11219. void hotplug_trigger()
  11220. {
  11221. applog(LOG_DEBUG, "%s: Scheduling rescan immediately", __func__);
  11222. struct timeval tv_now;
  11223. timer_set_now(&tv_now);
  11224. schedule_rescan(&tv_now);
  11225. }
  11226. #if defined(HAVE_LIBUDEV) && defined(HAVE_SYS_EPOLL_H)
  11227. static
  11228. void *hotplug_thread(__maybe_unused void *p)
  11229. {
  11230. pthread_detach(pthread_self());
  11231. RenameThread("hotplug");
  11232. struct udev * const udev = udev_new();
  11233. if (unlikely(!udev))
  11234. applogfailr(NULL, LOG_ERR, "udev_new");
  11235. struct udev_monitor * const mon = udev_monitor_new_from_netlink(udev, "udev");
  11236. if (unlikely(!mon))
  11237. applogfailr(NULL, LOG_ERR, "udev_monitor_new_from_netlink");
  11238. if (unlikely(udev_monitor_enable_receiving(mon)))
  11239. applogfailr(NULL, LOG_ERR, "udev_monitor_enable_receiving");
  11240. const int epfd = epoll_create(1);
  11241. if (unlikely(epfd == -1))
  11242. applogfailr(NULL, LOG_ERR, "epoll_create");
  11243. {
  11244. const int fd = udev_monitor_get_fd(mon);
  11245. struct epoll_event ev = {
  11246. .events = EPOLLIN | EPOLLPRI,
  11247. .data.fd = fd,
  11248. };
  11249. if (epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev))
  11250. applogfailr(NULL, LOG_ERR, "epoll_ctl");
  11251. }
  11252. struct epoll_event ev;
  11253. int rv;
  11254. bool pending = false;
  11255. while (true)
  11256. {
  11257. rv = epoll_wait(epfd, &ev, 1, pending ? hotplug_delay_ms : -1);
  11258. if (rv == -1)
  11259. {
  11260. if (errno == EAGAIN || errno == EINTR)
  11261. continue;
  11262. break;
  11263. }
  11264. if (!rv)
  11265. {
  11266. hotplug_trigger();
  11267. pending = false;
  11268. continue;
  11269. }
  11270. struct udev_device * const device = udev_monitor_receive_device(mon);
  11271. if (!device)
  11272. continue;
  11273. const char * const action = udev_device_get_action(device);
  11274. applog(LOG_DEBUG, "%s: Received %s event", __func__, action);
  11275. if (!strcmp(action, "add"))
  11276. pending = true;
  11277. udev_device_unref(device);
  11278. }
  11279. applogfailr(NULL, LOG_ERR, "epoll_wait");
  11280. }
  11281. #elif defined(WIN32)
  11282. static UINT_PTR _hotplug_wintimer_id;
  11283. VOID CALLBACK hotplug_win_timer(HWND hwnd, UINT msg, UINT_PTR idEvent, DWORD dwTime)
  11284. {
  11285. KillTimer(NULL, _hotplug_wintimer_id);
  11286. _hotplug_wintimer_id = 0;
  11287. hotplug_trigger();
  11288. }
  11289. LRESULT CALLBACK hotplug_win_callback(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
  11290. {
  11291. if (msg == WM_DEVICECHANGE && wParam == DBT_DEVNODES_CHANGED)
  11292. {
  11293. applog(LOG_DEBUG, "%s: Received DBT_DEVNODES_CHANGED event", __func__);
  11294. _hotplug_wintimer_id = SetTimer(NULL, _hotplug_wintimer_id, hotplug_delay_ms, hotplug_win_timer);
  11295. }
  11296. return DefWindowProc(hwnd, msg, wParam, lParam);
  11297. }
  11298. static
  11299. void *hotplug_thread(__maybe_unused void *p)
  11300. {
  11301. pthread_detach(pthread_self());
  11302. WNDCLASS DummyWinCls = {
  11303. .lpszClassName = "BFGDummyWinCls",
  11304. .lpfnWndProc = hotplug_win_callback,
  11305. };
  11306. ATOM a = RegisterClass(&DummyWinCls);
  11307. if (unlikely(!a))
  11308. applogfailinfor(NULL, LOG_ERR, "RegisterClass", "%d", (int)GetLastError());
  11309. HWND hwnd = CreateWindow((void*)(intptr_t)a, NULL, WS_OVERLAPPED, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, NULL, NULL);
  11310. if (unlikely(!hwnd))
  11311. applogfailinfor(NULL, LOG_ERR, "CreateWindow", "%d", (int)GetLastError());
  11312. MSG msg;
  11313. while (GetMessage(&msg, NULL, 0, 0))
  11314. {
  11315. TranslateMessage(&msg);
  11316. DispatchMessage(&msg);
  11317. }
  11318. quit(0, "WM_QUIT received");
  11319. return NULL;
  11320. }
  11321. #endif
  11322. #ifdef HAVE_BFG_HOTPLUG
  11323. static
  11324. void hotplug_start()
  11325. {
  11326. pthread_t pth;
  11327. if (unlikely(pthread_create(&pth, NULL, hotplug_thread, NULL)))
  11328. applog(LOG_ERR, "Failed to start hotplug thread");
  11329. }
  11330. #endif
  11331. static void probe_pools(void)
  11332. {
  11333. int i;
  11334. for (i = 0; i < total_pools; i++) {
  11335. struct pool *pool = pools[i];
  11336. pool->testing = true;
  11337. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  11338. }
  11339. }
  11340. static void raise_fd_limits(void)
  11341. {
  11342. #ifdef HAVE_SETRLIMIT
  11343. struct rlimit fdlimit;
  11344. rlim_t old_soft_limit;
  11345. char frombuf[0x10] = "unlimited";
  11346. char hardbuf[0x10] = "unlimited";
  11347. if (getrlimit(RLIMIT_NOFILE, &fdlimit))
  11348. applogr(, LOG_DEBUG, "setrlimit: Failed to getrlimit(RLIMIT_NOFILE)");
  11349. old_soft_limit = fdlimit.rlim_cur;
  11350. if (fdlimit.rlim_max > FD_SETSIZE || fdlimit.rlim_max == RLIM_INFINITY)
  11351. fdlimit.rlim_cur = FD_SETSIZE;
  11352. else
  11353. fdlimit.rlim_cur = fdlimit.rlim_max;
  11354. if (fdlimit.rlim_max != RLIM_INFINITY)
  11355. snprintf(hardbuf, sizeof(hardbuf), "%lu", (unsigned long)fdlimit.rlim_max);
  11356. if (old_soft_limit != RLIM_INFINITY)
  11357. snprintf(frombuf, sizeof(frombuf), "%lu", (unsigned long)old_soft_limit);
  11358. if (fdlimit.rlim_cur == old_soft_limit)
  11359. applogr(, LOG_DEBUG, "setrlimit: Soft fd limit not being changed from %lu (FD_SETSIZE=%lu; hard limit=%s)",
  11360. (unsigned long)old_soft_limit, (unsigned long)FD_SETSIZE, hardbuf);
  11361. if (setrlimit(RLIMIT_NOFILE, &fdlimit))
  11362. applogr(, LOG_DEBUG, "setrlimit: Failed to change soft fd limit from %s to %lu (FD_SETSIZE=%lu; hard limit=%s)",
  11363. frombuf, (unsigned long)fdlimit.rlim_cur, (unsigned long)FD_SETSIZE, hardbuf);
  11364. applog(LOG_DEBUG, "setrlimit: Changed soft fd limit from %s to %lu (FD_SETSIZE=%lu; hard limit=%s)",
  11365. frombuf, (unsigned long)fdlimit.rlim_cur, (unsigned long)FD_SETSIZE, hardbuf);
  11366. #else
  11367. applog(LOG_DEBUG, "setrlimit: Not supported by platform");
  11368. #endif
  11369. }
  11370. static
  11371. void bfg_atexit(void)
  11372. {
  11373. puts("");
  11374. }
  11375. extern void bfg_init_threadlocal();
  11376. extern void stratumsrv_start();
  11377. extern void test_aan_pll(void);
  11378. int main(int argc, char *argv[])
  11379. {
  11380. struct sigaction handler;
  11381. struct thr_info *thr;
  11382. unsigned int k;
  11383. int i;
  11384. int rearrange_pools = 0;
  11385. char *s;
  11386. #ifdef WIN32
  11387. LoadLibrary("backtrace.dll");
  11388. #endif
  11389. atexit(bfg_atexit);
  11390. b58_sha256_impl = my_blkmaker_sha256_callback;
  11391. blkmk_sha256_impl = my_blkmaker_sha256_callback;
  11392. bfg_init_threadlocal();
  11393. #ifndef HAVE_PTHREAD_CANCEL
  11394. setup_pthread_cancel_workaround();
  11395. #endif
  11396. bfg_init_checksums();
  11397. #ifdef WIN32
  11398. {
  11399. WSADATA wsa;
  11400. i = WSAStartup(MAKEWORD(2, 2), &wsa);
  11401. if (i)
  11402. quit(1, "Failed to initialise Winsock: %s", bfg_strerror(i, BST_SOCKET));
  11403. }
  11404. #endif
  11405. /* This dangerous functions tramples random dynamically allocated
  11406. * variables so do it before anything at all */
  11407. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  11408. quit(1, "Failed to curl_global_init");
  11409. initial_args = malloc(sizeof(char *) * (argc + 1));
  11410. for (i = 0; i < argc; i++)
  11411. initial_args[i] = strdup(argv[i]);
  11412. initial_args[argc] = NULL;
  11413. mutex_init(&hash_lock);
  11414. mutex_init(&console_lock);
  11415. cglock_init(&control_lock);
  11416. mutex_init(&stats_lock);
  11417. mutex_init(&sharelog_lock);
  11418. cglock_init(&ch_lock);
  11419. mutex_init(&sshare_lock);
  11420. rwlock_init(&blk_lock);
  11421. rwlock_init(&netacc_lock);
  11422. rwlock_init(&mining_thr_lock);
  11423. rwlock_init(&devices_lock);
  11424. mutex_init(&lp_lock);
  11425. if (unlikely(pthread_cond_init(&lp_cond, bfg_condattr)))
  11426. quit(1, "Failed to pthread_cond_init lp_cond");
  11427. if (unlikely(pthread_cond_init(&gws_cond, bfg_condattr)))
  11428. quit(1, "Failed to pthread_cond_init gws_cond");
  11429. notifier_init(submit_waiting_notifier);
  11430. timer_unset(&tv_rescan);
  11431. notifier_init(rescan_notifier);
  11432. /* Create a unique get work queue */
  11433. getq = tq_new();
  11434. if (!getq)
  11435. quit(1, "Failed to create getq");
  11436. /* We use the getq mutex as the staged lock */
  11437. stgd_lock = &getq->mutex;
  11438. #if defined(USE_CPUMINING) && defined(USE_SHA256D)
  11439. init_max_name_len();
  11440. #endif
  11441. handler.sa_handler = &sighandler;
  11442. handler.sa_flags = 0;
  11443. sigemptyset(&handler.sa_mask);
  11444. #ifdef HAVE_PTHREAD_CANCEL
  11445. sigaction(SIGTERM, &handler, &termhandler);
  11446. #else
  11447. // Need to let pthread_cancel emulation handle SIGTERM first
  11448. termhandler = pcwm_orig_term_handler;
  11449. pcwm_orig_term_handler = handler;
  11450. #endif
  11451. sigaction(SIGINT, &handler, &inthandler);
  11452. #ifndef WIN32
  11453. signal(SIGPIPE, SIG_IGN);
  11454. #else
  11455. timeBeginPeriod(1);
  11456. #endif
  11457. opt_kernel_path = CGMINER_PREFIX;
  11458. cgminer_path = alloca(PATH_MAX);
  11459. s = strdup(argv[0]);
  11460. strcpy(cgminer_path, dirname(s));
  11461. free(s);
  11462. strcat(cgminer_path, "/");
  11463. #if defined(USE_CPUMINING) && defined(WIN32)
  11464. {
  11465. char buf[32];
  11466. int gev = GetEnvironmentVariable("BFGMINER_BENCH_ALGO", buf, sizeof(buf));
  11467. if (gev > 0 && gev < sizeof(buf))
  11468. {
  11469. setup_benchmark_pool();
  11470. double rate = bench_algo_stage3(atoi(buf));
  11471. // Write result to shared memory for parent
  11472. char unique_name[64];
  11473. if (GetEnvironmentVariable("BFGMINER_SHARED_MEM", unique_name, 32))
  11474. {
  11475. HANDLE map_handle = CreateFileMapping(
  11476. INVALID_HANDLE_VALUE, // use paging file
  11477. NULL, // default security attributes
  11478. PAGE_READWRITE, // read/write access
  11479. 0, // size: high 32-bits
  11480. 4096, // size: low 32-bits
  11481. unique_name // name of map object
  11482. );
  11483. if (NULL != map_handle) {
  11484. void *shared_mem = MapViewOfFile(
  11485. map_handle, // object to map view of
  11486. FILE_MAP_WRITE, // read/write access
  11487. 0, // high offset: map from
  11488. 0, // low offset: beginning
  11489. 0 // default: map entire file
  11490. );
  11491. if (NULL != shared_mem)
  11492. CopyMemory(shared_mem, &rate, sizeof(rate));
  11493. (void)UnmapViewOfFile(shared_mem);
  11494. }
  11495. (void)CloseHandle(map_handle);
  11496. }
  11497. exit(0);
  11498. }
  11499. }
  11500. #endif
  11501. #ifdef HAVE_CURSES
  11502. devcursor = 8;
  11503. logstart = devcursor;
  11504. logcursor = logstart;
  11505. #endif
  11506. mutex_init(&submitting_lock);
  11507. // Ensure at least the default goal is created
  11508. get_mining_goal("default");
  11509. #ifdef USE_OPENCL
  11510. opencl_early_init();
  11511. #endif
  11512. schedstart.tm.tm_sec = 1;
  11513. schedstop .tm.tm_sec = 1;
  11514. opt_register_table(opt_early_table, NULL);
  11515. opt_register_table(opt_config_table, NULL);
  11516. opt_register_table(opt_cmdline_table, NULL);
  11517. opt_early_parse(argc, argv, applog_and_exit);
  11518. if (!config_loaded)
  11519. {
  11520. load_default_config();
  11521. rearrange_pools = total_pools;
  11522. }
  11523. opt_free_table();
  11524. /* parse command line */
  11525. opt_register_table(opt_config_table,
  11526. "Options for both config file and command line");
  11527. opt_register_table(opt_cmdline_table,
  11528. "Options for command line only");
  11529. opt_parse(&argc, argv, applog_and_exit);
  11530. if (argc != 1)
  11531. quit(1, "Unexpected extra commandline arguments");
  11532. if (rearrange_pools && rearrange_pools < total_pools)
  11533. {
  11534. // Prioritise commandline pools before default-config pools
  11535. for (i = 0; i < rearrange_pools; ++i)
  11536. pools[i]->prio += rearrange_pools;
  11537. for ( ; i < total_pools; ++i)
  11538. pools[i]->prio -= rearrange_pools;
  11539. }
  11540. #ifndef HAVE_PTHREAD_CANCEL
  11541. // Can't do this any earlier, or config isn't loaded
  11542. applog(LOG_DEBUG, "pthread_cancel workaround in use");
  11543. #endif
  11544. #ifdef HAVE_PWD_H
  11545. struct passwd *user_info = NULL;
  11546. if (opt_setuid != NULL) {
  11547. if ((user_info = getpwnam(opt_setuid)) == NULL) {
  11548. quit(1, "Unable to find setuid user information");
  11549. }
  11550. }
  11551. #endif
  11552. #ifdef HAVE_CHROOT
  11553. if (chroot_dir != NULL) {
  11554. #ifdef HAVE_PWD_H
  11555. if (user_info == NULL && getuid() == 0) {
  11556. applog(LOG_WARNING, "Running as root inside chroot");
  11557. }
  11558. #endif
  11559. if (chroot(chroot_dir) != 0) {
  11560. quit(1, "Unable to chroot");
  11561. }
  11562. if (chdir("/"))
  11563. quit(1, "Unable to chdir to chroot");
  11564. }
  11565. #endif
  11566. #ifdef HAVE_PWD_H
  11567. if (user_info != NULL) {
  11568. if (setgid((*user_info).pw_gid) != 0)
  11569. quit(1, "Unable to setgid");
  11570. if (setuid((*user_info).pw_uid) != 0)
  11571. quit(1, "Unable to setuid");
  11572. }
  11573. #endif
  11574. raise_fd_limits();
  11575. if (opt_benchmark) {
  11576. while (total_pools)
  11577. remove_pool(pools[0]);
  11578. setup_benchmark_pool();
  11579. }
  11580. if (opt_unittest) {
  11581. test_cgpu_match();
  11582. test_intrange();
  11583. test_decimal_width();
  11584. test_domain_funcs();
  11585. #ifdef USE_SCRYPT
  11586. test_scrypt();
  11587. #endif
  11588. test_target();
  11589. test_uri_get_param();
  11590. utf8_test();
  11591. #ifdef USE_JINGTIAN
  11592. test_aan_pll();
  11593. #endif
  11594. if (unittest_failures)
  11595. quit(1, "Unit tests failed");
  11596. }
  11597. #ifdef HAVE_CURSES
  11598. if (opt_realquiet || opt_display_devs)
  11599. use_curses = false;
  11600. setlocale(LC_ALL, "C");
  11601. if (use_curses)
  11602. enable_curses();
  11603. #endif
  11604. #ifdef HAVE_LIBUSB
  11605. int err = libusb_init(NULL);
  11606. if (err)
  11607. applog(LOG_WARNING, "libusb_init() failed err %d", err);
  11608. else
  11609. have_libusb = true;
  11610. #endif
  11611. applog(LOG_WARNING, "Started %s", packagename);
  11612. {
  11613. struct bfg_loaded_configfile *configfile;
  11614. LL_FOREACH(bfg_loaded_configfiles, configfile)
  11615. {
  11616. char * const cnfbuf = configfile->filename;
  11617. int fileconf_load = configfile->fileconf_load;
  11618. applog(LOG_NOTICE, "Loaded configuration file %s", cnfbuf);
  11619. switch (fileconf_load) {
  11620. case 0:
  11621. applog(LOG_WARNING, "Fatal JSON error in configuration file.");
  11622. applog(LOG_WARNING, "Configuration file could not be used.");
  11623. break;
  11624. case -1:
  11625. applog(LOG_WARNING, "Error in configuration file, partially loaded.");
  11626. if (use_curses)
  11627. applog(LOG_WARNING, "Start BFGMiner with -T to see what failed to load.");
  11628. break;
  11629. default:
  11630. break;
  11631. }
  11632. }
  11633. }
  11634. i = strlen(opt_kernel_path) + 2;
  11635. char __kernel_path[i];
  11636. snprintf(__kernel_path, i, "%s/", opt_kernel_path);
  11637. opt_kernel_path = __kernel_path;
  11638. if (want_per_device_stats)
  11639. opt_log_output = true;
  11640. bfg_devapi_init();
  11641. drv_detect_all();
  11642. total_devices = total_devices_new;
  11643. devices = devices_new;
  11644. total_devices_new = 0;
  11645. devices_new = NULL;
  11646. if (opt_display_devs) {
  11647. int devcount = 0;
  11648. applog(LOG_ERR, "Devices detected:");
  11649. for (i = 0; i < total_devices; ++i) {
  11650. struct cgpu_info *cgpu = devices[i];
  11651. char buf[0x100];
  11652. if (cgpu->device != cgpu)
  11653. continue;
  11654. if (cgpu->name)
  11655. snprintf(buf, sizeof(buf), " %s", cgpu->name);
  11656. else
  11657. if (cgpu->dev_manufacturer)
  11658. snprintf(buf, sizeof(buf), " %s by %s", (cgpu->dev_product ?: "Device"), cgpu->dev_manufacturer);
  11659. else
  11660. if (cgpu->dev_product)
  11661. snprintf(buf, sizeof(buf), " %s", cgpu->dev_product);
  11662. else
  11663. strcpy(buf, " Device");
  11664. tailsprintf(buf, sizeof(buf), " (driver=%s; procs=%d", cgpu->drv->dname, cgpu->procs);
  11665. if (cgpu->dev_serial)
  11666. tailsprintf(buf, sizeof(buf), "; serial=%s", cgpu->dev_serial);
  11667. if (cgpu->device_path)
  11668. tailsprintf(buf, sizeof(buf), "; path=%s", cgpu->device_path);
  11669. tailsprintf(buf, sizeof(buf), ")");
  11670. _applog(LOG_NOTICE, buf);
  11671. ++devcount;
  11672. }
  11673. quit(0, "%d devices listed", devcount);
  11674. }
  11675. mining_threads = 0;
  11676. for (i = 0; i < total_devices; ++i)
  11677. register_device(devices[i]);
  11678. if (!total_devices) {
  11679. applog(LOG_WARNING, "No devices detected!");
  11680. if (use_curses)
  11681. applog(LOG_WARNING, "Waiting for devices; press 'M+' to add, or 'Q' to quit");
  11682. else
  11683. applog(LOG_WARNING, "Waiting for devices");
  11684. }
  11685. #ifdef HAVE_CURSES
  11686. switch_logsize();
  11687. #endif
  11688. #if BLKMAKER_VERSION > 1 && defined(USE_SHA256D)
  11689. if (opt_load_bitcoin_conf && !(get_mining_goal("default")->malgo->algo != POW_SHA256D || opt_benchmark))
  11690. add_local_gbt(total_pools);
  11691. #endif
  11692. if (!total_pools) {
  11693. applog(LOG_WARNING, "Need to specify at least one pool server.");
  11694. #ifdef HAVE_CURSES
  11695. if (!use_curses || !input_pool(false))
  11696. #endif
  11697. quit(1, "Pool setup failed");
  11698. }
  11699. for (i = 0; i < total_pools; i++) {
  11700. struct pool *pool = pools[i];
  11701. size_t siz;
  11702. if (!pool->rpc_url)
  11703. quit(1, "No URI supplied for pool %u", i);
  11704. if (!pool->rpc_userpass) {
  11705. if (!pool->rpc_user || !pool->rpc_pass)
  11706. quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  11707. siz = strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2;
  11708. pool->rpc_userpass = malloc(siz);
  11709. if (!pool->rpc_userpass)
  11710. quit(1, "Failed to malloc userpass");
  11711. snprintf(pool->rpc_userpass, siz, "%s:%s", pool->rpc_user, pool->rpc_pass);
  11712. }
  11713. }
  11714. /* Set the currentpool to pool with priority 0 */
  11715. validate_pool_priorities();
  11716. for (i = 0; i < total_pools; i++) {
  11717. struct pool *pool = pools[i];
  11718. if (!pool->prio)
  11719. currentpool = pool;
  11720. }
  11721. #ifdef HAVE_SYSLOG_H
  11722. if (use_syslog)
  11723. openlog(PACKAGE, LOG_PID, LOG_USER);
  11724. #endif
  11725. #if defined(unix) || defined(__APPLE__)
  11726. if (opt_stderr_cmd)
  11727. fork_monitor();
  11728. #endif // defined(unix)
  11729. mining_thr = calloc(mining_threads, sizeof(thr));
  11730. if (!mining_thr)
  11731. quit(1, "Failed to calloc mining_thr");
  11732. for (i = 0; i < mining_threads; i++) {
  11733. mining_thr[i] = calloc(1, sizeof(*thr));
  11734. if (!mining_thr[i])
  11735. quit(1, "Failed to calloc mining_thr[%d]", i);
  11736. }
  11737. total_control_threads = 6;
  11738. control_thr = calloc(total_control_threads, sizeof(*thr));
  11739. if (!control_thr)
  11740. quit(1, "Failed to calloc control_thr");
  11741. if (opt_benchmark)
  11742. goto begin_bench;
  11743. applog(LOG_NOTICE, "Probing for an alive pool");
  11744. do {
  11745. bool still_testing;
  11746. int i;
  11747. /* Look for at least one active pool before starting */
  11748. probe_pools();
  11749. do {
  11750. sleep(1);
  11751. if (pools_active)
  11752. break;
  11753. still_testing = false;
  11754. for (int i = 0; i < total_pools; ++i)
  11755. if (pools[i]->testing)
  11756. still_testing = true;
  11757. } while (still_testing);
  11758. if (!pools_active) {
  11759. applog(LOG_ERR, "No servers were found that could be used to get work from.");
  11760. applog(LOG_ERR, "Please check the details from the list below of the servers you have input");
  11761. applog(LOG_ERR, "Most likely you have input the wrong URL, forgotten to add a port, or have not set up workers");
  11762. for (i = 0; i < total_pools; i++) {
  11763. struct pool *pool;
  11764. pool = pools[i];
  11765. applog(LOG_WARNING, "Pool: %d URL: %s User: %s Password: %s",
  11766. i, pool->rpc_url, pool->rpc_user, pool->rpc_pass);
  11767. }
  11768. #ifdef HAVE_CURSES
  11769. if (use_curses) {
  11770. halfdelay(150);
  11771. applog(LOG_ERR, "Press any key to exit, or BFGMiner will try again in 15s.");
  11772. if (getch() != ERR)
  11773. quit(0, "No servers could be used! Exiting.");
  11774. cbreak();
  11775. } else
  11776. #endif
  11777. quit(0, "No servers could be used! Exiting.");
  11778. }
  11779. } while (!pools_active);
  11780. #ifdef USE_SCRYPT
  11781. if (detect_algo == 1 && get_mining_goal("default")->malgo->algo != POW_SCRYPT) {
  11782. applog(LOG_NOTICE, "Detected scrypt algorithm");
  11783. set_malgo_scrypt();
  11784. }
  11785. #endif
  11786. detect_algo = 0;
  11787. begin_bench:
  11788. total_mhashes_done = 0;
  11789. for (i = 0; i < total_devices; i++) {
  11790. struct cgpu_info *cgpu = devices[i];
  11791. cgpu->rolling = cgpu->total_mhashes = 0;
  11792. }
  11793. cgtime(&total_tv_start);
  11794. cgtime(&total_tv_end);
  11795. miner_started = total_tv_start;
  11796. time_t miner_start_ts = time(NULL);
  11797. if (schedstart.tm.tm_sec)
  11798. localtime_r(&miner_start_ts, &schedstart.tm);
  11799. if (schedstop.tm.tm_sec)
  11800. localtime_r(&miner_start_ts, &schedstop .tm);
  11801. get_datestamp(datestamp, sizeof(datestamp), miner_start_ts);
  11802. // Initialise processors and threads
  11803. k = 0;
  11804. for (i = 0; i < total_devices; ++i) {
  11805. struct cgpu_info *cgpu = devices[i];
  11806. allocate_cgpu(cgpu, &k);
  11807. }
  11808. // Start threads
  11809. for (i = 0; i < total_devices; ++i) {
  11810. struct cgpu_info *cgpu = devices[i];
  11811. start_cgpu(cgpu);
  11812. }
  11813. #ifdef USE_OPENCL
  11814. for (i = 0; i < nDevs; i++)
  11815. pause_dynamic_threads(i);
  11816. #endif
  11817. #if defined(USE_CPUMINING) && defined(USE_SHA256D)
  11818. if (opt_n_threads > 0)
  11819. applog(LOG_INFO, "%d cpu miner threads started, using '%s' algorithm.",
  11820. opt_n_threads, algo_names[opt_algo]);
  11821. #endif
  11822. cgtime(&total_tv_start);
  11823. cgtime(&total_tv_end);
  11824. if (!opt_benchmark)
  11825. {
  11826. pthread_t submit_thread;
  11827. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, NULL)))
  11828. quit(1, "submit_work thread create failed");
  11829. }
  11830. watchpool_thr_id = 1;
  11831. thr = &control_thr[watchpool_thr_id];
  11832. /* start watchpool thread */
  11833. if (thr_info_create(thr, NULL, watchpool_thread, NULL))
  11834. quit(1, "watchpool thread create failed");
  11835. pthread_detach(thr->pth);
  11836. watchdog_thr_id = 2;
  11837. thr = &control_thr[watchdog_thr_id];
  11838. /* start watchdog thread */
  11839. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  11840. quit(1, "watchdog thread create failed");
  11841. pthread_detach(thr->pth);
  11842. #ifdef USE_OPENCL
  11843. /* Create reinit gpu thread */
  11844. gpur_thr_id = 3;
  11845. thr = &control_thr[gpur_thr_id];
  11846. thr->q = tq_new();
  11847. if (!thr->q)
  11848. quit(1, "tq_new failed for gpur_thr_id");
  11849. if (thr_info_create(thr, NULL, reinit_gpu, thr))
  11850. quit(1, "reinit_gpu thread create failed");
  11851. #endif
  11852. /* Create API socket thread */
  11853. api_thr_id = 4;
  11854. thr = &control_thr[api_thr_id];
  11855. if (thr_info_create(thr, NULL, api_thread, thr))
  11856. quit(1, "API thread create failed");
  11857. #ifdef USE_LIBMICROHTTPD
  11858. if (httpsrv_port != -1)
  11859. httpsrv_start(httpsrv_port);
  11860. #endif
  11861. #ifdef USE_LIBEVENT
  11862. if (stratumsrv_port != -1)
  11863. stratumsrv_start();
  11864. #endif
  11865. #ifdef HAVE_BFG_HOTPLUG
  11866. if (opt_hotplug)
  11867. hotplug_start();
  11868. #endif
  11869. #ifdef HAVE_CURSES
  11870. /* Create curses input thread for keyboard input. Create this last so
  11871. * that we know all threads are created since this can call kill_work
  11872. * to try and shut down ll previous threads. */
  11873. input_thr_id = 5;
  11874. thr = &control_thr[input_thr_id];
  11875. if (thr_info_create(thr, NULL, input_thread, thr))
  11876. quit(1, "input thread create failed");
  11877. pthread_detach(thr->pth);
  11878. #endif
  11879. /* Just to be sure */
  11880. if (total_control_threads != 6)
  11881. quit(1, "incorrect total_control_threads (%d) should be 7", total_control_threads);
  11882. /* Once everything is set up, main() becomes the getwork scheduler */
  11883. while (42) {
  11884. int ts, max_staged = opt_queue;
  11885. struct pool *pool, *cp;
  11886. bool lagging = false;
  11887. struct curl_ent *ce;
  11888. struct work *work;
  11889. struct mining_algorithm *malgo = NULL;
  11890. cp = current_pool();
  11891. // Generally, each processor needs a new work, and all at once during work restarts
  11892. max_staged += base_queue;
  11893. mutex_lock(stgd_lock);
  11894. ts = __total_staged(false);
  11895. if (!pool_localgen(cp) && !ts && !opt_fail_only)
  11896. lagging = true;
  11897. /* Wait until hash_pop tells us we need to create more work */
  11898. if (ts > max_staged) {
  11899. {
  11900. LL_FOREACH(mining_algorithms, malgo)
  11901. {
  11902. if (!malgo->goal_refs)
  11903. continue;
  11904. if (!malgo->base_queue)
  11905. continue;
  11906. if (malgo->staged < malgo->base_queue + opt_queue)
  11907. {
  11908. mutex_unlock(stgd_lock);
  11909. pool = select_pool(lagging, malgo);
  11910. if (pool)
  11911. {
  11912. work = make_work();
  11913. work->spare = true;
  11914. goto retry;
  11915. }
  11916. mutex_lock(stgd_lock);
  11917. }
  11918. }
  11919. malgo = NULL;
  11920. }
  11921. staged_full = true;
  11922. pthread_cond_wait(&gws_cond, stgd_lock);
  11923. ts = __total_staged(false);
  11924. }
  11925. mutex_unlock(stgd_lock);
  11926. if (ts > max_staged)
  11927. continue;
  11928. work = make_work();
  11929. if (lagging && !pool_tset(cp, &cp->lagging)) {
  11930. applog(LOG_WARNING, "Pool %d not providing work fast enough", cp->pool_no);
  11931. cp->getfail_occasions++;
  11932. total_go++;
  11933. }
  11934. pool = select_pool(lagging, malgo);
  11935. retry:
  11936. if (pool->has_stratum) {
  11937. while (!pool->stratum_active || !pool->stratum_notify) {
  11938. struct pool *altpool = select_pool(true, malgo);
  11939. if (altpool == pool && pool->has_stratum)
  11940. cgsleep_ms(5000);
  11941. pool = altpool;
  11942. goto retry;
  11943. }
  11944. gen_stratum_work(pool, work);
  11945. applog(LOG_DEBUG, "Generated stratum work");
  11946. stage_work(work);
  11947. continue;
  11948. }
  11949. if (pool->last_work_copy) {
  11950. mutex_lock(&pool->last_work_lock);
  11951. struct work *last_work = pool->last_work_copy;
  11952. if (!last_work)
  11953. {}
  11954. else
  11955. if (can_roll(last_work) && should_roll(last_work)) {
  11956. struct timeval tv_now;
  11957. cgtime(&tv_now);
  11958. free_work(work);
  11959. work = make_clone(pool->last_work_copy);
  11960. mutex_unlock(&pool->last_work_lock);
  11961. roll_work(work);
  11962. 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));
  11963. stage_work(work);
  11964. continue;
  11965. } else if (last_work->tr && pool->proto == PLP_GETBLOCKTEMPLATE && blkmk_work_left(last_work->tr->tmpl) > (unsigned long)mining_threads) {
  11966. // Don't free last_work_copy, since it is used to detect upstream provides plenty of work per template
  11967. } else {
  11968. free_work(last_work);
  11969. pool->last_work_copy = NULL;
  11970. }
  11971. mutex_unlock(&pool->last_work_lock);
  11972. }
  11973. if (clone_available()) {
  11974. applog(LOG_DEBUG, "Cloned getwork work");
  11975. free_work(work);
  11976. continue;
  11977. }
  11978. if (opt_benchmark) {
  11979. get_benchmark_work(work, opt_benchmark_intense);
  11980. applog(LOG_DEBUG, "Generated benchmark work");
  11981. stage_work(work);
  11982. continue;
  11983. }
  11984. work->pool = pool;
  11985. ce = pop_curl_entry3(pool, 2);
  11986. /* obtain new work from bitcoin via JSON-RPC */
  11987. if (!get_upstream_work(work, ce->curl)) {
  11988. struct pool *next_pool;
  11989. /* Make sure the pool just hasn't stopped serving
  11990. * requests but is up as we'll keep hammering it */
  11991. push_curl_entry(ce, pool);
  11992. ++pool->seq_getfails;
  11993. pool_died(pool);
  11994. next_pool = select_pool(!opt_fail_only, malgo);
  11995. if (pool == next_pool) {
  11996. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, retrying in 5s", pool->pool_no);
  11997. cgsleep_ms(5000);
  11998. } else {
  11999. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, failover activated", pool->pool_no);
  12000. pool = next_pool;
  12001. }
  12002. goto retry;
  12003. }
  12004. if (ts >= max_staged)
  12005. pool_tclear(pool, &pool->lagging);
  12006. if (pool_tclear(pool, &pool->idle))
  12007. pool_resus(pool);
  12008. applog(LOG_DEBUG, "Generated getwork work");
  12009. stage_work(work);
  12010. push_curl_entry(ce, pool);
  12011. }
  12012. return 0;
  12013. }