miner.c 354 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726
  1. /*
  2. * Copyright 2011-2014 Con Kolivas
  3. * Copyright 2011-2014 Luke Dashjr
  4. * Copyright 2014 Nate Woolls
  5. * Copyright 2012-2013 Andrew Smith
  6. * Copyright 2010 Jeff Garzik
  7. *
  8. * This program is free software; you can redistribute it and/or modify it
  9. * under the terms of the GNU General Public License as published by the Free
  10. * Software Foundation; either version 3 of the License, or (at your option)
  11. * any later version. See COPYING for more details.
  12. */
  13. #include "config.h"
  14. #ifdef HAVE_CURSES
  15. #ifdef USE_UNICODE
  16. #define PDC_WIDE
  17. #endif
  18. // Must be before stdbool, since pdcurses typedefs bool :/
  19. #include <curses.h>
  20. #endif
  21. #include <ctype.h>
  22. #include <float.h>
  23. #include <limits.h>
  24. #include <locale.h>
  25. #include <stdio.h>
  26. #include <stdlib.h>
  27. #include <string.h>
  28. #include <stdbool.h>
  29. #include <stdint.h>
  30. #include <unistd.h>
  31. #include <sys/time.h>
  32. #include <time.h>
  33. #include <math.h>
  34. #include <stdarg.h>
  35. #include <assert.h>
  36. #include <signal.h>
  37. #include <wctype.h>
  38. #include <sys/stat.h>
  39. #include <sys/types.h>
  40. #include <dirent.h>
  41. #ifdef HAVE_PWD_H
  42. #include <pwd.h>
  43. #endif
  44. #ifndef WIN32
  45. #include <sys/resource.h>
  46. #include <sys/socket.h>
  47. #if defined(HAVE_LIBUDEV) && defined(HAVE_SYS_EPOLL_H)
  48. #include <libudev.h>
  49. #include <sys/epoll.h>
  50. #define HAVE_BFG_HOTPLUG
  51. #endif
  52. #else
  53. #include <winsock2.h>
  54. #include <windows.h>
  55. #include <dbt.h>
  56. #define HAVE_BFG_HOTPLUG
  57. #endif
  58. #include <ccan/opt/opt.h>
  59. #include <jansson.h>
  60. #include <curl/curl.h>
  61. #include <libgen.h>
  62. #include <sha2.h>
  63. #include <utlist.h>
  64. #include <blkmaker.h>
  65. #include <blkmaker_jansson.h>
  66. #include <blktemplate.h>
  67. #include <libbase58.h>
  68. #include "compat.h"
  69. #include "deviceapi.h"
  70. #include "logging.h"
  71. #include "miner.h"
  72. #include "adl.h"
  73. #include "driver-cpu.h"
  74. #include "driver-opencl.h"
  75. #include "scrypt.h"
  76. #include "util.h"
  77. #ifdef USE_AVALON
  78. #include "driver-avalon.h"
  79. #endif
  80. #ifdef HAVE_BFG_LOWLEVEL
  81. #include "lowlevel.h"
  82. #endif
  83. #if defined(unix) || defined(__APPLE__)
  84. #include <errno.h>
  85. #include <fcntl.h>
  86. #include <sys/wait.h>
  87. #endif
  88. #ifdef USE_SCRYPT
  89. #include "scrypt.h"
  90. #endif
  91. #include "version.h"
  92. #if defined(USE_AVALON) || defined(USE_BITFORCE) || defined(USE_ICARUS) || defined(USE_MODMINER) || defined(USE_NANOFURY) || defined(USE_X6500) || defined(USE_ZTEX)
  93. # define USE_FPGA
  94. #endif
  95. enum bfg_quit_summary {
  96. BQS_DEFAULT,
  97. BQS_NONE,
  98. BQS_DEVS,
  99. BQS_PROCS,
  100. BQS_DETAILED,
  101. };
  102. struct strategies strategies[] = {
  103. { "Failover" },
  104. { "Round Robin" },
  105. { "Rotate" },
  106. { "Load Balance" },
  107. { "Balance" },
  108. };
  109. static char packagename[256];
  110. bool opt_protocol;
  111. bool opt_dev_protocol;
  112. static bool opt_benchmark, opt_benchmark_intense;
  113. static bool want_longpoll = true;
  114. static bool want_gbt = true;
  115. static bool want_getwork = true;
  116. #if BLKMAKER_VERSION > 1
  117. static bool opt_load_bitcoin_conf = true;
  118. static uint32_t coinbase_script_block_id;
  119. static uint32_t template_nonce;
  120. #endif
  121. #if BLKMAKER_VERSION > 0
  122. char *opt_coinbase_sig;
  123. #endif
  124. static enum bfg_quit_summary opt_quit_summary = BQS_DEFAULT;
  125. static bool include_serial_in_statline;
  126. char *request_target_str;
  127. float request_pdiff = 1.0;
  128. double request_bdiff;
  129. static bool want_stratum = true;
  130. int opt_skip_checks;
  131. bool want_per_device_stats;
  132. bool use_syslog;
  133. bool opt_quiet_work_updates = true;
  134. bool opt_quiet;
  135. bool opt_realquiet;
  136. int loginput_size;
  137. bool opt_compact;
  138. bool opt_show_procs;
  139. const int opt_cutofftemp = 95;
  140. int opt_hysteresis = 3;
  141. static int opt_retries = -1;
  142. int opt_fail_pause = 5;
  143. int opt_log_interval = 20;
  144. int opt_queue = 1;
  145. int opt_scantime = 60;
  146. int opt_expiry = 120;
  147. int opt_expiry_lp = 3600;
  148. unsigned long long global_hashrate;
  149. static bool opt_unittest = false;
  150. unsigned unittest_failures;
  151. unsigned long global_quota_gcd = 1;
  152. time_t last_getwork;
  153. #ifdef HAVE_OPENCL
  154. int opt_dynamic_interval = 7;
  155. int nDevs;
  156. int opt_g_threads = -1;
  157. #endif
  158. #ifdef USE_SCRYPT
  159. static char detect_algo = 1;
  160. #else
  161. static char detect_algo;
  162. #endif
  163. bool opt_restart = true;
  164. #ifdef USE_LIBMICROHTTPD
  165. #include "httpsrv.h"
  166. int httpsrv_port = -1;
  167. #endif
  168. #ifdef USE_LIBEVENT
  169. int stratumsrv_port = -1;
  170. #endif
  171. const
  172. int rescan_delay_ms = 1000;
  173. #ifdef HAVE_BFG_HOTPLUG
  174. bool opt_hotplug = 1;
  175. const
  176. int hotplug_delay_ms = 100;
  177. #else
  178. const bool opt_hotplug;
  179. #endif
  180. struct string_elist *scan_devices;
  181. static struct string_elist *opt_set_device_list;
  182. bool opt_force_dev_init;
  183. static struct string_elist *opt_devices_enabled_list;
  184. static bool opt_display_devs;
  185. int total_devices;
  186. struct cgpu_info **devices;
  187. int total_devices_new;
  188. struct cgpu_info **devices_new;
  189. bool have_opencl;
  190. int opt_n_threads = -1;
  191. int mining_threads;
  192. int base_queue;
  193. int num_processors;
  194. #ifdef HAVE_CURSES
  195. bool use_curses = true;
  196. #else
  197. bool use_curses;
  198. #endif
  199. int last_logstatusline_len;
  200. #ifdef HAVE_LIBUSB
  201. bool have_libusb;
  202. #endif
  203. static bool opt_submit_stale = true;
  204. static float opt_shares;
  205. static int opt_submit_threads = 0x40;
  206. bool opt_fail_only;
  207. int opt_fail_switch_delay = 300;
  208. bool opt_autofan;
  209. bool opt_autoengine;
  210. bool opt_noadl;
  211. char *opt_api_allow = NULL;
  212. char *opt_api_groups;
  213. char *opt_api_description = PACKAGE_STRING;
  214. int opt_api_port = 4028;
  215. bool opt_api_listen;
  216. bool opt_api_mcast;
  217. char *opt_api_mcast_addr = API_MCAST_ADDR;
  218. char *opt_api_mcast_code = API_MCAST_CODE;
  219. char *opt_api_mcast_des = "";
  220. int opt_api_mcast_port = 4028;
  221. bool opt_api_network;
  222. bool opt_delaynet;
  223. bool opt_disable_pool;
  224. bool opt_disable_client_reconnect = false;
  225. static bool no_work;
  226. bool opt_worktime;
  227. bool opt_weighed_stats;
  228. char *opt_kernel_path;
  229. char *cgminer_path;
  230. #if defined(USE_BITFORCE)
  231. bool opt_bfl_noncerange;
  232. #endif
  233. #define QUIET (opt_quiet || opt_realquiet)
  234. struct thr_info *control_thr;
  235. struct thr_info **mining_thr;
  236. static int watchpool_thr_id;
  237. static int watchdog_thr_id;
  238. #ifdef HAVE_CURSES
  239. static int input_thr_id;
  240. #endif
  241. int gpur_thr_id;
  242. static int api_thr_id;
  243. static int total_control_threads;
  244. pthread_mutex_t hash_lock;
  245. static pthread_mutex_t *stgd_lock;
  246. pthread_mutex_t console_lock;
  247. cglock_t ch_lock;
  248. static pthread_rwlock_t blk_lock;
  249. static pthread_mutex_t sshare_lock;
  250. pthread_rwlock_t netacc_lock;
  251. pthread_rwlock_t mining_thr_lock;
  252. pthread_rwlock_t devices_lock;
  253. static pthread_mutex_t lp_lock;
  254. static pthread_cond_t lp_cond;
  255. pthread_cond_t gws_cond;
  256. bool shutting_down;
  257. double total_rolling;
  258. double total_mhashes_done;
  259. static struct timeval total_tv_start, total_tv_end;
  260. static struct timeval miner_started;
  261. cglock_t control_lock;
  262. pthread_mutex_t stats_lock;
  263. static pthread_mutex_t submitting_lock;
  264. static int total_submitting;
  265. static struct work *submit_waiting;
  266. notifier_t submit_waiting_notifier;
  267. int hw_errors;
  268. int total_accepted, total_rejected;
  269. int total_getworks, total_stale, total_discarded;
  270. uint64_t total_bytes_rcvd, total_bytes_sent;
  271. double total_diff1, total_bad_diff1;
  272. double total_diff_accepted, total_diff_rejected, total_diff_stale;
  273. static int staged_rollable;
  274. unsigned int new_blocks;
  275. unsigned int found_blocks;
  276. unsigned int local_work;
  277. unsigned int total_go, total_ro;
  278. struct pool **pools;
  279. static struct pool *currentpool = NULL;
  280. int total_pools, enabled_pools;
  281. enum pool_strategy pool_strategy = POOL_FAILOVER;
  282. int opt_rotate_period;
  283. static int total_urls, total_users, total_passes;
  284. static
  285. #ifndef HAVE_CURSES
  286. const
  287. #endif
  288. bool curses_active;
  289. #ifdef HAVE_CURSES
  290. #if !(defined(PDCURSES) || defined(NCURSES_VERSION))
  291. const
  292. #endif
  293. short default_bgcolor = COLOR_BLACK;
  294. static int attr_title = A_BOLD;
  295. #endif
  296. static
  297. #if defined(HAVE_CURSES) && defined(USE_UNICODE)
  298. bool use_unicode;
  299. static
  300. bool have_unicode_degrees;
  301. static
  302. wchar_t unicode_micro = 'u';
  303. #else
  304. const bool use_unicode;
  305. static
  306. const bool have_unicode_degrees;
  307. #ifdef HAVE_CURSES
  308. static
  309. const char unicode_micro = 'u';
  310. #endif
  311. #endif
  312. #ifdef HAVE_CURSES
  313. #define U8_BAD_START "\xef\x80\x81"
  314. #define U8_BAD_END "\xef\x80\x80"
  315. #define AS_BAD(x) U8_BAD_START x U8_BAD_END
  316. /* logstart is where the log window should start */
  317. static int devcursor, logstart, logcursor;
  318. bool selecting_device;
  319. unsigned selected_device;
  320. #endif
  321. static int max_lpdigits;
  322. // current_hash was replaced with goal->current_goal_detail
  323. // current_block_id was replaced with blkchain->currentblk->block_id
  324. static char datestamp[40];
  325. static char best_share[ALLOC_H2B_SHORTV] = "0";
  326. double best_diff = 0;
  327. struct mining_algorithm *mining_algorithms;
  328. struct mining_goal_info *mining_goals;
  329. int active_goals = 1;
  330. int swork_id;
  331. /* For creating a hash database of stratum shares submitted that have not had
  332. * a response yet */
  333. struct stratum_share {
  334. UT_hash_handle hh;
  335. bool block;
  336. struct work *work;
  337. int id;
  338. };
  339. static struct stratum_share *stratum_shares = NULL;
  340. char *opt_socks_proxy = NULL;
  341. static const char def_conf[] = "bfgminer.conf";
  342. static bool config_loaded;
  343. static int include_count;
  344. #define JSON_INCLUDE_CONF "include"
  345. #define JSON_LOAD_ERROR "JSON decode of file '%s' failed\n %s"
  346. #define JSON_LOAD_ERROR_LEN strlen(JSON_LOAD_ERROR)
  347. #define JSON_MAX_DEPTH 10
  348. #define JSON_MAX_DEPTH_ERR "Too many levels of JSON includes (limit 10) or a loop"
  349. char *cmd_idle, *cmd_sick, *cmd_dead;
  350. #if defined(unix) || defined(__APPLE__)
  351. static char *opt_stderr_cmd = NULL;
  352. static int forkpid;
  353. #endif // defined(unix)
  354. #ifdef HAVE_CHROOT
  355. char *chroot_dir;
  356. #endif
  357. #ifdef HAVE_PWD_H
  358. char *opt_setuid;
  359. #endif
  360. struct sigaction termhandler, inthandler;
  361. struct thread_q *getq;
  362. static int total_work;
  363. static bool staged_full;
  364. struct work *staged_work = NULL;
  365. struct schedtime {
  366. bool enable;
  367. struct tm tm;
  368. };
  369. struct schedtime schedstart;
  370. struct schedtime schedstop;
  371. bool sched_paused;
  372. static bool time_before(struct tm *tm1, struct tm *tm2)
  373. {
  374. if (tm1->tm_hour < tm2->tm_hour)
  375. return true;
  376. if (tm1->tm_hour == tm2->tm_hour && tm1->tm_min < tm2->tm_min)
  377. return true;
  378. return false;
  379. }
  380. static bool should_run(void)
  381. {
  382. struct tm tm;
  383. time_t tt;
  384. bool within_range;
  385. if (!schedstart.enable && !schedstop.enable)
  386. return true;
  387. tt = time(NULL);
  388. localtime_r(&tt, &tm);
  389. // NOTE: This is delicately balanced so that should_run is always false if schedstart==schedstop
  390. if (time_before(&schedstop.tm, &schedstart.tm))
  391. within_range = (time_before(&tm, &schedstop.tm) || !time_before(&tm, &schedstart.tm));
  392. else
  393. within_range = (time_before(&tm, &schedstop.tm) && !time_before(&tm, &schedstart.tm));
  394. if (within_range && !schedstop.enable)
  395. /* This is a once off event with no stop time set */
  396. schedstart.enable = false;
  397. return within_range;
  398. }
  399. void get_datestamp(char *f, size_t fsiz, time_t tt)
  400. {
  401. struct tm _tm;
  402. struct tm *tm = &_tm;
  403. if (tt == INVALID_TIMESTAMP)
  404. tt = time(NULL);
  405. localtime_r(&tt, tm);
  406. snprintf(f, fsiz, "[%d-%02d-%02d %02d:%02d:%02d]",
  407. tm->tm_year + 1900,
  408. tm->tm_mon + 1,
  409. tm->tm_mday,
  410. tm->tm_hour,
  411. tm->tm_min,
  412. tm->tm_sec);
  413. }
  414. static
  415. void get_timestamp(char *f, size_t fsiz, time_t tt)
  416. {
  417. struct tm _tm;
  418. struct tm *tm = &_tm;
  419. localtime_r(&tt, tm);
  420. snprintf(f, fsiz, "[%02d:%02d:%02d]",
  421. tm->tm_hour,
  422. tm->tm_min,
  423. tm->tm_sec);
  424. }
  425. static void applog_and_exit(const char *fmt, ...) FORMAT_SYNTAX_CHECK(printf, 1, 2);
  426. static char exit_buf[512];
  427. static void applog_and_exit(const char *fmt, ...)
  428. {
  429. va_list ap;
  430. va_start(ap, fmt);
  431. vsnprintf(exit_buf, sizeof(exit_buf), fmt, ap);
  432. va_end(ap);
  433. _applog(LOG_ERR, exit_buf);
  434. exit(1);
  435. }
  436. static
  437. float drv_min_nonce_diff(const struct device_drv * const drv, struct cgpu_info * const proc, const struct mining_algorithm * const malgo)
  438. {
  439. if (drv->drv_min_nonce_diff)
  440. return drv->drv_min_nonce_diff(proc, malgo);
  441. return (malgo->algo == POW_SHA256D) ? 1. : -1.;
  442. }
  443. char *devpath_to_devid(const char *devpath)
  444. {
  445. #ifndef WIN32
  446. if (devpath[0] != '/')
  447. return NULL;
  448. struct stat my_stat;
  449. if (stat(devpath, &my_stat))
  450. return NULL;
  451. char *devs = malloc(6 + (sizeof(dev_t) * 2) + 1);
  452. memcpy(devs, "dev_t:", 6);
  453. bin2hex(&devs[6], &my_stat.st_rdev, sizeof(dev_t));
  454. #else
  455. if (!strncmp(devpath, "\\\\.\\", 4))
  456. devpath += 4;
  457. if (strncasecmp(devpath, "COM", 3) || !devpath[3])
  458. return NULL;
  459. devpath += 3;
  460. char *p;
  461. strtol(devpath, &p, 10);
  462. if (p[0])
  463. return NULL;
  464. const int sz = (p - devpath);
  465. char *devs = malloc(4 + sz + 1);
  466. sprintf(devs, "com:%s", devpath);
  467. #endif
  468. return devs;
  469. }
  470. static
  471. bool devpaths_match(const char * const ap, const char * const bp)
  472. {
  473. char * const a = devpath_to_devid(ap);
  474. if (!a)
  475. return false;
  476. char * const b = devpath_to_devid(bp);
  477. bool rv = false;
  478. if (b)
  479. {
  480. rv = !strcmp(a, b);
  481. free(b);
  482. }
  483. free(a);
  484. return rv;
  485. }
  486. static
  487. int proc_letter_to_number(const char *s, const char ** const rem)
  488. {
  489. int n = 0, c;
  490. for ( ; s[0]; ++s)
  491. {
  492. if (unlikely(n > INT_MAX / 26))
  493. break;
  494. c = tolower(s[0]) - 'a';
  495. if (unlikely(c < 0 || c > 25))
  496. break;
  497. if (unlikely(INT_MAX - c < n))
  498. break;
  499. n = (n * 26) + c;
  500. }
  501. *rem = s;
  502. return n;
  503. }
  504. static
  505. bool cgpu_match(const char * const pattern, const struct cgpu_info * const cgpu)
  506. {
  507. // all - matches anything
  508. // d0 - matches all processors of device 0
  509. // d0-3 - matches all processors of device 0, 1, 2, or 3
  510. // d0a - matches first processor of device 0
  511. // 0 - matches processor 0
  512. // 0-4 - matches processors 0, 1, 2, 3, or 4
  513. // ___ - matches all processors on all devices using driver/name ___
  514. // ___0 - matches all processors of 0th device using driver/name ___
  515. // ___0a - matches first processor of 0th device using driver/name ___
  516. // @* - matches device with serial or path *
  517. // @*@a - matches first processor of device with serial or path *
  518. // ___@* - matches device with serial or path * using driver/name ___
  519. if (!strcasecmp(pattern, "all"))
  520. return true;
  521. const struct device_drv * const drv = cgpu->drv;
  522. const char *p = pattern, *p2;
  523. size_t L;
  524. int n, i, c = -1;
  525. int n2;
  526. int proc_first = -1, proc_last = -1;
  527. struct cgpu_info *device;
  528. if (!(strncasecmp(drv->dname, p, (L = strlen(drv->dname)))
  529. && strncasecmp(drv-> name, p, (L = strlen(drv-> name)))))
  530. // dname or name
  531. p = &pattern[L];
  532. else
  533. if (p[0] == 'd' && (isdigit(p[1]) || p[1] == '-'))
  534. // d#
  535. ++p;
  536. else
  537. if (isdigit(p[0]) || p[0] == '@' || p[0] == '-')
  538. // # or @
  539. {}
  540. else
  541. return false;
  542. L = p - pattern;
  543. while (isspace(p[0]))
  544. ++p;
  545. if (p[0] == '@')
  546. {
  547. // Serial/path
  548. const char * const ser = &p[1];
  549. for (p = ser; p[0] != '@' && p[0] != '\0'; ++p)
  550. {}
  551. p2 = (p[0] == '@') ? &p[1] : p;
  552. const size_t serlen = (p - ser);
  553. p = "";
  554. n = n2 = 0;
  555. const char * const devpath = cgpu->device_path ?: "";
  556. const char * const devser = cgpu->dev_serial ?: "";
  557. if ((!strncmp(devpath, ser, serlen)) && devpath[serlen] == '\0')
  558. {} // Match
  559. else
  560. if ((!strncmp(devser, ser, serlen)) && devser[serlen] == '\0')
  561. {} // Match
  562. else
  563. {
  564. char devpath2[serlen + 1];
  565. memcpy(devpath2, ser, serlen);
  566. devpath2[serlen] = '\0';
  567. if (!devpaths_match(devpath, ser))
  568. return false;
  569. }
  570. }
  571. else
  572. {
  573. if (isdigit(p[0]))
  574. n = strtol(p, (void*)&p2, 0);
  575. else
  576. {
  577. n = 0;
  578. p2 = p;
  579. }
  580. if (p2[0] == '-')
  581. {
  582. ++p2;
  583. if (p2[0] && isdigit(p2[0]))
  584. n2 = strtol(p2, (void*)&p2, 0);
  585. else
  586. n2 = INT_MAX;
  587. }
  588. else
  589. n2 = n;
  590. if (p == pattern)
  591. {
  592. if (!p[0])
  593. return true;
  594. if (p2 && p2[0])
  595. goto invsyntax;
  596. for (i = n; i <= n2; ++i)
  597. {
  598. if (i >= total_devices)
  599. break;
  600. if (cgpu == devices[i])
  601. return true;
  602. }
  603. return false;
  604. }
  605. }
  606. if (p2[0])
  607. {
  608. proc_first = proc_letter_to_number(&p2[0], &p2);
  609. if (p2[0] == '-')
  610. {
  611. ++p2;
  612. if (p2[0])
  613. proc_last = proc_letter_to_number(p2, &p2);
  614. else
  615. proc_last = INT_MAX;
  616. }
  617. else
  618. proc_last = proc_first;
  619. if (p2[0])
  620. goto invsyntax;
  621. }
  622. if (L > 1 || tolower(pattern[0]) != 'd' || !p[0])
  623. {
  624. if ((L == 3 && !strncasecmp(pattern, drv->name, 3)) ||
  625. (!L) ||
  626. (L == strlen(drv->dname) && !strncasecmp(pattern, drv->dname, L)))
  627. {} // Matched name or dname
  628. else
  629. return false;
  630. if (p[0] && (cgpu->device_id < n || cgpu->device_id > n2))
  631. return false;
  632. if (proc_first != -1 && (cgpu->proc_id < proc_first || cgpu->proc_id > proc_last))
  633. return false;
  634. return true;
  635. }
  636. // d#
  637. c = -1;
  638. for (i = 0; ; ++i)
  639. {
  640. if (i == total_devices)
  641. return false;
  642. if (devices[i]->device != devices[i])
  643. continue;
  644. ++c;
  645. if (c < n)
  646. continue;
  647. if (c > n2)
  648. break;
  649. for (device = devices[i]; device; device = device->next_proc)
  650. {
  651. if (proc_first != -1 && (device->proc_id < proc_first || device->proc_id > proc_last))
  652. continue;
  653. if (device == cgpu)
  654. return true;
  655. }
  656. }
  657. return false;
  658. invsyntax:
  659. applog(LOG_WARNING, "%s: Invalid syntax: %s", __func__, pattern);
  660. return false;
  661. }
  662. #define TEST_CGPU_MATCH(pattern) \
  663. if (!cgpu_match(pattern, &cgpu)) \
  664. { \
  665. ++unittest_failures; \
  666. applog(LOG_ERR, "%s: Pattern \"%s\" should have matched!", __func__, pattern); \
  667. } \
  668. // END TEST_CGPU_MATCH
  669. #define TEST_CGPU_NOMATCH(pattern) \
  670. if (cgpu_match(pattern, &cgpu)) \
  671. { \
  672. ++unittest_failures; \
  673. applog(LOG_ERR, "%s: Pattern \"%s\" should NOT have matched!", __func__, pattern); \
  674. } \
  675. // END TEST_CGPU_MATCH
  676. static __maybe_unused
  677. void test_cgpu_match()
  678. {
  679. struct device_drv drv = {
  680. .dname = "test",
  681. .name = "TST",
  682. };
  683. struct cgpu_info cgpu = {
  684. .drv = &drv,
  685. .device = &cgpu,
  686. .device_id = 1,
  687. .proc_id = 1,
  688. .proc_repr = "TST 1b",
  689. }, cgpu0a = {
  690. .drv = &drv,
  691. .device = &cgpu0a,
  692. .device_id = 0,
  693. .proc_id = 0,
  694. .proc_repr = "TST 0a",
  695. }, cgpu1a = {
  696. .drv = &drv,
  697. .device = &cgpu0a,
  698. .device_id = 1,
  699. .proc_id = 0,
  700. .proc_repr = "TST 1a",
  701. };
  702. struct cgpu_info *devices_list[3] = {&cgpu0a, &cgpu1a, &cgpu,};
  703. devices = devices_list;
  704. total_devices = 3;
  705. TEST_CGPU_MATCH("all")
  706. TEST_CGPU_MATCH("d1")
  707. TEST_CGPU_NOMATCH("d2")
  708. TEST_CGPU_MATCH("d0-5")
  709. TEST_CGPU_NOMATCH("d0-0")
  710. TEST_CGPU_NOMATCH("d2-5")
  711. TEST_CGPU_MATCH("d-1")
  712. TEST_CGPU_MATCH("d1-")
  713. TEST_CGPU_NOMATCH("d-0")
  714. TEST_CGPU_NOMATCH("d2-")
  715. TEST_CGPU_MATCH("2")
  716. TEST_CGPU_NOMATCH("3")
  717. TEST_CGPU_MATCH("1-2")
  718. TEST_CGPU_MATCH("2-3")
  719. TEST_CGPU_NOMATCH("1-1")
  720. TEST_CGPU_NOMATCH("3-4")
  721. TEST_CGPU_MATCH("TST")
  722. TEST_CGPU_MATCH("test")
  723. TEST_CGPU_MATCH("tst")
  724. TEST_CGPU_MATCH("TEST")
  725. TEST_CGPU_NOMATCH("TSF")
  726. TEST_CGPU_NOMATCH("TS")
  727. TEST_CGPU_NOMATCH("TSTF")
  728. TEST_CGPU_MATCH("TST1")
  729. TEST_CGPU_MATCH("test1")
  730. TEST_CGPU_MATCH("TST0-1")
  731. TEST_CGPU_MATCH("TST 1")
  732. TEST_CGPU_MATCH("TST 1-2")
  733. TEST_CGPU_MATCH("TEST 1-2")
  734. TEST_CGPU_NOMATCH("TST2")
  735. TEST_CGPU_NOMATCH("TST2-3")
  736. TEST_CGPU_NOMATCH("TST0-0")
  737. TEST_CGPU_MATCH("TST1b")
  738. TEST_CGPU_MATCH("tst1b")
  739. TEST_CGPU_NOMATCH("TST1c")
  740. TEST_CGPU_NOMATCH("TST1bb")
  741. TEST_CGPU_MATCH("TST0-1b")
  742. TEST_CGPU_NOMATCH("TST0-1c")
  743. TEST_CGPU_MATCH("TST1a-d")
  744. TEST_CGPU_NOMATCH("TST1a-a")
  745. TEST_CGPU_NOMATCH("TST1-a")
  746. TEST_CGPU_NOMATCH("TST1c-z")
  747. TEST_CGPU_NOMATCH("TST1c-")
  748. TEST_CGPU_MATCH("@")
  749. TEST_CGPU_NOMATCH("@abc")
  750. TEST_CGPU_MATCH("@@b")
  751. TEST_CGPU_NOMATCH("@@c")
  752. TEST_CGPU_MATCH("TST@")
  753. TEST_CGPU_NOMATCH("TST@abc")
  754. TEST_CGPU_MATCH("TST@@b")
  755. TEST_CGPU_NOMATCH("TST@@c")
  756. TEST_CGPU_MATCH("TST@@b-f")
  757. TEST_CGPU_NOMATCH("TST@@c-f")
  758. TEST_CGPU_NOMATCH("TST@@-a")
  759. cgpu.device_path = "/dev/test";
  760. cgpu.dev_serial = "testy";
  761. TEST_CGPU_MATCH("TST@/dev/test")
  762. TEST_CGPU_MATCH("TST@testy")
  763. TEST_CGPU_NOMATCH("TST@")
  764. TEST_CGPU_NOMATCH("TST@/dev/test5@b")
  765. TEST_CGPU_NOMATCH("TST@testy3@b")
  766. TEST_CGPU_MATCH("TST@/dev/test@b")
  767. TEST_CGPU_MATCH("TST@testy@b")
  768. TEST_CGPU_NOMATCH("TST@/dev/test@c")
  769. TEST_CGPU_NOMATCH("TST@testy@c")
  770. cgpu.device_path = "usb:000:999";
  771. TEST_CGPU_MATCH("TST@usb:000:999")
  772. drv.dname = "test7";
  773. TEST_CGPU_MATCH("test7")
  774. TEST_CGPU_MATCH("TEST7")
  775. TEST_CGPU_NOMATCH("test&")
  776. TEST_CGPU_MATCH("test7 1-2")
  777. TEST_CGPU_MATCH("test7@testy@b")
  778. }
  779. static
  780. int cgpu_search(const char * const pattern, const int first)
  781. {
  782. int i;
  783. struct cgpu_info *cgpu;
  784. #define CHECK_CGPU_SEARCH do{ \
  785. cgpu = get_devices(i); \
  786. if (cgpu_match(pattern, cgpu)) \
  787. return i; \
  788. }while(0)
  789. for (i = first; i < total_devices; ++i)
  790. CHECK_CGPU_SEARCH;
  791. for (i = 0; i < first; ++i)
  792. CHECK_CGPU_SEARCH;
  793. #undef CHECK_CGPU_SEARCH
  794. return -1;
  795. }
  796. static pthread_mutex_t sharelog_lock;
  797. static FILE *sharelog_file = NULL;
  798. struct thr_info *get_thread(int thr_id)
  799. {
  800. struct thr_info *thr;
  801. rd_lock(&mining_thr_lock);
  802. thr = mining_thr[thr_id];
  803. rd_unlock(&mining_thr_lock);
  804. return thr;
  805. }
  806. static struct cgpu_info *get_thr_cgpu(int thr_id)
  807. {
  808. struct thr_info *thr = get_thread(thr_id);
  809. return thr->cgpu;
  810. }
  811. struct cgpu_info *get_devices(int id)
  812. {
  813. struct cgpu_info *cgpu;
  814. rd_lock(&devices_lock);
  815. cgpu = devices[id];
  816. rd_unlock(&devices_lock);
  817. return cgpu;
  818. }
  819. static pthread_mutex_t noncelog_lock = PTHREAD_MUTEX_INITIALIZER;
  820. static FILE *noncelog_file = NULL;
  821. static
  822. void noncelog(const struct work * const work)
  823. {
  824. const int thr_id = work->thr_id;
  825. const struct cgpu_info *proc = get_thr_cgpu(thr_id);
  826. char buf[0x200], hash[65], data[161], midstate[65];
  827. int rv;
  828. size_t ret;
  829. bin2hex(hash, work->hash, 32);
  830. bin2hex(data, work->data, 80);
  831. bin2hex(midstate, work->midstate, 32);
  832. // timestamp,proc,hash,data,midstate
  833. rv = snprintf(buf, sizeof(buf), "%lu,%s,%s,%s,%s\n",
  834. (unsigned long)time(NULL), proc->proc_repr_ns,
  835. hash, data, midstate);
  836. if (unlikely(rv < 1))
  837. {
  838. applog(LOG_ERR, "noncelog printf error");
  839. return;
  840. }
  841. mutex_lock(&noncelog_lock);
  842. ret = fwrite(buf, rv, 1, noncelog_file);
  843. fflush(noncelog_file);
  844. mutex_unlock(&noncelog_lock);
  845. if (ret != 1)
  846. applog(LOG_ERR, "noncelog fwrite error");
  847. }
  848. static void sharelog(const char*disposition, const struct work*work)
  849. {
  850. char target[(sizeof(work->target) * 2) + 1];
  851. char hash[(sizeof(work->hash) * 2) + 1];
  852. char data[(sizeof(work->data) * 2) + 1];
  853. struct cgpu_info *cgpu;
  854. unsigned long int t;
  855. struct pool *pool;
  856. int thr_id, rv;
  857. char s[1024];
  858. size_t ret;
  859. if (!sharelog_file)
  860. return;
  861. thr_id = work->thr_id;
  862. cgpu = get_thr_cgpu(thr_id);
  863. pool = work->pool;
  864. t = work->ts_getwork + timer_elapsed(&work->tv_getwork, &work->tv_work_found);
  865. bin2hex(target, work->target, sizeof(work->target));
  866. bin2hex(hash, work->hash, sizeof(work->hash));
  867. bin2hex(data, work->data, sizeof(work->data));
  868. // timestamp,disposition,target,pool,dev,thr,sharehash,sharedata
  869. 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);
  870. if (rv >= (int)(sizeof(s)))
  871. s[sizeof(s) - 1] = '\0';
  872. else if (rv < 0) {
  873. applog(LOG_ERR, "sharelog printf error");
  874. return;
  875. }
  876. mutex_lock(&sharelog_lock);
  877. ret = fwrite(s, rv, 1, sharelog_file);
  878. fflush(sharelog_file);
  879. mutex_unlock(&sharelog_lock);
  880. if (ret != 1)
  881. applog(LOG_ERR, "sharelog fwrite error");
  882. }
  883. #ifdef HAVE_CURSES
  884. static void switch_logsize(void);
  885. #endif
  886. static
  887. void goal_set_malgo(struct mining_goal_info * const goal, struct mining_algorithm * const malgo)
  888. {
  889. if (goal->malgo == malgo)
  890. return;
  891. if (goal->malgo)
  892. --goal->malgo->goal_refs;
  893. ++malgo->goal_refs;
  894. goal->malgo = malgo;
  895. }
  896. static struct mining_algorithm malgo_sha256d = {
  897. .algo = POW_SHA256D,
  898. .ui_skip_hash_bytes = 4,
  899. .worktime_skip_prevblk_u32 = 1,
  900. .reasonable_low_nonce_diff = 1.,
  901. .hash_data_f = hash_data,
  902. };
  903. #ifdef USE_SCRYPT
  904. static struct mining_algorithm malgo_scrypt = {
  905. .algo = POW_SCRYPT,
  906. .ui_skip_hash_bytes = 2,
  907. .reasonable_low_nonce_diff = 1./0x10000,
  908. .hash_data_f = scrypt_hash_data,
  909. };
  910. static
  911. const char *set_malgo_scrypt()
  912. {
  913. goal_set_malgo(get_mining_goal("default"), &malgo_scrypt);
  914. return NULL;
  915. }
  916. #endif
  917. static
  918. __attribute__((constructor))
  919. void init_mining_goals(struct mining_goal_info * const goal, const struct mining_algorithm * const malgo)
  920. {
  921. LL_APPEND(mining_algorithms, (&malgo_sha256d));
  922. #ifdef USE_SCRYPT
  923. LL_APPEND(mining_algorithms, (&malgo_scrypt));
  924. #endif
  925. }
  926. static
  927. int mining_goals_name_cmp(const struct mining_goal_info * const a, const struct mining_goal_info * const b)
  928. {
  929. // default always goes first
  930. if (a->is_default)
  931. return -1;
  932. if (b->is_default)
  933. return 1;
  934. return strcmp(a->name, b->name);
  935. }
  936. static
  937. void blkchain_init_block(struct blockchain_info * const blkchain)
  938. {
  939. struct block_info * const dummy_block = calloc(sizeof(*dummy_block), 1);
  940. memset(dummy_block->prevblkhash, 0, 0x20);
  941. HASH_ADD(hh, blkchain->blocks, prevblkhash, sizeof(dummy_block->prevblkhash), dummy_block);
  942. blkchain->currentblk = dummy_block;
  943. }
  944. struct mining_goal_info *get_mining_goal(const char * const name)
  945. {
  946. static unsigned next_goal_id;
  947. struct mining_goal_info *goal;
  948. HASH_FIND_STR(mining_goals, name, goal);
  949. if (!goal)
  950. {
  951. struct blockchain_info * const blkchain = malloc(sizeof(*blkchain) + sizeof(*goal));
  952. goal = (void*)(&blkchain[1]);
  953. *blkchain = (struct blockchain_info){
  954. .currentblk = NULL,
  955. };
  956. blkchain_init_block(blkchain);
  957. *goal = (struct mining_goal_info){
  958. .id = next_goal_id++,
  959. .name = strdup(name),
  960. .is_default = !strcmp(name, "default"),
  961. .blkchain = blkchain,
  962. .current_diff = 0xFFFFFFFFFFFFFFFFULL,
  963. };
  964. goal_set_malgo(goal, &malgo_sha256d);
  965. HASH_ADD_STR(mining_goals, name, goal);
  966. HASH_SORT(mining_goals, mining_goals_name_cmp);
  967. #ifdef HAVE_CURSES
  968. devcursor = 7 + active_goals;
  969. switch_logsize();
  970. #endif
  971. }
  972. return goal;
  973. }
  974. void mining_goal_reset(struct mining_goal_info * const goal)
  975. {
  976. struct blockchain_info * const blkchain = goal->blkchain;
  977. struct block_info *blkinfo, *tmpblkinfo;
  978. HASH_ITER(hh, blkchain->blocks, blkinfo, tmpblkinfo)
  979. {
  980. HASH_DEL(blkchain->blocks, blkinfo);
  981. free(blkinfo);
  982. }
  983. blkchain_init_block(blkchain);
  984. }
  985. static char *getwork_req = "{\"method\": \"getwork\", \"params\": [], \"id\":0}\n";
  986. /* Adjust all the pools' quota to the greatest common denominator after a pool
  987. * has been added or the quotas changed. */
  988. void adjust_quota_gcd(void)
  989. {
  990. unsigned long gcd, lowest_quota = ~0UL, quota;
  991. struct pool *pool;
  992. int i;
  993. for (i = 0; i < total_pools; i++) {
  994. pool = pools[i];
  995. quota = pool->quota;
  996. if (!quota)
  997. continue;
  998. if (quota < lowest_quota)
  999. lowest_quota = quota;
  1000. }
  1001. if (likely(lowest_quota < ~0UL)) {
  1002. gcd = lowest_quota;
  1003. for (i = 0; i < total_pools; i++) {
  1004. pool = pools[i];
  1005. quota = pool->quota;
  1006. if (!quota)
  1007. continue;
  1008. while (quota % gcd)
  1009. gcd--;
  1010. }
  1011. } else
  1012. gcd = 1;
  1013. for (i = 0; i < total_pools; i++) {
  1014. pool = pools[i];
  1015. pool->quota_used *= global_quota_gcd;
  1016. pool->quota_used /= gcd;
  1017. pool->quota_gcd = pool->quota / gcd;
  1018. }
  1019. global_quota_gcd = gcd;
  1020. applog(LOG_DEBUG, "Global quota greatest common denominator set to %lu", gcd);
  1021. }
  1022. /* Return value is ignored if not called from add_pool_details */
  1023. struct pool *add_pool2(struct mining_goal_info * const goal)
  1024. {
  1025. struct pool *pool;
  1026. pool = calloc(sizeof(struct pool), 1);
  1027. if (!pool)
  1028. quit(1, "Failed to malloc pool in add_pool");
  1029. pool->pool_no = pool->prio = total_pools;
  1030. mutex_init(&pool->last_work_lock);
  1031. mutex_init(&pool->pool_lock);
  1032. mutex_init(&pool->pool_test_lock);
  1033. if (unlikely(pthread_cond_init(&pool->cr_cond, bfg_condattr)))
  1034. quit(1, "Failed to pthread_cond_init in add_pool");
  1035. cglock_init(&pool->data_lock);
  1036. mutex_init(&pool->stratum_lock);
  1037. timer_unset(&pool->swork.tv_transparency);
  1038. pool->swork.pool = pool;
  1039. pool->goal = goal;
  1040. pool->idle = true;
  1041. /* Make sure the pool doesn't think we've been idle since time 0 */
  1042. pool->tv_idle.tv_sec = ~0UL;
  1043. cgtime(&pool->cgminer_stats.start_tv);
  1044. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  1045. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  1046. pool->rpc_proxy = NULL;
  1047. pool->quota = 1;
  1048. pool->sock = INVSOCK;
  1049. pool->lp_socket = CURL_SOCKET_BAD;
  1050. pools = realloc(pools, sizeof(struct pool *) * (total_pools + 2));
  1051. pools[total_pools++] = pool;
  1052. if (opt_benchmark)
  1053. {
  1054. // Immediately remove it
  1055. remove_pool(pool);
  1056. return pool;
  1057. }
  1058. adjust_quota_gcd();
  1059. if (!currentpool)
  1060. currentpool = pool;
  1061. enable_pool(pool);
  1062. return pool;
  1063. }
  1064. static
  1065. void pool_set_uri(struct pool * const pool, char * const uri)
  1066. {
  1067. pool->rpc_url = uri;
  1068. }
  1069. /* Pool variant of test and set */
  1070. static bool pool_tset(struct pool *pool, bool *var)
  1071. {
  1072. bool ret;
  1073. mutex_lock(&pool->pool_lock);
  1074. ret = *var;
  1075. *var = true;
  1076. mutex_unlock(&pool->pool_lock);
  1077. return ret;
  1078. }
  1079. bool pool_tclear(struct pool *pool, bool *var)
  1080. {
  1081. bool ret;
  1082. mutex_lock(&pool->pool_lock);
  1083. ret = *var;
  1084. *var = false;
  1085. mutex_unlock(&pool->pool_lock);
  1086. return ret;
  1087. }
  1088. struct pool *current_pool(void)
  1089. {
  1090. struct pool *pool;
  1091. cg_rlock(&control_lock);
  1092. pool = currentpool;
  1093. cg_runlock(&control_lock);
  1094. return pool;
  1095. }
  1096. static
  1097. char *set_bool_ignore_arg(const char * const arg, bool * const b)
  1098. {
  1099. return opt_set_bool(b);
  1100. }
  1101. char *set_int_range(const char *arg, int *i, int min, int max)
  1102. {
  1103. char *err = opt_set_intval(arg, i);
  1104. if (err)
  1105. return err;
  1106. if (*i < min || *i > max)
  1107. return "Value out of range";
  1108. return NULL;
  1109. }
  1110. static char *set_int_0_to_9999(const char *arg, int *i)
  1111. {
  1112. return set_int_range(arg, i, 0, 9999);
  1113. }
  1114. static char *set_int_1_to_65535(const char *arg, int *i)
  1115. {
  1116. return set_int_range(arg, i, 1, 65535);
  1117. }
  1118. static char *set_int_0_to_10(const char *arg, int *i)
  1119. {
  1120. return set_int_range(arg, i, 0, 10);
  1121. }
  1122. static char *set_int_1_to_10(const char *arg, int *i)
  1123. {
  1124. return set_int_range(arg, i, 1, 10);
  1125. }
  1126. char *set_strdup(const char *arg, char **p)
  1127. {
  1128. *p = strdup((char *)arg);
  1129. return NULL;
  1130. }
  1131. #if BLKMAKER_VERSION > 1
  1132. static
  1133. char *set_b58addr(const char * const arg, bytes_t * const b)
  1134. {
  1135. size_t scriptsz = blkmk_address_to_script(NULL, 0, arg);
  1136. if (!scriptsz)
  1137. return "Invalid address";
  1138. char *script = malloc(scriptsz);
  1139. if (blkmk_address_to_script(script, scriptsz, arg) != scriptsz) {
  1140. free(script);
  1141. return "Failed to convert address to script";
  1142. }
  1143. bytes_assimilate_raw(b, script, scriptsz, scriptsz);
  1144. return NULL;
  1145. }
  1146. static char *set_generate_addr2(struct mining_goal_info *, const char *);
  1147. static
  1148. char *set_generate_addr(char *arg)
  1149. {
  1150. char * const colon = strchr(arg, ':');
  1151. struct mining_goal_info *goal;
  1152. if (colon)
  1153. {
  1154. colon[0] = '\0';
  1155. goal = get_mining_goal(arg);
  1156. arg = &colon[1];
  1157. }
  1158. else
  1159. goal = get_mining_goal("default");
  1160. return set_generate_addr2(goal, arg);
  1161. }
  1162. static
  1163. char *set_generate_addr2(struct mining_goal_info * const goal, const char * const arg)
  1164. {
  1165. bytes_t newscript = BYTES_INIT;
  1166. char *estr = set_b58addr(arg, &newscript);
  1167. if (estr)
  1168. {
  1169. bytes_free(&newscript);
  1170. return estr;
  1171. }
  1172. if (!goal->generation_script)
  1173. {
  1174. goal->generation_script = malloc(sizeof(*goal->generation_script));
  1175. bytes_init(goal->generation_script);
  1176. }
  1177. bytes_assimilate(goal->generation_script, &newscript);
  1178. bytes_free(&newscript);
  1179. return NULL;
  1180. }
  1181. #endif
  1182. static
  1183. char *set_quit_summary(const char * const arg)
  1184. {
  1185. if (!(strcasecmp(arg, "none") && strcasecmp(arg, "no")))
  1186. opt_quit_summary = BQS_NONE;
  1187. else
  1188. if (!(strcasecmp(arg, "devs") && strcasecmp(arg, "devices")))
  1189. opt_quit_summary = BQS_DEVS;
  1190. else
  1191. if (!(strcasecmp(arg, "procs") && strcasecmp(arg, "processors") && strcasecmp(arg, "chips") && strcasecmp(arg, "cores")))
  1192. opt_quit_summary = BQS_PROCS;
  1193. else
  1194. if (!(strcasecmp(arg, "detailed") && strcasecmp(arg, "detail") && strcasecmp(arg, "all")))
  1195. opt_quit_summary = BQS_DETAILED;
  1196. else
  1197. return "Quit summary must be one of none/devs/procs/detailed";
  1198. return NULL;
  1199. }
  1200. static void pdiff_target_leadzero(void *, double);
  1201. char *set_request_diff(const char *arg, float *p)
  1202. {
  1203. unsigned char target[32];
  1204. char *e = opt_set_floatval(arg, p);
  1205. if (e)
  1206. return e;
  1207. request_bdiff = (double)*p * 0.9999847412109375;
  1208. pdiff_target_leadzero(target, *p);
  1209. request_target_str = malloc(65);
  1210. bin2hex(request_target_str, target, 32);
  1211. return NULL;
  1212. }
  1213. #ifdef NEED_BFG_LOWL_VCOM
  1214. extern struct lowlevel_device_info *_vcom_devinfo_findorcreate(struct lowlevel_device_info **, const char *);
  1215. #ifdef WIN32
  1216. void _vcom_devinfo_scan_querydosdevice(struct lowlevel_device_info ** const devinfo_list)
  1217. {
  1218. char dev[PATH_MAX];
  1219. char *devp = dev;
  1220. size_t bufLen = 0x100;
  1221. tryagain: ;
  1222. char buf[bufLen];
  1223. if (!QueryDosDevice(NULL, buf, bufLen)) {
  1224. if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
  1225. bufLen *= 2;
  1226. applog(LOG_DEBUG, "QueryDosDevice returned insufficent buffer error; enlarging to %lx", (unsigned long)bufLen);
  1227. goto tryagain;
  1228. }
  1229. applogr(, LOG_WARNING, "Error occurred trying to enumerate COM ports with QueryDosDevice");
  1230. }
  1231. size_t tLen;
  1232. memcpy(devp, "\\\\.\\", 4);
  1233. devp = &devp[4];
  1234. for (char *t = buf; *t; t += tLen) {
  1235. tLen = strlen(t) + 1;
  1236. if (strncmp("COM", t, 3))
  1237. continue;
  1238. memcpy(devp, t, tLen);
  1239. // NOTE: We depend on _vcom_devinfo_findorcreate to further check that there's a number (and only a number) on the end
  1240. _vcom_devinfo_findorcreate(devinfo_list, dev);
  1241. }
  1242. }
  1243. #else
  1244. void _vcom_devinfo_scan_lsdev(struct lowlevel_device_info ** const devinfo_list)
  1245. {
  1246. char dev[PATH_MAX];
  1247. char *devp = dev;
  1248. DIR *D;
  1249. struct dirent *de;
  1250. const char devdir[] = "/dev";
  1251. const size_t devdirlen = sizeof(devdir) - 1;
  1252. char *devpath = devp;
  1253. char *devfile = devpath + devdirlen + 1;
  1254. D = opendir(devdir);
  1255. if (!D)
  1256. applogr(, LOG_DEBUG, "No /dev directory to look for VCOM devices in");
  1257. memcpy(devpath, devdir, devdirlen);
  1258. devpath[devdirlen] = '/';
  1259. while ( (de = readdir(D)) ) {
  1260. if (!strncmp(de->d_name, "cu.", 3)
  1261. //don't probe Bluetooth devices - causes bus errors and segfaults
  1262. && strncmp(de->d_name, "cu.Bluetooth", 12))
  1263. goto trydev;
  1264. if (strncmp(de->d_name, "tty", 3))
  1265. continue;
  1266. if (strncmp(&de->d_name[3], "USB", 3) && strncmp(&de->d_name[3], "ACM", 3))
  1267. continue;
  1268. trydev:
  1269. strcpy(devfile, de->d_name);
  1270. _vcom_devinfo_findorcreate(devinfo_list, dev);
  1271. }
  1272. closedir(D);
  1273. }
  1274. #endif
  1275. #endif
  1276. static char *add_serial(const char *arg)
  1277. {
  1278. string_elist_add(arg, &scan_devices);
  1279. return NULL;
  1280. }
  1281. static
  1282. char *opt_string_elist_add(const char *arg, struct string_elist **elist)
  1283. {
  1284. string_elist_add(arg, elist);
  1285. return NULL;
  1286. }
  1287. bool get_intrange(const char *arg, int *val1, int *val2)
  1288. {
  1289. // NOTE: This could be done with sscanf, but its %n is broken in strange ways on Windows
  1290. char *p, *p2;
  1291. *val1 = strtol(arg, &p, 0);
  1292. if (arg == p)
  1293. // Zero-length ending number, invalid
  1294. return false;
  1295. while (true)
  1296. {
  1297. if (!p[0])
  1298. {
  1299. *val2 = *val1;
  1300. return true;
  1301. }
  1302. if (p[0] == '-')
  1303. break;
  1304. if (!isspace(p[0]))
  1305. // Garbage, invalid
  1306. return false;
  1307. ++p;
  1308. }
  1309. p2 = &p[1];
  1310. *val2 = strtol(p2, &p, 0);
  1311. if (p2 == p)
  1312. // Zero-length ending number, invalid
  1313. return false;
  1314. while (true)
  1315. {
  1316. if (!p[0])
  1317. return true;
  1318. if (!isspace(p[0]))
  1319. // Garbage, invalid
  1320. return false;
  1321. ++p;
  1322. }
  1323. }
  1324. static
  1325. void _test_intrange(const char *s, const int v[2])
  1326. {
  1327. int a[2];
  1328. if (!get_intrange(s, &a[0], &a[1]))
  1329. {
  1330. ++unittest_failures;
  1331. applog(LOG_ERR, "Test \"%s\" failed: returned false", s);
  1332. }
  1333. for (int i = 0; i < 2; ++i)
  1334. if (unlikely(a[i] != v[i]))
  1335. {
  1336. ++unittest_failures;
  1337. applog(LOG_ERR, "Test \"%s\" failed: value %d should be %d but got %d", s, i, v[i], a[i]);
  1338. }
  1339. }
  1340. #define _test_intrange(s, ...) _test_intrange(s, (int[]){ __VA_ARGS__ })
  1341. static
  1342. void _test_intrange_fail(const char *s)
  1343. {
  1344. int a[2];
  1345. if (get_intrange(s, &a[0], &a[1]))
  1346. {
  1347. ++unittest_failures;
  1348. applog(LOG_ERR, "Test !\"%s\" failed: returned true with %d and %d", s, a[0], a[1]);
  1349. }
  1350. }
  1351. static
  1352. void test_intrange()
  1353. {
  1354. _test_intrange("-1--2", -1, -2);
  1355. _test_intrange("-1-2", -1, 2);
  1356. _test_intrange("1--2", 1, -2);
  1357. _test_intrange("1-2", 1, 2);
  1358. _test_intrange("111-222", 111, 222);
  1359. _test_intrange(" 11 - 22 ", 11, 22);
  1360. _test_intrange("+11-+22", 11, 22);
  1361. _test_intrange("-1", -1, -1);
  1362. _test_intrange_fail("all");
  1363. _test_intrange_fail("1-");
  1364. _test_intrange_fail("");
  1365. _test_intrange_fail("1-54x");
  1366. }
  1367. static char *set_devices(char *arg)
  1368. {
  1369. if (*arg) {
  1370. if (*arg == '?') {
  1371. opt_display_devs = true;
  1372. return NULL;
  1373. }
  1374. } else
  1375. return "Invalid device parameters";
  1376. string_elist_add(arg, &opt_devices_enabled_list);
  1377. return NULL;
  1378. }
  1379. static char *set_balance(enum pool_strategy *strategy)
  1380. {
  1381. *strategy = POOL_BALANCE;
  1382. return NULL;
  1383. }
  1384. static char *set_loadbalance(enum pool_strategy *strategy)
  1385. {
  1386. *strategy = POOL_LOADBALANCE;
  1387. return NULL;
  1388. }
  1389. static char *set_rotate(const char *arg, int *i)
  1390. {
  1391. pool_strategy = POOL_ROTATE;
  1392. return set_int_range(arg, i, 0, 9999);
  1393. }
  1394. static char *set_rr(enum pool_strategy *strategy)
  1395. {
  1396. *strategy = POOL_ROUNDROBIN;
  1397. return NULL;
  1398. }
  1399. static
  1400. char *set_benchmark_intense()
  1401. {
  1402. opt_benchmark = true;
  1403. opt_benchmark_intense = true;
  1404. return NULL;
  1405. }
  1406. /* Detect that url is for a stratum protocol either via the presence of
  1407. * stratum+tcp or by detecting a stratum server response */
  1408. bool detect_stratum(struct pool *pool, char *url)
  1409. {
  1410. if (!extract_sockaddr(url, &pool->sockaddr_url, &pool->stratum_port))
  1411. return false;
  1412. if (!strncasecmp(url, "stratum+tcp://", 14)) {
  1413. pool_set_uri(pool, strdup(url));
  1414. pool->has_stratum = true;
  1415. pool->stratum_url = pool->sockaddr_url;
  1416. return true;
  1417. }
  1418. return false;
  1419. }
  1420. static struct pool *add_url(void)
  1421. {
  1422. total_urls++;
  1423. if (total_urls > total_pools)
  1424. add_pool();
  1425. return pools[total_urls - 1];
  1426. }
  1427. static void setup_url(struct pool *pool, char *arg)
  1428. {
  1429. if (detect_stratum(pool, arg))
  1430. return;
  1431. opt_set_charp(arg, &pool->rpc_url);
  1432. if (strncmp(arg, "http://", 7) &&
  1433. strncmp(arg, "https://", 8)) {
  1434. const size_t L = strlen(arg);
  1435. char *httpinput;
  1436. httpinput = malloc(8 + L);
  1437. if (!httpinput)
  1438. quit(1, "Failed to malloc httpinput");
  1439. sprintf(httpinput, "http://%s", arg);
  1440. pool_set_uri(pool, httpinput);
  1441. }
  1442. }
  1443. static char *set_url(char *arg)
  1444. {
  1445. struct pool *pool = add_url();
  1446. setup_url(pool, arg);
  1447. return NULL;
  1448. }
  1449. static char *set_quota(char *arg)
  1450. {
  1451. char *semicolon = strchr(arg, ';'), *url;
  1452. int len, qlen, quota;
  1453. struct pool *pool;
  1454. if (!semicolon)
  1455. return "No semicolon separated quota;URL pair found";
  1456. len = strlen(arg);
  1457. *semicolon = '\0';
  1458. qlen = strlen(arg);
  1459. if (!qlen)
  1460. return "No parameter for quota found";
  1461. len -= qlen + 1;
  1462. if (len < 1)
  1463. return "No parameter for URL found";
  1464. quota = atoi(arg);
  1465. if (quota < 0)
  1466. return "Invalid negative parameter for quota set";
  1467. url = arg + qlen + 1;
  1468. pool = add_url();
  1469. setup_url(pool, url);
  1470. pool->quota = quota;
  1471. applog(LOG_INFO, "Setting pool %d to quota %d", pool->pool_no, pool->quota);
  1472. adjust_quota_gcd();
  1473. return NULL;
  1474. }
  1475. static char *set_user(const char *arg)
  1476. {
  1477. struct pool *pool;
  1478. total_users++;
  1479. if (total_users > total_pools)
  1480. add_pool();
  1481. pool = pools[total_users - 1];
  1482. opt_set_charp(arg, &pool->rpc_user);
  1483. return NULL;
  1484. }
  1485. static char *set_pass(const char *arg)
  1486. {
  1487. struct pool *pool;
  1488. total_passes++;
  1489. if (total_passes > total_pools)
  1490. add_pool();
  1491. pool = pools[total_passes - 1];
  1492. opt_set_charp(arg, &pool->rpc_pass);
  1493. return NULL;
  1494. }
  1495. static char *set_userpass(const char *arg)
  1496. {
  1497. struct pool *pool;
  1498. char *updup;
  1499. if (total_users != total_passes)
  1500. return "User + pass options must be balanced before userpass";
  1501. ++total_users;
  1502. ++total_passes;
  1503. if (total_users > total_pools)
  1504. add_pool();
  1505. pool = pools[total_users - 1];
  1506. updup = strdup(arg);
  1507. opt_set_charp(arg, &pool->rpc_userpass);
  1508. pool->rpc_user = updup;
  1509. pool->rpc_pass = strchr(updup, ':');
  1510. if (pool->rpc_pass)
  1511. pool->rpc_pass++[0] = '\0';
  1512. else
  1513. pool->rpc_pass = &updup[strlen(updup)];
  1514. return NULL;
  1515. }
  1516. static char *set_cbcaddr(char *arg)
  1517. {
  1518. struct pool *pool;
  1519. char *p, *addr;
  1520. bytes_t target_script = BYTES_INIT;
  1521. if (!total_pools)
  1522. return "Define pool first, then the --coinbase-check-addr list";
  1523. pool = pools[total_pools - 1];
  1524. /* NOTE: 'x' is a new prefix which leads both mainnet and testnet address, we would
  1525. * need support it later, but now leave the code just so.
  1526. *
  1527. * Regarding details of address prefix 'x', check the below URL:
  1528. * https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#Serialization_format
  1529. */
  1530. pool->cb_param.testnet = (arg[0] != '1' && arg[0] != '3' && arg[0] != 'x');
  1531. for (; (addr = strtok_r(arg, ",", &p)); arg = NULL)
  1532. {
  1533. struct bytes_hashtbl *ah;
  1534. if (set_b58addr(addr, &target_script))
  1535. /* No bother to free memory since we are going to exit anyway */
  1536. return "Invalid address in --coinbase-check-address list";
  1537. HASH_FIND(hh, pool->cb_param.scripts, bytes_buf(&target_script), bytes_len(&target_script), ah);
  1538. if (!ah)
  1539. {
  1540. /* Note: for the below allocated memory we have good way to release its memory
  1541. * since we can't be sure there are no reference to the pool struct when remove_pool()
  1542. * get called.
  1543. *
  1544. * We just hope the remove_pool() would not be called many many times during
  1545. * the whole running life of this program.
  1546. */
  1547. ah = malloc(sizeof(*ah));
  1548. bytes_init(&ah->b);
  1549. bytes_assimilate(&ah->b, &target_script);
  1550. HASH_ADD(hh, pool->cb_param.scripts, b.buf, bytes_len(&ah->b), ah);
  1551. }
  1552. }
  1553. bytes_free(&target_script);
  1554. return NULL;
  1555. }
  1556. static char *set_cbctotal(const char *arg)
  1557. {
  1558. struct pool *pool;
  1559. if (!total_pools)
  1560. return "Define pool first, then the --coinbase-check-total argument";
  1561. pool = pools[total_pools - 1];
  1562. pool->cb_param.total = atoll(arg);
  1563. if (pool->cb_param.total < 0)
  1564. return "The total payout amount in coinbase should be greater than 0";
  1565. return NULL;
  1566. }
  1567. static char *set_cbcperc(const char *arg)
  1568. {
  1569. struct pool *pool;
  1570. if (!total_pools)
  1571. return "Define pool first, then the --coinbase-check-percent argument";
  1572. pool = pools[total_pools - 1];
  1573. if (!pool->cb_param.scripts)
  1574. return "Define --coinbase-check-addr list first, then the --coinbase-check-total argument";
  1575. pool->cb_param.perc = atof(arg) / 100;
  1576. if (pool->cb_param.perc < 0.0 || pool->cb_param.perc > 1.0)
  1577. return "The percentage should be between 0 and 100";
  1578. return NULL;
  1579. }
  1580. static
  1581. 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)
  1582. {
  1583. *out_success = SDR_ERR;
  1584. if (!(strcasecmp(optname, "malgo") && strcasecmp(optname, "algo")))
  1585. {
  1586. if (!newvalue)
  1587. return "Goal option 'malgo' requires a value (eg, SHA256d)";
  1588. struct mining_algorithm *new_malgo;
  1589. if (!(strcasecmp(newvalue, "SHA256d") && strcasecmp(newvalue, "SHA256") && strcasecmp(newvalue, "SHA2")))
  1590. new_malgo = &malgo_sha256d;
  1591. #ifdef USE_SCRYPT
  1592. else
  1593. if (!strcasecmp(newvalue, "scrypt"))
  1594. new_malgo = &malgo_scrypt;
  1595. #endif
  1596. else
  1597. return "Unrecognised mining algorithm";
  1598. goal_set_malgo(goal, new_malgo);
  1599. goto success;
  1600. }
  1601. #if BLKMAKER_VERSION > 1
  1602. 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))
  1603. {
  1604. if (!newvalue)
  1605. return "Missing value for 'generate-to' goal option";
  1606. const char * const emsg = set_generate_addr2(goal, newvalue);
  1607. if (emsg)
  1608. return emsg;
  1609. goto success;
  1610. }
  1611. #endif
  1612. *out_success = SDR_UNKNOWN;
  1613. return "Unknown goal option";
  1614. success:
  1615. *out_success = SDR_OK;
  1616. return NULL;
  1617. }
  1618. // May leak replybuf if returning an error
  1619. static
  1620. const char *set_goal_params(struct mining_goal_info * const goal, char *arg)
  1621. {
  1622. bytes_t replybuf = BYTES_INIT;
  1623. for (char *param, *nextptr; (param = strtok_r(arg, ",", &nextptr)); arg = NULL)
  1624. {
  1625. char *val = strchr(param, '=');
  1626. if (val)
  1627. val++[0] = '\0';
  1628. enum bfg_set_device_replytype success;
  1629. const char * const emsg = goal_set(goal, param, val, &replybuf, &success);
  1630. if (success != SDR_OK)
  1631. return emsg ?: "Error setting goal param";
  1632. }
  1633. bytes_free(&replybuf);
  1634. return NULL;
  1635. }
  1636. static
  1637. const char *set_pool_goal(const char * const arg)
  1638. {
  1639. struct pool *pool;
  1640. if (!total_pools)
  1641. return "Usage of --pool-goal before pools are defined does not make sense";
  1642. pool = pools[total_pools - 1];
  1643. char *param = strchr(arg, ':');
  1644. if (param)
  1645. param++[0] = '\0';
  1646. pool->goal = get_mining_goal(arg);
  1647. if (param)
  1648. return set_goal_params(pool->goal, param);
  1649. return NULL;
  1650. }
  1651. static char *set_pool_priority(const char *arg)
  1652. {
  1653. struct pool *pool;
  1654. if (!total_pools)
  1655. return "Usage of --pool-priority before pools are defined does not make sense";
  1656. pool = pools[total_pools - 1];
  1657. opt_set_intval(arg, &pool->prio);
  1658. return NULL;
  1659. }
  1660. static char *set_pool_proxy(const char *arg)
  1661. {
  1662. struct pool *pool;
  1663. if (!total_pools)
  1664. return "Usage of --pool-proxy before pools are defined does not make sense";
  1665. if (!our_curl_supports_proxy_uris())
  1666. return "Your installed cURL library does not support proxy URIs. At least version 7.21.7 is required.";
  1667. pool = pools[total_pools - 1];
  1668. opt_set_charp(arg, &pool->rpc_proxy);
  1669. return NULL;
  1670. }
  1671. static char *set_pool_force_rollntime(const char *arg)
  1672. {
  1673. struct pool *pool;
  1674. if (!total_pools)
  1675. return "Usage of --force-rollntime before pools are defined does not make sense";
  1676. pool = pools[total_pools - 1];
  1677. opt_set_intval(arg, &pool->force_rollntime);
  1678. return NULL;
  1679. }
  1680. static char *enable_debug(bool *flag)
  1681. {
  1682. *flag = true;
  1683. opt_debug_console = true;
  1684. /* Turn on verbose output, too. */
  1685. opt_log_output = true;
  1686. return NULL;
  1687. }
  1688. static char *set_schedtime(const char *arg, struct schedtime *st)
  1689. {
  1690. if (sscanf(arg, "%d:%d", &st->tm.tm_hour, &st->tm.tm_min) != 2)
  1691. {
  1692. if (strcasecmp(arg, "now"))
  1693. return "Invalid time set, should be HH:MM";
  1694. } else
  1695. schedstop.tm.tm_sec = 0;
  1696. if (st->tm.tm_hour > 23 || st->tm.tm_min > 59 || st->tm.tm_hour < 0 || st->tm.tm_min < 0)
  1697. return "Invalid time set.";
  1698. st->enable = true;
  1699. return NULL;
  1700. }
  1701. static
  1702. char *set_log_file(char *arg)
  1703. {
  1704. char *r = "";
  1705. long int i = strtol(arg, &r, 10);
  1706. int fd, stderr_fd = fileno(stderr);
  1707. if ((!*r) && i >= 0 && i <= INT_MAX)
  1708. fd = i;
  1709. else
  1710. if (!strcmp(arg, "-"))
  1711. {
  1712. fd = fileno(stdout);
  1713. if (unlikely(fd == -1))
  1714. return "Standard output missing for log-file";
  1715. }
  1716. else
  1717. {
  1718. fd = open(arg, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR);
  1719. if (unlikely(fd == -1))
  1720. return "Failed to open log-file";
  1721. }
  1722. close(stderr_fd);
  1723. if (unlikely(-1 == dup2(fd, stderr_fd)))
  1724. return "Failed to dup2 for log-file";
  1725. close(fd);
  1726. return NULL;
  1727. }
  1728. static
  1729. char *_bfgopt_set_file(const char *arg, FILE **F, const char *mode, const char *purpose)
  1730. {
  1731. char *r = "";
  1732. long int i = strtol(arg, &r, 10);
  1733. static char *err = NULL;
  1734. const size_t errbufsz = 0x100;
  1735. free(err);
  1736. err = NULL;
  1737. if ((!*r) && i >= 0 && i <= INT_MAX) {
  1738. *F = fdopen((int)i, mode);
  1739. if (!*F)
  1740. {
  1741. err = malloc(errbufsz);
  1742. snprintf(err, errbufsz, "Failed to open fd %d for %s",
  1743. (int)i, purpose);
  1744. return err;
  1745. }
  1746. } else if (!strcmp(arg, "-")) {
  1747. *F = (mode[0] == 'a') ? stdout : stdin;
  1748. if (!*F)
  1749. {
  1750. err = malloc(errbufsz);
  1751. snprintf(err, errbufsz, "Standard %sput missing for %s",
  1752. (mode[0] == 'a') ? "out" : "in", purpose);
  1753. return err;
  1754. }
  1755. } else {
  1756. *F = fopen(arg, mode);
  1757. if (!*F)
  1758. {
  1759. err = malloc(errbufsz);
  1760. snprintf(err, errbufsz, "Failed to open %s for %s",
  1761. arg, purpose);
  1762. return err;
  1763. }
  1764. }
  1765. return NULL;
  1766. }
  1767. static char *set_noncelog(char *arg)
  1768. {
  1769. return _bfgopt_set_file(arg, &noncelog_file, "a", "nonce log");
  1770. }
  1771. static char *set_sharelog(char *arg)
  1772. {
  1773. return _bfgopt_set_file(arg, &sharelog_file, "a", "share log");
  1774. }
  1775. static
  1776. void _add_set_device_option(const char * const func, const char * const buf)
  1777. {
  1778. applog(LOG_DEBUG, "%s: Using --set-device %s", func, buf);
  1779. string_elist_add(buf, &opt_set_device_list);
  1780. }
  1781. #define add_set_device_option(...) do{ \
  1782. char _tmp1718[0x100]; \
  1783. snprintf(_tmp1718, sizeof(_tmp1718), __VA_ARGS__); \
  1784. _add_set_device_option(__func__, _tmp1718); \
  1785. }while(0)
  1786. char *set_temp_cutoff(char *arg)
  1787. {
  1788. if (strchr(arg, ','))
  1789. return "temp-cutoff no longer supports comma-delimited syntax, use --set-device for better control";
  1790. applog(LOG_WARNING, "temp-cutoff is deprecated! Use --set-device for better control");
  1791. add_set_device_option("all:temp-cutoff=%s", arg);
  1792. return NULL;
  1793. }
  1794. char *set_temp_target(char *arg)
  1795. {
  1796. if (strchr(arg, ','))
  1797. return "temp-target no longer supports comma-delimited syntax, use --set-device for better control";
  1798. applog(LOG_WARNING, "temp-target is deprecated! Use --set-device for better control");
  1799. add_set_device_option("all:temp-target=%s", arg);
  1800. return NULL;
  1801. }
  1802. #ifdef HAVE_OPENCL
  1803. static
  1804. char *set_no_opencl_binaries(__maybe_unused void * const dummy)
  1805. {
  1806. applog(LOG_WARNING, "The --no-opencl-binaries option is deprecated! Use --set-device OCL:binary=no");
  1807. add_set_device_option("OCL:binary=no");
  1808. return NULL;
  1809. }
  1810. #endif
  1811. static
  1812. char *disable_pool_redirect(__maybe_unused void * const dummy)
  1813. {
  1814. opt_disable_client_reconnect = true;
  1815. want_stratum = false;
  1816. return NULL;
  1817. }
  1818. static char *set_api_allow(const char *arg)
  1819. {
  1820. opt_set_charp(arg, &opt_api_allow);
  1821. return NULL;
  1822. }
  1823. static char *set_api_groups(const char *arg)
  1824. {
  1825. opt_set_charp(arg, &opt_api_groups);
  1826. return NULL;
  1827. }
  1828. static char *set_api_description(const char *arg)
  1829. {
  1830. opt_set_charp(arg, &opt_api_description);
  1831. return NULL;
  1832. }
  1833. static char *set_api_mcast_des(const char *arg)
  1834. {
  1835. opt_set_charp(arg, &opt_api_mcast_des);
  1836. return NULL;
  1837. }
  1838. #ifdef USE_ICARUS
  1839. extern const struct bfg_set_device_definition icarus_set_device_funcs[];
  1840. static char *set_icarus_options(const char *arg)
  1841. {
  1842. if (strchr(arg, ','))
  1843. return "icarus-options no longer supports comma-delimited syntax, see README.FPGA for better control";
  1844. applog(LOG_WARNING, "icarus-options is deprecated! See README.FPGA for better control");
  1845. char *opts = strdup(arg), *argdup;
  1846. argdup = opts;
  1847. const struct bfg_set_device_definition *sdf = icarus_set_device_funcs;
  1848. const char *drivers[] = {"antminer", "cairnsmore", "erupter", "icarus"};
  1849. char *saveptr, *opt;
  1850. for (int i = 0; i < 4; ++i, ++sdf)
  1851. {
  1852. opt = strtok_r(opts, ":", &saveptr);
  1853. opts = NULL;
  1854. if (!opt)
  1855. break;
  1856. if (!opt[0])
  1857. continue;
  1858. for (int j = 0; j < 4; ++j)
  1859. add_set_device_option("%s:%s=%s", drivers[j], sdf->optname, opt);
  1860. }
  1861. free(argdup);
  1862. return NULL;
  1863. }
  1864. static char *set_icarus_timing(const char *arg)
  1865. {
  1866. if (strchr(arg, ','))
  1867. return "icarus-timing no longer supports comma-delimited syntax, see README.FPGA for better control";
  1868. applog(LOG_WARNING, "icarus-timing is deprecated! See README.FPGA for better control");
  1869. const char *drivers[] = {"antminer", "cairnsmore", "erupter", "icarus"};
  1870. for (int j = 0; j < 4; ++j)
  1871. add_set_device_option("%s:timing=%s", drivers[j], arg);
  1872. return NULL;
  1873. }
  1874. #endif
  1875. #ifdef USE_AVALON
  1876. extern const struct bfg_set_device_definition avalon_set_device_funcs[];
  1877. static char *set_avalon_options(const char *arg)
  1878. {
  1879. if (strchr(arg, ','))
  1880. return "avalon-options no longer supports comma-delimited syntax, see README.FPGA for better control";
  1881. applog(LOG_WARNING, "avalon-options is deprecated! See README.FPGA for better control");
  1882. char *opts = strdup(arg), *argdup;
  1883. argdup = opts;
  1884. const struct bfg_set_device_definition *sdf = avalon_set_device_funcs;
  1885. char *saveptr, *opt;
  1886. for (int i = 0; i < 5; ++i, ++sdf)
  1887. {
  1888. opt = strtok_r(opts, ":", &saveptr);
  1889. opts = NULL;
  1890. if (!opt)
  1891. break;
  1892. if (!opt[0])
  1893. continue;
  1894. add_set_device_option("avalon:%s=%s", sdf->optname, opt);
  1895. }
  1896. free(argdup);
  1897. return NULL;
  1898. }
  1899. #endif
  1900. #ifdef USE_KLONDIKE
  1901. static char *set_klondike_options(const char *arg)
  1902. {
  1903. int hashclock;
  1904. double temptarget;
  1905. switch (sscanf(arg, "%d:%lf", &hashclock, &temptarget))
  1906. {
  1907. default:
  1908. return "Unrecognised --klondike-options";
  1909. case 2:
  1910. add_set_device_option("klondike:temp-target=%lf", temptarget);
  1911. // fallthru
  1912. case 1:
  1913. add_set_device_option("klondike:clock=%d", hashclock);
  1914. }
  1915. applog(LOG_WARNING, "klondike-options is deprecated! Use --set-device for better control");
  1916. return NULL;
  1917. }
  1918. #endif
  1919. __maybe_unused
  1920. static char *set_null(const char __maybe_unused *arg)
  1921. {
  1922. return NULL;
  1923. }
  1924. /* These options are available from config file or commandline */
  1925. static struct opt_table opt_config_table[] = {
  1926. #ifdef WANT_CPUMINE
  1927. OPT_WITH_ARG("--algo",
  1928. set_algo, show_algo, &opt_algo,
  1929. "Specify sha256 implementation for CPU mining:\n"
  1930. "\tfastauto*\tQuick benchmark at startup to pick a working algorithm\n"
  1931. "\tauto\t\tBenchmark at startup and pick fastest algorithm"
  1932. "\n\tc\t\tLinux kernel sha256, implemented in C"
  1933. #ifdef WANT_SSE2_4WAY
  1934. "\n\t4way\t\ttcatm's 4-way SSE2 implementation"
  1935. #endif
  1936. #ifdef WANT_VIA_PADLOCK
  1937. "\n\tvia\t\tVIA padlock implementation"
  1938. #endif
  1939. "\n\tcryptopp\tCrypto++ C/C++ implementation"
  1940. #ifdef WANT_CRYPTOPP_ASM32
  1941. "\n\tcryptopp_asm32\tCrypto++ 32-bit assembler implementation"
  1942. #endif
  1943. #ifdef WANT_X8632_SSE2
  1944. "\n\tsse2_32\t\tSSE2 32 bit implementation for i386 machines"
  1945. #endif
  1946. #ifdef WANT_X8664_SSE2
  1947. "\n\tsse2_64\t\tSSE2 64 bit implementation for x86_64 machines"
  1948. #endif
  1949. #ifdef WANT_X8664_SSE4
  1950. "\n\tsse4_64\t\tSSE4.1 64 bit implementation for x86_64 machines"
  1951. #endif
  1952. #ifdef WANT_ALTIVEC_4WAY
  1953. "\n\taltivec_4way\tAltivec implementation for PowerPC G4 and G5 machines"
  1954. #endif
  1955. ),
  1956. OPT_WITH_ARG("-a",
  1957. set_algo, show_algo, &opt_algo,
  1958. opt_hidden),
  1959. #endif
  1960. OPT_WITH_ARG("--api-allow",
  1961. set_api_allow, NULL, NULL,
  1962. "Allow API access only to the given list of [G:]IP[/Prefix] addresses[/subnets]"),
  1963. OPT_WITH_ARG("--api-description",
  1964. set_api_description, NULL, NULL,
  1965. "Description placed in the API status header, default: BFGMiner version"),
  1966. OPT_WITH_ARG("--api-groups",
  1967. set_api_groups, NULL, NULL,
  1968. "API one letter groups G:cmd:cmd[,P:cmd:*...] defining the cmds a groups can use"),
  1969. OPT_WITHOUT_ARG("--api-listen",
  1970. opt_set_bool, &opt_api_listen,
  1971. "Enable API, default: disabled"),
  1972. OPT_WITHOUT_ARG("--api-mcast",
  1973. opt_set_bool, &opt_api_mcast,
  1974. "Enable API Multicast listener, default: disabled"),
  1975. OPT_WITH_ARG("--api-mcast-addr",
  1976. opt_set_charp, opt_show_charp, &opt_api_mcast_addr,
  1977. "API Multicast listen address"),
  1978. OPT_WITH_ARG("--api-mcast-code",
  1979. opt_set_charp, opt_show_charp, &opt_api_mcast_code,
  1980. "Code expected in the API Multicast message, don't use '-'"),
  1981. OPT_WITH_ARG("--api-mcast-des",
  1982. set_api_mcast_des, NULL, NULL,
  1983. "Description appended to the API Multicast reply, default: ''"),
  1984. OPT_WITH_ARG("--api-mcast-port",
  1985. set_int_1_to_65535, opt_show_intval, &opt_api_mcast_port,
  1986. "API Multicast listen port"),
  1987. OPT_WITHOUT_ARG("--api-network",
  1988. opt_set_bool, &opt_api_network,
  1989. "Allow API (if enabled) to listen on/for any address, default: only 127.0.0.1"),
  1990. OPT_WITH_ARG("--api-port",
  1991. set_int_1_to_65535, opt_show_intval, &opt_api_port,
  1992. "Port number of miner API"),
  1993. #ifdef HAVE_ADL
  1994. OPT_WITHOUT_ARG("--auto-fan",
  1995. opt_set_bool, &opt_autofan,
  1996. opt_hidden),
  1997. OPT_WITHOUT_ARG("--auto-gpu",
  1998. opt_set_bool, &opt_autoengine,
  1999. opt_hidden),
  2000. #endif
  2001. OPT_WITHOUT_ARG("--balance",
  2002. set_balance, &pool_strategy,
  2003. "Change multipool strategy from failover to even share balance"),
  2004. OPT_WITHOUT_ARG("--benchmark",
  2005. opt_set_bool, &opt_benchmark,
  2006. "Run BFGMiner in benchmark mode - produces no shares"),
  2007. OPT_WITHOUT_ARG("--benchmark-intense",
  2008. set_benchmark_intense, &opt_benchmark_intense,
  2009. "Run BFGMiner in intensive benchmark mode - produces no shares"),
  2010. #if defined(USE_BITFORCE)
  2011. OPT_WITHOUT_ARG("--bfl-range",
  2012. opt_set_bool, &opt_bfl_noncerange,
  2013. "Use nonce range on bitforce devices if supported"),
  2014. #endif
  2015. #ifdef HAVE_CHROOT
  2016. OPT_WITH_ARG("--chroot-dir",
  2017. opt_set_charp, NULL, &chroot_dir,
  2018. "Chroot to a directory right after startup"),
  2019. #endif
  2020. OPT_WITH_ARG("--cmd-idle",
  2021. opt_set_charp, NULL, &cmd_idle,
  2022. "Execute a command when a device is allowed to be idle (rest or wait)"),
  2023. OPT_WITH_ARG("--cmd-sick",
  2024. opt_set_charp, NULL, &cmd_sick,
  2025. "Execute a command when a device is declared sick"),
  2026. OPT_WITH_ARG("--cmd-dead",
  2027. opt_set_charp, NULL, &cmd_dead,
  2028. "Execute a command when a device is declared dead"),
  2029. #if BLKMAKER_VERSION > 0
  2030. OPT_WITH_ARG("--coinbase-sig",
  2031. set_strdup, NULL, &opt_coinbase_sig,
  2032. "Set coinbase signature when possible"),
  2033. OPT_WITH_ARG("--coinbase|--cbsig|--cb-sig|--cb|--prayer",
  2034. set_strdup, NULL, &opt_coinbase_sig,
  2035. opt_hidden),
  2036. #endif
  2037. #ifdef HAVE_CURSES
  2038. OPT_WITHOUT_ARG("--compact",
  2039. opt_set_bool, &opt_compact,
  2040. "Use compact display without per device statistics"),
  2041. #endif
  2042. #ifdef WANT_CPUMINE
  2043. OPT_WITH_ARG("--cpu-threads",
  2044. force_nthreads_int, opt_show_intval, &opt_n_threads,
  2045. "Number of miner CPU threads"),
  2046. OPT_WITH_ARG("-t",
  2047. force_nthreads_int, opt_show_intval, &opt_n_threads,
  2048. opt_hidden),
  2049. #endif
  2050. OPT_WITHOUT_ARG("--debug|-D",
  2051. enable_debug, &opt_debug,
  2052. "Enable debug output"),
  2053. OPT_WITHOUT_ARG("--debuglog",
  2054. opt_set_bool, &opt_debug,
  2055. "Enable debug logging"),
  2056. OPT_WITHOUT_ARG("--device-protocol-dump",
  2057. opt_set_bool, &opt_dev_protocol,
  2058. "Verbose dump of device protocol-level activities"),
  2059. OPT_WITH_ARG("--device|-d",
  2060. set_devices, NULL, NULL,
  2061. "Enable only devices matching pattern (default: all)"),
  2062. OPT_WITHOUT_ARG("--disable-rejecting",
  2063. opt_set_bool, &opt_disable_pool,
  2064. "Automatically disable pools that continually reject shares"),
  2065. #ifdef USE_LIBMICROHTTPD
  2066. OPT_WITH_ARG("--http-port",
  2067. opt_set_intval, opt_show_intval, &httpsrv_port,
  2068. "Port number to listen on for HTTP getwork miners (-1 means disabled)"),
  2069. #endif
  2070. OPT_WITH_ARG("--expiry",
  2071. set_int_0_to_9999, opt_show_intval, &opt_expiry,
  2072. "Upper bound on how many seconds after getting work we consider a share from it stale (w/o longpoll active)"),
  2073. OPT_WITH_ARG("-E",
  2074. set_int_0_to_9999, opt_show_intval, &opt_expiry,
  2075. opt_hidden),
  2076. OPT_WITH_ARG("--expiry-lp",
  2077. set_int_0_to_9999, opt_show_intval, &opt_expiry_lp,
  2078. "Upper bound on how many seconds after getting work we consider a share from it stale (with longpoll active)"),
  2079. OPT_WITHOUT_ARG("--failover-only",
  2080. opt_set_bool, &opt_fail_only,
  2081. "Don't leak work to backup pools when primary pool is lagging"),
  2082. OPT_WITH_ARG("--failover-switch-delay",
  2083. set_int_1_to_65535, opt_show_intval, &opt_fail_switch_delay,
  2084. "Delay in seconds before switching back to a failed pool"),
  2085. #ifdef USE_FPGA
  2086. OPT_WITHOUT_ARG("--force-dev-init",
  2087. opt_set_bool, &opt_force_dev_init,
  2088. "Always initialize devices when possible (such as bitstream uploads to some FPGAs)"),
  2089. #endif
  2090. #if BLKMAKER_VERSION > 1
  2091. OPT_WITH_ARG("--generate-to",
  2092. set_generate_addr, NULL, NULL,
  2093. "Set an address to generate to for solo mining"),
  2094. 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",
  2095. set_generate_addr, NULL, NULL,
  2096. opt_hidden),
  2097. #endif
  2098. #ifdef HAVE_OPENCL
  2099. OPT_WITH_ARG("--gpu-dyninterval",
  2100. set_int_1_to_65535, opt_show_intval, &opt_dynamic_interval,
  2101. opt_hidden),
  2102. OPT_WITH_ARG("--gpu-platform",
  2103. set_int_0_to_9999, opt_show_intval, &opt_platform_id,
  2104. "Select OpenCL platform ID to use for GPU mining"),
  2105. OPT_WITH_ARG("--gpu-threads|-g",
  2106. set_gpu_threads, opt_show_intval, &opt_g_threads,
  2107. opt_hidden),
  2108. #ifdef HAVE_ADL
  2109. OPT_WITH_ARG("--gpu-engine",
  2110. set_gpu_engine, NULL, NULL,
  2111. opt_hidden),
  2112. OPT_WITH_ARG("--gpu-fan",
  2113. set_gpu_fan, NULL, NULL,
  2114. opt_hidden),
  2115. OPT_WITH_ARG("--gpu-map",
  2116. set_gpu_map, NULL, NULL,
  2117. "Map OpenCL to ADL device order manually, paired CSV (e.g. 1:0,2:1 maps OpenCL 1 to ADL 0, 2 to 1)"),
  2118. OPT_WITH_ARG("--gpu-memclock",
  2119. set_gpu_memclock, NULL, NULL,
  2120. opt_hidden),
  2121. OPT_WITH_ARG("--gpu-memdiff",
  2122. set_gpu_memdiff, NULL, NULL,
  2123. opt_hidden),
  2124. OPT_WITH_ARG("--gpu-powertune",
  2125. set_gpu_powertune, NULL, NULL,
  2126. opt_hidden),
  2127. OPT_WITHOUT_ARG("--gpu-reorder",
  2128. opt_set_bool, &opt_reorder,
  2129. "Attempt to reorder GPU devices according to PCI Bus ID"),
  2130. OPT_WITH_ARG("--gpu-vddc",
  2131. set_gpu_vddc, NULL, NULL,
  2132. opt_hidden),
  2133. #endif
  2134. #ifdef USE_SCRYPT
  2135. OPT_WITH_ARG("--lookup-gap",
  2136. set_lookup_gap, NULL, NULL,
  2137. opt_hidden),
  2138. #endif
  2139. OPT_WITH_ARG("--intensity|-I",
  2140. set_intensity, NULL, NULL,
  2141. opt_hidden),
  2142. #endif
  2143. #if defined(HAVE_OPENCL) || defined(USE_MODMINER) || defined(USE_X6500) || defined(USE_ZTEX)
  2144. OPT_WITH_ARG("--kernel-path",
  2145. opt_set_charp, opt_show_charp, &opt_kernel_path,
  2146. "Specify a path to where bitstream and kernel files are"),
  2147. OPT_WITH_ARG("-K",
  2148. opt_set_charp, opt_show_charp, &opt_kernel_path,
  2149. opt_hidden),
  2150. #endif
  2151. #ifdef HAVE_OPENCL
  2152. OPT_WITH_ARG("--kernel|-k",
  2153. set_kernel, NULL, NULL,
  2154. opt_hidden),
  2155. #endif
  2156. #ifdef USE_ICARUS
  2157. OPT_WITH_ARG("--icarus-options",
  2158. set_icarus_options, NULL, NULL,
  2159. opt_hidden),
  2160. OPT_WITH_ARG("--icarus-timing",
  2161. set_icarus_timing, NULL, NULL,
  2162. opt_hidden),
  2163. #endif
  2164. #ifdef USE_AVALON
  2165. OPT_WITH_ARG("--avalon-options",
  2166. set_avalon_options, NULL, NULL,
  2167. opt_hidden),
  2168. #endif
  2169. #ifdef USE_KLONDIKE
  2170. OPT_WITH_ARG("--klondike-options",
  2171. set_klondike_options, NULL, NULL,
  2172. "Set klondike options clock:temptarget"),
  2173. #endif
  2174. OPT_WITHOUT_ARG("--load-balance",
  2175. set_loadbalance, &pool_strategy,
  2176. "Change multipool strategy from failover to quota based balance"),
  2177. OPT_WITH_ARG("--log|-l",
  2178. set_int_0_to_9999, opt_show_intval, &opt_log_interval,
  2179. "Interval in seconds between log output"),
  2180. OPT_WITH_ARG("--log-file|-L",
  2181. set_log_file, NULL, NULL,
  2182. "Append log file for output messages"),
  2183. OPT_WITH_ARG("--logfile",
  2184. set_log_file, NULL, NULL,
  2185. opt_hidden),
  2186. OPT_WITHOUT_ARG("--log-microseconds",
  2187. opt_set_bool, &opt_log_microseconds,
  2188. "Include microseconds in log output"),
  2189. #if defined(unix) || defined(__APPLE__)
  2190. OPT_WITH_ARG("--monitor|-m",
  2191. opt_set_charp, NULL, &opt_stderr_cmd,
  2192. "Use custom pipe cmd for output messages"),
  2193. #endif // defined(unix)
  2194. OPT_WITHOUT_ARG("--net-delay",
  2195. opt_set_bool, &opt_delaynet,
  2196. "Impose small delays in networking to avoid overloading slow routers"),
  2197. OPT_WITHOUT_ARG("--no-adl",
  2198. opt_set_bool, &opt_noadl,
  2199. #ifdef HAVE_ADL
  2200. "Disable the ATI display library used for monitoring and setting GPU parameters"
  2201. #else
  2202. opt_hidden
  2203. #endif
  2204. ),
  2205. OPT_WITHOUT_ARG("--no-gbt",
  2206. opt_set_invbool, &want_gbt,
  2207. "Disable getblocktemplate support"),
  2208. OPT_WITHOUT_ARG("--no-getwork",
  2209. opt_set_invbool, &want_getwork,
  2210. "Disable getwork support"),
  2211. OPT_WITHOUT_ARG("--no-hotplug",
  2212. #ifdef HAVE_BFG_HOTPLUG
  2213. opt_set_invbool, &opt_hotplug,
  2214. "Disable hotplug detection"
  2215. #else
  2216. set_null, &opt_hotplug,
  2217. opt_hidden
  2218. #endif
  2219. ),
  2220. OPT_WITHOUT_ARG("--no-local-bitcoin",
  2221. #if BLKMAKER_VERSION > 1
  2222. opt_set_invbool, &opt_load_bitcoin_conf,
  2223. "Disable adding pools for local bitcoin RPC servers"),
  2224. #else
  2225. set_null, NULL, opt_hidden),
  2226. #endif
  2227. OPT_WITHOUT_ARG("--no-longpoll",
  2228. opt_set_invbool, &want_longpoll,
  2229. "Disable X-Long-Polling support"),
  2230. OPT_WITHOUT_ARG("--no-pool-disable",
  2231. opt_set_invbool, &opt_disable_pool,
  2232. opt_hidden),
  2233. OPT_WITHOUT_ARG("--no-client-reconnect",
  2234. opt_set_invbool, &opt_disable_client_reconnect,
  2235. opt_hidden),
  2236. OPT_WITHOUT_ARG("--no-pool-redirect",
  2237. disable_pool_redirect, NULL,
  2238. "Ignore pool requests to redirect to another server"),
  2239. OPT_WITHOUT_ARG("--no-restart",
  2240. opt_set_invbool, &opt_restart,
  2241. "Do not attempt to restart devices that hang"
  2242. ),
  2243. OPT_WITHOUT_ARG("--no-show-processors",
  2244. opt_set_invbool, &opt_show_procs,
  2245. opt_hidden),
  2246. OPT_WITHOUT_ARG("--no-show-procs",
  2247. opt_set_invbool, &opt_show_procs,
  2248. opt_hidden),
  2249. OPT_WITHOUT_ARG("--no-stratum",
  2250. opt_set_invbool, &want_stratum,
  2251. "Disable Stratum detection"),
  2252. OPT_WITHOUT_ARG("--no-submit-stale",
  2253. opt_set_invbool, &opt_submit_stale,
  2254. "Don't submit shares if they are detected as stale"),
  2255. #ifdef HAVE_OPENCL
  2256. OPT_WITHOUT_ARG("--no-opencl-binaries",
  2257. set_no_opencl_binaries, NULL,
  2258. opt_hidden),
  2259. #endif
  2260. OPT_WITHOUT_ARG("--no-unicode",
  2261. #ifdef USE_UNICODE
  2262. opt_set_invbool, &use_unicode,
  2263. "Don't use Unicode characters in TUI"
  2264. #else
  2265. set_null, &use_unicode,
  2266. opt_hidden
  2267. #endif
  2268. ),
  2269. OPT_WITH_ARG("--noncelog",
  2270. set_noncelog, NULL, NULL,
  2271. "Create log of all nonces found"),
  2272. OPT_WITH_ARG("--pass|-p",
  2273. set_pass, NULL, NULL,
  2274. "Password for bitcoin JSON-RPC server"),
  2275. OPT_WITHOUT_ARG("--per-device-stats",
  2276. opt_set_bool, &want_per_device_stats,
  2277. "Force verbose mode and output per-device statistics"),
  2278. OPT_WITH_ARG("--userpass|-O",
  2279. set_userpass, NULL, NULL,
  2280. "Username:Password pair for bitcoin JSON-RPC server"),
  2281. OPT_WITH_ARG("--pool-goal",
  2282. set_pool_goal, NULL, NULL,
  2283. "Named goal for the previous-defined pool"),
  2284. OPT_WITH_ARG("--pool-priority",
  2285. set_pool_priority, NULL, NULL,
  2286. "Priority for just the previous-defined pool"),
  2287. OPT_WITH_ARG("--pool-proxy|-x",
  2288. set_pool_proxy, NULL, NULL,
  2289. "Proxy URI to use for connecting to just the previous-defined pool"),
  2290. OPT_WITH_ARG("--force-rollntime", // NOTE: must be after --pass for config file ordering
  2291. set_pool_force_rollntime, NULL, NULL,
  2292. opt_hidden),
  2293. OPT_WITHOUT_ARG("--protocol-dump|-P",
  2294. opt_set_bool, &opt_protocol,
  2295. "Verbose dump of protocol-level activities"),
  2296. OPT_WITH_ARG("--queue|-Q",
  2297. set_int_0_to_9999, opt_show_intval, &opt_queue,
  2298. "Minimum number of work items to have queued (0+)"),
  2299. OPT_WITHOUT_ARG("--quiet|-q",
  2300. opt_set_bool, &opt_quiet,
  2301. "Disable logging output, display status and errors"),
  2302. OPT_WITHOUT_ARG("--quiet-work-updates|--quiet-work-update",
  2303. opt_set_bool, &opt_quiet_work_updates,
  2304. opt_hidden),
  2305. OPT_WITH_ARG("--quit-summary",
  2306. set_quit_summary, NULL, NULL,
  2307. "Summary printed when you quit: none/devs/procs/detailed"),
  2308. OPT_WITH_ARG("--quota|-U",
  2309. set_quota, NULL, NULL,
  2310. "quota;URL combination for server with load-balance strategy quotas"),
  2311. OPT_WITHOUT_ARG("--real-quiet",
  2312. opt_set_bool, &opt_realquiet,
  2313. "Disable all output"),
  2314. OPT_WITH_ARG("--request-diff",
  2315. set_request_diff, opt_show_floatval, &request_pdiff,
  2316. "Request a specific difficulty from pools"),
  2317. OPT_WITH_ARG("--retries",
  2318. opt_set_intval, opt_show_intval, &opt_retries,
  2319. "Number of times to retry failed submissions before giving up (-1 means never)"),
  2320. OPT_WITH_ARG("--retry-pause",
  2321. set_null, NULL, NULL,
  2322. opt_hidden),
  2323. OPT_WITH_ARG("--rotate",
  2324. set_rotate, opt_show_intval, &opt_rotate_period,
  2325. "Change multipool strategy from failover to regularly rotate at N minutes"),
  2326. OPT_WITHOUT_ARG("--round-robin",
  2327. set_rr, &pool_strategy,
  2328. "Change multipool strategy from failover to round robin on failure"),
  2329. OPT_WITH_ARG("--scan|-S",
  2330. add_serial, NULL, NULL,
  2331. "Configure how to scan for mining devices"),
  2332. OPT_WITH_ARG("--scan-device|--scan-serial|--devscan",
  2333. add_serial, NULL, NULL,
  2334. opt_hidden),
  2335. OPT_WITH_ARG("--scan-time",
  2336. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  2337. "Upper bound on time spent scanning current work, in seconds"),
  2338. OPT_WITH_ARG("-s",
  2339. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  2340. opt_hidden),
  2341. OPT_WITH_ARG("--scantime",
  2342. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  2343. opt_hidden),
  2344. OPT_WITH_ARG("--sched-start",
  2345. set_schedtime, NULL, &schedstart,
  2346. "Set a time of day in HH:MM to start mining (a once off without a stop time)"),
  2347. OPT_WITH_ARG("--sched-stop",
  2348. set_schedtime, NULL, &schedstop,
  2349. "Set a time of day in HH:MM to stop mining (will quit without a start time)"),
  2350. #ifdef USE_SCRYPT
  2351. OPT_WITHOUT_ARG("--scrypt",
  2352. set_malgo_scrypt, NULL,
  2353. "Use the scrypt algorithm for mining (non-bitcoin)"),
  2354. #endif
  2355. OPT_WITH_ARG("--set-device|--set",
  2356. opt_string_elist_add, NULL, &opt_set_device_list,
  2357. "Set default parameters on devices; eg, NFY:osc6_bits=50"),
  2358. #if defined(USE_SCRYPT) && defined(HAVE_OPENCL)
  2359. OPT_WITH_ARG("--shaders",
  2360. set_shaders, NULL, NULL,
  2361. opt_hidden),
  2362. #endif
  2363. #ifdef HAVE_PWD_H
  2364. OPT_WITH_ARG("--setuid",
  2365. opt_set_charp, NULL, &opt_setuid,
  2366. "Username of an unprivileged user to run as"),
  2367. #endif
  2368. OPT_WITH_ARG("--sharelog",
  2369. set_sharelog, NULL, NULL,
  2370. "Append share log to file"),
  2371. OPT_WITH_ARG("--shares",
  2372. opt_set_floatval, NULL, &opt_shares,
  2373. "Quit after mining 2^32 * N hashes worth of shares (default: unlimited)"),
  2374. OPT_WITHOUT_ARG("--show-processors",
  2375. opt_set_bool, &opt_show_procs,
  2376. "Show per processor statistics in summary"),
  2377. OPT_WITHOUT_ARG("--show-procs",
  2378. opt_set_bool, &opt_show_procs,
  2379. opt_hidden),
  2380. OPT_WITH_ARG("--skip-security-checks",
  2381. set_int_0_to_9999, NULL, &opt_skip_checks,
  2382. "Skip security checks sometimes to save bandwidth; only check 1/<arg>th of the time (default: never skip)"),
  2383. OPT_WITH_ARG("--socks-proxy",
  2384. opt_set_charp, NULL, &opt_socks_proxy,
  2385. "Set socks proxy (host:port)"),
  2386. #ifdef USE_LIBEVENT
  2387. OPT_WITH_ARG("--stratum-port",
  2388. opt_set_intval, opt_show_intval, &stratumsrv_port,
  2389. "Port number to listen on for stratum miners (-1 means disabled)"),
  2390. #endif
  2391. OPT_WITHOUT_ARG("--submit-stale",
  2392. opt_set_bool, &opt_submit_stale,
  2393. opt_hidden),
  2394. OPT_WITH_ARG("--submit-threads",
  2395. opt_set_intval, opt_show_intval, &opt_submit_threads,
  2396. "Minimum number of concurrent share submissions (default: 64)"),
  2397. #ifdef HAVE_SYSLOG_H
  2398. OPT_WITHOUT_ARG("--syslog",
  2399. opt_set_bool, &use_syslog,
  2400. "Use system log for output messages (default: standard error)"),
  2401. #endif
  2402. OPT_WITH_ARG("--temp-cutoff",
  2403. set_temp_cutoff, NULL, &opt_cutofftemp,
  2404. opt_hidden),
  2405. OPT_WITH_ARG("--temp-hysteresis",
  2406. set_int_1_to_10, opt_show_intval, &opt_hysteresis,
  2407. "Set how much the temperature can fluctuate outside limits when automanaging speeds"),
  2408. #ifdef HAVE_ADL
  2409. OPT_WITH_ARG("--temp-overheat",
  2410. set_temp_overheat, opt_show_intval, &opt_overheattemp,
  2411. opt_hidden),
  2412. #endif
  2413. OPT_WITH_ARG("--temp-target",
  2414. set_temp_target, NULL, NULL,
  2415. opt_hidden),
  2416. OPT_WITHOUT_ARG("--text-only|-T",
  2417. opt_set_invbool, &use_curses,
  2418. #ifdef HAVE_CURSES
  2419. "Disable ncurses formatted screen output"
  2420. #else
  2421. opt_hidden
  2422. #endif
  2423. ),
  2424. #if defined(USE_SCRYPT) && defined(HAVE_OPENCL)
  2425. OPT_WITH_ARG("--thread-concurrency",
  2426. set_thread_concurrency, NULL, NULL,
  2427. opt_hidden),
  2428. #endif
  2429. #ifdef USE_UNICODE
  2430. OPT_WITHOUT_ARG("--unicode",
  2431. opt_set_bool, &use_unicode,
  2432. "Use Unicode characters in TUI"),
  2433. #endif
  2434. OPT_WITH_ARG("--url|-o",
  2435. set_url, NULL, NULL,
  2436. "URL for bitcoin JSON-RPC server"),
  2437. OPT_WITH_ARG("--user|-u",
  2438. set_user, NULL, NULL,
  2439. "Username for bitcoin JSON-RPC server"),
  2440. #ifdef HAVE_OPENCL
  2441. OPT_WITH_ARG("--vectors|-v",
  2442. set_vector, NULL, NULL,
  2443. opt_hidden),
  2444. #endif
  2445. OPT_WITHOUT_ARG("--verbose",
  2446. opt_set_bool, &opt_log_output,
  2447. "Log verbose output to stderr as well as status output"),
  2448. OPT_WITHOUT_ARG("--verbose-work-updates|--verbose-work-update",
  2449. opt_set_invbool, &opt_quiet_work_updates,
  2450. opt_hidden),
  2451. OPT_WITHOUT_ARG("--weighed-stats",
  2452. opt_set_bool, &opt_weighed_stats,
  2453. "Display statistics weighed to difficulty 1"),
  2454. #ifdef HAVE_OPENCL
  2455. OPT_WITH_ARG("--worksize|-w",
  2456. set_worksize, NULL, NULL,
  2457. opt_hidden),
  2458. #endif
  2459. OPT_WITHOUT_ARG("--unittest",
  2460. opt_set_bool, &opt_unittest, opt_hidden),
  2461. OPT_WITH_ARG("--coinbase-check-addr",
  2462. set_cbcaddr, NULL, NULL,
  2463. "A list of address to check against in coinbase payout list received from the previous-defined pool, separated by ','"),
  2464. OPT_WITH_ARG("--cbcheck-addr|--cbc-addr|--cbcaddr",
  2465. set_cbcaddr, NULL, NULL,
  2466. opt_hidden),
  2467. OPT_WITH_ARG("--coinbase-check-total",
  2468. set_cbctotal, NULL, NULL,
  2469. "The least total payout amount expected in coinbase received from the previous-defined pool"),
  2470. OPT_WITH_ARG("--cbcheck-total|--cbc-total|--cbctotal",
  2471. set_cbctotal, NULL, NULL,
  2472. opt_hidden),
  2473. OPT_WITH_ARG("--coinbase-check-percent",
  2474. set_cbcperc, NULL, NULL,
  2475. "The least benefit percentage expected for the sum of addr(s) listed in --cbaddr argument for previous-defined pool"),
  2476. OPT_WITH_ARG("--cbcheck-percent|--cbc-percent|--cbcpercent|--cbcperc",
  2477. set_cbcperc, NULL, NULL,
  2478. opt_hidden),
  2479. OPT_WITHOUT_ARG("--worktime",
  2480. opt_set_bool, &opt_worktime,
  2481. "Display extra work time debug information"),
  2482. OPT_WITH_ARG("--pools",
  2483. opt_set_bool, NULL, NULL, opt_hidden),
  2484. OPT_ENDTABLE
  2485. };
  2486. static char *load_config(const char *arg, void __maybe_unused *unused);
  2487. static char *parse_config(json_t *config, bool fileconf, int * const fileconf_load_p)
  2488. {
  2489. static char err_buf[200];
  2490. struct opt_table *opt;
  2491. json_t *val;
  2492. if (fileconf && !*fileconf_load_p)
  2493. *fileconf_load_p = 1;
  2494. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  2495. char *p, *name, *sp;
  2496. /* We don't handle subtables. */
  2497. assert(!(opt->type & OPT_SUBTABLE));
  2498. if (!opt->names)
  2499. continue;
  2500. /* Pull apart the option name(s). */
  2501. name = strdup(opt->names);
  2502. for (p = strtok_r(name, "|", &sp); p; p = strtok_r(NULL, "|", &sp)) {
  2503. char *err = "Invalid value";
  2504. /* Ignore short options. */
  2505. if (p[1] != '-')
  2506. continue;
  2507. val = json_object_get(config, p+2);
  2508. if (!val)
  2509. continue;
  2510. if (opt->type & OPT_HASARG) {
  2511. if (json_is_string(val)) {
  2512. err = opt->cb_arg(json_string_value(val),
  2513. opt->u.arg);
  2514. } else if (json_is_number(val)) {
  2515. char buf[256], *p, *q;
  2516. snprintf(buf, 256, "%f", json_number_value(val));
  2517. if ( (p = strchr(buf, '.')) ) {
  2518. // Trim /\.0*$/ to work properly with integer-only arguments
  2519. q = p;
  2520. while (*(++q) == '0') {}
  2521. if (*q == '\0')
  2522. *p = '\0';
  2523. }
  2524. err = opt->cb_arg(buf, opt->u.arg);
  2525. } else if (json_is_array(val)) {
  2526. int n, size = json_array_size(val);
  2527. err = NULL;
  2528. for (n = 0; n < size && !err; n++) {
  2529. if (json_is_string(json_array_get(val, n)))
  2530. err = opt->cb_arg(json_string_value(json_array_get(val, n)), opt->u.arg);
  2531. else if (json_is_object(json_array_get(val, n)))
  2532. err = parse_config(json_array_get(val, n), false, fileconf_load_p);
  2533. }
  2534. }
  2535. } else if (opt->type & OPT_NOARG) {
  2536. if (json_is_true(val))
  2537. err = opt->cb(opt->u.arg);
  2538. else if (json_is_boolean(val)) {
  2539. if (opt->cb == (void*)opt_set_bool)
  2540. err = opt_set_invbool(opt->u.arg);
  2541. else if (opt->cb == (void*)opt_set_invbool)
  2542. err = opt_set_bool(opt->u.arg);
  2543. }
  2544. }
  2545. if (err) {
  2546. /* Allow invalid values to be in configuration
  2547. * file, just skipping over them provided the
  2548. * JSON is still valid after that. */
  2549. if (fileconf) {
  2550. applog(LOG_ERR, "Invalid config option %s: %s", p, err);
  2551. *fileconf_load_p = -1;
  2552. } else {
  2553. snprintf(err_buf, sizeof(err_buf), "Parsing JSON option %s: %s",
  2554. p, err);
  2555. return err_buf;
  2556. }
  2557. }
  2558. }
  2559. free(name);
  2560. }
  2561. val = json_object_get(config, JSON_INCLUDE_CONF);
  2562. if (val && json_is_string(val))
  2563. return load_config(json_string_value(val), NULL);
  2564. return NULL;
  2565. }
  2566. struct bfg_loaded_configfile *bfg_loaded_configfiles;
  2567. static char *load_config(const char *arg, void __maybe_unused *unused)
  2568. {
  2569. json_error_t err;
  2570. json_t *config;
  2571. char *json_error;
  2572. size_t siz;
  2573. struct bfg_loaded_configfile *cfginfo;
  2574. cfginfo = malloc(sizeof(*cfginfo));
  2575. *cfginfo = (struct bfg_loaded_configfile){
  2576. .filename = strdup(arg),
  2577. };
  2578. LL_APPEND(bfg_loaded_configfiles, cfginfo);
  2579. if (++include_count > JSON_MAX_DEPTH)
  2580. return JSON_MAX_DEPTH_ERR;
  2581. #if JANSSON_MAJOR_VERSION > 1
  2582. config = json_load_file(arg, 0, &err);
  2583. #else
  2584. config = json_load_file(arg, &err);
  2585. #endif
  2586. if (!json_is_object(config)) {
  2587. siz = JSON_LOAD_ERROR_LEN + strlen(arg) + strlen(err.text);
  2588. json_error = malloc(siz);
  2589. if (!json_error)
  2590. quit(1, "Malloc failure in json error");
  2591. snprintf(json_error, siz, JSON_LOAD_ERROR, arg, err.text);
  2592. return json_error;
  2593. }
  2594. config_loaded = true;
  2595. /* Parse the config now, so we can override it. That can keep pointers
  2596. * so don't free config object. */
  2597. return parse_config(config, true, &cfginfo->fileconf_load);
  2598. }
  2599. static
  2600. bool _load_default_configs(const char * const filepath, void * __maybe_unused userp)
  2601. {
  2602. bool * const found_defcfg_p = userp;
  2603. *found_defcfg_p = true;
  2604. load_config(filepath, NULL);
  2605. // Regardless of status of loading the config file, we should continue loading other defaults
  2606. return false;
  2607. }
  2608. static void load_default_config(void)
  2609. {
  2610. bool found_defcfg = false;
  2611. appdata_file_call("BFGMiner", def_conf, _load_default_configs, &found_defcfg);
  2612. if (!found_defcfg)
  2613. {
  2614. // No BFGMiner config, try Cgminer's...
  2615. appdata_file_call("cgminer", "cgminer.conf", _load_default_configs, &found_defcfg);
  2616. }
  2617. }
  2618. extern const char *opt_argv0;
  2619. static char *opt_verusage_and_exit(const char *extra)
  2620. {
  2621. puts(packagename);
  2622. printf(" Lowlevel:%s\n", BFG_LOWLLIST);
  2623. printf(" Drivers:%s\n", BFG_DRIVERLIST);
  2624. printf(" Algorithms:%s\n", BFG_ALGOLIST);
  2625. printf(" Options:%s\n", BFG_OPTLIST);
  2626. printf("%s", opt_usage(opt_argv0, extra));
  2627. fflush(stdout);
  2628. exit(0);
  2629. }
  2630. /* These options are parsed before anything else */
  2631. static struct opt_table opt_early_table[] = {
  2632. // Default config is loaded in command line order, like a regular config
  2633. OPT_EARLY_WITH_ARG("--config|-c|--default-config",
  2634. set_bool_ignore_arg, NULL, &config_loaded,
  2635. opt_hidden),
  2636. OPT_EARLY_WITHOUT_ARG("--no-config|--no-default-config",
  2637. opt_set_bool, &config_loaded,
  2638. "Inhibit loading default config file"),
  2639. OPT_ENDTABLE
  2640. };
  2641. /* These options are available from commandline only */
  2642. static struct opt_table opt_cmdline_table[] = {
  2643. OPT_WITH_ARG("--config|-c",
  2644. load_config, NULL, NULL,
  2645. "Load a JSON-format configuration file\n"
  2646. "See example.conf for an example configuration."),
  2647. OPT_EARLY_WITHOUT_ARG("--no-config",
  2648. opt_set_bool, &config_loaded,
  2649. opt_hidden),
  2650. OPT_EARLY_WITHOUT_ARG("--no-default-config",
  2651. opt_set_bool, &config_loaded,
  2652. "Inhibit loading default config file"),
  2653. OPT_WITHOUT_ARG("--default-config",
  2654. load_default_config, NULL,
  2655. "Always load the default config file"),
  2656. OPT_WITHOUT_ARG("--help|-h",
  2657. opt_verusage_and_exit, NULL,
  2658. "Print this message"),
  2659. #ifdef HAVE_OPENCL
  2660. OPT_WITHOUT_ARG("--ndevs|-n",
  2661. print_ndevs_and_exit, &nDevs,
  2662. opt_hidden),
  2663. #endif
  2664. OPT_WITHOUT_ARG("--version|-V",
  2665. opt_version_and_exit, packagename,
  2666. "Display version and exit"),
  2667. OPT_ENDTABLE
  2668. };
  2669. static bool jobj_binary(const json_t *obj, const char *key,
  2670. void *buf, size_t buflen, bool required)
  2671. {
  2672. const char *hexstr;
  2673. json_t *tmp;
  2674. tmp = json_object_get(obj, key);
  2675. if (unlikely(!tmp)) {
  2676. if (unlikely(required))
  2677. applog(LOG_ERR, "JSON key '%s' not found", key);
  2678. return false;
  2679. }
  2680. hexstr = json_string_value(tmp);
  2681. if (unlikely(!hexstr)) {
  2682. applog(LOG_ERR, "JSON key '%s' is not a string", key);
  2683. return false;
  2684. }
  2685. if (!hex2bin(buf, hexstr, buflen))
  2686. return false;
  2687. return true;
  2688. }
  2689. static void calc_midstate(struct work *work)
  2690. {
  2691. union {
  2692. unsigned char c[64];
  2693. uint32_t i[16];
  2694. } data;
  2695. swap32yes(&data.i[0], work->data, 16);
  2696. sha256_ctx ctx;
  2697. sha256_init(&ctx);
  2698. sha256_update(&ctx, data.c, 64);
  2699. memcpy(work->midstate, ctx.h, sizeof(work->midstate));
  2700. swap32tole(work->midstate, work->midstate, 8);
  2701. }
  2702. static
  2703. struct bfg_tmpl_ref *tmpl_makeref(blktemplate_t * const tmpl)
  2704. {
  2705. struct bfg_tmpl_ref * const tr = malloc(sizeof(*tr));
  2706. *tr = (struct bfg_tmpl_ref){
  2707. .tmpl = tmpl,
  2708. .refcount = 1,
  2709. };
  2710. mutex_init(&tr->mutex);
  2711. return tr;
  2712. }
  2713. static
  2714. void tmpl_incref(struct bfg_tmpl_ref * const tr)
  2715. {
  2716. mutex_lock(&tr->mutex);
  2717. ++tr->refcount;
  2718. mutex_unlock(&tr->mutex);
  2719. }
  2720. void tmpl_decref(struct bfg_tmpl_ref * const tr)
  2721. {
  2722. mutex_lock(&tr->mutex);
  2723. bool free_tmpl = !--tr->refcount;
  2724. mutex_unlock(&tr->mutex);
  2725. if (free_tmpl)
  2726. {
  2727. blktmpl_free(tr->tmpl);
  2728. mutex_destroy(&tr->mutex);
  2729. free(tr);
  2730. }
  2731. }
  2732. static struct work *make_work(void)
  2733. {
  2734. struct work *work = calloc(1, sizeof(struct work));
  2735. if (unlikely(!work))
  2736. quit(1, "Failed to calloc work in make_work");
  2737. cg_wlock(&control_lock);
  2738. work->id = total_work++;
  2739. cg_wunlock(&control_lock);
  2740. return work;
  2741. }
  2742. /* This is the central place all work that is about to be retired should be
  2743. * cleaned to remove any dynamically allocated arrays within the struct */
  2744. void clean_work(struct work *work)
  2745. {
  2746. free(work->job_id);
  2747. bytes_free(&work->nonce2);
  2748. free(work->nonce1);
  2749. if (work->device_data_free_func)
  2750. work->device_data_free_func(work);
  2751. if (work->tr)
  2752. tmpl_decref(work->tr);
  2753. memset(work, 0, sizeof(struct work));
  2754. }
  2755. /* All dynamically allocated work structs should be freed here to not leak any
  2756. * ram from arrays allocated within the work struct */
  2757. void free_work(struct work *work)
  2758. {
  2759. clean_work(work);
  2760. free(work);
  2761. }
  2762. 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";
  2763. #define workpadding_bin bfg_workpadding_bin
  2764. static const size_t block_info_str_sz = 3 /* ... */ + 16 /* block hash segment */ + 1;
  2765. static
  2766. void block_info_str(char * const out, const struct block_info * const blkinfo)
  2767. {
  2768. unsigned char hash_swap[32];
  2769. swap256(hash_swap, blkinfo->prevblkhash);
  2770. swap32tole(hash_swap, hash_swap, 32 / 4);
  2771. memset(out, '.', 3);
  2772. // FIXME: The block number will overflow this sometime around AD 2025-2027
  2773. if (blkinfo->height > 0 && blkinfo->height < 1000000)
  2774. {
  2775. bin2hex(&out[3], &hash_swap[0x1c], 4);
  2776. snprintf(&out[11], block_info_str_sz-11, " #%6u", blkinfo->height);
  2777. }
  2778. else
  2779. bin2hex(&out[3], &hash_swap[0x18], 8);
  2780. }
  2781. #ifdef HAVE_CURSES
  2782. static void update_block_display(void);
  2783. #endif
  2784. // Must only be called with ch_lock held!
  2785. static
  2786. void __update_block_title(struct mining_goal_info * const goal)
  2787. {
  2788. struct blockchain_info * const blkchain = goal->blkchain;
  2789. if (!goal->current_goal_detail)
  2790. goal->current_goal_detail = malloc(block_info_str_sz);
  2791. block_info_str(goal->current_goal_detail, blkchain->currentblk);
  2792. #ifdef HAVE_CURSES
  2793. update_block_display();
  2794. #endif
  2795. }
  2796. static struct block_info *block_exists(const struct blockchain_info *, const void *);
  2797. static
  2798. void have_block_height(struct mining_goal_info * const goal, const void * const prevblkhash, uint32_t blkheight)
  2799. {
  2800. struct blockchain_info * const blkchain = goal->blkchain;
  2801. struct block_info * const blkinfo = block_exists(blkchain, prevblkhash);
  2802. if ((!blkinfo) || blkinfo->height)
  2803. return;
  2804. uint32_t block_id = ((uint32_t*)prevblkhash)[0];
  2805. applog(LOG_DEBUG, "Learned that block id %08" PRIx32 " is height %" PRIu32, (uint32_t)be32toh(block_id), blkheight);
  2806. cg_wlock(&ch_lock);
  2807. blkinfo->height = blkheight;
  2808. if (blkinfo == blkchain->currentblk)
  2809. {
  2810. blkchain->currentblk_subsidy = 5000000000LL >> (blkheight / 210000);
  2811. __update_block_title(goal);
  2812. }
  2813. cg_wunlock(&ch_lock);
  2814. }
  2815. static
  2816. void pool_set_opaque(struct pool *pool, bool opaque)
  2817. {
  2818. if (pool->swork.opaque == opaque)
  2819. return;
  2820. pool->swork.opaque = opaque;
  2821. if (opaque)
  2822. applog(LOG_WARNING, "Pool %u is hiding block contents from us",
  2823. pool->pool_no);
  2824. else
  2825. applog(LOG_NOTICE, "Pool %u now providing block contents to us",
  2826. pool->pool_no);
  2827. }
  2828. bool pool_may_redirect_to(struct pool * const pool, const char * const uri)
  2829. {
  2830. if (uri_get_param_bool(pool->rpc_url, "redirect", false))
  2831. return true;
  2832. return match_domains(pool->rpc_url, strlen(pool->rpc_url), uri, strlen(uri));
  2833. }
  2834. void pool_check_coinbase(struct pool * const pool, const uint8_t * const cbtxn, const size_t cbtxnsz)
  2835. {
  2836. if (uri_get_param_bool(pool->rpc_url, "skipcbcheck", false))
  2837. {}
  2838. else
  2839. if (!check_coinbase(cbtxn, cbtxnsz, &pool->cb_param))
  2840. {
  2841. if (pool->enabled == POOL_ENABLED)
  2842. {
  2843. applog(LOG_ERR, "Pool %d misbehaving (%s), disabling!", pool->pool_no, "coinbase check");
  2844. disable_pool(pool, POOL_MISBEHAVING);
  2845. }
  2846. }
  2847. else
  2848. if (pool->enabled == POOL_MISBEHAVING)
  2849. {
  2850. applog(LOG_NOTICE, "Pool %d no longer misbehaving, re-enabling!", pool->pool_no);
  2851. enable_pool(pool);
  2852. }
  2853. }
  2854. 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)
  2855. {
  2856. const int offsets = max(ntime_roll, 60);
  2857. *nrl = (struct ntime_roll_limits){
  2858. .min = ntime_base,
  2859. .max = ntime_base + ntime_roll,
  2860. .tv_ref = *tvp_ref,
  2861. .minoff = -offsets,
  2862. .maxoff = offsets,
  2863. };
  2864. }
  2865. void work_set_simple_ntime_roll_limit(struct work * const work, const int ntime_roll, const struct timeval * const tvp_ref)
  2866. {
  2867. set_simple_ntime_roll_limit(&work->ntime_roll_limits, upk_u32be(work->data, 0x44), ntime_roll, tvp_ref);
  2868. }
  2869. int work_ntime_range(struct work * const work, const struct timeval * const tvp_earliest, const struct timeval * const tvp_latest, const int desired_roll)
  2870. {
  2871. const struct ntime_roll_limits * const nrl = &work->ntime_roll_limits;
  2872. const uint32_t ref_ntime = work_get_ntime(work);
  2873. const int earliest_elapsed = timer_elapsed(&nrl->tv_ref, tvp_earliest);
  2874. const int latest_elapsed = timer_elapsed(&nrl->tv_ref, tvp_latest);
  2875. // minimum ntime is the latest possible result (add a second to spare) adjusted for minimum offset (or fixed minimum ntime)
  2876. uint32_t min_ntime = max(nrl->min, ref_ntime + latest_elapsed+1 + nrl->minoff);
  2877. // maximum ntime is the earliest possible result adjusted for maximum offset (or fixed maximum ntime)
  2878. uint32_t max_ntime = min(nrl->max, ref_ntime + earliest_elapsed + nrl->maxoff);
  2879. if (max_ntime < min_ntime)
  2880. return -1;
  2881. if (max_ntime - min_ntime > desired_roll)
  2882. {
  2883. // Adjust min_ntime upward for accuracy, when possible
  2884. const int mid_elapsed = ((latest_elapsed - earliest_elapsed) / 2) + earliest_elapsed;
  2885. uint32_t ideal_ntime = ref_ntime + mid_elapsed;
  2886. if (ideal_ntime > min_ntime)
  2887. min_ntime = min(ideal_ntime, max_ntime - desired_roll);
  2888. }
  2889. work_set_ntime(work, min_ntime);
  2890. return max_ntime - min_ntime;
  2891. }
  2892. #if BLKMAKER_VERSION > 1
  2893. static
  2894. bool goal_has_at_least_one_getcbaddr(const struct mining_goal_info * const goal)
  2895. {
  2896. for (int i = 0; i < total_pools; ++i)
  2897. {
  2898. struct pool * const pool = pools[i];
  2899. if (uri_get_param_bool(pool->rpc_url, "getcbaddr", false))
  2900. return true;
  2901. }
  2902. return false;
  2903. }
  2904. static
  2905. void refresh_bitcoind_address(struct mining_goal_info * const goal, const bool fresh)
  2906. {
  2907. struct blockchain_info * const blkchain = goal->blkchain;
  2908. if (!goal_has_at_least_one_getcbaddr(goal))
  2909. return;
  2910. char getcbaddr_req[60];
  2911. CURL *curl = NULL;
  2912. json_t *json, *j2;
  2913. const char *s, *s2;
  2914. bytes_t newscript = BYTES_INIT;
  2915. snprintf(getcbaddr_req, sizeof(getcbaddr_req), "{\"method\":\"get%saddress\",\"id\":0,\"params\":[\"BFGMiner\"]}", fresh ? "new" : "account");
  2916. for (int i = 0; i < total_pools; ++i)
  2917. {
  2918. struct pool * const pool = pools[i];
  2919. if (!uri_get_param_bool(pool->rpc_url, "getcbaddr", false))
  2920. continue;
  2921. if (pool->goal != goal)
  2922. continue;
  2923. applog(LOG_DEBUG, "Refreshing coinbase address from pool %d", pool->pool_no);
  2924. if (!curl)
  2925. {
  2926. curl = curl_easy_init();
  2927. if (unlikely(!curl))
  2928. {
  2929. applogfail(LOG_ERR, "curl_easy_init");
  2930. break;
  2931. }
  2932. }
  2933. json = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, getcbaddr_req, false, false, NULL, pool, true);
  2934. if (unlikely((!json) || !json_is_null( (j2 = json_object_get(json, "error")) )))
  2935. {
  2936. const char *estrc;
  2937. char *estr = NULL;
  2938. if (!(json && j2))
  2939. estrc = NULL;
  2940. else
  2941. {
  2942. estrc = json_string_value(j2);
  2943. if (!estrc)
  2944. estrc = estr = json_dumps_ANY(j2, JSON_ENSURE_ASCII | JSON_SORT_KEYS);
  2945. }
  2946. applog(LOG_WARNING, "Error %cetting coinbase address from pool %d: %s", 'g', pool->pool_no, estrc);
  2947. free(estr);
  2948. continue;
  2949. }
  2950. s = bfg_json_obj_string(json, "result", NULL);
  2951. if (unlikely(!s))
  2952. {
  2953. applog(LOG_WARNING, "Error %cetting coinbase address from pool %d: %s", 'g', pool->pool_no, "(return value was not a String)");
  2954. continue;
  2955. }
  2956. s2 = set_b58addr(s, &newscript);
  2957. if (unlikely(s2))
  2958. {
  2959. applog(LOG_WARNING, "Error %cetting coinbase address from pool %d: %s", 's', pool->pool_no, s2);
  2960. continue;
  2961. }
  2962. if (goal->generation_script)
  2963. {
  2964. if (bytes_eq(&newscript, goal->generation_script))
  2965. {
  2966. applog(LOG_DEBUG, "Pool %d returned coinbase address already in use (%s)", pool->pool_no, s2);
  2967. break;
  2968. }
  2969. }
  2970. else
  2971. {
  2972. goal->generation_script = malloc(sizeof(*goal->generation_script));
  2973. bytes_init(goal->generation_script);
  2974. }
  2975. bytes_assimilate(goal->generation_script, &newscript);
  2976. coinbase_script_block_id = blkchain->currentblk->block_id;
  2977. applog(LOG_NOTICE, "Now using coinbase address %s, provided by pool %d", s, pool->pool_no);
  2978. break;
  2979. }
  2980. bytes_free(&newscript);
  2981. if (curl)
  2982. curl_easy_cleanup(curl);
  2983. }
  2984. #endif
  2985. #define GBT_XNONCESZ (sizeof(uint32_t))
  2986. #if BLKMAKER_VERSION > 4
  2987. #define blkmk_append_coinbase_safe(tmpl, append, appendsz) \
  2988. blkmk_append_coinbase_safe2(tmpl, append, appendsz, GBT_XNONCESZ, false)
  2989. #endif
  2990. static bool work_decode(struct pool *pool, struct work *work, json_t *val)
  2991. {
  2992. json_t *res_val = json_object_get(val, "result");
  2993. json_t *tmp_val;
  2994. bool ret = false;
  2995. struct timeval tv_now;
  2996. if (unlikely(detect_algo == 1)) {
  2997. json_t *tmp = json_object_get(res_val, "algorithm");
  2998. const char *v = tmp ? json_string_value(tmp) : "";
  2999. if (strncasecmp(v, "scrypt", 6))
  3000. detect_algo = 2;
  3001. }
  3002. timer_set_now(&tv_now);
  3003. if (work->tr)
  3004. {
  3005. blktemplate_t * const tmpl = work->tr->tmpl;
  3006. const char *err = blktmpl_add_jansson(tmpl, res_val, tv_now.tv_sec);
  3007. if (err) {
  3008. applog(LOG_ERR, "blktmpl error: %s", err);
  3009. return false;
  3010. }
  3011. work->rolltime = blkmk_time_left(tmpl, tv_now.tv_sec);
  3012. #if BLKMAKER_VERSION > 1
  3013. struct mining_goal_info * const goal = pool->goal;
  3014. const uint32_t tmpl_block_id = ((uint32_t*)tmpl->prevblk)[0];
  3015. if ((!tmpl->cbtxn) && coinbase_script_block_id != tmpl_block_id)
  3016. refresh_bitcoind_address(goal, false);
  3017. if (goal->generation_script)
  3018. {
  3019. bool newcb;
  3020. #if BLKMAKER_VERSION > 2
  3021. blkmk_init_generation2(tmpl, bytes_buf(goal->generation_script), bytes_len(goal->generation_script), &newcb);
  3022. #else
  3023. newcb = !tmpl->cbtxn;
  3024. blkmk_init_generation(tmpl, bytes_buf(goal->generation_script), bytes_len(goal->generation_script));
  3025. #endif
  3026. if (newcb)
  3027. {
  3028. ssize_t ae = blkmk_append_coinbase_safe(tmpl, &template_nonce, sizeof(template_nonce));
  3029. if (ae < (ssize_t)sizeof(template_nonce))
  3030. 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);
  3031. ++template_nonce;
  3032. }
  3033. }
  3034. #endif
  3035. #if BLKMAKER_VERSION > 0
  3036. {
  3037. ssize_t ae = blkmk_append_coinbase_safe(tmpl, opt_coinbase_sig, 101);
  3038. static bool appenderr = false;
  3039. if (ae <= 0) {
  3040. if (opt_coinbase_sig) {
  3041. applog((appenderr ? LOG_DEBUG : LOG_WARNING), "Cannot append coinbase signature at all on pool %u (%"PRId64")", pool->pool_no, (int64_t)ae);
  3042. appenderr = true;
  3043. }
  3044. } else if (ae >= 3 || opt_coinbase_sig) {
  3045. const char *cbappend = opt_coinbase_sig;
  3046. const char full[] = PACKAGE " " VERSION;
  3047. char *need_free = NULL;
  3048. if (!cbappend) {
  3049. if ((size_t)ae >= sizeof(full) - 1)
  3050. cbappend = full;
  3051. else if ((size_t)ae >= sizeof(PACKAGE) - 1)
  3052. {
  3053. const char *pos = strchr(full, '-');
  3054. size_t sz = (pos - full);
  3055. if (pos && ae > sz)
  3056. {
  3057. cbappend = need_free = malloc(sz + 1);
  3058. memcpy(need_free, full, sz);
  3059. need_free[sz] = '\0';
  3060. }
  3061. else
  3062. cbappend = PACKAGE;
  3063. }
  3064. else
  3065. cbappend = "BFG";
  3066. }
  3067. size_t cbappendsz = strlen(cbappend);
  3068. static bool truncatewarning = false;
  3069. if (cbappendsz <= (size_t)ae) {
  3070. if (cbappendsz < (size_t)ae)
  3071. // If we have space, include the trailing \0
  3072. ++cbappendsz;
  3073. ae = cbappendsz;
  3074. truncatewarning = false;
  3075. } else {
  3076. char *tmp = malloc(ae + 1);
  3077. memcpy(tmp, opt_coinbase_sig, ae);
  3078. tmp[ae] = '\0';
  3079. applog((truncatewarning ? LOG_DEBUG : LOG_WARNING),
  3080. "Pool %u truncating appended coinbase signature at %"PRId64" bytes: %s(%s)",
  3081. pool->pool_no, (int64_t)ae, tmp, &opt_coinbase_sig[ae]);
  3082. free(tmp);
  3083. truncatewarning = true;
  3084. }
  3085. ae = blkmk_append_coinbase_safe(tmpl, cbappend, ae);
  3086. free(need_free);
  3087. if (ae <= 0) {
  3088. applog((appenderr ? LOG_DEBUG : LOG_WARNING), "Error appending coinbase signature (%"PRId64")", (int64_t)ae);
  3089. appenderr = true;
  3090. } else
  3091. appenderr = false;
  3092. }
  3093. }
  3094. #endif
  3095. if (blkmk_get_data(tmpl, work->data, 80, tv_now.tv_sec, NULL, &work->dataid) < 76)
  3096. return false;
  3097. swap32yes(work->data, work->data, 80 / 4);
  3098. memcpy(&work->data[80], workpadding_bin, 48);
  3099. work->ntime_roll_limits = (struct ntime_roll_limits){
  3100. .min = tmpl->mintime,
  3101. .max = tmpl->maxtime,
  3102. .tv_ref = tv_now,
  3103. .minoff = tmpl->mintimeoff,
  3104. .maxoff = tmpl->maxtimeoff,
  3105. };
  3106. const struct blktmpl_longpoll_req *lp;
  3107. if ((lp = blktmpl_get_longpoll(tmpl)) && ((!pool->lp_id) || strcmp(lp->id, pool->lp_id))) {
  3108. free(pool->lp_id);
  3109. pool->lp_id = strdup(lp->id);
  3110. #if 0 /* This just doesn't work :( */
  3111. curl_socket_t sock = pool->lp_socket;
  3112. if (sock != CURL_SOCKET_BAD) {
  3113. pool->lp_socket = CURL_SOCKET_BAD;
  3114. applog(LOG_WARNING, "Pool %u long poll request hanging, reconnecting", pool->pool_no);
  3115. shutdown(sock, SHUT_RDWR);
  3116. }
  3117. #endif
  3118. }
  3119. }
  3120. else
  3121. if (unlikely(!jobj_binary(res_val, "data", work->data, sizeof(work->data), true))) {
  3122. applog(LOG_ERR, "JSON inval data");
  3123. return false;
  3124. }
  3125. else
  3126. work_set_simple_ntime_roll_limit(work, 0, &tv_now);
  3127. if (!jobj_binary(res_val, "midstate", work->midstate, sizeof(work->midstate), false)) {
  3128. // Calculate it ourselves
  3129. applog(LOG_DEBUG, "Calculating midstate locally");
  3130. calc_midstate(work);
  3131. }
  3132. if (unlikely(!jobj_binary(res_val, "target", work->target, sizeof(work->target), true))) {
  3133. applog(LOG_ERR, "JSON inval target");
  3134. return false;
  3135. }
  3136. if (work->tr)
  3137. {
  3138. for (size_t i = 0; i < sizeof(work->target) / 2; ++i)
  3139. {
  3140. int p = (sizeof(work->target) - 1) - i;
  3141. unsigned char c = work->target[i];
  3142. work->target[i] = work->target[p];
  3143. work->target[p] = c;
  3144. }
  3145. }
  3146. if ( (tmp_val = json_object_get(res_val, "height")) ) {
  3147. struct mining_goal_info * const goal = pool->goal;
  3148. uint32_t blkheight = json_number_value(tmp_val);
  3149. const void * const prevblkhash = &work->data[4];
  3150. have_block_height(goal, prevblkhash, blkheight);
  3151. }
  3152. memset(work->hash, 0, sizeof(work->hash));
  3153. work->tv_staged = tv_now;
  3154. #if BLKMAKER_VERSION > 4
  3155. if (work->tr)
  3156. {
  3157. blktemplate_t * const tmpl = work->tr->tmpl;
  3158. uint8_t buf[80];
  3159. int16_t expire;
  3160. uint8_t *cbtxn;
  3161. size_t cbtxnsz;
  3162. size_t cbextranonceoffset;
  3163. int branchcount;
  3164. libblkmaker_hash_t *branches;
  3165. if (blkmk_get_mdata(tmpl, buf, sizeof(buf), tv_now.tv_sec, &expire, &cbtxn, &cbtxnsz, &cbextranonceoffset, &branchcount, &branches, GBT_XNONCESZ, false))
  3166. {
  3167. struct stratum_work * const swork = &pool->swork;
  3168. const size_t branchdatasz = branchcount * 0x20;
  3169. pool_check_coinbase(pool, cbtxn, cbtxnsz);
  3170. cg_wlock(&pool->data_lock);
  3171. swork->tr = work->tr;
  3172. bytes_assimilate_raw(&swork->coinbase, cbtxn, cbtxnsz, cbtxnsz);
  3173. swork->nonce2_offset = cbextranonceoffset;
  3174. bytes_assimilate_raw(&swork->merkle_bin, branches, branchdatasz, branchdatasz);
  3175. swork->merkles = branchcount;
  3176. memcpy(swork->header1, &buf[0], 36);
  3177. swork->ntime = le32toh(*(uint32_t *)(&buf[68]));
  3178. swork->tv_received = tv_now;
  3179. memcpy(swork->diffbits, &buf[72], 4);
  3180. memcpy(swork->target, work->target, sizeof(swork->target));
  3181. free(swork->job_id);
  3182. swork->job_id = NULL;
  3183. swork->clean = true;
  3184. swork->work_restart_id = pool->work_restart_id;
  3185. // FIXME: Do something with expire
  3186. pool->nonce2sz = swork->n2size = GBT_XNONCESZ;
  3187. pool->nonce2 = 0;
  3188. cg_wunlock(&pool->data_lock);
  3189. }
  3190. else
  3191. applog(LOG_DEBUG, "blkmk_get_mdata failed for pool %u", pool->pool_no);
  3192. }
  3193. #endif // BLKMAKER_VERSION > 4
  3194. pool_set_opaque(pool, !work->tr);
  3195. ret = true;
  3196. return ret;
  3197. }
  3198. /* Returns whether the pool supports local work generation or not. */
  3199. static bool pool_localgen(struct pool *pool)
  3200. {
  3201. return (pool->last_work_copy || pool->has_stratum);
  3202. }
  3203. int dev_from_id(int thr_id)
  3204. {
  3205. struct cgpu_info *cgpu = get_thr_cgpu(thr_id);
  3206. return cgpu->device_id;
  3207. }
  3208. /* Create an exponentially decaying average over the opt_log_interval */
  3209. void decay_time(double *f, double fadd, double fsecs)
  3210. {
  3211. double ftotal, fprop;
  3212. fprop = 1.0 - 1 / (exp(fsecs / (double)opt_log_interval));
  3213. ftotal = 1.0 + fprop;
  3214. *f += (fadd * fprop);
  3215. *f /= ftotal;
  3216. }
  3217. static int __total_staged(void)
  3218. {
  3219. return HASH_COUNT(staged_work);
  3220. }
  3221. static int total_staged(void)
  3222. {
  3223. int ret;
  3224. mutex_lock(stgd_lock);
  3225. ret = __total_staged();
  3226. mutex_unlock(stgd_lock);
  3227. return ret;
  3228. }
  3229. #ifdef HAVE_CURSES
  3230. WINDOW *mainwin, *statuswin, *logwin;
  3231. #endif
  3232. double total_secs = 1.0;
  3233. #ifdef HAVE_CURSES
  3234. static char statusline[256];
  3235. /* statusy is where the status window goes up to in cases where it won't fit at startup */
  3236. static int statusy;
  3237. static int devsummaryYOffset;
  3238. static int total_lines;
  3239. #endif
  3240. #ifdef HAVE_OPENCL
  3241. struct cgpu_info gpus[MAX_GPUDEVICES]; /* Maximum number apparently possible */
  3242. #endif
  3243. struct cgpu_info *cpus;
  3244. bool _bfg_console_cancel_disabled;
  3245. int _bfg_console_prev_cancelstate;
  3246. #ifdef HAVE_CURSES
  3247. #define lock_curses() bfg_console_lock()
  3248. #define unlock_curses() bfg_console_unlock()
  3249. static bool curses_active_locked(void)
  3250. {
  3251. bool ret;
  3252. lock_curses();
  3253. ret = curses_active;
  3254. if (!ret)
  3255. unlock_curses();
  3256. return ret;
  3257. }
  3258. // Cancellable getch
  3259. int my_cancellable_getch(void)
  3260. {
  3261. // This only works because the macro only hits direct getch() calls
  3262. typedef int (*real_getch_t)(void);
  3263. const real_getch_t real_getch = __real_getch;
  3264. int type, rv;
  3265. bool sct;
  3266. sct = !pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &type);
  3267. rv = real_getch();
  3268. if (sct)
  3269. pthread_setcanceltype(type, &type);
  3270. return rv;
  3271. }
  3272. #ifdef PDCURSES
  3273. static
  3274. int bfg_wresize(WINDOW *win, int lines, int columns)
  3275. {
  3276. int rv = wresize(win, lines, columns);
  3277. int x, y;
  3278. getyx(win, y, x);
  3279. if (unlikely(y >= lines || x >= columns))
  3280. {
  3281. if (y >= lines)
  3282. y = lines - 1;
  3283. if (x >= columns)
  3284. x = columns - 1;
  3285. wmove(win, y, x);
  3286. }
  3287. return rv;
  3288. }
  3289. #else
  3290. # define bfg_wresize wresize
  3291. #endif
  3292. #endif
  3293. void tailsprintf(char *buf, size_t bufsz, const char *fmt, ...)
  3294. {
  3295. va_list ap;
  3296. size_t presz = strlen(buf);
  3297. va_start(ap, fmt);
  3298. vsnprintf(&buf[presz], bufsz - presz, fmt, ap);
  3299. va_end(ap);
  3300. }
  3301. double stats_elapsed(struct cgminer_stats *stats)
  3302. {
  3303. struct timeval now;
  3304. double elapsed;
  3305. if (stats->start_tv.tv_sec == 0)
  3306. elapsed = total_secs;
  3307. else {
  3308. cgtime(&now);
  3309. elapsed = tdiff(&now, &stats->start_tv);
  3310. }
  3311. if (elapsed < 1.0)
  3312. elapsed = 1.0;
  3313. return elapsed;
  3314. }
  3315. bool drv_ready(struct cgpu_info *cgpu)
  3316. {
  3317. switch (cgpu->status) {
  3318. case LIFE_INIT:
  3319. case LIFE_DEAD2:
  3320. return false;
  3321. default:
  3322. return true;
  3323. }
  3324. }
  3325. double cgpu_utility(struct cgpu_info *cgpu)
  3326. {
  3327. double dev_runtime = cgpu_runtime(cgpu);
  3328. return cgpu->utility = cgpu->accepted / dev_runtime * 60;
  3329. }
  3330. #define suffix_string(val, buf, bufsiz, sigdigits) do{ \
  3331. _Static_assert(sigdigits == 0, "suffix_string only supported with sigdigits==0"); \
  3332. format_unit3(buf, bufsiz, FUP_DIFF, "", H2B_SHORTV, val, -1); \
  3333. }while(0)
  3334. static float
  3335. utility_to_hashrate(double utility)
  3336. {
  3337. return utility * 0x4444444;
  3338. }
  3339. static const char*_unitchar = "pn\xb5m kMGTPEZY?";
  3340. static const int _unitbase = 4;
  3341. static
  3342. void pick_unit(float hashrate, unsigned char *unit)
  3343. {
  3344. unsigned char i;
  3345. if (hashrate == 0 || !isfinite(hashrate))
  3346. {
  3347. if (*unit < _unitbase)
  3348. *unit = _unitbase;
  3349. return;
  3350. }
  3351. hashrate *= 1e12;
  3352. for (i = 0; i < *unit; ++i)
  3353. hashrate /= 1e3;
  3354. // 1000 but with tolerance for floating-point rounding, avoid showing "1000.0"
  3355. while (hashrate >= 999.95)
  3356. {
  3357. hashrate /= 1e3;
  3358. if (likely(_unitchar[*unit] != '?'))
  3359. ++*unit;
  3360. }
  3361. }
  3362. #define hashrate_pick_unit(hashrate, unit) pick_unit(hashrate, unit)
  3363. enum h2bs_fmt {
  3364. H2B_NOUNIT, // "xxx.x"
  3365. H2B_SHORT, // "xxx.xMH/s"
  3366. H2B_SPACED, // "xxx.x MH/s"
  3367. H2B_SHORTV, // Like H2B_SHORT, but omit space for base unit
  3368. };
  3369. enum bfu_floatprec {
  3370. FUP_INTEGER,
  3371. FUP_HASHES,
  3372. FUP_BTC,
  3373. FUP_DIFF,
  3374. };
  3375. static
  3376. int format_unit3(char *buf, size_t sz, enum bfu_floatprec fprec, const char *measurement, enum h2bs_fmt fmt, float hashrate, signed char unitin)
  3377. {
  3378. char *s = buf;
  3379. unsigned char prec, i, unit;
  3380. int rv = 0;
  3381. if (unitin == -1)
  3382. {
  3383. unit = 0;
  3384. hashrate_pick_unit(hashrate, &unit);
  3385. }
  3386. else
  3387. unit = unitin;
  3388. hashrate *= 1e12;
  3389. for (i = 0; i < unit; ++i)
  3390. hashrate /= 1000;
  3391. switch (fprec)
  3392. {
  3393. case FUP_HASHES:
  3394. // 100 but with tolerance for floating-point rounding, max "99.99" then "100.0"
  3395. if (hashrate >= 99.995 || unit < 6)
  3396. prec = 1;
  3397. else
  3398. prec = 2;
  3399. _SNP("%5.*f", prec, hashrate);
  3400. break;
  3401. case FUP_INTEGER:
  3402. _SNP("%3d", (int)hashrate);
  3403. break;
  3404. case FUP_BTC:
  3405. if (hashrate >= 99.995)
  3406. prec = 0;
  3407. else
  3408. prec = 2;
  3409. _SNP("%5.*f", prec, hashrate);
  3410. break;
  3411. case FUP_DIFF:
  3412. if (unit > _unitbase)
  3413. _SNP("%.3g", hashrate);
  3414. else
  3415. _SNP("%u", (unsigned int)hashrate);
  3416. }
  3417. if (fmt != H2B_NOUNIT)
  3418. {
  3419. char uc[3] = {_unitchar[unit], '\0'};
  3420. switch (fmt) {
  3421. case H2B_SPACED:
  3422. _SNP(" ");
  3423. default:
  3424. break;
  3425. case H2B_SHORTV:
  3426. if (isspace(uc[0]))
  3427. uc[0] = '\0';
  3428. }
  3429. if (uc[0] == '\xb5')
  3430. // Convert to UTF-8
  3431. snprintf(uc, sizeof(uc), "%s", U8_MICRO);
  3432. _SNP("%s%s", uc, measurement);
  3433. }
  3434. return rv;
  3435. }
  3436. #define format_unit2(buf, sz, floatprec, measurement, fmt, n, unit) \
  3437. format_unit3(buf, sz, floatprec ? FUP_HASHES : FUP_INTEGER, measurement, fmt, n, unit)
  3438. static
  3439. 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)
  3440. {
  3441. unsigned char unit = 0;
  3442. bool allzero = true;
  3443. int i;
  3444. size_t delimsz = 0;
  3445. char *buf = buflist[0];
  3446. size_t bufsz = bufszlist[0];
  3447. size_t itemwidth = (floatprec ? 5 : 3);
  3448. if (!isarray)
  3449. delimsz = strlen(delim);
  3450. for (i = 0; i < count; ++i)
  3451. if (numbers[i] != 0)
  3452. {
  3453. pick_unit(numbers[i], &unit);
  3454. allzero = false;
  3455. }
  3456. if (allzero)
  3457. unit = _unitbase;
  3458. --count;
  3459. for (i = 0; i < count; ++i)
  3460. {
  3461. format_unit2(buf, bufsz, floatprec, NULL, H2B_NOUNIT, numbers[i], unit);
  3462. if (isarray)
  3463. {
  3464. buf = buflist[i + 1];
  3465. bufsz = bufszlist[i + 1];
  3466. }
  3467. else
  3468. {
  3469. buf += itemwidth;
  3470. bufsz -= itemwidth;
  3471. if (delimsz > bufsz)
  3472. delimsz = bufsz;
  3473. memcpy(buf, delim, delimsz);
  3474. buf += delimsz;
  3475. bufsz -= delimsz;
  3476. }
  3477. }
  3478. // Last entry has the unit
  3479. format_unit2(buf, bufsz, floatprec, measurement, fmt, numbers[count], unit);
  3480. return buflist[0];
  3481. }
  3482. #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)
  3483. #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)
  3484. static
  3485. int percentf3(char * const buf, size_t sz, double p, const double t)
  3486. {
  3487. char *s = buf;
  3488. int rv = 0;
  3489. if (!p)
  3490. _SNP("none");
  3491. else
  3492. if (t <= p)
  3493. _SNP("100%%");
  3494. else
  3495. {
  3496. p /= t;
  3497. if (p < 0.00995) // 0.01 but with tolerance for floating-point rounding, max ".99%"
  3498. _SNP(".%02.0f%%", p * 10000); // ".01%"
  3499. else
  3500. if (p < 0.0995) // 0.1 but with tolerance for floating-point rounding, max "9.9%"
  3501. _SNP("%.1f%%", p * 100); // "9.1%"
  3502. else
  3503. _SNP("%3.0f%%", p * 100); // " 99%"
  3504. }
  3505. return rv;
  3506. }
  3507. #define percentf4(buf, bufsz, p, t) percentf3(buf, bufsz, p, p + t)
  3508. static
  3509. void test_decimal_width()
  3510. {
  3511. // The pipe character at end of each line should perfectly line up
  3512. char printbuf[512];
  3513. char testbuf1[64];
  3514. char testbuf2[64];
  3515. char testbuf3[64];
  3516. char testbuf4[64];
  3517. double testn;
  3518. int width;
  3519. int saved;
  3520. // Hotspots around 0.1 and 0.01
  3521. saved = -1;
  3522. for (testn = 0.09; testn <= 0.11; testn += 0.000001) {
  3523. percentf3(testbuf1, sizeof(testbuf1), testn, 1.0);
  3524. percentf3(testbuf2, sizeof(testbuf2), testn, 10.0);
  3525. width = snprintf(printbuf, sizeof(printbuf), "%10g %s %s |", testn, testbuf1, testbuf2);
  3526. if (unlikely((saved != -1) && (width != saved))) {
  3527. ++unittest_failures;
  3528. applog(LOG_ERR, "Test width mismatch in percentf3! %d not %d at %10g", width, saved, testn);
  3529. applog(LOG_ERR, "%s", printbuf);
  3530. }
  3531. saved = width;
  3532. }
  3533. // Hotspot around 100 (but test this in several units because format_unit2 also has unit<2 check)
  3534. saved = -1;
  3535. for (testn = 99.0; testn <= 101.0; testn += 0.0001) {
  3536. format_unit2(testbuf1, sizeof(testbuf1), true, "x", H2B_SHORT, testn , -1);
  3537. format_unit2(testbuf2, sizeof(testbuf2), true, "x", H2B_SHORT, testn * 1e3, -1);
  3538. format_unit2(testbuf3, sizeof(testbuf3), true, "x", H2B_SHORT, testn * 1e6, -1);
  3539. snprintf(printbuf, sizeof(printbuf), "%10g %s %s %s |", testn, testbuf1, testbuf2, testbuf3);
  3540. width = utf8_strlen(printbuf);
  3541. if (unlikely((saved != -1) && (width != saved))) {
  3542. ++unittest_failures;
  3543. applog(LOG_ERR, "Test width mismatch in format_unit2! %d not %d at %10g", width, saved, testn);
  3544. applog(LOG_ERR, "%s", printbuf);
  3545. }
  3546. saved = width;
  3547. }
  3548. // Hotspot around unit transition boundary in pick_unit
  3549. saved = -1;
  3550. for (testn = 999.0; testn <= 1001.0; testn += 0.0001) {
  3551. format_unit2(testbuf1, sizeof(testbuf1), true, "x", H2B_SHORT, testn , -1);
  3552. format_unit2(testbuf2, sizeof(testbuf2), true, "x", H2B_SHORT, testn * 1e3, -1);
  3553. format_unit2(testbuf3, sizeof(testbuf3), true, "x", H2B_SHORT, testn * 1e6, -1);
  3554. format_unit2(testbuf4, sizeof(testbuf4), true, "x", H2B_SHORT, testn * 1e9, -1);
  3555. snprintf(printbuf, sizeof(printbuf), "%10g %s %s %s %s |", testn, testbuf1, testbuf2, testbuf3, testbuf4);
  3556. width = utf8_strlen(printbuf);
  3557. if (unlikely((saved != -1) && (width != saved))) {
  3558. ++unittest_failures;
  3559. applog(LOG_ERR, "Test width mismatch in pick_unit! %d not %d at %10g", width, saved, testn);
  3560. applog(LOG_ERR, "%s", printbuf);
  3561. }
  3562. saved = width;
  3563. }
  3564. }
  3565. #ifdef HAVE_CURSES
  3566. static void adj_width(int var, int *length);
  3567. #endif
  3568. #ifdef HAVE_CURSES
  3569. static int awidth = 1, rwidth = 1, swidth = 1, hwwidth = 1;
  3570. static
  3571. 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)
  3572. {
  3573. char rejpcbuf[6];
  3574. char bnbuf[6];
  3575. adj_width(accepted, &awidth);
  3576. adj_width(rejected, &rwidth);
  3577. adj_width(stale, &swidth);
  3578. adj_width(hwerrs, &hwwidth);
  3579. percentf4(rejpcbuf, sizeof(rejpcbuf), wnotaccepted, waccepted);
  3580. percentf3(bnbuf, sizeof(bnbuf), bad_diff1, allnonces);
  3581. tailsprintf(buf, bufsz, "%s/%s/%s | A:%*d R:%*d+%*d(%s) HW:%*d/%s",
  3582. cHr, aHr, uHr,
  3583. awidth, accepted,
  3584. rwidth, rejected,
  3585. swidth, stale,
  3586. rejpcbuf,
  3587. hwwidth, hwerrs,
  3588. bnbuf
  3589. );
  3590. }
  3591. static
  3592. const char *pool_proto_str(const struct pool * const pool)
  3593. {
  3594. if (pool->idle)
  3595. return "Dead ";
  3596. if (pool->has_stratum)
  3597. return "Strtm";
  3598. if (pool->lp_url && pool->proto != pool->lp_proto)
  3599. return "Mixed";
  3600. switch (pool->proto)
  3601. {
  3602. case PLP_GETBLOCKTEMPLATE:
  3603. return " GBT ";
  3604. case PLP_GETWORK:
  3605. return "GWork";
  3606. default:
  3607. return "Alive";
  3608. }
  3609. }
  3610. #endif
  3611. static inline
  3612. void temperature_column(char *buf, size_t bufsz, bool maybe_unicode, const float * const temp)
  3613. {
  3614. if (!(use_unicode && have_unicode_degrees))
  3615. maybe_unicode = false;
  3616. if (temp && *temp > 0.)
  3617. if (maybe_unicode)
  3618. snprintf(buf, bufsz, "%4.1f"U8_DEGREE"C", *temp);
  3619. else
  3620. snprintf(buf, bufsz, "%4.1fC", *temp);
  3621. else
  3622. {
  3623. if (temp)
  3624. snprintf(buf, bufsz, " ");
  3625. if (maybe_unicode)
  3626. tailsprintf(buf, bufsz, " ");
  3627. }
  3628. tailsprintf(buf, bufsz, " | ");
  3629. }
  3630. void get_statline3(char *buf, size_t bufsz, struct cgpu_info *cgpu, bool for_curses, bool opt_show_procs)
  3631. {
  3632. #ifndef HAVE_CURSES
  3633. assert(for_curses == false);
  3634. #endif
  3635. struct device_drv *drv = cgpu->drv;
  3636. enum h2bs_fmt hashrate_style = for_curses ? H2B_SHORT : H2B_SPACED;
  3637. char cHr[ALLOC_H2B_NOUNIT+1], aHr[ALLOC_H2B_NOUNIT+1], uHr[max(ALLOC_H2B_SHORT, ALLOC_H2B_SPACED)+3+1];
  3638. char rejpcbuf[6];
  3639. char bnbuf[6];
  3640. double dev_runtime;
  3641. if (!opt_show_procs)
  3642. cgpu = cgpu->device;
  3643. dev_runtime = cgpu_runtime(cgpu);
  3644. double rolling, mhashes;
  3645. int accepted, rejected, stale;
  3646. double waccepted;
  3647. double wnotaccepted;
  3648. int hwerrs;
  3649. double bad_diff1, good_diff1;
  3650. rolling = mhashes = waccepted = wnotaccepted = 0;
  3651. accepted = rejected = stale = hwerrs = bad_diff1 = good_diff1 = 0;
  3652. {
  3653. struct cgpu_info *slave = cgpu;
  3654. for (int i = 0; i < cgpu->procs; ++i, (slave = slave->next_proc))
  3655. {
  3656. slave->utility = slave->accepted / dev_runtime * 60;
  3657. slave->utility_diff1 = slave->diff_accepted / dev_runtime * 60;
  3658. rolling += slave->rolling;
  3659. mhashes += slave->total_mhashes;
  3660. if (opt_weighed_stats)
  3661. {
  3662. accepted += slave->diff_accepted;
  3663. rejected += slave->diff_rejected;
  3664. stale += slave->diff_stale;
  3665. }
  3666. else
  3667. {
  3668. accepted += slave->accepted;
  3669. rejected += slave->rejected;
  3670. stale += slave->stale;
  3671. }
  3672. waccepted += slave->diff_accepted;
  3673. wnotaccepted += slave->diff_rejected + slave->diff_stale;
  3674. hwerrs += slave->hw_errors;
  3675. bad_diff1 += slave->bad_diff1;
  3676. good_diff1 += slave->diff1;
  3677. if (opt_show_procs)
  3678. break;
  3679. }
  3680. }
  3681. double wtotal = (waccepted + wnotaccepted);
  3682. multi_format_unit_array2(
  3683. ((char*[]){cHr, aHr, uHr}),
  3684. ((size_t[]){sizeof(cHr), sizeof(aHr), sizeof(uHr)}),
  3685. true, "h/s", hashrate_style,
  3686. 3,
  3687. 1e6*rolling,
  3688. 1e6*mhashes / dev_runtime,
  3689. utility_to_hashrate(good_diff1 * (wtotal ? (waccepted / wtotal) : 1) * 60 / dev_runtime));
  3690. // Processor representation
  3691. #ifdef HAVE_CURSES
  3692. if (for_curses)
  3693. {
  3694. if (opt_show_procs)
  3695. snprintf(buf, bufsz, " %*s: ", -(5 + max_lpdigits), cgpu->proc_repr);
  3696. else
  3697. snprintf(buf, bufsz, " %s: ", cgpu->dev_repr);
  3698. }
  3699. else
  3700. #endif
  3701. snprintf(buf, bufsz, "%s ", opt_show_procs ? cgpu->proc_repr_ns : cgpu->dev_repr_ns);
  3702. if (include_serial_in_statline && cgpu->dev_serial)
  3703. tailsprintf(buf, bufsz, "[serial=%s] ", cgpu->dev_serial);
  3704. if (unlikely(cgpu->status == LIFE_INIT))
  3705. {
  3706. tailsprintf(buf, bufsz, "Initializing...");
  3707. return;
  3708. }
  3709. {
  3710. const size_t bufln = strlen(buf);
  3711. const size_t abufsz = (bufln >= bufsz) ? 0 : (bufsz - bufln);
  3712. if (likely(cgpu->status != LIFE_DEAD2) && drv->override_statline_temp2 && drv->override_statline_temp2(buf, bufsz, cgpu, opt_show_procs))
  3713. temperature_column(&buf[bufln], abufsz, for_curses, NULL);
  3714. else
  3715. {
  3716. float temp = cgpu->temp;
  3717. if (!opt_show_procs)
  3718. {
  3719. // Find the highest temperature of all processors
  3720. struct cgpu_info *proc = cgpu;
  3721. for (int i = 0; i < cgpu->procs; ++i, (proc = proc->next_proc))
  3722. if (proc->temp > temp)
  3723. temp = proc->temp;
  3724. }
  3725. temperature_column(&buf[bufln], abufsz, for_curses, &temp);
  3726. }
  3727. }
  3728. #ifdef HAVE_CURSES
  3729. if (for_curses)
  3730. {
  3731. const char *cHrStatsOpt[] = {AS_BAD("DEAD "), AS_BAD("SICK "), "OFF ", AS_BAD("REST "), AS_BAD(" ERR "), AS_BAD("WAIT "), cHr};
  3732. const char *cHrStats;
  3733. int cHrStatsI = (sizeof(cHrStatsOpt) / sizeof(*cHrStatsOpt)) - 1;
  3734. bool all_dead = true, all_off = true, all_rdrv = true;
  3735. struct cgpu_info *proc = cgpu;
  3736. for (int i = 0; i < cgpu->procs; ++i, (proc = proc->next_proc))
  3737. {
  3738. switch (cHrStatsI) {
  3739. default:
  3740. if (proc->status == LIFE_WAIT)
  3741. cHrStatsI = 5;
  3742. case 5:
  3743. if (proc->deven == DEV_RECOVER_ERR)
  3744. cHrStatsI = 4;
  3745. case 4:
  3746. if (proc->deven == DEV_RECOVER)
  3747. cHrStatsI = 3;
  3748. case 3:
  3749. if (proc->status == LIFE_SICK || proc->status == LIFE_DEAD || proc->status == LIFE_DEAD2)
  3750. {
  3751. cHrStatsI = 1;
  3752. all_off = false;
  3753. }
  3754. else
  3755. {
  3756. if (likely(proc->deven == DEV_ENABLED))
  3757. all_off = false;
  3758. if (proc->deven != DEV_RECOVER_DRV)
  3759. all_rdrv = false;
  3760. }
  3761. case 1:
  3762. break;
  3763. }
  3764. if (likely(proc->status != LIFE_DEAD && proc->status != LIFE_DEAD2))
  3765. all_dead = false;
  3766. if (opt_show_procs)
  3767. break;
  3768. }
  3769. if (unlikely(all_dead))
  3770. cHrStatsI = 0;
  3771. else
  3772. if (unlikely(all_off))
  3773. cHrStatsI = 2;
  3774. cHrStats = cHrStatsOpt[cHrStatsI];
  3775. if (cHrStatsI == 2 && all_rdrv)
  3776. cHrStats = " RST ";
  3777. format_statline(buf, bufsz,
  3778. cHrStats,
  3779. aHr, uHr,
  3780. accepted, rejected, stale,
  3781. wnotaccepted, waccepted,
  3782. hwerrs,
  3783. bad_diff1, bad_diff1 + good_diff1);
  3784. }
  3785. else
  3786. #endif
  3787. {
  3788. percentf4(rejpcbuf, sizeof(rejpcbuf), wnotaccepted, waccepted);
  3789. percentf4(bnbuf, sizeof(bnbuf), bad_diff1, good_diff1);
  3790. tailsprintf(buf, bufsz, "%ds:%s avg:%s u:%s | A:%d R:%d+%d(%s) HW:%d/%s",
  3791. opt_log_interval,
  3792. cHr, aHr, uHr,
  3793. accepted,
  3794. rejected,
  3795. stale,
  3796. rejpcbuf,
  3797. hwerrs,
  3798. bnbuf
  3799. );
  3800. }
  3801. }
  3802. #define get_statline(buf, bufsz, cgpu) get_statline3(buf, bufsz, cgpu, false, opt_show_procs)
  3803. #define get_statline2(buf, bufsz, cgpu, for_curses) get_statline3(buf, bufsz, cgpu, for_curses, opt_show_procs)
  3804. static void text_print_status(int thr_id)
  3805. {
  3806. struct cgpu_info *cgpu;
  3807. char logline[256];
  3808. cgpu = get_thr_cgpu(thr_id);
  3809. if (cgpu) {
  3810. get_statline(logline, sizeof(logline), cgpu);
  3811. printf("\n%s\r", logline);
  3812. fflush(stdout);
  3813. }
  3814. }
  3815. #ifdef HAVE_CURSES
  3816. static int attr_bad = A_BOLD;
  3817. #ifdef WIN32
  3818. #define swprintf snwprintf
  3819. #endif
  3820. static
  3821. void bfg_waddstr(WINDOW *win, const char *s)
  3822. {
  3823. const char *p = s;
  3824. int32_t w;
  3825. int wlen;
  3826. unsigned char stop_ascii = (use_unicode ? '|' : 0x80);
  3827. while (true)
  3828. {
  3829. while (likely(p[0] == '\n' || (p[0] >= 0x20 && p[0] < stop_ascii)))
  3830. {
  3831. // Printable ASCII
  3832. ++p;
  3833. }
  3834. if (p != s)
  3835. waddnstr(win, s, p - s);
  3836. w = utf8_decode(p, &wlen);
  3837. s = p += wlen;
  3838. switch(w)
  3839. {
  3840. // NOTE: U+F000-U+F7FF are reserved for font hacks
  3841. case '\0':
  3842. return;
  3843. case 0xb5: // micro symbol
  3844. w = unicode_micro;
  3845. goto default_addch;
  3846. case 0xf000: // "bad" off
  3847. wattroff(win, attr_bad);
  3848. break;
  3849. case 0xf001: // "bad" on
  3850. wattron(win, attr_bad);
  3851. break;
  3852. #ifdef USE_UNICODE
  3853. case '|':
  3854. wadd_wch(win, WACS_VLINE);
  3855. break;
  3856. #endif
  3857. case 0x2500: // BOX DRAWINGS LIGHT HORIZONTAL
  3858. case 0x2534: // BOX DRAWINGS LIGHT UP AND HORIZONTAL
  3859. if (!use_unicode)
  3860. {
  3861. waddch(win, '-');
  3862. break;
  3863. }
  3864. #ifdef USE_UNICODE
  3865. wadd_wch(win, (w == 0x2500) ? WACS_HLINE : WACS_BTEE);
  3866. break;
  3867. #endif
  3868. case 0x2022:
  3869. if (w > WCHAR_MAX || !iswprint(w))
  3870. w = '*';
  3871. default:
  3872. default_addch:
  3873. if (w > WCHAR_MAX || !(iswprint(w) || w == '\n'))
  3874. {
  3875. #if REPLACEMENT_CHAR <= WCHAR_MAX
  3876. if (iswprint(REPLACEMENT_CHAR))
  3877. w = REPLACEMENT_CHAR;
  3878. else
  3879. #endif
  3880. w = '?';
  3881. }
  3882. {
  3883. #ifdef USE_UNICODE
  3884. wchar_t wbuf[0x10];
  3885. int wbuflen = sizeof(wbuf) / sizeof(*wbuf);
  3886. wbuflen = swprintf(wbuf, wbuflen, L"%lc", (wint_t)w);
  3887. waddnwstr(win, wbuf, wbuflen);
  3888. #else
  3889. wprintw(win, "%lc", (wint_t)w);
  3890. #endif
  3891. }
  3892. }
  3893. }
  3894. }
  3895. static inline
  3896. void bfg_hline(WINDOW *win, int y)
  3897. {
  3898. int maxx, __maybe_unused maxy;
  3899. getmaxyx(win, maxy, maxx);
  3900. #ifdef USE_UNICODE
  3901. if (use_unicode)
  3902. mvwhline_set(win, y, 0, WACS_HLINE, maxx);
  3903. else
  3904. #endif
  3905. mvwhline(win, y, 0, '-', maxx);
  3906. }
  3907. static
  3908. int bfg_win_linelen(WINDOW * const win)
  3909. {
  3910. int maxx;
  3911. int __maybe_unused y;
  3912. getmaxyx(win, y, maxx);
  3913. return maxx;
  3914. }
  3915. // Spaces until end of line, using current attributes (ie, not completely clear)
  3916. static
  3917. void bfg_wspctoeol(WINDOW * const win, const int offset)
  3918. {
  3919. int x, maxx;
  3920. int __maybe_unused y;
  3921. getmaxyx(win, y, maxx);
  3922. getyx(win, y, x);
  3923. const int space_count = (maxx - x) - offset;
  3924. // Check for negative - terminal too narrow
  3925. if (space_count <= 0)
  3926. return;
  3927. char buf[space_count];
  3928. memset(buf, ' ', space_count);
  3929. waddnstr(win, buf, space_count);
  3930. }
  3931. static int menu_attr = A_REVERSE;
  3932. #define CURBUFSIZ 256
  3933. #define cg_mvwprintw(win, y, x, fmt, ...) do { \
  3934. char tmp42[CURBUFSIZ]; \
  3935. snprintf(tmp42, sizeof(tmp42), fmt, ##__VA_ARGS__); \
  3936. wmove(win, y, x); \
  3937. bfg_waddstr(win, tmp42); \
  3938. } while (0)
  3939. #define cg_wprintw(win, fmt, ...) do { \
  3940. char tmp42[CURBUFSIZ]; \
  3941. snprintf(tmp42, sizeof(tmp42), fmt, ##__VA_ARGS__); \
  3942. bfg_waddstr(win, tmp42); \
  3943. } while (0)
  3944. static
  3945. void update_block_display_line(const int blky, struct mining_goal_info *goal)
  3946. {
  3947. struct blockchain_info * const blkchain = goal->blkchain;
  3948. struct block_info * const blkinfo = blkchain->currentblk;
  3949. double income;
  3950. char incomestr[ALLOC_H2B_SHORT+6+1];
  3951. if (blkinfo->height)
  3952. {
  3953. income = goal->diff_accepted * 3600 * blkchain->currentblk_subsidy / total_secs / goal->current_diff;
  3954. format_unit3(incomestr, sizeof(incomestr), FUP_BTC, "BTC/hr", H2B_SHORT, income/1e8, -1);
  3955. }
  3956. else
  3957. strcpy(incomestr, "?");
  3958. int linelen = bfg_win_linelen(statuswin);
  3959. wmove(statuswin, blky, 0);
  3960. bfg_waddstr(statuswin, " Block");
  3961. if (!goal->is_default)
  3962. linelen -= strlen(goal->name) + 1;
  3963. linelen -= 6; // " Block"
  3964. if (blkinfo->height && blkinfo->height < 1000000)
  3965. {
  3966. cg_wprintw(statuswin, " #%6u", blkinfo->height);
  3967. linelen -= 8;
  3968. }
  3969. bfg_waddstr(statuswin, ":");
  3970. if (linelen > 55)
  3971. bfg_waddstr(statuswin, " ");
  3972. if (linelen >= 65)
  3973. bfg_waddstr(statuswin, "...");
  3974. {
  3975. char hexpbh[0x11];
  3976. if (!(blkinfo->height && blkinfo->height < 1000000))
  3977. {
  3978. bin2hex(hexpbh, &blkinfo->prevblkhash[4], 4);
  3979. bfg_waddstr(statuswin, hexpbh);
  3980. }
  3981. bin2hex(hexpbh, &blkinfo->prevblkhash[0], 4);
  3982. bfg_waddstr(statuswin, hexpbh);
  3983. }
  3984. if (linelen >= 55)
  3985. bfg_waddstr(statuswin, " ");
  3986. cg_wprintw(statuswin, " Diff:%s", goal->current_diff_str);
  3987. if (linelen >= 69)
  3988. bfg_waddstr(statuswin, " ");
  3989. cg_wprintw(statuswin, "(%s) ", goal->net_hashrate);
  3990. if (linelen >= 62)
  3991. {
  3992. if (linelen >= 69)
  3993. bfg_waddstr(statuswin, " ");
  3994. bfg_waddstr(statuswin, "Started:");
  3995. }
  3996. else
  3997. bfg_waddstr(statuswin, "S:");
  3998. if (linelen >= 69)
  3999. bfg_waddstr(statuswin, " ");
  4000. bfg_waddstr(statuswin, blkchain->currentblk_first_seen_time_str);
  4001. if (linelen >= 69)
  4002. bfg_waddstr(statuswin, " ");
  4003. cg_wprintw(statuswin, " I:%s", incomestr);
  4004. if (!goal->is_default)
  4005. cg_wprintw(statuswin, " %s", goal->name);
  4006. wclrtoeol(statuswin);
  4007. }
  4008. static bool pool_actively_in_use(const struct pool *, const struct pool *);
  4009. static
  4010. void update_block_display(void)
  4011. {
  4012. struct mining_goal_info *goal, *tmpgoal;
  4013. int blky = 3, i, total_found_goals = 0;
  4014. HASH_ITER(hh, mining_goals, goal, tmpgoal)
  4015. {
  4016. for (i = 0; i < total_pools; ++i)
  4017. {
  4018. struct pool * const pool = pools[i];
  4019. if (pool->goal == goal && pool_actively_in_use(pool, NULL))
  4020. break;
  4021. }
  4022. if (i >= total_pools)
  4023. // no pools using this goal, so it's probably stale anyway
  4024. continue;
  4025. update_block_display_line(blky++, goal);
  4026. ++total_found_goals;
  4027. }
  4028. if (total_found_goals != active_goals)
  4029. {
  4030. active_goals = total_found_goals;
  4031. devcursor = 7 + active_goals;
  4032. switch_logsize();
  4033. }
  4034. }
  4035. static bool pool_unworkable(const struct pool *);
  4036. /* Must be called with curses mutex lock held and curses_active */
  4037. static void curses_print_status(const int ts)
  4038. {
  4039. struct pool *pool = currentpool;
  4040. struct timeval now, tv;
  4041. float efficiency;
  4042. int logdiv;
  4043. efficiency = total_bytes_xfer ? total_diff_accepted * 2048. / total_bytes_xfer : 0.0;
  4044. wattron(statuswin, attr_title);
  4045. const int linelen = bfg_win_linelen(statuswin);
  4046. int titlelen = 1 + strlen(PACKAGE) + 1 + strlen(VERSION) + 3 + 21 + 3 + 19;
  4047. cg_mvwprintw(statuswin, 0, 0, " " PACKAGE " ");
  4048. if (titlelen + 17 < linelen)
  4049. cg_wprintw(statuswin, "version ");
  4050. cg_wprintw(statuswin, VERSION " - ");
  4051. if (titlelen + 9 < linelen)
  4052. cg_wprintw(statuswin, "Started: ");
  4053. else
  4054. if (titlelen + 7 <= linelen)
  4055. cg_wprintw(statuswin, "Start: ");
  4056. cg_wprintw(statuswin, "%s", datestamp);
  4057. timer_set_now(&now);
  4058. {
  4059. unsigned int days, hours;
  4060. div_t d;
  4061. timersub(&now, &miner_started, &tv);
  4062. d = div(tv.tv_sec, 86400);
  4063. days = d.quot;
  4064. d = div(d.rem, 3600);
  4065. hours = d.quot;
  4066. d = div(d.rem, 60);
  4067. cg_wprintw(statuswin, " - [%3u day%c %02d:%02d:%02d]"
  4068. , days
  4069. , (days == 1) ? ' ' : 's'
  4070. , hours
  4071. , d.quot
  4072. , d.rem
  4073. );
  4074. }
  4075. bfg_wspctoeol(statuswin, 0);
  4076. wattroff(statuswin, attr_title);
  4077. wattron(statuswin, menu_attr);
  4078. wmove(statuswin, 1, 0);
  4079. bfg_waddstr(statuswin, " [M]anage devices [P]ool management [S]ettings [D]isplay options ");
  4080. bfg_wspctoeol(statuswin, 14);
  4081. bfg_waddstr(statuswin, "[H]elp [Q]uit ");
  4082. wattroff(statuswin, menu_attr);
  4083. if ((pool_strategy == POOL_LOADBALANCE || pool_strategy == POOL_BALANCE) && enabled_pools > 1) {
  4084. char poolinfo[20], poolinfo2[20];
  4085. int poolinfooff = 0, poolinfo2off, workable_pools = 0;
  4086. double lowdiff = DBL_MAX, highdiff = -1;
  4087. struct pool *lowdiff_pool = pools[0], *highdiff_pool = pools[0];
  4088. time_t oldest_work_restart = time(NULL) + 1;
  4089. struct pool *oldest_work_restart_pool = pools[0];
  4090. for (int i = 0; i < total_pools; ++i)
  4091. {
  4092. if (pool_unworkable(pools[i]))
  4093. continue;
  4094. // NOTE: Only set pool var when it's workable; if only one is, it gets used by single-pool code
  4095. pool = pools[i];
  4096. ++workable_pools;
  4097. if (poolinfooff < sizeof(poolinfo))
  4098. poolinfooff += snprintf(&poolinfo[poolinfooff], sizeof(poolinfo) - poolinfooff, "%u,", pool->pool_no);
  4099. struct cgminer_pool_stats * const pool_stats = &pool->cgminer_pool_stats;
  4100. if (pool_stats->last_diff < lowdiff)
  4101. {
  4102. lowdiff = pool_stats->last_diff;
  4103. lowdiff_pool = pool;
  4104. }
  4105. if (pool_stats->last_diff > highdiff)
  4106. {
  4107. highdiff = pool_stats->last_diff;
  4108. highdiff_pool = pool;
  4109. }
  4110. if (oldest_work_restart >= pool->work_restart_time)
  4111. {
  4112. oldest_work_restart = pool->work_restart_time;
  4113. oldest_work_restart_pool = pool;
  4114. }
  4115. }
  4116. if (unlikely(!workable_pools))
  4117. goto no_workable_pools;
  4118. if (workable_pools == 1)
  4119. goto one_workable_pool;
  4120. poolinfo2off = snprintf(poolinfo2, sizeof(poolinfo2), "%u (", workable_pools);
  4121. if (poolinfooff > sizeof(poolinfo2) - poolinfo2off - 1)
  4122. snprintf(&poolinfo2[poolinfo2off], sizeof(poolinfo2) - poolinfo2off, "%.*s...)", (int)(sizeof(poolinfo2) - poolinfo2off - 5), poolinfo);
  4123. else
  4124. snprintf(&poolinfo2[poolinfo2off], sizeof(poolinfo2) - poolinfo2off, "%.*s)%*s", (int)(poolinfooff - 1), poolinfo, (int)(sizeof(poolinfo2)), "");
  4125. cg_mvwprintw(statuswin, 2, 0, " Pools: %s Diff:%s%s%s %c LU:%s",
  4126. poolinfo2,
  4127. lowdiff_pool->diff,
  4128. (lowdiff == highdiff) ? "" : "-",
  4129. (lowdiff == highdiff) ? "" : highdiff_pool->diff,
  4130. pool->goal->have_longpoll ? '+' : '-',
  4131. oldest_work_restart_pool->work_restart_timestamp);
  4132. }
  4133. else
  4134. if (pool_unworkable(pool))
  4135. {
  4136. no_workable_pools: ;
  4137. wattron(statuswin, attr_bad);
  4138. cg_mvwprintw(statuswin, 2, 0, " (all pools are dead) ");
  4139. wattroff(statuswin, attr_bad);
  4140. }
  4141. else
  4142. {
  4143. one_workable_pool: ;
  4144. char pooladdr[19];
  4145. {
  4146. const char *rawaddr = pool->sockaddr_url;
  4147. BFGINIT(rawaddr, pool->rpc_url);
  4148. size_t pooladdrlen = strlen(rawaddr);
  4149. if (pooladdrlen > 20)
  4150. snprintf(pooladdr, sizeof(pooladdr), "...%s", &rawaddr[pooladdrlen - (sizeof(pooladdr) - 4)]);
  4151. else
  4152. snprintf(pooladdr, sizeof(pooladdr), "%*s", -(int)(sizeof(pooladdr) - 1), rawaddr);
  4153. }
  4154. cg_mvwprintw(statuswin, 2, 0, " Pool%2u: %s Diff:%s %c%s LU:%s User:%s",
  4155. pool->pool_no, pooladdr, pool->diff,
  4156. pool->goal->have_longpoll ? '+' : '-', pool_proto_str(pool),
  4157. pool->work_restart_timestamp,
  4158. pool->rpc_user);
  4159. }
  4160. wclrtoeol(statuswin);
  4161. char bwstr[(ALLOC_H2B_SHORT*2)+3+1];
  4162. cg_mvwprintw(statuswin, devcursor - 4, 0, " ST:%d F:%d NB:%d AS:%d BW:[%s] E:%.2f BS:%s",
  4163. ts,
  4164. total_go + total_ro,
  4165. new_blocks,
  4166. total_submitting,
  4167. multi_format_unit2(bwstr, sizeof(bwstr),
  4168. false, "B/s", H2B_SHORT, "/", 2,
  4169. (float)(total_bytes_rcvd / total_secs),
  4170. (float)(total_bytes_sent / total_secs)),
  4171. efficiency,
  4172. best_share);
  4173. wclrtoeol(statuswin);
  4174. mvwaddstr(statuswin, devcursor - 3, 0, " ");
  4175. bfg_waddstr(statuswin, statusline);
  4176. wclrtoeol(statuswin);
  4177. int devdiv = devcursor - 2;
  4178. logdiv = statusy - 1;
  4179. bfg_hline(statuswin, devdiv);
  4180. bfg_hline(statuswin, logdiv);
  4181. #ifdef USE_UNICODE
  4182. if (use_unicode)
  4183. {
  4184. int offset = 8 /* device */ + 5 /* temperature */ + 1 /* padding space */;
  4185. if (opt_show_procs && !opt_compact)
  4186. offset += max_lpdigits; // proc letter(s)
  4187. if (have_unicode_degrees)
  4188. ++offset; // degrees symbol
  4189. mvwadd_wch(statuswin, devdiv, offset, WACS_PLUS);
  4190. mvwadd_wch(statuswin, logdiv, offset, WACS_BTEE);
  4191. offset += 24; // hashrates etc
  4192. mvwadd_wch(statuswin, devdiv, offset, WACS_PLUS);
  4193. mvwadd_wch(statuswin, logdiv, offset, WACS_BTEE);
  4194. }
  4195. #endif
  4196. }
  4197. static void adj_width(int var, int *length)
  4198. {
  4199. if ((int)(log10(var) + 1) > *length)
  4200. (*length)++;
  4201. }
  4202. static int dev_width;
  4203. static void curses_print_devstatus(struct cgpu_info *cgpu)
  4204. {
  4205. char logline[256];
  4206. int ypos;
  4207. if (opt_compact)
  4208. return;
  4209. /* Check this isn't out of the window size */
  4210. if (opt_show_procs)
  4211. ypos = cgpu->cgminer_id;
  4212. else
  4213. {
  4214. if (cgpu->proc_id)
  4215. return;
  4216. ypos = cgpu->device_line_id;
  4217. }
  4218. ypos += devsummaryYOffset;
  4219. if (ypos < 0)
  4220. return;
  4221. ypos += devcursor - 1;
  4222. if (ypos >= statusy - 1)
  4223. return;
  4224. if (wmove(statuswin, ypos, 0) == ERR)
  4225. return;
  4226. get_statline2(logline, sizeof(logline), cgpu, true);
  4227. if (selecting_device && (opt_show_procs ? (selected_device == cgpu->cgminer_id) : (devices[selected_device]->device == cgpu)))
  4228. wattron(statuswin, A_REVERSE);
  4229. bfg_waddstr(statuswin, logline);
  4230. wattroff(statuswin, A_REVERSE);
  4231. wclrtoeol(statuswin);
  4232. }
  4233. static
  4234. void _refresh_devstatus(const bool already_have_lock) {
  4235. if ((!opt_compact) && (already_have_lock || curses_active_locked())) {
  4236. int i;
  4237. if (unlikely(!total_devices))
  4238. {
  4239. const int ypos = devcursor - 1;
  4240. if (ypos < statusy - 1 && wmove(statuswin, ypos, 0) != ERR)
  4241. {
  4242. wattron(statuswin, attr_bad);
  4243. bfg_waddstr(statuswin, "NO DEVICES FOUND: Press 'M' and '+' to add");
  4244. wclrtoeol(statuswin);
  4245. wattroff(statuswin, attr_bad);
  4246. }
  4247. }
  4248. for (i = 0; i < total_devices; i++)
  4249. curses_print_devstatus(get_devices(i));
  4250. touchwin(statuswin);
  4251. wrefresh(statuswin);
  4252. if (!already_have_lock)
  4253. unlock_curses();
  4254. }
  4255. }
  4256. #define refresh_devstatus() _refresh_devstatus(false)
  4257. #endif
  4258. static void print_status(int thr_id)
  4259. {
  4260. if (!curses_active)
  4261. text_print_status(thr_id);
  4262. }
  4263. #ifdef HAVE_CURSES
  4264. static
  4265. bool set_statusy(int maxy)
  4266. {
  4267. if (loginput_size)
  4268. {
  4269. maxy -= loginput_size;
  4270. if (maxy < 0)
  4271. maxy = 0;
  4272. }
  4273. if (logstart < maxy)
  4274. maxy = logstart;
  4275. if (statusy == maxy)
  4276. return false;
  4277. statusy = maxy;
  4278. logcursor = statusy;
  4279. return true;
  4280. }
  4281. /* Check for window resize. Called with curses mutex locked */
  4282. static inline void change_logwinsize(void)
  4283. {
  4284. int x, y, logx, logy;
  4285. getmaxyx(mainwin, y, x);
  4286. if (x < 80 || y < 25)
  4287. return;
  4288. if (y > statusy + 2 && statusy < logstart) {
  4289. set_statusy(y - 2);
  4290. mvwin(logwin, logcursor, 0);
  4291. bfg_wresize(statuswin, statusy, x);
  4292. }
  4293. y -= logcursor;
  4294. getmaxyx(logwin, logy, logx);
  4295. /* Detect screen size change */
  4296. if (x != logx || y != logy)
  4297. bfg_wresize(logwin, y, x);
  4298. }
  4299. static void check_winsizes(void)
  4300. {
  4301. if (!use_curses)
  4302. return;
  4303. if (curses_active_locked()) {
  4304. int y, x;
  4305. x = getmaxx(statuswin);
  4306. if (set_statusy(LINES - 2))
  4307. {
  4308. erase();
  4309. bfg_wresize(statuswin, statusy, x);
  4310. getmaxyx(mainwin, y, x);
  4311. y -= logcursor;
  4312. bfg_wresize(logwin, y, x);
  4313. mvwin(logwin, logcursor, 0);
  4314. }
  4315. unlock_curses();
  4316. }
  4317. }
  4318. static int device_line_id_count;
  4319. static void switch_logsize(void)
  4320. {
  4321. if (curses_active_locked()) {
  4322. if (opt_compact) {
  4323. logstart = devcursor - 1;
  4324. logcursor = logstart + 1;
  4325. } else {
  4326. total_lines = (opt_show_procs ? total_devices : device_line_id_count) ?: 1;
  4327. logstart = devcursor + total_lines;
  4328. logcursor = logstart;
  4329. }
  4330. unlock_curses();
  4331. }
  4332. check_winsizes();
  4333. update_block_display();
  4334. }
  4335. /* For mandatory printing when mutex is already locked */
  4336. void _wlog(const char *str)
  4337. {
  4338. static bool newline;
  4339. size_t end = strlen(str) - 1;
  4340. if (newline)
  4341. bfg_waddstr(logwin, "\n");
  4342. if (str[end] == '\n')
  4343. {
  4344. char *s;
  4345. newline = true;
  4346. s = alloca(end + 1);
  4347. memcpy(s, str, end);
  4348. s[end] = '\0';
  4349. str = s;
  4350. }
  4351. else
  4352. newline = false;
  4353. bfg_waddstr(logwin, str);
  4354. }
  4355. /* Mandatory printing */
  4356. void _wlogprint(const char *str)
  4357. {
  4358. if (curses_active_locked()) {
  4359. _wlog(str);
  4360. unlock_curses();
  4361. }
  4362. }
  4363. #endif
  4364. #ifdef HAVE_CURSES
  4365. bool _log_curses_only(int prio, const char *datetime, const char *str)
  4366. {
  4367. bool high_prio;
  4368. high_prio = (prio == LOG_WARNING || prio == LOG_ERR);
  4369. if (curses_active)
  4370. {
  4371. if (!loginput_size || high_prio) {
  4372. wlog(" %s %s\n", datetime, str);
  4373. if (high_prio) {
  4374. touchwin(logwin);
  4375. wrefresh(logwin);
  4376. }
  4377. }
  4378. return true;
  4379. }
  4380. return false;
  4381. }
  4382. void clear_logwin(void)
  4383. {
  4384. if (curses_active_locked()) {
  4385. wclear(logwin);
  4386. unlock_curses();
  4387. }
  4388. }
  4389. void logwin_update(void)
  4390. {
  4391. if (curses_active_locked()) {
  4392. touchwin(logwin);
  4393. wrefresh(logwin);
  4394. unlock_curses();
  4395. }
  4396. }
  4397. #endif
  4398. void enable_pool(struct pool * const pool)
  4399. {
  4400. if (pool->enabled != POOL_ENABLED) {
  4401. mutex_lock(&lp_lock);
  4402. enabled_pools++;
  4403. pool->enabled = POOL_ENABLED;
  4404. pthread_cond_broadcast(&lp_cond);
  4405. mutex_unlock(&lp_lock);
  4406. if (pool->prio < current_pool()->prio)
  4407. switch_pools(pool);
  4408. }
  4409. }
  4410. void disable_pool(struct pool * const pool, const enum pool_enable enable_status)
  4411. {
  4412. if (pool->enabled == POOL_DISABLED)
  4413. /* had been manually disabled before */
  4414. return;
  4415. if (pool->enabled != POOL_ENABLED)
  4416. {
  4417. /* has been programmatically disabled already, just change to the new status directly */
  4418. pool->enabled = enable_status;
  4419. return;
  4420. }
  4421. /* Fall into the lock area */
  4422. mutex_lock(&lp_lock);
  4423. --enabled_pools;
  4424. pool->enabled = enable_status;
  4425. mutex_unlock(&lp_lock);
  4426. if (pool == current_pool())
  4427. switch_pools(NULL);
  4428. }
  4429. static
  4430. void share_result_msg(const struct work *work, const char *disp, const char *reason, bool resubmit, const char *worktime) {
  4431. struct cgpu_info *cgpu;
  4432. const struct mining_algorithm * const malgo = work_mining_algorithm(work);
  4433. const unsigned char *hashpart = &work->hash[0x1c - malgo->ui_skip_hash_bytes];
  4434. char shrdiffdisp[ALLOC_H2B_SHORTV];
  4435. const double tgtdiff = work->work_difficulty;
  4436. char tgtdiffdisp[ALLOC_H2B_SHORTV];
  4437. char where[20];
  4438. cgpu = get_thr_cgpu(work->thr_id);
  4439. suffix_string(work->share_diff, shrdiffdisp, sizeof(shrdiffdisp), 0);
  4440. suffix_string(tgtdiff, tgtdiffdisp, sizeof(tgtdiffdisp), 0);
  4441. if (total_pools > 1)
  4442. snprintf(where, sizeof(where), " pool %d", work->pool->pool_no);
  4443. else
  4444. where[0] = '\0';
  4445. applog(LOG_NOTICE, "%s %02x%02x%02x%02x %"PRIprepr"%s Diff %s/%s%s %s%s",
  4446. disp,
  4447. (unsigned)hashpart[3], (unsigned)hashpart[2], (unsigned)hashpart[1], (unsigned)hashpart[0],
  4448. cgpu->proc_repr,
  4449. where,
  4450. shrdiffdisp, tgtdiffdisp,
  4451. reason,
  4452. resubmit ? "(resubmit)" : "",
  4453. worktime
  4454. );
  4455. }
  4456. static bool test_work_current(struct work *);
  4457. static void _submit_work_async(struct work *);
  4458. static
  4459. void maybe_local_submit(const struct work *work)
  4460. {
  4461. #if BLKMAKER_VERSION > 3
  4462. if (unlikely(work->block && work->tr))
  4463. {
  4464. // This is a block with a full template (GBT)
  4465. // Regardless of the result, submit to local bitcoind(s) as well
  4466. struct work *work_cp;
  4467. for (int i = 0; i < total_pools; ++i)
  4468. {
  4469. if (!uri_get_param_bool(pools[i]->rpc_url, "allblocks", false))
  4470. continue;
  4471. applog(LOG_DEBUG, "Attempting submission of full block to pool %d", pools[i]->pool_no);
  4472. work_cp = copy_work(work);
  4473. work_cp->pool = pools[i];
  4474. work_cp->do_foreign_submit = true;
  4475. _submit_work_async(work_cp);
  4476. }
  4477. }
  4478. #endif
  4479. }
  4480. static
  4481. json_t *extract_reject_reason_j(json_t * const val, json_t *res, json_t * const err, const struct work * const work)
  4482. {
  4483. if (json_is_string(res))
  4484. return res;
  4485. if ( (res = json_object_get(val, "reject-reason")) )
  4486. return res;
  4487. if (work->stratum && err && json_is_array(err) && json_array_size(err) >= 2 && (res = json_array_get(err, 1)) && json_is_string(res))
  4488. return res;
  4489. return NULL;
  4490. }
  4491. static
  4492. const char *extract_reject_reason(json_t * const val, json_t *res, json_t * const err, const struct work * const work)
  4493. {
  4494. json_t * const j = extract_reject_reason_j(val, res, err, work);
  4495. return j ? json_string_value(j) : NULL;
  4496. }
  4497. static
  4498. int put_in_parens(char * const buf, const size_t bufsz, const char * const s)
  4499. {
  4500. if (!s)
  4501. {
  4502. if (bufsz)
  4503. buf[0] = '\0';
  4504. return 0;
  4505. }
  4506. int p = snprintf(buf, bufsz, " (%s", s);
  4507. if (p >= bufsz - 1)
  4508. p = bufsz - 2;
  4509. strcpy(&buf[p], ")");
  4510. return p + 1;
  4511. }
  4512. /* Theoretically threads could race when modifying accepted and
  4513. * rejected values but the chance of two submits completing at the
  4514. * same time is zero so there is no point adding extra locking */
  4515. static void
  4516. share_result(json_t *val, json_t *res, json_t *err, const struct work *work,
  4517. /*char *hashshow,*/ bool resubmit, char *worktime)
  4518. {
  4519. struct pool *pool = work->pool;
  4520. struct cgpu_info *cgpu;
  4521. cgpu = get_thr_cgpu(work->thr_id);
  4522. if ((json_is_null(err) || !err) && (json_is_null(res) || json_is_true(res))) {
  4523. struct mining_goal_info * const goal = pool->goal;
  4524. mutex_lock(&stats_lock);
  4525. cgpu->accepted++;
  4526. total_accepted++;
  4527. pool->accepted++;
  4528. cgpu->diff_accepted += work->work_difficulty;
  4529. total_diff_accepted += work->work_difficulty;
  4530. pool->diff_accepted += work->work_difficulty;
  4531. goal->diff_accepted += work->work_difficulty;
  4532. mutex_unlock(&stats_lock);
  4533. pool->seq_rejects = 0;
  4534. cgpu->last_share_pool = pool->pool_no;
  4535. cgpu->last_share_pool_time = time(NULL);
  4536. cgpu->last_share_diff = work->work_difficulty;
  4537. pool->last_share_time = cgpu->last_share_pool_time;
  4538. pool->last_share_diff = work->work_difficulty;
  4539. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  4540. if (!QUIET) {
  4541. share_result_msg(work, "Accepted", "", resubmit, worktime);
  4542. }
  4543. sharelog("accept", work);
  4544. if (opt_shares && total_diff_accepted >= opt_shares) {
  4545. applog(LOG_WARNING, "Successfully mined %g accepted shares as requested and exiting.", opt_shares);
  4546. kill_work();
  4547. return;
  4548. }
  4549. /* Detect if a pool that has been temporarily disabled for
  4550. * continually rejecting shares has started accepting shares.
  4551. * This will only happen with the work returned from a
  4552. * longpoll */
  4553. if (unlikely(pool->enabled == POOL_REJECTING)) {
  4554. applog(LOG_WARNING, "Rejecting pool %d now accepting shares, re-enabling!", pool->pool_no);
  4555. enable_pool(pool);
  4556. }
  4557. if (unlikely(work->block)) {
  4558. // Force moving on to this new block :)
  4559. struct work fakework;
  4560. memset(&fakework, 0, sizeof(fakework));
  4561. fakework.pool = work->pool;
  4562. // Copy block version, bits, and time from share
  4563. memcpy(&fakework.data[ 0], &work->data[ 0], 4);
  4564. memcpy(&fakework.data[68], &work->data[68], 8);
  4565. // Set prevblock to winning hash (swap32'd)
  4566. swap32yes(&fakework.data[4], &work->hash[0], 32 / 4);
  4567. test_work_current(&fakework);
  4568. }
  4569. }
  4570. else
  4571. if (!hash_target_check(work->hash, work->target))
  4572. {
  4573. // This was submitted despite failing the proper target
  4574. // Quietly ignore the reject
  4575. char reason[32];
  4576. put_in_parens(reason, sizeof(reason), extract_reject_reason(val, res, err, work));
  4577. applog(LOG_DEBUG, "Share above target rejected%s by pool %u as expected, ignoring", reason, pool->pool_no);
  4578. } else {
  4579. mutex_lock(&stats_lock);
  4580. cgpu->rejected++;
  4581. total_rejected++;
  4582. pool->rejected++;
  4583. cgpu->diff_rejected += work->work_difficulty;
  4584. total_diff_rejected += work->work_difficulty;
  4585. pool->diff_rejected += work->work_difficulty;
  4586. pool->seq_rejects++;
  4587. mutex_unlock(&stats_lock);
  4588. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  4589. if (!QUIET) {
  4590. char disposition[36] = "reject";
  4591. char reason[32];
  4592. const char *reasontmp = extract_reject_reason(val, res, err, work);
  4593. int n = put_in_parens(reason, sizeof(reason), reasontmp);
  4594. if (reason[0])
  4595. snprintf(&disposition[6], sizeof(disposition) - 6, ":%.*s", n - 3, &reason[2]);
  4596. share_result_msg(work, "Rejected", reason, resubmit, worktime);
  4597. sharelog(disposition, work);
  4598. }
  4599. /* Once we have more than a nominal amount of sequential rejects,
  4600. * at least 10 and more than 3 mins at the current utility,
  4601. * disable the pool because some pool error is likely to have
  4602. * ensued. Do not do this if we know the share just happened to
  4603. * be stale due to networking delays.
  4604. */
  4605. if (pool->seq_rejects > 10 && !work->stale && opt_disable_pool && enabled_pools > 1) {
  4606. double utility = total_accepted / total_secs * 60;
  4607. if (pool->seq_rejects > utility * 3) {
  4608. applog(LOG_WARNING, "Pool %d rejected %d sequential shares, disabling!",
  4609. pool->pool_no, pool->seq_rejects);
  4610. disable_pool(pool, POOL_REJECTING);
  4611. pool->seq_rejects = 0;
  4612. }
  4613. }
  4614. }
  4615. maybe_local_submit(work);
  4616. }
  4617. static char *submit_upstream_work_request(struct work *work)
  4618. {
  4619. char *hexstr = NULL;
  4620. char *s, *sd;
  4621. struct pool *pool = work->pool;
  4622. if (work->tr)
  4623. {
  4624. blktemplate_t * const tmpl = work->tr->tmpl;
  4625. json_t *req;
  4626. unsigned char data[80];
  4627. swap32yes(data, work->data, 80 / 4);
  4628. #if BLKMAKER_VERSION > 3
  4629. if (work->do_foreign_submit)
  4630. req = blkmk_submit_foreign_jansson(tmpl, data, work->dataid, le32toh(*((uint32_t*)&work->data[76])));
  4631. else
  4632. #endif
  4633. req = blkmk_submit_jansson(tmpl, data, work->dataid, le32toh(*((uint32_t*)&work->data[76])));
  4634. s = json_dumps(req, 0);
  4635. json_decref(req);
  4636. sd = malloc(161);
  4637. bin2hex(sd, data, 80);
  4638. } else {
  4639. /* build hex string */
  4640. hexstr = malloc((sizeof(work->data) * 2) + 1);
  4641. bin2hex(hexstr, work->data, sizeof(work->data));
  4642. /* build JSON-RPC request */
  4643. s = strdup("{\"method\": \"getwork\", \"params\": [ \"");
  4644. s = realloc_strcat(s, hexstr);
  4645. s = realloc_strcat(s, "\" ], \"id\":1}");
  4646. free(hexstr);
  4647. sd = s;
  4648. }
  4649. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->rpc_url, sd);
  4650. if (work->tr)
  4651. free(sd);
  4652. else
  4653. s = realloc_strcat(s, "\n");
  4654. return s;
  4655. }
  4656. static bool submit_upstream_work_completed(struct work *work, bool resubmit, struct timeval *ptv_submit, json_t *val) {
  4657. json_t *res, *err;
  4658. bool rc = false;
  4659. int thr_id = work->thr_id;
  4660. struct pool *pool = work->pool;
  4661. struct timeval tv_submit_reply;
  4662. time_t ts_submit_reply;
  4663. char worktime[200] = "";
  4664. cgtime(&tv_submit_reply);
  4665. ts_submit_reply = time(NULL);
  4666. if (unlikely(!val)) {
  4667. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  4668. if (!pool_tset(pool, &pool->submit_fail)) {
  4669. total_ro++;
  4670. pool->remotefail_occasions++;
  4671. applog(LOG_WARNING, "Pool %d communication failure, caching submissions", pool->pool_no);
  4672. }
  4673. goto out;
  4674. } else if (pool_tclear(pool, &pool->submit_fail))
  4675. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  4676. res = json_object_get(val, "result");
  4677. err = json_object_get(val, "error");
  4678. if (!QUIET) {
  4679. if (opt_worktime) {
  4680. char workclone[20];
  4681. struct tm _tm;
  4682. struct tm *tm, tm_getwork, tm_submit_reply;
  4683. tm = &_tm;
  4684. double getwork_time = tdiff((struct timeval *)&(work->tv_getwork_reply),
  4685. (struct timeval *)&(work->tv_getwork));
  4686. double getwork_to_work = tdiff((struct timeval *)&(work->tv_work_start),
  4687. (struct timeval *)&(work->tv_getwork_reply));
  4688. double work_time = tdiff((struct timeval *)&(work->tv_work_found),
  4689. (struct timeval *)&(work->tv_work_start));
  4690. double work_to_submit = tdiff(ptv_submit,
  4691. (struct timeval *)&(work->tv_work_found));
  4692. double submit_time = tdiff(&tv_submit_reply, ptv_submit);
  4693. int diffplaces = 3;
  4694. localtime_r(&work->ts_getwork, tm);
  4695. memcpy(&tm_getwork, tm, sizeof(struct tm));
  4696. localtime_r(&ts_submit_reply, tm);
  4697. memcpy(&tm_submit_reply, tm, sizeof(struct tm));
  4698. if (work->clone) {
  4699. snprintf(workclone, sizeof(workclone), "C:%1.3f",
  4700. tdiff((struct timeval *)&(work->tv_cloned),
  4701. (struct timeval *)&(work->tv_getwork_reply)));
  4702. }
  4703. else
  4704. strcpy(workclone, "O");
  4705. if (work->work_difficulty < 1)
  4706. diffplaces = 6;
  4707. const struct mining_algorithm * const malgo = work_mining_algorithm(work);
  4708. const uint8_t * const prevblkhash = &work->data[4];
  4709. snprintf(worktime, sizeof(worktime),
  4710. " <-%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",
  4711. (unsigned long)be32toh(((uint32_t *)prevblkhash)[7 - malgo->worktime_skip_prevblk_u32]),
  4712. (unsigned long)be32toh(((uint32_t *)prevblkhash)[6 - malgo->worktime_skip_prevblk_u32]),
  4713. work->getwork_mode, diffplaces, work->work_difficulty,
  4714. tm_getwork.tm_hour, tm_getwork.tm_min,
  4715. tm_getwork.tm_sec, getwork_time, workclone,
  4716. getwork_to_work, work_time, work_to_submit, submit_time,
  4717. tm_submit_reply.tm_hour, tm_submit_reply.tm_min,
  4718. tm_submit_reply.tm_sec);
  4719. }
  4720. }
  4721. share_result(val, res, err, work, resubmit, worktime);
  4722. if (!opt_realquiet)
  4723. print_status(thr_id);
  4724. if (!want_per_device_stats) {
  4725. char logline[256];
  4726. struct cgpu_info *cgpu;
  4727. cgpu = get_thr_cgpu(thr_id);
  4728. get_statline(logline, sizeof(logline), cgpu);
  4729. applog(LOG_INFO, "%s", logline);
  4730. }
  4731. json_decref(val);
  4732. rc = true;
  4733. out:
  4734. return rc;
  4735. }
  4736. /* Specifies whether we can use this pool for work or not. */
  4737. static bool pool_unworkable(const struct pool * const pool)
  4738. {
  4739. if (pool->idle)
  4740. return true;
  4741. if (pool->enabled != POOL_ENABLED)
  4742. return true;
  4743. if (pool->has_stratum && !pool->stratum_active)
  4744. return true;
  4745. return false;
  4746. }
  4747. static
  4748. bool pool_actively_desired(const struct pool * const pool, const struct pool *cp)
  4749. {
  4750. if (pool->enabled != POOL_ENABLED)
  4751. return false;
  4752. if (pool_strategy == POOL_LOADBALANCE || pool_strategy == POOL_BALANCE)
  4753. return true;
  4754. if (!cp)
  4755. cp = current_pool();
  4756. return (pool == cp);
  4757. }
  4758. static
  4759. bool pool_actively_in_use(const struct pool * const pool, const struct pool *cp)
  4760. {
  4761. return (!pool_unworkable(pool)) && pool_actively_desired(pool, cp);
  4762. }
  4763. static
  4764. bool pool_supports_block_change_notification(struct pool * const pool)
  4765. {
  4766. return pool->has_stratum || pool->lp_url;
  4767. }
  4768. static
  4769. bool pool_has_active_block_change_notification(struct pool * const pool)
  4770. {
  4771. return pool->stratum_active || pool->lp_active;
  4772. }
  4773. static struct pool *_select_longpoll_pool(struct pool *, bool(*)(struct pool *));
  4774. #define select_longpoll_pool(pool) _select_longpoll_pool(pool, pool_supports_block_change_notification)
  4775. #define pool_active_lp_pool(pool) _select_longpoll_pool(pool, pool_has_active_block_change_notification)
  4776. /* In balanced mode, the amount of diff1 solutions per pool is monitored as a
  4777. * rolling average per 10 minutes and if pools start getting more, it biases
  4778. * away from them to distribute work evenly. The share count is reset to the
  4779. * rolling average every 10 minutes to not send all work to one pool after it
  4780. * has been disabled/out for an extended period. */
  4781. static
  4782. struct pool *select_balanced(struct pool *cp, struct mining_algorithm * const malgo)
  4783. {
  4784. int i, lowest = cp->shares;
  4785. struct pool *ret = cp, *failover_pool = NULL;
  4786. for (i = 0; i < total_pools; i++) {
  4787. struct pool *pool = pools[i];
  4788. if (malgo && pool->goal->malgo != malgo)
  4789. continue;
  4790. if (pool_unworkable(pool))
  4791. continue;
  4792. if (pool->failover_only)
  4793. {
  4794. BFGINIT(failover_pool, pool);
  4795. continue;
  4796. }
  4797. if (pool->shares < lowest) {
  4798. lowest = pool->shares;
  4799. ret = pool;
  4800. }
  4801. }
  4802. if (malgo && ret->goal->malgo != malgo)
  4803. // Yes, we want failover_pool even if it's NULL
  4804. ret = failover_pool;
  4805. else
  4806. if (pool_unworkable(ret) && failover_pool)
  4807. ret = failover_pool;
  4808. if (ret)
  4809. ++ret->shares;
  4810. return ret;
  4811. }
  4812. static struct pool *priority_pool(int choice);
  4813. static
  4814. struct pool *select_loadbalance(struct mining_algorithm * const malgo)
  4815. {
  4816. static int rotating_pool = 0;
  4817. struct pool *pool;
  4818. bool avail = false;
  4819. int tested, i, rpsave;
  4820. for (i = 0; i < total_pools; i++) {
  4821. struct pool *tp = pools[i];
  4822. if (tp->quota_used < tp->quota_gcd) {
  4823. avail = true;
  4824. break;
  4825. }
  4826. }
  4827. /* There are no pools with quota, so reset them. */
  4828. if (!avail) {
  4829. for (i = 0; i < total_pools; i++)
  4830. {
  4831. struct pool * const tp = pools[i];
  4832. tp->quota_used -= tp->quota_gcd;
  4833. }
  4834. if (++rotating_pool >= total_pools)
  4835. rotating_pool = 0;
  4836. }
  4837. /* Try to find the first pool in the rotation that is usable */
  4838. // Look for the lowest integer quota_used / quota_gcd in case we are imbalanced by algorithm demands
  4839. struct pool *pool_lowest = NULL;
  4840. int lowest = INT_MAX;
  4841. rpsave = rotating_pool;
  4842. for (tested = 0; tested < total_pools; ++tested)
  4843. {
  4844. pool = pools[rotating_pool];
  4845. if (malgo && pool->goal->malgo != malgo)
  4846. goto continue_tested;
  4847. if (pool->quota_used < pool->quota_gcd)
  4848. {
  4849. ++pool->quota_used;
  4850. if (!pool_unworkable(pool))
  4851. goto out;
  4852. /* Failover-only flag for load-balance means distribute
  4853. * unused quota to priority pool 0. */
  4854. if (opt_fail_only)
  4855. priority_pool(0)->quota_used--;
  4856. }
  4857. if (malgo)
  4858. {
  4859. const int count = pool->quota_used / pool->quota_gcd;
  4860. if (count < lowest)
  4861. {
  4862. pool_lowest = pool;
  4863. lowest = count;
  4864. }
  4865. }
  4866. continue_tested: ;
  4867. if (++rotating_pool >= total_pools)
  4868. rotating_pool = 0;
  4869. }
  4870. // Even if pool_lowest is NULL, we want to return that to indicate failure
  4871. // Note it isn't possible to get here if !malgo
  4872. pool = pool_lowest;
  4873. out: ;
  4874. // Restore rotating_pool static, so malgo searches don't affect the usual load balancing
  4875. if (malgo)
  4876. rotating_pool = rpsave;
  4877. return pool;
  4878. }
  4879. static bool pool_unusable(struct pool *pool);
  4880. static
  4881. struct pool *select_failover(struct mining_algorithm * const malgo)
  4882. {
  4883. int i;
  4884. for (i = 0; i < total_pools; i++) {
  4885. struct pool *tp = priority_pool(i);
  4886. if (malgo && tp->goal->malgo != malgo)
  4887. continue;
  4888. if (!pool_unusable(tp)) {
  4889. return tp;
  4890. }
  4891. }
  4892. return NULL;
  4893. }
  4894. static bool pool_active(struct pool *, bool pinging);
  4895. static void pool_died(struct pool *);
  4896. /* Select any active pool in a rotating fashion when loadbalance is chosen if
  4897. * it has any quota left. */
  4898. static inline struct pool *select_pool(bool lagging, struct mining_algorithm * const malgo)
  4899. {
  4900. struct pool *pool = NULL, *cp;
  4901. retry:
  4902. cp = current_pool();
  4903. if (pool_strategy == POOL_BALANCE) {
  4904. pool = select_balanced(cp, malgo);
  4905. if ((!pool) || pool_unworkable(pool))
  4906. goto simple_failover;
  4907. goto out;
  4908. }
  4909. if (pool_strategy != POOL_LOADBALANCE && (!lagging || opt_fail_only)) {
  4910. if (malgo && cp->goal->malgo != malgo)
  4911. goto simple_failover;
  4912. pool = cp;
  4913. goto out;
  4914. } else
  4915. pool = select_loadbalance(malgo);
  4916. simple_failover:
  4917. /* If there are no alive pools with quota, choose according to
  4918. * priority. */
  4919. if (!pool) {
  4920. pool = select_failover(malgo);
  4921. }
  4922. /* If still nothing is usable, use the current pool */
  4923. if (!pool)
  4924. {
  4925. if (malgo && cp->goal->malgo != malgo)
  4926. {
  4927. applog(LOG_DEBUG, "Failed to select pool for specific mining algorithm");
  4928. return NULL;
  4929. }
  4930. pool = cp;
  4931. }
  4932. out:
  4933. if (!pool_actively_in_use(pool, cp))
  4934. {
  4935. if (!pool_active(pool, false))
  4936. {
  4937. pool_died(pool);
  4938. goto retry;
  4939. }
  4940. pool_tclear(pool, &pool->idle);
  4941. }
  4942. applog(LOG_DEBUG, "Selecting pool %d for work", pool->pool_no);
  4943. return pool;
  4944. }
  4945. static double DIFFEXACTONE = 26959946667150639794667015087019630673637144422540572481103610249215.0;
  4946. double target_diff(const unsigned char *target)
  4947. {
  4948. double targ = 0;
  4949. signed int i;
  4950. for (i = 31; i >= 0; --i)
  4951. targ = (targ * 0x100) + target[i];
  4952. return DIFFEXACTONE / (targ ?: 1);
  4953. }
  4954. /*
  4955. * Calculate the work share difficulty
  4956. */
  4957. static void calc_diff(struct work *work, int known)
  4958. {
  4959. struct cgminer_pool_stats *pool_stats = &(work->pool->cgminer_pool_stats);
  4960. double difficulty;
  4961. if (!known) {
  4962. work->work_difficulty = target_diff(work->target);
  4963. } else
  4964. work->work_difficulty = known;
  4965. difficulty = work->work_difficulty;
  4966. pool_stats->last_diff = difficulty;
  4967. suffix_string(difficulty, work->pool->diff, sizeof(work->pool->diff), 0);
  4968. if (difficulty == pool_stats->min_diff)
  4969. pool_stats->min_diff_count++;
  4970. else if (difficulty < pool_stats->min_diff || pool_stats->min_diff == 0) {
  4971. pool_stats->min_diff = difficulty;
  4972. pool_stats->min_diff_count = 1;
  4973. }
  4974. if (difficulty == pool_stats->max_diff)
  4975. pool_stats->max_diff_count++;
  4976. else if (difficulty > pool_stats->max_diff) {
  4977. pool_stats->max_diff = difficulty;
  4978. pool_stats->max_diff_count = 1;
  4979. }
  4980. }
  4981. static void gen_stratum_work(struct pool *, struct work *);
  4982. static void pool_update_work_restart_time(struct pool *);
  4983. static void restart_threads(void);
  4984. static uint32_t benchmark_blkhdr[20];
  4985. static const int benchmark_update_interval = 1;
  4986. static
  4987. void *benchmark_intense_work_update_thread(void *userp)
  4988. {
  4989. pthread_detach(pthread_self());
  4990. RenameThread("benchmark-intense");
  4991. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  4992. struct pool * const pool = userp;
  4993. struct stratum_work * const swork = &pool->swork;
  4994. uint8_t * const blkhdr = swork->header1;
  4995. while (true)
  4996. {
  4997. sleep(benchmark_update_interval);
  4998. cg_wlock(&pool->data_lock);
  4999. for (int i = 36; --i >= 0; )
  5000. if (++blkhdr[i])
  5001. break;
  5002. cg_wunlock(&pool->data_lock);
  5003. struct work *work = make_work();
  5004. gen_stratum_work(pool, work);
  5005. pool->swork.work_restart_id = ++pool->work_restart_id;
  5006. pool_update_work_restart_time(pool);
  5007. test_work_current(work);
  5008. free_work(work);
  5009. restart_threads();
  5010. }
  5011. return NULL;
  5012. }
  5013. static
  5014. void setup_benchmark_pool()
  5015. {
  5016. struct pool *pool;
  5017. want_longpoll = false;
  5018. // Temporarily disable opt_benchmark to avoid auto-removal
  5019. opt_benchmark = false;
  5020. pool = add_pool();
  5021. opt_benchmark = true;
  5022. pool->rpc_url = malloc(255);
  5023. strcpy(pool->rpc_url, "Benchmark");
  5024. pool_set_uri(pool, pool->rpc_url);
  5025. pool->rpc_user = pool->rpc_url;
  5026. pool->rpc_pass = pool->rpc_url;
  5027. enable_pool(pool);
  5028. pool->idle = false;
  5029. successful_connect = true;
  5030. {
  5031. uint32_t * const blkhdr = benchmark_blkhdr;
  5032. blkhdr[2] = htobe32(1);
  5033. blkhdr[17] = htobe32(0x7fffffff); // timestamp
  5034. blkhdr[18] = htobe32(0x1700ffff); // "bits"
  5035. }
  5036. {
  5037. struct stratum_work * const swork = &pool->swork;
  5038. const int branchcount = 15; // 1 MB block
  5039. const size_t branchdatasz = branchcount * 0x20;
  5040. const size_t coinbase_sz = (opt_benchmark_intense ? 250 : 6) * 1024;
  5041. bytes_resize(&swork->coinbase, coinbase_sz);
  5042. memset(bytes_buf(&swork->coinbase), '\xff', coinbase_sz);
  5043. swork->nonce2_offset = 0;
  5044. bytes_resize(&swork->merkle_bin, branchdatasz);
  5045. memset(bytes_buf(&swork->merkle_bin), '\xff', branchdatasz);
  5046. swork->merkles = branchcount;
  5047. swork->header1[0] = '\xff';
  5048. memset(&swork->header1[1], '\0', 34);
  5049. swork->header1[35] = '\x01';
  5050. swork->ntime = 0x7fffffff;
  5051. timer_unset(&swork->tv_received);
  5052. memcpy(swork->diffbits, "\x17\0\xff\xff", 4);
  5053. const struct mining_goal_info * const goal = get_mining_goal("default");
  5054. const struct mining_algorithm * const malgo = goal->malgo;
  5055. set_target_to_pdiff(swork->target, malgo->reasonable_low_nonce_diff);
  5056. pool->nonce2sz = swork->n2size = GBT_XNONCESZ;
  5057. pool->nonce2 = 0;
  5058. }
  5059. if (opt_benchmark_intense)
  5060. {
  5061. pthread_t pth;
  5062. if (unlikely(pthread_create(&pth, NULL, benchmark_intense_work_update_thread, pool)))
  5063. applog(LOG_WARNING, "Failed to start benchmark intense work update thread");
  5064. }
  5065. }
  5066. void get_benchmark_work(struct work *work, bool use_swork)
  5067. {
  5068. if (use_swork)
  5069. {
  5070. struct timeval tv_now;
  5071. timer_set_now(&tv_now);
  5072. gen_stratum_work(pools[0], work);
  5073. work->getwork_mode = GETWORK_MODE_BENCHMARK;
  5074. work_set_simple_ntime_roll_limit(work, 0, &tv_now);
  5075. return;
  5076. }
  5077. struct pool * const pool = pools[0];
  5078. uint32_t * const blkhdr = benchmark_blkhdr;
  5079. for (int i = 16; i >= 0; --i)
  5080. if (++blkhdr[i])
  5081. break;
  5082. memcpy(&work->data[ 0], blkhdr, 80);
  5083. memcpy(&work->data[80], workpadding_bin, 48);
  5084. char hex[161];
  5085. bin2hex(hex, work->data, 80);
  5086. applog(LOG_DEBUG, "Generated benchmark header %s", hex);
  5087. calc_midstate(work);
  5088. memcpy(work->target, pool->swork.target, sizeof(work->target));
  5089. work->mandatory = true;
  5090. work->pool = pools[0];
  5091. cgtime(&work->tv_getwork);
  5092. copy_time(&work->tv_getwork_reply, &work->tv_getwork);
  5093. copy_time(&work->tv_staged, &work->tv_getwork);
  5094. work->getwork_mode = GETWORK_MODE_BENCHMARK;
  5095. calc_diff(work, 0);
  5096. work_set_simple_ntime_roll_limit(work, 60, &work->tv_getwork);
  5097. }
  5098. static void wake_gws(void);
  5099. static void update_last_work(struct work *work)
  5100. {
  5101. if (!work->tr)
  5102. // Only save GBT jobs, since rollntime isn't coordinated well yet
  5103. return;
  5104. struct pool *pool = work->pool;
  5105. mutex_lock(&pool->last_work_lock);
  5106. if (pool->last_work_copy)
  5107. free_work(pool->last_work_copy);
  5108. pool->last_work_copy = copy_work(work);
  5109. pool->last_work_copy->work_restart_id = pool->work_restart_id;
  5110. mutex_unlock(&pool->last_work_lock);
  5111. }
  5112. static
  5113. void gbt_req_target(json_t *req)
  5114. {
  5115. json_t *j;
  5116. json_t *n;
  5117. if (!request_target_str)
  5118. return;
  5119. j = json_object_get(req, "params");
  5120. if (!j)
  5121. {
  5122. n = json_array();
  5123. if (!n)
  5124. return;
  5125. if (json_object_set_new(req, "params", n))
  5126. goto erradd;
  5127. j = n;
  5128. }
  5129. n = json_array_get(j, 0);
  5130. if (!n)
  5131. {
  5132. n = json_object();
  5133. if (!n)
  5134. return;
  5135. if (json_array_append_new(j, n))
  5136. goto erradd;
  5137. }
  5138. j = n;
  5139. n = json_string(request_target_str);
  5140. if (!n)
  5141. return;
  5142. if (json_object_set_new(j, "target", n))
  5143. goto erradd;
  5144. return;
  5145. erradd:
  5146. json_decref(n);
  5147. }
  5148. static char *prepare_rpc_req2(struct work *work, enum pool_protocol proto, const char *lpid, bool probe, struct pool * const pool)
  5149. {
  5150. char *rpc_req;
  5151. clean_work(work);
  5152. switch (proto) {
  5153. case PLP_GETWORK:
  5154. work->getwork_mode = GETWORK_MODE_POOL;
  5155. return strdup(getwork_req);
  5156. case PLP_GETBLOCKTEMPLATE:
  5157. work->getwork_mode = GETWORK_MODE_GBT;
  5158. blktemplate_t * const tmpl = blktmpl_create();
  5159. if (!tmpl)
  5160. goto gbtfail2;
  5161. work->tr = tmpl_makeref(tmpl);
  5162. gbt_capabilities_t caps = blktmpl_addcaps(tmpl);
  5163. if (!caps)
  5164. goto gbtfail;
  5165. caps |= GBT_LONGPOLL;
  5166. #if BLKMAKER_VERSION > 1
  5167. const struct mining_goal_info * const goal = pool->goal;
  5168. if (goal->generation_script || goal_has_at_least_one_getcbaddr(goal))
  5169. caps |= GBT_CBVALUE;
  5170. #endif
  5171. json_t *req = blktmpl_request_jansson(caps, lpid);
  5172. if (!req)
  5173. goto gbtfail;
  5174. if (probe)
  5175. gbt_req_target(req);
  5176. rpc_req = json_dumps(req, 0);
  5177. if (!rpc_req)
  5178. goto gbtfail;
  5179. json_decref(req);
  5180. return rpc_req;
  5181. default:
  5182. return NULL;
  5183. }
  5184. return NULL;
  5185. gbtfail:
  5186. tmpl_decref(work->tr);
  5187. work->tr = NULL;
  5188. gbtfail2:
  5189. return NULL;
  5190. }
  5191. #define prepare_rpc_req(work, proto, lpid, pool) prepare_rpc_req2(work, proto, lpid, false, pool)
  5192. #define prepare_rpc_req_probe(work, proto, lpid, pool) prepare_rpc_req2(work, proto, lpid, true, pool)
  5193. static const char *pool_protocol_name(enum pool_protocol proto)
  5194. {
  5195. switch (proto) {
  5196. case PLP_GETBLOCKTEMPLATE:
  5197. return "getblocktemplate";
  5198. case PLP_GETWORK:
  5199. return "getwork";
  5200. default:
  5201. return "UNKNOWN";
  5202. }
  5203. }
  5204. static enum pool_protocol pool_protocol_fallback(enum pool_protocol proto)
  5205. {
  5206. switch (proto) {
  5207. case PLP_GETBLOCKTEMPLATE:
  5208. if (want_getwork)
  5209. return PLP_GETWORK;
  5210. default:
  5211. return PLP_NONE;
  5212. }
  5213. }
  5214. static bool get_upstream_work(struct work *work, CURL *curl)
  5215. {
  5216. struct pool *pool = work->pool;
  5217. struct cgminer_pool_stats *pool_stats = &(pool->cgminer_pool_stats);
  5218. struct timeval tv_elapsed;
  5219. json_t *val = NULL;
  5220. bool rc = false;
  5221. char *url;
  5222. enum pool_protocol proto;
  5223. char *rpc_req;
  5224. if (pool->proto == PLP_NONE)
  5225. pool->proto = PLP_GETBLOCKTEMPLATE;
  5226. tryagain:
  5227. rpc_req = prepare_rpc_req(work, pool->proto, NULL, pool);
  5228. work->pool = pool;
  5229. if (!rpc_req)
  5230. return false;
  5231. applog(LOG_DEBUG, "DBG: sending %s get RPC call: %s", pool->rpc_url, rpc_req);
  5232. url = pool->rpc_url;
  5233. cgtime(&work->tv_getwork);
  5234. val = json_rpc_call(curl, url, pool->rpc_userpass, rpc_req, false,
  5235. false, &work->rolltime, pool, false);
  5236. pool_stats->getwork_attempts++;
  5237. free(rpc_req);
  5238. if (likely(val)) {
  5239. rc = work_decode(pool, work, val);
  5240. if (unlikely(!rc))
  5241. applog(LOG_DEBUG, "Failed to decode work in get_upstream_work");
  5242. } else if (PLP_NONE != (proto = pool_protocol_fallback(pool->proto))) {
  5243. applog(LOG_WARNING, "Pool %u failed getblocktemplate request; falling back to getwork protocol", pool->pool_no);
  5244. pool->proto = proto;
  5245. goto tryagain;
  5246. } else
  5247. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  5248. cgtime(&work->tv_getwork_reply);
  5249. timersub(&(work->tv_getwork_reply), &(work->tv_getwork), &tv_elapsed);
  5250. pool_stats->getwork_wait_rolling += ((double)tv_elapsed.tv_sec + ((double)tv_elapsed.tv_usec / 1000000)) * 0.63;
  5251. pool_stats->getwork_wait_rolling /= 1.63;
  5252. timeradd(&tv_elapsed, &(pool_stats->getwork_wait), &(pool_stats->getwork_wait));
  5253. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_max), >)) {
  5254. pool_stats->getwork_wait_max.tv_sec = tv_elapsed.tv_sec;
  5255. pool_stats->getwork_wait_max.tv_usec = tv_elapsed.tv_usec;
  5256. }
  5257. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_min), <)) {
  5258. pool_stats->getwork_wait_min.tv_sec = tv_elapsed.tv_sec;
  5259. pool_stats->getwork_wait_min.tv_usec = tv_elapsed.tv_usec;
  5260. }
  5261. pool_stats->getwork_calls++;
  5262. work->pool = pool;
  5263. work->longpoll = false;
  5264. calc_diff(work, 0);
  5265. total_getworks++;
  5266. pool->getwork_requested++;
  5267. if (rc)
  5268. update_last_work(work);
  5269. if (likely(val))
  5270. json_decref(val);
  5271. return rc;
  5272. }
  5273. #ifdef HAVE_CURSES
  5274. static void disable_curses(void)
  5275. {
  5276. if (curses_active_locked()) {
  5277. use_curses = false;
  5278. curses_active = false;
  5279. leaveok(logwin, false);
  5280. leaveok(statuswin, false);
  5281. leaveok(mainwin, false);
  5282. nocbreak();
  5283. echo();
  5284. delwin(logwin);
  5285. delwin(statuswin);
  5286. delwin(mainwin);
  5287. endwin();
  5288. #ifdef WIN32
  5289. // Move the cursor to after curses output.
  5290. HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
  5291. CONSOLE_SCREEN_BUFFER_INFO csbi;
  5292. COORD coord;
  5293. if (GetConsoleScreenBufferInfo(hout, &csbi)) {
  5294. coord.X = 0;
  5295. coord.Y = csbi.dwSize.Y - 1;
  5296. SetConsoleCursorPosition(hout, coord);
  5297. }
  5298. #endif
  5299. unlock_curses();
  5300. }
  5301. }
  5302. #endif
  5303. static void __kill_work(void)
  5304. {
  5305. struct cgpu_info *cgpu;
  5306. struct thr_info *thr;
  5307. int i;
  5308. if (!successful_connect)
  5309. return;
  5310. applog(LOG_INFO, "Received kill message");
  5311. shutting_down = true;
  5312. applog(LOG_DEBUG, "Prompting submit_work thread to finish");
  5313. notifier_wake(submit_waiting_notifier);
  5314. #ifdef USE_LIBMICROHTTPD
  5315. httpsrv_stop();
  5316. #endif
  5317. applog(LOG_DEBUG, "Killing off watchpool thread");
  5318. /* Kill the watchpool thread */
  5319. thr = &control_thr[watchpool_thr_id];
  5320. thr_info_cancel(thr);
  5321. applog(LOG_DEBUG, "Killing off watchdog thread");
  5322. /* Kill the watchdog thread */
  5323. thr = &control_thr[watchdog_thr_id];
  5324. thr_info_cancel(thr);
  5325. applog(LOG_DEBUG, "Shutting down mining threads");
  5326. for (i = 0; i < mining_threads; i++) {
  5327. thr = get_thread(i);
  5328. if (!thr)
  5329. continue;
  5330. cgpu = thr->cgpu;
  5331. if (!cgpu)
  5332. continue;
  5333. if (!cgpu->threads)
  5334. continue;
  5335. cgpu->shutdown = true;
  5336. thr->work_restart = true;
  5337. notifier_wake(thr->notifier);
  5338. notifier_wake(thr->work_restart_notifier);
  5339. }
  5340. sleep(1);
  5341. applog(LOG_DEBUG, "Killing off mining threads");
  5342. /* Kill the mining threads*/
  5343. for (i = 0; i < mining_threads; i++) {
  5344. thr = get_thread(i);
  5345. if (!thr)
  5346. continue;
  5347. cgpu = thr->cgpu;
  5348. if (cgpu->threads)
  5349. {
  5350. applog(LOG_WARNING, "Killing %"PRIpreprv, thr->cgpu->proc_repr);
  5351. thr_info_cancel(thr);
  5352. }
  5353. cgpu->status = LIFE_DEAD2;
  5354. }
  5355. /* Stop the others */
  5356. applog(LOG_DEBUG, "Killing off API thread");
  5357. thr = &control_thr[api_thr_id];
  5358. thr_info_cancel(thr);
  5359. }
  5360. /* This should be the common exit path */
  5361. void kill_work(void)
  5362. {
  5363. __kill_work();
  5364. quit(0, "Shutdown signal received.");
  5365. }
  5366. static
  5367. #ifdef WIN32
  5368. #ifndef _WIN64
  5369. const
  5370. #endif
  5371. #endif
  5372. char **initial_args;
  5373. void _bfg_clean_up(bool);
  5374. void app_restart(void)
  5375. {
  5376. applog(LOG_WARNING, "Attempting to restart %s", packagename);
  5377. __kill_work();
  5378. _bfg_clean_up(true);
  5379. #if defined(unix) || defined(__APPLE__)
  5380. if (forkpid > 0) {
  5381. kill(forkpid, SIGTERM);
  5382. forkpid = 0;
  5383. }
  5384. #endif
  5385. execv(initial_args[0], initial_args);
  5386. applog(LOG_WARNING, "Failed to restart application");
  5387. }
  5388. static void sighandler(int __maybe_unused sig)
  5389. {
  5390. /* Restore signal handlers so we can still quit if kill_work fails */
  5391. sigaction(SIGTERM, &termhandler, NULL);
  5392. sigaction(SIGINT, &inthandler, NULL);
  5393. kill_work();
  5394. }
  5395. static void start_longpoll(void);
  5396. static void stop_longpoll(void);
  5397. /* Called with pool_lock held. Recruit an extra curl if none are available for
  5398. * this pool. */
  5399. static void recruit_curl(struct pool *pool)
  5400. {
  5401. struct curl_ent *ce = calloc(sizeof(struct curl_ent), 1);
  5402. if (unlikely(!ce))
  5403. quit(1, "Failed to calloc in recruit_curl");
  5404. ce->curl = curl_easy_init();
  5405. if (unlikely(!ce->curl))
  5406. quit(1, "Failed to init in recruit_curl");
  5407. LL_PREPEND(pool->curllist, ce);
  5408. pool->curls++;
  5409. }
  5410. /* Grab an available curl if there is one. If not, then recruit extra curls
  5411. * unless we are in a submit_fail situation, or we have opt_delaynet enabled
  5412. * and there are already 5 curls in circulation. Limit total number to the
  5413. * number of mining threads per pool as well to prevent blasting a pool during
  5414. * network delays/outages. */
  5415. static struct curl_ent *pop_curl_entry3(struct pool *pool, int blocking)
  5416. {
  5417. int curl_limit = opt_delaynet ? 5 : (mining_threads + opt_queue) * 2;
  5418. bool recruited = false;
  5419. struct curl_ent *ce;
  5420. mutex_lock(&pool->pool_lock);
  5421. retry:
  5422. if (!pool->curls) {
  5423. recruit_curl(pool);
  5424. recruited = true;
  5425. } else if (!pool->curllist) {
  5426. if (blocking < 2 && pool->curls >= curl_limit && (blocking || pool->curls >= opt_submit_threads)) {
  5427. if (!blocking) {
  5428. mutex_unlock(&pool->pool_lock);
  5429. return NULL;
  5430. }
  5431. pthread_cond_wait(&pool->cr_cond, &pool->pool_lock);
  5432. goto retry;
  5433. } else {
  5434. recruit_curl(pool);
  5435. recruited = true;
  5436. }
  5437. }
  5438. ce = pool->curllist;
  5439. LL_DELETE(pool->curllist, ce);
  5440. mutex_unlock(&pool->pool_lock);
  5441. if (recruited)
  5442. applog(LOG_DEBUG, "Recruited curl for pool %d", pool->pool_no);
  5443. return ce;
  5444. }
  5445. static struct curl_ent *pop_curl_entry2(struct pool *pool, bool blocking)
  5446. {
  5447. return pop_curl_entry3(pool, blocking ? 1 : 0);
  5448. }
  5449. __maybe_unused
  5450. static struct curl_ent *pop_curl_entry(struct pool *pool)
  5451. {
  5452. return pop_curl_entry3(pool, 1);
  5453. }
  5454. static void push_curl_entry(struct curl_ent *ce, struct pool *pool)
  5455. {
  5456. mutex_lock(&pool->pool_lock);
  5457. if (!ce || !ce->curl)
  5458. quithere(1, "Attempted to add NULL");
  5459. LL_PREPEND(pool->curllist, ce);
  5460. cgtime(&ce->tv);
  5461. pthread_cond_broadcast(&pool->cr_cond);
  5462. mutex_unlock(&pool->pool_lock);
  5463. }
  5464. bool stale_work(struct work *work, bool share);
  5465. static inline bool should_roll(struct work *work)
  5466. {
  5467. struct timeval now;
  5468. time_t expiry;
  5469. if (!pool_actively_in_use(work->pool, NULL))
  5470. return false;
  5471. if (stale_work(work, false))
  5472. return false;
  5473. if (work->rolltime > opt_scantime)
  5474. expiry = work->rolltime;
  5475. else
  5476. expiry = opt_scantime;
  5477. expiry = expiry * 2 / 3;
  5478. /* We shouldn't roll if we're unlikely to get one shares' duration
  5479. * work out of doing so */
  5480. cgtime(&now);
  5481. if (now.tv_sec - work->tv_staged.tv_sec > expiry)
  5482. return false;
  5483. return true;
  5484. }
  5485. /* Limit rolls to 7000 to not beyond 2 hours in the future where bitcoind will
  5486. * reject blocks as invalid. */
  5487. static inline bool can_roll(struct work *work)
  5488. {
  5489. if (work->stratum)
  5490. return false;
  5491. if (!(work->pool && !work->clone))
  5492. return false;
  5493. if (work->tr)
  5494. {
  5495. if (stale_work(work, false))
  5496. return false;
  5497. return blkmk_work_left(work->tr->tmpl);
  5498. }
  5499. return (work->rolltime &&
  5500. work->rolls < 7000 && !stale_work(work, false));
  5501. }
  5502. static void roll_work(struct work *work)
  5503. {
  5504. if (work->tr)
  5505. {
  5506. struct timeval tv_now;
  5507. cgtime(&tv_now);
  5508. if (blkmk_get_data(work->tr->tmpl, work->data, 80, tv_now.tv_sec, NULL, &work->dataid) < 76)
  5509. applog(LOG_ERR, "Failed to get next data from template; spinning wheels!");
  5510. swap32yes(work->data, work->data, 80 / 4);
  5511. calc_midstate(work);
  5512. applog(LOG_DEBUG, "Successfully rolled extranonce to dataid %u", work->dataid);
  5513. } else {
  5514. uint32_t *work_ntime;
  5515. uint32_t ntime;
  5516. work_ntime = (uint32_t *)(work->data + 68);
  5517. ntime = be32toh(*work_ntime);
  5518. ntime++;
  5519. *work_ntime = htobe32(ntime);
  5520. work_set_simple_ntime_roll_limit(work, 0, &work->ntime_roll_limits.tv_ref);
  5521. applog(LOG_DEBUG, "Successfully rolled time header in work");
  5522. }
  5523. local_work++;
  5524. work->rolls++;
  5525. work->blk.nonce = 0;
  5526. /* This is now a different work item so it needs a different ID for the
  5527. * hashtable */
  5528. work->id = total_work++;
  5529. }
  5530. /* Duplicates any dynamically allocated arrays within the work struct to
  5531. * prevent a copied work struct from freeing ram belonging to another struct */
  5532. static void _copy_work(struct work *work, const struct work *base_work, int noffset)
  5533. {
  5534. int id = work->id;
  5535. clean_work(work);
  5536. memcpy(work, base_work, sizeof(struct work));
  5537. /* Keep the unique new id assigned during make_work to prevent copied
  5538. * work from having the same id. */
  5539. work->id = id;
  5540. if (base_work->job_id)
  5541. work->job_id = strdup(base_work->job_id);
  5542. if (base_work->nonce1)
  5543. work->nonce1 = strdup(base_work->nonce1);
  5544. bytes_cpy(&work->nonce2, &base_work->nonce2);
  5545. if (base_work->tr)
  5546. tmpl_incref(base_work->tr);
  5547. if (noffset)
  5548. {
  5549. uint32_t *work_ntime = (uint32_t *)(work->data + 68);
  5550. uint32_t ntime = be32toh(*work_ntime);
  5551. ntime += noffset;
  5552. *work_ntime = htobe32(ntime);
  5553. }
  5554. if (work->device_data_dup_func)
  5555. work->device_data = work->device_data_dup_func(work);
  5556. }
  5557. /* Generates a copy of an existing work struct, creating fresh heap allocations
  5558. * for all dynamically allocated arrays within the struct. noffset is used for
  5559. * when a driver has internally rolled the ntime, noffset is a relative value.
  5560. * The macro copy_work() calls this function with an noffset of 0. */
  5561. struct work *copy_work_noffset(const struct work *base_work, int noffset)
  5562. {
  5563. struct work *work = make_work();
  5564. _copy_work(work, base_work, noffset);
  5565. return work;
  5566. }
  5567. void __copy_work(struct work *work, const struct work *base_work)
  5568. {
  5569. _copy_work(work, base_work, 0);
  5570. }
  5571. static struct work *make_clone(struct work *work)
  5572. {
  5573. struct work *work_clone = copy_work(work);
  5574. work_clone->clone = true;
  5575. cgtime((struct timeval *)&(work_clone->tv_cloned));
  5576. work_clone->longpoll = false;
  5577. work_clone->mandatory = false;
  5578. /* Make cloned work appear slightly older to bias towards keeping the
  5579. * master work item which can be further rolled */
  5580. work_clone->tv_staged.tv_sec -= 1;
  5581. return work_clone;
  5582. }
  5583. static void stage_work(struct work *work);
  5584. static bool clone_available(void)
  5585. {
  5586. struct work *work_clone = NULL, *work, *tmp;
  5587. bool cloned = false;
  5588. mutex_lock(stgd_lock);
  5589. if (!staged_rollable)
  5590. goto out_unlock;
  5591. HASH_ITER(hh, staged_work, work, tmp) {
  5592. if (can_roll(work) && should_roll(work)) {
  5593. roll_work(work);
  5594. work_clone = make_clone(work);
  5595. applog(LOG_DEBUG, "%s: Rolling work %d to %d", __func__, work->id, work_clone->id);
  5596. roll_work(work);
  5597. cloned = true;
  5598. break;
  5599. }
  5600. }
  5601. out_unlock:
  5602. mutex_unlock(stgd_lock);
  5603. if (cloned) {
  5604. applog(LOG_DEBUG, "Pushing cloned available work to stage thread");
  5605. stage_work(work_clone);
  5606. }
  5607. return cloned;
  5608. }
  5609. static void pool_died(struct pool *pool)
  5610. {
  5611. mutex_lock(&lp_lock);
  5612. if (!pool_tset(pool, &pool->idle)) {
  5613. cgtime(&pool->tv_idle);
  5614. pthread_cond_broadcast(&lp_cond);
  5615. mutex_unlock(&lp_lock);
  5616. if (pool == current_pool()) {
  5617. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  5618. switch_pools(NULL);
  5619. } else
  5620. applog(LOG_INFO, "Pool %d %s failed to return work", pool->pool_no, pool->rpc_url);
  5621. }
  5622. else
  5623. mutex_unlock(&lp_lock);
  5624. }
  5625. bool stale_work(struct work *work, bool share)
  5626. {
  5627. unsigned work_expiry;
  5628. struct pool *pool;
  5629. uint32_t block_id;
  5630. unsigned getwork_delay;
  5631. block_id = ((uint32_t*)work->data)[1];
  5632. pool = work->pool;
  5633. struct mining_goal_info * const goal = pool->goal;
  5634. struct blockchain_info * const blkchain = goal->blkchain;
  5635. /* Technically the rolltime should be correct but some pools
  5636. * advertise a broken expire= that is lower than a meaningful
  5637. * scantime */
  5638. if (work->rolltime >= opt_scantime || work->tr)
  5639. work_expiry = work->rolltime;
  5640. else
  5641. work_expiry = opt_expiry;
  5642. unsigned max_expiry = (goal->have_longpoll ? opt_expiry_lp : opt_expiry);
  5643. if (work_expiry > max_expiry)
  5644. work_expiry = max_expiry;
  5645. if (share) {
  5646. /* If the share isn't on this pool's latest block, it's stale */
  5647. if (pool->block_id && pool->block_id != block_id)
  5648. {
  5649. applog(LOG_DEBUG, "Share stale due to block mismatch (%08lx != %08lx)", (long)block_id, (long)pool->block_id);
  5650. return true;
  5651. }
  5652. /* If the pool doesn't want old shares, then any found in work before
  5653. * the most recent longpoll is stale */
  5654. if ((!pool->submit_old) && work->work_restart_id != pool->work_restart_id)
  5655. {
  5656. applog(LOG_DEBUG, "Share stale due to mandatory work update (%02x != %02x)", work->work_restart_id, pool->work_restart_id);
  5657. return true;
  5658. }
  5659. } else {
  5660. /* If this work isn't for the latest Bitcoin block, it's stale */
  5661. /* But only care about the current pool if failover-only */
  5662. if (enabled_pools <= 1 || opt_fail_only) {
  5663. if (pool->block_id && block_id != pool->block_id)
  5664. {
  5665. 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);
  5666. return true;
  5667. }
  5668. } else {
  5669. if (block_id != blkchain->currentblk->block_id)
  5670. {
  5671. 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);
  5672. return true;
  5673. }
  5674. }
  5675. /* If the pool has asked us to restart since this work, it's stale */
  5676. if (work->work_restart_id != pool->work_restart_id)
  5677. {
  5678. applog(LOG_DEBUG, "Work stale due to work update (%02x != %02x)", work->work_restart_id, pool->work_restart_id);
  5679. return true;
  5680. }
  5681. if (pool->has_stratum && work->job_id) {
  5682. bool same_job;
  5683. if (!pool->stratum_active || !pool->stratum_notify) {
  5684. applog(LOG_DEBUG, "Work stale due to stratum inactive");
  5685. return true;
  5686. }
  5687. same_job = true;
  5688. cg_rlock(&pool->data_lock);
  5689. if (strcmp(work->job_id, pool->swork.job_id))
  5690. same_job = false;
  5691. cg_runlock(&pool->data_lock);
  5692. if (!same_job) {
  5693. applog(LOG_DEBUG, "Work stale due to stratum job_id mismatch");
  5694. return true;
  5695. }
  5696. }
  5697. /* Factor in the average getwork delay of this pool, rounding it up to
  5698. * the nearest second */
  5699. getwork_delay = pool->cgminer_pool_stats.getwork_wait_rolling * 5 + 1;
  5700. if (unlikely(work_expiry <= getwork_delay + 5))
  5701. work_expiry = 5;
  5702. else
  5703. work_expiry -= getwork_delay;
  5704. }
  5705. int elapsed_since_staged = timer_elapsed(&work->tv_staged, NULL);
  5706. if (elapsed_since_staged > work_expiry) {
  5707. applog(LOG_DEBUG, "%s stale due to expiry (%d >= %u)", share?"Share":"Work", elapsed_since_staged, work_expiry);
  5708. return true;
  5709. }
  5710. /* If the user only wants strict failover, any work from a pool other than
  5711. * the current one is always considered stale */
  5712. if (opt_fail_only && !share && !work->mandatory && !pool_actively_in_use(pool, NULL))
  5713. {
  5714. applog(LOG_DEBUG, "Work stale due to fail only pool mismatch (pool %u vs %u)", pool->pool_no, current_pool()->pool_no);
  5715. return true;
  5716. }
  5717. return false;
  5718. }
  5719. double share_diff(const struct work *work)
  5720. {
  5721. double ret;
  5722. bool new_best = false;
  5723. ret = target_diff(work->hash);
  5724. cg_wlock(&control_lock);
  5725. if (unlikely(ret > best_diff)) {
  5726. new_best = true;
  5727. best_diff = ret;
  5728. suffix_string(best_diff, best_share, sizeof(best_share), 0);
  5729. }
  5730. if (unlikely(ret > work->pool->best_diff))
  5731. work->pool->best_diff = ret;
  5732. cg_wunlock(&control_lock);
  5733. if (unlikely(new_best))
  5734. applog(LOG_INFO, "New best share: %s", best_share);
  5735. return ret;
  5736. }
  5737. static
  5738. void work_check_for_block(struct work * const work)
  5739. {
  5740. struct pool * const pool = work->pool;
  5741. struct mining_goal_info * const goal = pool->goal;
  5742. work->share_diff = share_diff(work);
  5743. if (unlikely(work->share_diff >= goal->current_diff)) {
  5744. work->block = true;
  5745. work->pool->solved++;
  5746. found_blocks++;
  5747. work->mandatory = true;
  5748. applog(LOG_NOTICE, "Found block for pool %d!", work->pool->pool_no);
  5749. }
  5750. }
  5751. static void submit_discard_share2(const char *reason, struct work *work)
  5752. {
  5753. struct cgpu_info *cgpu = get_thr_cgpu(work->thr_id);
  5754. sharelog(reason, work);
  5755. mutex_lock(&stats_lock);
  5756. ++total_stale;
  5757. ++cgpu->stale;
  5758. ++(work->pool->stale_shares);
  5759. total_diff_stale += work->work_difficulty;
  5760. cgpu->diff_stale += work->work_difficulty;
  5761. work->pool->diff_stale += work->work_difficulty;
  5762. mutex_unlock(&stats_lock);
  5763. }
  5764. static void submit_discard_share(struct work *work)
  5765. {
  5766. submit_discard_share2("discard", work);
  5767. }
  5768. struct submit_work_state {
  5769. struct work *work;
  5770. bool resubmit;
  5771. struct curl_ent *ce;
  5772. int failures;
  5773. struct timeval tv_staleexpire;
  5774. char *s;
  5775. struct timeval tv_submit;
  5776. struct submit_work_state *next;
  5777. };
  5778. static int my_curl_timer_set(__maybe_unused CURLM *curlm, long timeout_ms, void *userp)
  5779. {
  5780. long *p_timeout_us = userp;
  5781. const long max_ms = LONG_MAX / 1000;
  5782. if (max_ms < timeout_ms)
  5783. timeout_ms = max_ms;
  5784. *p_timeout_us = timeout_ms * 1000;
  5785. return 0;
  5786. }
  5787. static void sws_has_ce(struct submit_work_state *sws)
  5788. {
  5789. struct pool *pool = sws->work->pool;
  5790. sws->s = submit_upstream_work_request(sws->work);
  5791. cgtime(&sws->tv_submit);
  5792. json_rpc_call_async(sws->ce->curl, pool->rpc_url, pool->rpc_userpass, sws->s, false, pool, true, sws);
  5793. }
  5794. static struct submit_work_state *begin_submission(struct work *work)
  5795. {
  5796. struct pool *pool;
  5797. struct submit_work_state *sws = NULL;
  5798. pool = work->pool;
  5799. sws = malloc(sizeof(*sws));
  5800. *sws = (struct submit_work_state){
  5801. .work = work,
  5802. };
  5803. work_check_for_block(work);
  5804. if (stale_work(work, true)) {
  5805. work->stale = true;
  5806. if (opt_submit_stale)
  5807. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as user requested", pool->pool_no);
  5808. else if (pool->submit_old)
  5809. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as pool requested", pool->pool_no);
  5810. else {
  5811. applog(LOG_NOTICE, "Pool %d stale share detected, discarding", pool->pool_no);
  5812. submit_discard_share(work);
  5813. goto out;
  5814. }
  5815. timer_set_delay_from_now(&sws->tv_staleexpire, 300000000);
  5816. }
  5817. if (work->stratum) {
  5818. char *s;
  5819. s = malloc(1024);
  5820. sws->s = s;
  5821. } else {
  5822. /* submit solution to bitcoin via JSON-RPC */
  5823. sws->ce = pop_curl_entry2(pool, false);
  5824. if (sws->ce) {
  5825. sws_has_ce(sws);
  5826. } else {
  5827. sws->next = pool->sws_waiting_on_curl;
  5828. pool->sws_waiting_on_curl = sws;
  5829. if (sws->next)
  5830. applog(LOG_DEBUG, "submit_thread queuing submission");
  5831. else
  5832. applog(LOG_WARNING, "submit_thread queuing submissions (see --submit-threads)");
  5833. }
  5834. }
  5835. return sws;
  5836. out:
  5837. free(sws);
  5838. return NULL;
  5839. }
  5840. static bool retry_submission(struct submit_work_state *sws)
  5841. {
  5842. struct work *work = sws->work;
  5843. struct pool *pool = work->pool;
  5844. sws->resubmit = true;
  5845. if ((!work->stale) && stale_work(work, true)) {
  5846. work->stale = true;
  5847. if (opt_submit_stale)
  5848. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, will retry as user requested", pool->pool_no);
  5849. else if (pool->submit_old)
  5850. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, will retry as pool requested", pool->pool_no);
  5851. else {
  5852. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, discarding", pool->pool_no);
  5853. submit_discard_share(work);
  5854. return false;
  5855. }
  5856. timer_set_delay_from_now(&sws->tv_staleexpire, 300000000);
  5857. }
  5858. if (unlikely((opt_retries >= 0) && (++sws->failures > opt_retries))) {
  5859. applog(LOG_ERR, "Pool %d failed %d submission retries, discarding", pool->pool_no, opt_retries);
  5860. submit_discard_share(work);
  5861. return false;
  5862. }
  5863. else if (work->stale) {
  5864. if (unlikely(opt_retries < 0 && timer_passed(&sws->tv_staleexpire, NULL)))
  5865. {
  5866. applog(LOG_NOTICE, "Pool %d stale share failed to submit for 5 minutes, discarding", pool->pool_no);
  5867. submit_discard_share(work);
  5868. return false;
  5869. }
  5870. }
  5871. /* pause, then restart work-request loop */
  5872. applog(LOG_INFO, "json_rpc_call failed on submit_work, retrying");
  5873. cgtime(&sws->tv_submit);
  5874. json_rpc_call_async(sws->ce->curl, pool->rpc_url, pool->rpc_userpass, sws->s, false, pool, true, sws);
  5875. return true;
  5876. }
  5877. static void free_sws(struct submit_work_state *sws)
  5878. {
  5879. free(sws->s);
  5880. free_work(sws->work);
  5881. free(sws);
  5882. }
  5883. static void *submit_work_thread(__maybe_unused void *userdata)
  5884. {
  5885. int wip = 0;
  5886. CURLM *curlm;
  5887. long curlm_timeout_us = -1;
  5888. struct timeval curlm_timer;
  5889. struct submit_work_state *sws, **swsp;
  5890. struct submit_work_state *write_sws = NULL;
  5891. unsigned tsreduce = 0;
  5892. pthread_detach(pthread_self());
  5893. RenameThread("submit_work");
  5894. applog(LOG_DEBUG, "Creating extra submit work thread");
  5895. curlm = curl_multi_init();
  5896. curlm_timeout_us = -1;
  5897. curl_multi_setopt(curlm, CURLMOPT_TIMERDATA, &curlm_timeout_us);
  5898. curl_multi_setopt(curlm, CURLMOPT_TIMERFUNCTION, my_curl_timer_set);
  5899. fd_set rfds, wfds, efds;
  5900. int maxfd;
  5901. struct timeval tv_timeout, tv_now;
  5902. int n;
  5903. CURLMsg *cm;
  5904. FD_ZERO(&rfds);
  5905. while (1) {
  5906. mutex_lock(&submitting_lock);
  5907. total_submitting -= tsreduce;
  5908. tsreduce = 0;
  5909. if (FD_ISSET(submit_waiting_notifier[0], &rfds)) {
  5910. notifier_read(submit_waiting_notifier);
  5911. }
  5912. // Receive any new submissions
  5913. while (submit_waiting) {
  5914. struct work *work = submit_waiting;
  5915. DL_DELETE(submit_waiting, work);
  5916. if ( (sws = begin_submission(work)) ) {
  5917. if (sws->ce)
  5918. curl_multi_add_handle(curlm, sws->ce->curl);
  5919. else if (sws->s) {
  5920. sws->next = write_sws;
  5921. write_sws = sws;
  5922. }
  5923. ++wip;
  5924. }
  5925. else {
  5926. --total_submitting;
  5927. free_work(work);
  5928. }
  5929. }
  5930. if (unlikely(shutting_down && !wip))
  5931. break;
  5932. mutex_unlock(&submitting_lock);
  5933. FD_ZERO(&rfds);
  5934. FD_ZERO(&wfds);
  5935. FD_ZERO(&efds);
  5936. tv_timeout.tv_sec = -1;
  5937. // Setup cURL with select
  5938. // Need to call perform to ensure the timeout gets updated
  5939. curl_multi_perform(curlm, &n);
  5940. curl_multi_fdset(curlm, &rfds, &wfds, &efds, &maxfd);
  5941. if (curlm_timeout_us >= 0)
  5942. {
  5943. timer_set_delay_from_now(&curlm_timer, curlm_timeout_us);
  5944. reduce_timeout_to(&tv_timeout, &curlm_timer);
  5945. }
  5946. // Setup waiting stratum submissions with select
  5947. for (sws = write_sws; sws; sws = sws->next)
  5948. {
  5949. struct pool *pool = sws->work->pool;
  5950. int fd = pool->sock;
  5951. if (fd == INVSOCK || (!pool->stratum_init) || !pool->stratum_notify)
  5952. continue;
  5953. FD_SET(fd, &wfds);
  5954. set_maxfd(&maxfd, fd);
  5955. }
  5956. // Setup "submit waiting" notifier with select
  5957. FD_SET(submit_waiting_notifier[0], &rfds);
  5958. set_maxfd(&maxfd, submit_waiting_notifier[0]);
  5959. // Wait for something interesting to happen :)
  5960. cgtime(&tv_now);
  5961. if (select(maxfd+1, &rfds, &wfds, &efds, select_timeout(&tv_timeout, &tv_now)) < 0) {
  5962. FD_ZERO(&rfds);
  5963. continue;
  5964. }
  5965. // Handle any stratum ready-to-write results
  5966. for (swsp = &write_sws; (sws = *swsp); ) {
  5967. struct work *work = sws->work;
  5968. struct pool *pool = work->pool;
  5969. int fd = pool->sock;
  5970. bool sessionid_match;
  5971. if (fd == INVSOCK || (!pool->stratum_init) || (!pool->stratum_notify) || !FD_ISSET(fd, &wfds)) {
  5972. next_write_sws:
  5973. // TODO: Check if stale, possibly discard etc
  5974. swsp = &sws->next;
  5975. continue;
  5976. }
  5977. cg_rlock(&pool->data_lock);
  5978. // 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
  5979. // NOTE: Worst case scenario for a false positive: the pool rejects it as H-not-zero
  5980. sessionid_match = (!pool->swork.nonce1) || !strcmp(work->nonce1, pool->swork.nonce1);
  5981. cg_runlock(&pool->data_lock);
  5982. if (!sessionid_match)
  5983. {
  5984. applog(LOG_DEBUG, "No matching session id for resubmitting stratum share");
  5985. submit_discard_share2("disconnect", work);
  5986. ++tsreduce;
  5987. next_write_sws_del:
  5988. // Clear the fd from wfds, to avoid potentially blocking on other submissions to the same socket
  5989. FD_CLR(fd, &wfds);
  5990. // Delete sws for this submission, since we're done with it
  5991. *swsp = sws->next;
  5992. free_sws(sws);
  5993. --wip;
  5994. continue;
  5995. }
  5996. char *s = sws->s;
  5997. struct stratum_share *sshare = calloc(sizeof(struct stratum_share), 1);
  5998. int sshare_id;
  5999. uint32_t nonce;
  6000. char nonce2hex[(bytes_len(&work->nonce2) * 2) + 1];
  6001. char noncehex[9];
  6002. char ntimehex[9];
  6003. sshare->work = copy_work(work);
  6004. bin2hex(nonce2hex, bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  6005. nonce = *((uint32_t *)(work->data + 76));
  6006. bin2hex(noncehex, (const unsigned char *)&nonce, 4);
  6007. bin2hex(ntimehex, (void *)&work->data[68], 4);
  6008. mutex_lock(&sshare_lock);
  6009. /* Give the stratum share a unique id */
  6010. sshare_id =
  6011. sshare->id = swork_id++;
  6012. HASH_ADD_INT(stratum_shares, id, sshare);
  6013. snprintf(s, 1024, "{\"params\": [\"%s\", \"%s\", \"%s\", \"%s\", \"%s\"], \"id\": %d, \"method\": \"mining.submit\"}",
  6014. pool->rpc_user, work->job_id, nonce2hex, ntimehex, noncehex, sshare->id);
  6015. mutex_unlock(&sshare_lock);
  6016. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->stratum_url, s);
  6017. if (likely(stratum_send(pool, s, strlen(s)))) {
  6018. if (pool_tclear(pool, &pool->submit_fail))
  6019. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  6020. applog(LOG_DEBUG, "Successfully submitted, adding to stratum_shares db");
  6021. goto next_write_sws_del;
  6022. } else if (!pool_tset(pool, &pool->submit_fail)) {
  6023. // Undo stuff
  6024. mutex_lock(&sshare_lock);
  6025. // NOTE: Need to find it again in case something else has consumed it already (like the stratum-disconnect resubmitter...)
  6026. HASH_FIND_INT(stratum_shares, &sshare_id, sshare);
  6027. if (sshare)
  6028. HASH_DEL(stratum_shares, sshare);
  6029. mutex_unlock(&sshare_lock);
  6030. if (sshare)
  6031. {
  6032. free_work(sshare->work);
  6033. free(sshare);
  6034. }
  6035. applog(LOG_WARNING, "Pool %d stratum share submission failure", pool->pool_no);
  6036. total_ro++;
  6037. pool->remotefail_occasions++;
  6038. if (!sshare)
  6039. goto next_write_sws_del;
  6040. goto next_write_sws;
  6041. }
  6042. }
  6043. // Handle any cURL activities
  6044. curl_multi_perform(curlm, &n);
  6045. while( (cm = curl_multi_info_read(curlm, &n)) ) {
  6046. if (cm->msg == CURLMSG_DONE)
  6047. {
  6048. bool finished;
  6049. json_t *val = json_rpc_call_completed(cm->easy_handle, cm->data.result, false, NULL, &sws);
  6050. curl_multi_remove_handle(curlm, cm->easy_handle);
  6051. finished = submit_upstream_work_completed(sws->work, sws->resubmit, &sws->tv_submit, val);
  6052. if (!finished) {
  6053. if (retry_submission(sws))
  6054. curl_multi_add_handle(curlm, sws->ce->curl);
  6055. else
  6056. finished = true;
  6057. }
  6058. if (finished) {
  6059. --wip;
  6060. ++tsreduce;
  6061. struct pool *pool = sws->work->pool;
  6062. if (pool->sws_waiting_on_curl) {
  6063. pool->sws_waiting_on_curl->ce = sws->ce;
  6064. sws_has_ce(pool->sws_waiting_on_curl);
  6065. pool->sws_waiting_on_curl = pool->sws_waiting_on_curl->next;
  6066. curl_multi_add_handle(curlm, sws->ce->curl);
  6067. } else {
  6068. push_curl_entry(sws->ce, sws->work->pool);
  6069. }
  6070. free_sws(sws);
  6071. }
  6072. }
  6073. }
  6074. }
  6075. assert(!write_sws);
  6076. mutex_unlock(&submitting_lock);
  6077. curl_multi_cleanup(curlm);
  6078. applog(LOG_DEBUG, "submit_work thread exiting");
  6079. return NULL;
  6080. }
  6081. /* Find the pool that currently has the highest priority */
  6082. static struct pool *priority_pool(int choice)
  6083. {
  6084. struct pool *ret = NULL;
  6085. int i;
  6086. for (i = 0; i < total_pools; i++) {
  6087. struct pool *pool = pools[i];
  6088. if (pool->prio == choice) {
  6089. ret = pool;
  6090. break;
  6091. }
  6092. }
  6093. if (unlikely(!ret)) {
  6094. applog(LOG_ERR, "WTF No pool %d found!", choice);
  6095. return pools[choice];
  6096. }
  6097. return ret;
  6098. }
  6099. int prioritize_pools(char *param, int *pid)
  6100. {
  6101. char *ptr, *next;
  6102. int i, pr, prio = 0;
  6103. if (total_pools == 0) {
  6104. return MSG_NOPOOL;
  6105. }
  6106. if (param == NULL || *param == '\0') {
  6107. return MSG_MISPID;
  6108. }
  6109. bool pools_changed[total_pools];
  6110. int new_prio[total_pools];
  6111. for (i = 0; i < total_pools; ++i)
  6112. pools_changed[i] = false;
  6113. next = param;
  6114. while (next && *next) {
  6115. ptr = next;
  6116. next = strchr(ptr, ',');
  6117. if (next)
  6118. *(next++) = '\0';
  6119. i = atoi(ptr);
  6120. if (i < 0 || i >= total_pools) {
  6121. *pid = i;
  6122. return MSG_INVPID;
  6123. }
  6124. if (pools_changed[i]) {
  6125. *pid = i;
  6126. return MSG_DUPPID;
  6127. }
  6128. pools_changed[i] = true;
  6129. new_prio[i] = prio++;
  6130. }
  6131. // Only change them if no errors
  6132. for (i = 0; i < total_pools; i++) {
  6133. if (pools_changed[i])
  6134. pools[i]->prio = new_prio[i];
  6135. }
  6136. // In priority order, cycle through the unchanged pools and append them
  6137. for (pr = 0; pr < total_pools; pr++)
  6138. for (i = 0; i < total_pools; i++) {
  6139. if (!pools_changed[i] && pools[i]->prio == pr) {
  6140. pools[i]->prio = prio++;
  6141. pools_changed[i] = true;
  6142. break;
  6143. }
  6144. }
  6145. if (current_pool()->prio)
  6146. switch_pools(NULL);
  6147. return MSG_POOLPRIO;
  6148. }
  6149. void validate_pool_priorities(void)
  6150. {
  6151. // TODO: this should probably do some sort of logging
  6152. int i, j;
  6153. bool used[total_pools];
  6154. bool valid[total_pools];
  6155. for (i = 0; i < total_pools; i++)
  6156. used[i] = valid[i] = false;
  6157. for (i = 0; i < total_pools; i++) {
  6158. if (pools[i]->prio >=0 && pools[i]->prio < total_pools) {
  6159. if (!used[pools[i]->prio]) {
  6160. valid[i] = true;
  6161. used[pools[i]->prio] = true;
  6162. }
  6163. }
  6164. }
  6165. for (i = 0; i < total_pools; i++) {
  6166. if (!valid[i]) {
  6167. for (j = 0; j < total_pools; j++) {
  6168. if (!used[j]) {
  6169. applog(LOG_WARNING, "Pool %d priority changed from %d to %d", i, pools[i]->prio, j);
  6170. pools[i]->prio = j;
  6171. used[j] = true;
  6172. break;
  6173. }
  6174. }
  6175. }
  6176. }
  6177. }
  6178. static void clear_pool_work(struct pool *pool);
  6179. /* Specifies whether we can switch to this pool or not. */
  6180. static bool pool_unusable(struct pool *pool)
  6181. {
  6182. if (pool->idle)
  6183. return true;
  6184. if (pool->enabled != POOL_ENABLED)
  6185. return true;
  6186. return false;
  6187. }
  6188. void switch_pools(struct pool *selected)
  6189. {
  6190. struct pool *pool, *last_pool, *failover_pool = NULL;
  6191. int i, pool_no, next_pool;
  6192. if (selected)
  6193. enable_pool(selected);
  6194. cg_wlock(&control_lock);
  6195. last_pool = currentpool;
  6196. pool_no = currentpool->pool_no;
  6197. /* Switch selected to pool number 0 and move the rest down */
  6198. if (selected) {
  6199. if (selected->prio != 0) {
  6200. for (i = 0; i < total_pools; i++) {
  6201. pool = pools[i];
  6202. if (pool->prio < selected->prio)
  6203. pool->prio++;
  6204. }
  6205. selected->prio = 0;
  6206. }
  6207. }
  6208. switch (pool_strategy) {
  6209. /* All of these set to the master pool */
  6210. case POOL_BALANCE:
  6211. case POOL_FAILOVER:
  6212. case POOL_LOADBALANCE:
  6213. for (i = 0; i < total_pools; i++) {
  6214. pool = priority_pool(i);
  6215. if (pool_unusable(pool))
  6216. continue;
  6217. pool_no = pool->pool_no;
  6218. break;
  6219. }
  6220. break;
  6221. /* Both of these simply increment and cycle */
  6222. case POOL_ROUNDROBIN:
  6223. case POOL_ROTATE:
  6224. if (selected && !selected->idle) {
  6225. pool_no = selected->pool_no;
  6226. break;
  6227. }
  6228. next_pool = pool_no;
  6229. /* Select the next alive pool */
  6230. for (i = 1; i < total_pools; i++) {
  6231. next_pool++;
  6232. if (next_pool >= total_pools)
  6233. next_pool = 0;
  6234. pool = pools[next_pool];
  6235. if (pool_unusable(pool))
  6236. continue;
  6237. if (pool->failover_only)
  6238. {
  6239. BFGINIT(failover_pool, pool);
  6240. continue;
  6241. }
  6242. pool_no = next_pool;
  6243. break;
  6244. }
  6245. break;
  6246. default:
  6247. break;
  6248. }
  6249. pool = pools[pool_no];
  6250. if (pool_unusable(pool) && failover_pool)
  6251. pool = failover_pool;
  6252. currentpool = pool;
  6253. cg_wunlock(&control_lock);
  6254. mutex_lock(&lp_lock);
  6255. pthread_cond_broadcast(&lp_cond);
  6256. mutex_unlock(&lp_lock);
  6257. /* Set the lagging flag to avoid pool not providing work fast enough
  6258. * messages in failover only mode since we have to get all fresh work
  6259. * as in restart_threads */
  6260. if (opt_fail_only)
  6261. pool_tset(pool, &pool->lagging);
  6262. if (pool != last_pool)
  6263. {
  6264. pool->block_id = 0;
  6265. if (pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  6266. applog(LOG_WARNING, "Switching to pool %d %s", pool->pool_no, pool->rpc_url);
  6267. if (pool_localgen(pool) || opt_fail_only)
  6268. clear_pool_work(last_pool);
  6269. }
  6270. }
  6271. mutex_lock(&lp_lock);
  6272. pthread_cond_broadcast(&lp_cond);
  6273. mutex_unlock(&lp_lock);
  6274. #ifdef HAVE_CURSES
  6275. update_block_display();
  6276. #endif
  6277. }
  6278. static void discard_work(struct work *work)
  6279. {
  6280. if (!work->clone && !work->rolls && !work->mined) {
  6281. if (work->pool) {
  6282. work->pool->discarded_work++;
  6283. work->pool->quota_used--;
  6284. work->pool->works--;
  6285. }
  6286. total_discarded++;
  6287. applog(LOG_DEBUG, "Discarded work");
  6288. } else
  6289. applog(LOG_DEBUG, "Discarded cloned or rolled work");
  6290. free_work(work);
  6291. }
  6292. static bool work_rollable(struct work *);
  6293. static
  6294. void unstage_work(struct work * const work)
  6295. {
  6296. HASH_DEL(staged_work, work);
  6297. --work_mining_algorithm(work)->staged;
  6298. if (work_rollable(work))
  6299. --staged_rollable;
  6300. staged_full = false;
  6301. }
  6302. static void wake_gws(void)
  6303. {
  6304. mutex_lock(stgd_lock);
  6305. pthread_cond_signal(&gws_cond);
  6306. mutex_unlock(stgd_lock);
  6307. }
  6308. static void discard_stale(void)
  6309. {
  6310. struct work *work, *tmp;
  6311. int stale = 0;
  6312. mutex_lock(stgd_lock);
  6313. HASH_ITER(hh, staged_work, work, tmp) {
  6314. if (stale_work(work, false)) {
  6315. unstage_work(work);
  6316. discard_work(work);
  6317. stale++;
  6318. }
  6319. }
  6320. pthread_cond_signal(&gws_cond);
  6321. mutex_unlock(stgd_lock);
  6322. if (stale)
  6323. applog(LOG_DEBUG, "Discarded %d stales that didn't match current hash", stale);
  6324. }
  6325. bool stale_work_future(struct work *work, bool share, unsigned long ustime)
  6326. {
  6327. bool rv;
  6328. struct timeval tv, orig;
  6329. ldiv_t d;
  6330. d = ldiv(ustime, 1000000);
  6331. tv = (struct timeval){
  6332. .tv_sec = d.quot,
  6333. .tv_usec = d.rem,
  6334. };
  6335. orig = work->tv_staged;
  6336. timersub(&orig, &tv, &work->tv_staged);
  6337. rv = stale_work(work, share);
  6338. work->tv_staged = orig;
  6339. return rv;
  6340. }
  6341. static
  6342. void pool_update_work_restart_time(struct pool * const pool)
  6343. {
  6344. pool->work_restart_time = time(NULL);
  6345. get_timestamp(pool->work_restart_timestamp, sizeof(pool->work_restart_timestamp), pool->work_restart_time);
  6346. }
  6347. static void restart_threads(void)
  6348. {
  6349. struct pool *cp = current_pool();
  6350. int i;
  6351. struct thr_info *thr;
  6352. /* Artificially set the lagging flag to avoid pool not providing work
  6353. * fast enough messages after every long poll */
  6354. pool_tset(cp, &cp->lagging);
  6355. /* Discard staged work that is now stale */
  6356. discard_stale();
  6357. rd_lock(&mining_thr_lock);
  6358. for (i = 0; i < mining_threads; i++)
  6359. {
  6360. thr = mining_thr[i];
  6361. thr->work_restart = true;
  6362. }
  6363. for (i = 0; i < mining_threads; i++)
  6364. {
  6365. thr = mining_thr[i];
  6366. notifier_wake(thr->work_restart_notifier);
  6367. }
  6368. rd_unlock(&mining_thr_lock);
  6369. }
  6370. void blkhashstr(char *rv, const unsigned char *hash)
  6371. {
  6372. unsigned char hash_swap[32];
  6373. swap256(hash_swap, hash);
  6374. swap32tole(hash_swap, hash_swap, 32 / 4);
  6375. bin2hex(rv, hash_swap, 32);
  6376. }
  6377. static
  6378. void set_curblock(struct mining_goal_info * const goal, struct block_info * const blkinfo)
  6379. {
  6380. struct blockchain_info * const blkchain = goal->blkchain;
  6381. blkchain->currentblk = blkinfo;
  6382. blkchain->currentblk_subsidy = 5000000000LL >> (blkinfo->height / 210000);
  6383. cg_wlock(&ch_lock);
  6384. __update_block_title(goal);
  6385. get_timestamp(blkchain->currentblk_first_seen_time_str, sizeof(blkchain->currentblk_first_seen_time_str), blkinfo->first_seen_time);
  6386. cg_wunlock(&ch_lock);
  6387. applog(LOG_INFO, "New block: %s diff %s (%s)", goal->current_goal_detail, goal->current_diff_str, goal->net_hashrate);
  6388. }
  6389. /* Search to see if this prevblkhash has been seen before */
  6390. static
  6391. struct block_info *block_exists(const struct blockchain_info * const blkchain, const void * const prevblkhash)
  6392. {
  6393. struct block_info *s;
  6394. rd_lock(&blk_lock);
  6395. HASH_FIND(hh, blkchain->blocks, prevblkhash, 0x20, s);
  6396. rd_unlock(&blk_lock);
  6397. return s;
  6398. }
  6399. static int block_sort(struct block_info * const blocka, struct block_info * const blockb)
  6400. {
  6401. return blocka->block_seen_order - blockb->block_seen_order;
  6402. }
  6403. static
  6404. void set_blockdiff(struct mining_goal_info * const goal, const struct work * const work)
  6405. {
  6406. unsigned char target[32];
  6407. double diff;
  6408. uint64_t diff64;
  6409. real_block_target(target, work->data);
  6410. diff = target_diff(target);
  6411. diff64 = diff;
  6412. suffix_string(diff64, goal->current_diff_str, sizeof(goal->current_diff_str), 0);
  6413. format_unit2(goal->net_hashrate, sizeof(goal->net_hashrate),
  6414. true, "h/s", H2B_SHORT, diff * 7158278, -1);
  6415. if (unlikely(goal->current_diff != diff))
  6416. applog(LOG_NOTICE, "Network difficulty changed to %s (%s)", goal->current_diff_str, goal->net_hashrate);
  6417. goal->current_diff = diff;
  6418. }
  6419. static bool test_work_current(struct work *work)
  6420. {
  6421. bool ret = true;
  6422. if (work->mandatory)
  6423. return ret;
  6424. uint32_t block_id = ((uint32_t*)(work->data))[1];
  6425. const uint8_t * const prevblkhash = &work->data[4];
  6426. {
  6427. /* Hack to work around dud work sneaking into test */
  6428. bool dudwork = true;
  6429. for (int i = 8; i < 26; ++i)
  6430. if (work->data[i])
  6431. {
  6432. dudwork = false;
  6433. break;
  6434. }
  6435. if (dudwork)
  6436. goto out_free;
  6437. }
  6438. struct pool * const pool = work->pool;
  6439. struct mining_goal_info * const goal = pool->goal;
  6440. struct blockchain_info * const blkchain = goal->blkchain;
  6441. /* Search to see if this block exists yet and if not, consider it a
  6442. * new block and set the current block details to this one */
  6443. if (!block_exists(blkchain, prevblkhash))
  6444. {
  6445. struct block_info * const s = calloc(sizeof(struct block_info), 1);
  6446. int deleted_block = 0;
  6447. ret = false;
  6448. if (unlikely(!s))
  6449. quit (1, "test_work_current OOM");
  6450. memcpy(s->prevblkhash, prevblkhash, sizeof(s->prevblkhash));
  6451. s->block_id = block_id;
  6452. s->block_seen_order = new_blocks++;
  6453. s->first_seen_time = time(NULL);
  6454. wr_lock(&blk_lock);
  6455. /* Only keep the last hour's worth of blocks in memory since
  6456. * work from blocks before this is virtually impossible and we
  6457. * want to prevent memory usage from continually rising */
  6458. if (HASH_COUNT(blkchain->blocks) > 6)
  6459. {
  6460. struct block_info *oldblock;
  6461. HASH_SORT(blkchain->blocks, block_sort);
  6462. oldblock = blkchain->blocks;
  6463. deleted_block = oldblock->block_seen_order;
  6464. HASH_DEL(blkchain->blocks, oldblock);
  6465. free(oldblock);
  6466. }
  6467. HASH_ADD(hh, blkchain->blocks, prevblkhash, sizeof(s->prevblkhash), s);
  6468. set_blockdiff(goal, work);
  6469. wr_unlock(&blk_lock);
  6470. pool->block_id = block_id;
  6471. pool_update_work_restart_time(pool);
  6472. if (deleted_block)
  6473. applog(LOG_DEBUG, "Deleted block %d from database", deleted_block);
  6474. #if BLKMAKER_VERSION > 1
  6475. template_nonce = 0;
  6476. #endif
  6477. set_curblock(goal, s);
  6478. if (unlikely(new_blocks == 1))
  6479. goto out_free;
  6480. if (!work->stratum)
  6481. {
  6482. if (work->longpoll)
  6483. {
  6484. applog(LOG_NOTICE, "Longpoll from pool %d detected new block",
  6485. pool->pool_no);
  6486. }
  6487. else
  6488. if (goal->have_longpoll)
  6489. applog(LOG_NOTICE, "New block detected on network before longpoll");
  6490. else
  6491. applog(LOG_NOTICE, "New block detected on network");
  6492. }
  6493. restart_threads();
  6494. }
  6495. else
  6496. {
  6497. bool restart = false;
  6498. if (unlikely(pool->block_id != block_id))
  6499. {
  6500. bool was_active = pool->block_id != 0;
  6501. pool->block_id = block_id;
  6502. pool_update_work_restart_time(pool);
  6503. if (!work->longpoll)
  6504. update_last_work(work);
  6505. if (was_active)
  6506. {
  6507. // Pool actively changed block
  6508. if (pool == current_pool())
  6509. restart = true;
  6510. if (block_id == blkchain->currentblk->block_id)
  6511. {
  6512. // Caught up, only announce if this pool is the one in use
  6513. if (restart)
  6514. applog(LOG_NOTICE, "%s %d caught up to new block",
  6515. work->longpoll ? "Longpoll from pool" : "Pool",
  6516. pool->pool_no);
  6517. }
  6518. else
  6519. {
  6520. // Switched to a block we know, but not the latest... why?
  6521. // This might detect pools trying to double-spend or 51%,
  6522. // but let's not make any accusations until it's had time
  6523. // in the real world.
  6524. char hexstr[65];
  6525. blkhashstr(hexstr, prevblkhash);
  6526. applog(LOG_WARNING, "%s %d is issuing work for an old block: %s",
  6527. work->longpoll ? "Longpoll from pool" : "Pool",
  6528. pool->pool_no,
  6529. hexstr);
  6530. }
  6531. }
  6532. }
  6533. if (work->longpoll)
  6534. {
  6535. struct pool * const cp = current_pool();
  6536. ++pool->work_restart_id;
  6537. if (work->tr && work->tr == pool->swork.tr)
  6538. pool->swork.work_restart_id = pool->work_restart_id;
  6539. update_last_work(work);
  6540. pool_update_work_restart_time(pool);
  6541. applog(
  6542. ((!opt_quiet_work_updates) && pool_actively_in_use(pool, cp) ? LOG_NOTICE : LOG_DEBUG),
  6543. "Longpoll from pool %d requested work update",
  6544. pool->pool_no);
  6545. if ((!restart) && pool == cp)
  6546. restart = true;
  6547. }
  6548. if (restart)
  6549. restart_threads();
  6550. }
  6551. work->longpoll = false;
  6552. out_free:
  6553. return ret;
  6554. }
  6555. static int tv_sort(struct work *worka, struct work *workb)
  6556. {
  6557. return worka->tv_staged.tv_sec - workb->tv_staged.tv_sec;
  6558. }
  6559. static bool work_rollable(struct work *work)
  6560. {
  6561. return (!work->clone && work->rolltime);
  6562. }
  6563. static bool hash_push(struct work *work)
  6564. {
  6565. bool rc = true;
  6566. mutex_lock(stgd_lock);
  6567. if (work_rollable(work))
  6568. staged_rollable++;
  6569. ++work_mining_algorithm(work)->staged;
  6570. if (likely(!getq->frozen)) {
  6571. HASH_ADD_INT(staged_work, id, work);
  6572. HASH_SORT(staged_work, tv_sort);
  6573. } else
  6574. rc = false;
  6575. pthread_cond_broadcast(&getq->cond);
  6576. mutex_unlock(stgd_lock);
  6577. return rc;
  6578. }
  6579. static void stage_work(struct work *work)
  6580. {
  6581. applog(LOG_DEBUG, "Pushing work %d from pool %d to hash queue",
  6582. work->id, work->pool->pool_no);
  6583. work->work_restart_id = work->pool->work_restart_id;
  6584. work->pool->last_work_time = time(NULL);
  6585. cgtime(&work->pool->tv_last_work_time);
  6586. test_work_current(work);
  6587. work->pool->works++;
  6588. hash_push(work);
  6589. }
  6590. #ifdef HAVE_CURSES
  6591. int curses_int(const char *query)
  6592. {
  6593. int ret;
  6594. char *cvar;
  6595. cvar = curses_input(query);
  6596. if (unlikely(!cvar))
  6597. return -1;
  6598. ret = atoi(cvar);
  6599. free(cvar);
  6600. return ret;
  6601. }
  6602. #endif
  6603. #ifdef HAVE_CURSES
  6604. static bool input_pool(bool live);
  6605. #endif
  6606. #ifdef HAVE_CURSES
  6607. static void display_pool_summary(struct pool *pool)
  6608. {
  6609. double efficiency = 0.0;
  6610. char xfer[ALLOC_H2B_NOUNIT+ALLOC_H2B_SPACED+4+1], bw[ALLOC_H2B_NOUNIT+ALLOC_H2B_SPACED+6+1];
  6611. int pool_secs;
  6612. if (curses_active_locked()) {
  6613. wlog("Pool: %s Goal: %s\n", pool->rpc_url, pool->goal->name);
  6614. if (pool->solved)
  6615. wlog("SOLVED %d BLOCK%s!\n", pool->solved, pool->solved > 1 ? "S" : "");
  6616. if (!pool->has_stratum)
  6617. wlog("%s own long-poll support\n", pool->lp_url ? "Has" : "Does not have");
  6618. wlog(" Queued work requests: %d\n", pool->getwork_requested);
  6619. wlog(" Share submissions: %d\n", pool->accepted + pool->rejected);
  6620. wlog(" Accepted shares: %d\n", pool->accepted);
  6621. wlog(" Rejected shares: %d + %d stale (%.2f%%)\n",
  6622. pool->rejected, pool->stale_shares,
  6623. (float)(pool->rejected + pool->stale_shares) / (float)(pool->rejected + pool->stale_shares + pool->accepted)
  6624. );
  6625. wlog(" Accepted difficulty shares: %1.f\n", pool->diff_accepted);
  6626. wlog(" Rejected difficulty shares: %1.f\n", pool->diff_rejected);
  6627. pool_secs = timer_elapsed(&pool->cgminer_stats.start_tv, NULL);
  6628. wlog(" Network transfer: %s (%s)\n",
  6629. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  6630. (float)pool->cgminer_pool_stats.net_bytes_received,
  6631. (float)pool->cgminer_pool_stats.net_bytes_sent),
  6632. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  6633. (float)(pool->cgminer_pool_stats.net_bytes_received / pool_secs),
  6634. (float)(pool->cgminer_pool_stats.net_bytes_sent / pool_secs)));
  6635. uint64_t pool_bytes_xfer = pool->cgminer_pool_stats.net_bytes_received + pool->cgminer_pool_stats.net_bytes_sent;
  6636. efficiency = pool_bytes_xfer ? pool->diff_accepted * 2048. / pool_bytes_xfer : 0.0;
  6637. wlog(" Efficiency (accepted * difficulty / 2 KB): %.2f\n", efficiency);
  6638. wlog(" Items worked on: %d\n", pool->works);
  6639. wlog(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  6640. wlog(" Unable to get work from server occasions: %d\n", pool->getfail_occasions);
  6641. wlog(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  6642. unlock_curses();
  6643. }
  6644. }
  6645. #endif
  6646. /* We can't remove the memory used for this struct pool because there may
  6647. * still be work referencing it. We just remove it from the pools list */
  6648. void remove_pool(struct pool *pool)
  6649. {
  6650. int i, last_pool = total_pools - 1;
  6651. struct pool *other;
  6652. disable_pool(pool, POOL_DISABLED);
  6653. /* Boost priority of any lower prio than this one */
  6654. for (i = 0; i < total_pools; i++) {
  6655. other = pools[i];
  6656. if (other->prio > pool->prio)
  6657. other->prio--;
  6658. }
  6659. if (pool->pool_no < last_pool) {
  6660. /* Swap the last pool for this one */
  6661. (pools[last_pool])->pool_no = pool->pool_no;
  6662. pools[pool->pool_no] = pools[last_pool];
  6663. }
  6664. /* Give it an invalid number */
  6665. pool->pool_no = total_pools;
  6666. pool->removed = true;
  6667. pool->has_stratum = false;
  6668. total_pools--;
  6669. }
  6670. /* add a mutex if this needs to be thread safe in the future */
  6671. static struct JE {
  6672. char *buf;
  6673. struct JE *next;
  6674. } *jedata = NULL;
  6675. static void json_escape_free()
  6676. {
  6677. struct JE *jeptr = jedata;
  6678. struct JE *jenext;
  6679. jedata = NULL;
  6680. while (jeptr) {
  6681. jenext = jeptr->next;
  6682. free(jeptr->buf);
  6683. free(jeptr);
  6684. jeptr = jenext;
  6685. }
  6686. }
  6687. static
  6688. char *json_escape(const char *str)
  6689. {
  6690. struct JE *jeptr;
  6691. char *buf, *ptr;
  6692. /* 2x is the max, may as well just allocate that */
  6693. ptr = buf = malloc(strlen(str) * 2 + 1);
  6694. jeptr = malloc(sizeof(*jeptr));
  6695. jeptr->buf = buf;
  6696. jeptr->next = jedata;
  6697. jedata = jeptr;
  6698. while (*str) {
  6699. if (*str == '\\' || *str == '"')
  6700. *(ptr++) = '\\';
  6701. *(ptr++) = *(str++);
  6702. }
  6703. *ptr = '\0';
  6704. return buf;
  6705. }
  6706. static
  6707. void _write_config_string_elist(FILE *fcfg, const char *configname, struct string_elist * const elist)
  6708. {
  6709. if (!elist)
  6710. return;
  6711. static struct string_elist *entry;
  6712. fprintf(fcfg, ",\n\"%s\" : [", configname);
  6713. bool first = true;
  6714. DL_FOREACH(elist, entry)
  6715. {
  6716. const char * const s = entry->string;
  6717. fprintf(fcfg, "%s\n\t\"%s\"", first ? "" : ",", json_escape(s));
  6718. first = false;
  6719. }
  6720. fprintf(fcfg, "\n]");
  6721. }
  6722. void write_config(FILE *fcfg)
  6723. {
  6724. int i;
  6725. /* Write pool values */
  6726. fputs("{\n\"pools\" : [", fcfg);
  6727. for(i = 0; i < total_pools; i++) {
  6728. struct pool *pool = pools[i];
  6729. if (pool->failover_only)
  6730. // Don't write failover-only (automatically added) pools to the config file for now
  6731. continue;
  6732. if (pool->quota != 1) {
  6733. fprintf(fcfg, "%s\n\t{\n\t\t\"quota\" : \"%d;%s\",", i > 0 ? "," : "",
  6734. pool->quota,
  6735. json_escape(pool->rpc_url));
  6736. } else {
  6737. fprintf(fcfg, "%s\n\t{\n\t\t\"url\" : \"%s\",", i > 0 ? "," : "",
  6738. json_escape(pool->rpc_url));
  6739. }
  6740. if (pool->rpc_proxy)
  6741. fprintf(fcfg, "\n\t\t\"pool-proxy\" : \"%s\",", json_escape(pool->rpc_proxy));
  6742. fprintf(fcfg, "\n\t\t\"user\" : \"%s\",", json_escape(pool->rpc_user));
  6743. fprintf(fcfg, "\n\t\t\"pass\" : \"%s\",", json_escape(pool->rpc_pass));
  6744. fprintf(fcfg, "\n\t\t\"pool-priority\" : \"%d\"", pool->prio);
  6745. if (pool->force_rollntime)
  6746. fprintf(fcfg, ",\n\t\t\"force-rollntime\" : %d", pool->force_rollntime);
  6747. fprintf(fcfg, "\n\t}");
  6748. }
  6749. fputs("\n]\n", fcfg);
  6750. #ifdef HAVE_OPENCL
  6751. write_config_opencl(fcfg);
  6752. #endif
  6753. #ifdef WANT_CPUMINE
  6754. fprintf(fcfg, ",\n\"algo\" : \"%s\"", algo_names[opt_algo]);
  6755. #endif
  6756. /* Simple bool and int options */
  6757. struct opt_table *opt;
  6758. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  6759. char *p, *name = strdup(opt->names);
  6760. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  6761. if (p[1] != '-')
  6762. continue;
  6763. if (opt->type & OPT_NOARG &&
  6764. ((void *)opt->cb == (void *)opt_set_bool || (void *)opt->cb == (void *)opt_set_invbool) &&
  6765. (*(bool *)opt->u.arg == ((void *)opt->cb == (void *)opt_set_bool)))
  6766. fprintf(fcfg, ",\n\"%s\" : true", p+2);
  6767. if (opt->type & OPT_HASARG &&
  6768. ((void *)opt->cb_arg == (void *)set_int_0_to_9999 ||
  6769. (void *)opt->cb_arg == (void *)set_int_1_to_65535 ||
  6770. (void *)opt->cb_arg == (void *)set_int_0_to_10 ||
  6771. (void *)opt->cb_arg == (void *)set_int_1_to_10) &&
  6772. opt->desc != opt_hidden &&
  6773. 0 <= *(int *)opt->u.arg)
  6774. fprintf(fcfg, ",\n\"%s\" : \"%d\"", p+2, *(int *)opt->u.arg);
  6775. }
  6776. }
  6777. /* Special case options */
  6778. if (request_target_str)
  6779. {
  6780. if (request_pdiff == (long)request_pdiff)
  6781. fprintf(fcfg, ",\n\"request-diff\" : %ld", (long)request_pdiff);
  6782. else
  6783. fprintf(fcfg, ",\n\"request-diff\" : %f", request_pdiff);
  6784. }
  6785. fprintf(fcfg, ",\n\"shares\" : %g", opt_shares);
  6786. if (pool_strategy == POOL_BALANCE)
  6787. fputs(",\n\"balance\" : true", fcfg);
  6788. if (pool_strategy == POOL_LOADBALANCE)
  6789. fputs(",\n\"load-balance\" : true", fcfg);
  6790. if (pool_strategy == POOL_ROUNDROBIN)
  6791. fputs(",\n\"round-robin\" : true", fcfg);
  6792. if (pool_strategy == POOL_ROTATE)
  6793. fprintf(fcfg, ",\n\"rotate\" : \"%d\"", opt_rotate_period);
  6794. #if defined(unix) || defined(__APPLE__)
  6795. if (opt_stderr_cmd && *opt_stderr_cmd)
  6796. fprintf(fcfg, ",\n\"monitor\" : \"%s\"", json_escape(opt_stderr_cmd));
  6797. #endif // defined(unix)
  6798. if (opt_kernel_path && *opt_kernel_path) {
  6799. char *kpath = strdup(opt_kernel_path);
  6800. if (kpath[strlen(kpath)-1] == '/')
  6801. kpath[strlen(kpath)-1] = 0;
  6802. fprintf(fcfg, ",\n\"kernel-path\" : \"%s\"", json_escape(kpath));
  6803. free(kpath);
  6804. }
  6805. if (schedstart.enable)
  6806. fprintf(fcfg, ",\n\"sched-time\" : \"%d:%d\"", schedstart.tm.tm_hour, schedstart.tm.tm_min);
  6807. if (schedstop.enable)
  6808. fprintf(fcfg, ",\n\"stop-time\" : \"%d:%d\"", schedstop.tm.tm_hour, schedstop.tm.tm_min);
  6809. if (opt_socks_proxy && *opt_socks_proxy)
  6810. fprintf(fcfg, ",\n\"socks-proxy\" : \"%s\"", json_escape(opt_socks_proxy));
  6811. _write_config_string_elist(fcfg, "scan", scan_devices);
  6812. #ifdef USE_LIBMICROHTTPD
  6813. if (httpsrv_port != -1)
  6814. fprintf(fcfg, ",\n\"http-port\" : %d", httpsrv_port);
  6815. #endif
  6816. #ifdef USE_LIBEVENT
  6817. if (stratumsrv_port != -1)
  6818. fprintf(fcfg, ",\n\"stratum-port\" : %d", stratumsrv_port);
  6819. #endif
  6820. _write_config_string_elist(fcfg, "device", opt_devices_enabled_list);
  6821. _write_config_string_elist(fcfg, "set-device", opt_set_device_list);
  6822. if (opt_api_allow)
  6823. fprintf(fcfg, ",\n\"api-allow\" : \"%s\"", json_escape(opt_api_allow));
  6824. if (strcmp(opt_api_mcast_addr, API_MCAST_ADDR) != 0)
  6825. fprintf(fcfg, ",\n\"api-mcast-addr\" : \"%s\"", json_escape(opt_api_mcast_addr));
  6826. if (strcmp(opt_api_mcast_code, API_MCAST_CODE) != 0)
  6827. fprintf(fcfg, ",\n\"api-mcast-code\" : \"%s\"", json_escape(opt_api_mcast_code));
  6828. if (*opt_api_mcast_des)
  6829. fprintf(fcfg, ",\n\"api-mcast-des\" : \"%s\"", json_escape(opt_api_mcast_des));
  6830. if (strcmp(opt_api_description, PACKAGE_STRING) != 0)
  6831. fprintf(fcfg, ",\n\"api-description\" : \"%s\"", json_escape(opt_api_description));
  6832. if (opt_api_groups)
  6833. fprintf(fcfg, ",\n\"api-groups\" : \"%s\"", json_escape(opt_api_groups));
  6834. fputs("\n}\n", fcfg);
  6835. json_escape_free();
  6836. }
  6837. void zero_bestshare(void)
  6838. {
  6839. int i;
  6840. best_diff = 0;
  6841. suffix_string(best_diff, best_share, sizeof(best_share), 0);
  6842. for (i = 0; i < total_pools; i++) {
  6843. struct pool *pool = pools[i];
  6844. pool->best_diff = 0;
  6845. }
  6846. }
  6847. void zero_stats(void)
  6848. {
  6849. int i;
  6850. applog(LOG_DEBUG, "Zeroing stats");
  6851. cgtime(&total_tv_start);
  6852. miner_started = total_tv_start;
  6853. total_rolling = 0;
  6854. total_mhashes_done = 0;
  6855. total_getworks = 0;
  6856. total_accepted = 0;
  6857. total_rejected = 0;
  6858. hw_errors = 0;
  6859. total_stale = 0;
  6860. total_discarded = 0;
  6861. total_bytes_rcvd = total_bytes_sent = 0;
  6862. new_blocks = 0;
  6863. local_work = 0;
  6864. total_go = 0;
  6865. total_ro = 0;
  6866. total_secs = 1.0;
  6867. total_diff1 = 0;
  6868. total_bad_diff1 = 0;
  6869. found_blocks = 0;
  6870. total_diff_accepted = 0;
  6871. total_diff_rejected = 0;
  6872. total_diff_stale = 0;
  6873. #ifdef HAVE_CURSES
  6874. awidth = rwidth = swidth = hwwidth = 1;
  6875. #endif
  6876. struct mining_goal_info *goal, *tmpgoal;
  6877. HASH_ITER(hh, mining_goals, goal, tmpgoal)
  6878. {
  6879. goal->diff_accepted = 0;
  6880. }
  6881. for (i = 0; i < total_pools; i++) {
  6882. struct pool *pool = pools[i];
  6883. pool->getwork_requested = 0;
  6884. pool->accepted = 0;
  6885. pool->rejected = 0;
  6886. pool->solved = 0;
  6887. pool->getwork_requested = 0;
  6888. pool->stale_shares = 0;
  6889. pool->discarded_work = 0;
  6890. pool->getfail_occasions = 0;
  6891. pool->remotefail_occasions = 0;
  6892. pool->last_share_time = 0;
  6893. pool->works = 0;
  6894. pool->diff1 = 0;
  6895. pool->diff_accepted = 0;
  6896. pool->diff_rejected = 0;
  6897. pool->diff_stale = 0;
  6898. pool->last_share_diff = 0;
  6899. pool->cgminer_stats.start_tv = total_tv_start;
  6900. pool->cgminer_stats.getwork_calls = 0;
  6901. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6902. pool->cgminer_stats.getwork_wait_max.tv_sec = 0;
  6903. pool->cgminer_stats.getwork_wait_max.tv_usec = 0;
  6904. pool->cgminer_pool_stats.getwork_calls = 0;
  6905. pool->cgminer_pool_stats.getwork_attempts = 0;
  6906. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6907. pool->cgminer_pool_stats.getwork_wait_max.tv_sec = 0;
  6908. pool->cgminer_pool_stats.getwork_wait_max.tv_usec = 0;
  6909. pool->cgminer_pool_stats.min_diff = 0;
  6910. pool->cgminer_pool_stats.max_diff = 0;
  6911. pool->cgminer_pool_stats.min_diff_count = 0;
  6912. pool->cgminer_pool_stats.max_diff_count = 0;
  6913. pool->cgminer_pool_stats.times_sent = 0;
  6914. pool->cgminer_pool_stats.bytes_sent = 0;
  6915. pool->cgminer_pool_stats.net_bytes_sent = 0;
  6916. pool->cgminer_pool_stats.times_received = 0;
  6917. pool->cgminer_pool_stats.bytes_received = 0;
  6918. pool->cgminer_pool_stats.net_bytes_received = 0;
  6919. }
  6920. zero_bestshare();
  6921. for (i = 0; i < total_devices; ++i) {
  6922. struct cgpu_info *cgpu = get_devices(i);
  6923. mutex_lock(&hash_lock);
  6924. cgpu->total_mhashes = 0;
  6925. cgpu->accepted = 0;
  6926. cgpu->rejected = 0;
  6927. cgpu->stale = 0;
  6928. cgpu->hw_errors = 0;
  6929. cgpu->utility = 0.0;
  6930. cgpu->utility_diff1 = 0;
  6931. cgpu->last_share_pool_time = 0;
  6932. cgpu->bad_diff1 = 0;
  6933. cgpu->diff1 = 0;
  6934. cgpu->diff_accepted = 0;
  6935. cgpu->diff_rejected = 0;
  6936. cgpu->diff_stale = 0;
  6937. cgpu->last_share_diff = 0;
  6938. cgpu->thread_fail_init_count = 0;
  6939. cgpu->thread_zero_hash_count = 0;
  6940. cgpu->thread_fail_queue_count = 0;
  6941. cgpu->dev_sick_idle_60_count = 0;
  6942. cgpu->dev_dead_idle_600_count = 0;
  6943. cgpu->dev_nostart_count = 0;
  6944. cgpu->dev_over_heat_count = 0;
  6945. cgpu->dev_thermal_cutoff_count = 0;
  6946. cgpu->dev_comms_error_count = 0;
  6947. cgpu->dev_throttle_count = 0;
  6948. cgpu->cgminer_stats.start_tv = total_tv_start;
  6949. cgpu->cgminer_stats.getwork_calls = 0;
  6950. cgpu->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6951. cgpu->cgminer_stats.getwork_wait_max.tv_sec = 0;
  6952. cgpu->cgminer_stats.getwork_wait_max.tv_usec = 0;
  6953. mutex_unlock(&hash_lock);
  6954. if (cgpu->drv->zero_stats)
  6955. cgpu->drv->zero_stats(cgpu);
  6956. }
  6957. }
  6958. #ifdef HAVE_CURSES
  6959. static
  6960. void loginput_mode(const int size)
  6961. {
  6962. clear_logwin();
  6963. loginput_size = size;
  6964. check_winsizes();
  6965. }
  6966. static void display_pools(void)
  6967. {
  6968. struct pool *pool;
  6969. int selected, i, j;
  6970. char input;
  6971. loginput_mode(7 + total_pools);
  6972. immedok(logwin, true);
  6973. updated:
  6974. for (j = 0; j < total_pools; j++) {
  6975. for (i = 0; i < total_pools; i++) {
  6976. pool = pools[i];
  6977. if (pool->prio != j)
  6978. continue;
  6979. if (pool == current_pool())
  6980. wattron(logwin, A_BOLD);
  6981. if (pool->enabled != POOL_ENABLED || pool->failover_only)
  6982. wattron(logwin, A_DIM);
  6983. wlogprint("%d: ", pool->prio);
  6984. switch (pool->enabled) {
  6985. case POOL_ENABLED:
  6986. if (pool->failover_only)
  6987. wlogprint("Failover ");
  6988. else
  6989. wlogprint("Enabled ");
  6990. break;
  6991. case POOL_DISABLED:
  6992. wlogprint("Disabled ");
  6993. break;
  6994. case POOL_REJECTING:
  6995. wlogprint("Rejectin ");
  6996. break;
  6997. case POOL_MISBEHAVING:
  6998. wlogprint("Misbehav ");
  6999. break;
  7000. }
  7001. _wlogprint(pool_proto_str(pool));
  7002. wlogprint(" Quota %d Pool %d: %s User:%s\n",
  7003. pool->quota,
  7004. pool->pool_no,
  7005. pool->rpc_url, pool->rpc_user);
  7006. wattroff(logwin, A_BOLD | A_DIM);
  7007. break; //for (i = 0; i < total_pools; i++)
  7008. }
  7009. }
  7010. retry:
  7011. wlogprint("\nCurrent pool management strategy: %s\n",
  7012. strategies[pool_strategy].s);
  7013. if (pool_strategy == POOL_ROTATE)
  7014. wlogprint("Set to rotate every %d minutes\n", opt_rotate_period);
  7015. wlogprint("[F]ailover only %s\n", opt_fail_only ? "enabled" : "disabled");
  7016. wlogprint("Pool [A]dd [R]emove [D]isable [E]nable [P]rioritize [Q]uota change\n");
  7017. wlogprint("[C]hange management strategy [S]witch pool [I]nformation\n");
  7018. wlogprint("Or press any other key to continue\n");
  7019. logwin_update();
  7020. input = getch();
  7021. if (!strncasecmp(&input, "a", 1)) {
  7022. if (opt_benchmark)
  7023. {
  7024. wlogprint("Cannot add pools in benchmark mode");
  7025. goto retry;
  7026. }
  7027. input_pool(true);
  7028. goto updated;
  7029. } else if (!strncasecmp(&input, "r", 1)) {
  7030. if (total_pools <= 1) {
  7031. wlogprint("Cannot remove last pool");
  7032. goto retry;
  7033. }
  7034. selected = curses_int("Select pool number");
  7035. if (selected < 0 || selected >= total_pools) {
  7036. wlogprint("Invalid selection\n");
  7037. goto retry;
  7038. }
  7039. pool = pools[selected];
  7040. if (pool == current_pool())
  7041. switch_pools(NULL);
  7042. if (pool == current_pool()) {
  7043. wlogprint("Unable to remove pool due to activity\n");
  7044. goto retry;
  7045. }
  7046. remove_pool(pool);
  7047. goto updated;
  7048. } else if (!strncasecmp(&input, "s", 1)) {
  7049. selected = curses_int("Select pool number");
  7050. if (selected < 0 || selected >= total_pools) {
  7051. wlogprint("Invalid selection\n");
  7052. goto retry;
  7053. }
  7054. pool = pools[selected];
  7055. pool->failover_only = false;
  7056. switch_pools(pool);
  7057. goto updated;
  7058. } else if (!strncasecmp(&input, "d", 1)) {
  7059. if (enabled_pools <= 1) {
  7060. wlogprint("Cannot disable last pool");
  7061. goto retry;
  7062. }
  7063. selected = curses_int("Select pool number");
  7064. if (selected < 0 || selected >= total_pools) {
  7065. wlogprint("Invalid selection\n");
  7066. goto retry;
  7067. }
  7068. pool = pools[selected];
  7069. disable_pool(pool, POOL_DISABLED);
  7070. goto updated;
  7071. } else if (!strncasecmp(&input, "e", 1)) {
  7072. selected = curses_int("Select pool number");
  7073. if (selected < 0 || selected >= total_pools) {
  7074. wlogprint("Invalid selection\n");
  7075. goto retry;
  7076. }
  7077. pool = pools[selected];
  7078. pool->failover_only = false;
  7079. enable_pool(pool);
  7080. goto updated;
  7081. } else if (!strncasecmp(&input, "c", 1)) {
  7082. for (i = 0; i <= TOP_STRATEGY; i++)
  7083. wlogprint("%d: %s\n", i, strategies[i].s);
  7084. selected = curses_int("Select strategy number type");
  7085. if (selected < 0 || selected > TOP_STRATEGY) {
  7086. wlogprint("Invalid selection\n");
  7087. goto retry;
  7088. }
  7089. if (selected == POOL_ROTATE) {
  7090. opt_rotate_period = curses_int("Select interval in minutes");
  7091. if (opt_rotate_period < 0 || opt_rotate_period > 9999) {
  7092. opt_rotate_period = 0;
  7093. wlogprint("Invalid selection\n");
  7094. goto retry;
  7095. }
  7096. }
  7097. mutex_lock(&lp_lock);
  7098. pool_strategy = selected;
  7099. pthread_cond_broadcast(&lp_cond);
  7100. mutex_unlock(&lp_lock);
  7101. switch_pools(NULL);
  7102. goto updated;
  7103. } else if (!strncasecmp(&input, "i", 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. display_pool_summary(pool);
  7111. goto retry;
  7112. } else if (!strncasecmp(&input, "q", 1)) {
  7113. selected = curses_int("Select pool number");
  7114. if (selected < 0 || selected >= total_pools) {
  7115. wlogprint("Invalid selection\n");
  7116. goto retry;
  7117. }
  7118. pool = pools[selected];
  7119. selected = curses_int("Set quota");
  7120. if (selected < 0) {
  7121. wlogprint("Invalid negative quota\n");
  7122. goto retry;
  7123. }
  7124. pool->quota = selected;
  7125. adjust_quota_gcd();
  7126. goto updated;
  7127. } else if (!strncasecmp(&input, "f", 1)) {
  7128. opt_fail_only ^= true;
  7129. goto updated;
  7130. } else if (!strncasecmp(&input, "p", 1)) {
  7131. char *prilist = curses_input("Enter new pool priority (comma separated list)");
  7132. if (!prilist)
  7133. {
  7134. wlogprint("Not changing priorities\n");
  7135. goto retry;
  7136. }
  7137. int res = prioritize_pools(prilist, &i);
  7138. free(prilist);
  7139. switch (res) {
  7140. case MSG_NOPOOL:
  7141. wlogprint("No pools\n");
  7142. goto retry;
  7143. case MSG_MISPID:
  7144. wlogprint("Missing pool id parameter\n");
  7145. goto retry;
  7146. case MSG_INVPID:
  7147. wlogprint("Invalid pool id %d - range is 0 - %d\n", i, total_pools - 1);
  7148. goto retry;
  7149. case MSG_DUPPID:
  7150. wlogprint("Duplicate pool specified %d\n", i);
  7151. goto retry;
  7152. case MSG_POOLPRIO:
  7153. default:
  7154. goto updated;
  7155. }
  7156. }
  7157. immedok(logwin, false);
  7158. loginput_mode(0);
  7159. }
  7160. static const char *summary_detail_level_str(void)
  7161. {
  7162. if (opt_compact)
  7163. return "compact";
  7164. if (opt_show_procs)
  7165. return "processors";
  7166. return "devices";
  7167. }
  7168. static void display_options(void)
  7169. {
  7170. int selected;
  7171. char input;
  7172. immedok(logwin, true);
  7173. loginput_mode(12);
  7174. retry:
  7175. clear_logwin();
  7176. wlogprint("[N]ormal [C]lear [S]ilent mode (disable all output)\n");
  7177. wlogprint("[D]ebug:%s\n[P]er-device:%s\n[Q]uiet:%s\n[V]erbose:%s\n"
  7178. "[R]PC debug:%s\n[W]orkTime details:%s\nsu[M]mary detail level:%s\n"
  7179. "[L]og interval:%d\nS[T]atistical counts: %s\n[Z]ero statistics\n",
  7180. opt_debug_console ? "on" : "off",
  7181. want_per_device_stats? "on" : "off",
  7182. opt_quiet ? "on" : "off",
  7183. opt_log_output ? "on" : "off",
  7184. opt_protocol ? "on" : "off",
  7185. opt_worktime ? "on" : "off",
  7186. summary_detail_level_str(),
  7187. opt_log_interval,
  7188. opt_weighed_stats ? "weighed" : "absolute");
  7189. wlogprint("Select an option or any other key to return\n");
  7190. logwin_update();
  7191. input = getch();
  7192. if (!strncasecmp(&input, "q", 1)) {
  7193. opt_quiet ^= true;
  7194. wlogprint("Quiet mode %s\n", opt_quiet ? "enabled" : "disabled");
  7195. goto retry;
  7196. } else if (!strncasecmp(&input, "v", 1)) {
  7197. opt_log_output ^= true;
  7198. if (opt_log_output)
  7199. opt_quiet = false;
  7200. wlogprint("Verbose mode %s\n", opt_log_output ? "enabled" : "disabled");
  7201. goto retry;
  7202. } else if (!strncasecmp(&input, "n", 1)) {
  7203. opt_log_output = false;
  7204. opt_debug_console = false;
  7205. opt_quiet = false;
  7206. opt_protocol = false;
  7207. opt_compact = false;
  7208. opt_show_procs = false;
  7209. devsummaryYOffset = 0;
  7210. want_per_device_stats = false;
  7211. wlogprint("Output mode reset to normal\n");
  7212. switch_logsize();
  7213. goto retry;
  7214. } else if (!strncasecmp(&input, "d", 1)) {
  7215. opt_debug = true;
  7216. opt_debug_console ^= true;
  7217. opt_log_output = opt_debug_console;
  7218. if (opt_debug_console)
  7219. opt_quiet = false;
  7220. wlogprint("Debug mode %s\n", opt_debug_console ? "enabled" : "disabled");
  7221. goto retry;
  7222. } else if (!strncasecmp(&input, "m", 1)) {
  7223. if (opt_compact)
  7224. opt_compact = false;
  7225. else
  7226. if (!opt_show_procs)
  7227. opt_show_procs = true;
  7228. else
  7229. {
  7230. opt_compact = true;
  7231. opt_show_procs = false;
  7232. devsummaryYOffset = 0;
  7233. }
  7234. wlogprint("su[M]mary detail level changed to: %s\n", summary_detail_level_str());
  7235. switch_logsize();
  7236. goto retry;
  7237. } else if (!strncasecmp(&input, "p", 1)) {
  7238. want_per_device_stats ^= true;
  7239. opt_log_output = want_per_device_stats;
  7240. wlogprint("Per-device stats %s\n", want_per_device_stats ? "enabled" : "disabled");
  7241. goto retry;
  7242. } else if (!strncasecmp(&input, "r", 1)) {
  7243. opt_protocol ^= true;
  7244. if (opt_protocol)
  7245. opt_quiet = false;
  7246. wlogprint("RPC protocol debugging %s\n", opt_protocol ? "enabled" : "disabled");
  7247. goto retry;
  7248. } else if (!strncasecmp(&input, "c", 1))
  7249. clear_logwin();
  7250. else if (!strncasecmp(&input, "l", 1)) {
  7251. selected = curses_int("Interval in seconds");
  7252. if (selected < 0 || selected > 9999) {
  7253. wlogprint("Invalid selection\n");
  7254. goto retry;
  7255. }
  7256. opt_log_interval = selected;
  7257. wlogprint("Log interval set to %d seconds\n", opt_log_interval);
  7258. goto retry;
  7259. } else if (!strncasecmp(&input, "s", 1)) {
  7260. opt_realquiet = true;
  7261. } else if (!strncasecmp(&input, "w", 1)) {
  7262. opt_worktime ^= true;
  7263. wlogprint("WorkTime details %s\n", opt_worktime ? "enabled" : "disabled");
  7264. goto retry;
  7265. } else if (!strncasecmp(&input, "t", 1)) {
  7266. opt_weighed_stats ^= true;
  7267. wlogprint("Now displaying %s statistics\n", opt_weighed_stats ? "weighed" : "absolute");
  7268. goto retry;
  7269. } else if (!strncasecmp(&input, "z", 1)) {
  7270. zero_stats();
  7271. goto retry;
  7272. }
  7273. immedok(logwin, false);
  7274. loginput_mode(0);
  7275. }
  7276. #endif
  7277. void default_save_file(char *filename)
  7278. {
  7279. #if defined(unix) || defined(__APPLE__)
  7280. if (getenv("HOME") && *getenv("HOME")) {
  7281. strcpy(filename, getenv("HOME"));
  7282. strcat(filename, "/");
  7283. }
  7284. else
  7285. strcpy(filename, "");
  7286. strcat(filename, ".bfgminer/");
  7287. mkdir(filename, 0777);
  7288. #else
  7289. strcpy(filename, "");
  7290. #endif
  7291. strcat(filename, def_conf);
  7292. }
  7293. #ifdef HAVE_CURSES
  7294. static void set_options(void)
  7295. {
  7296. int selected;
  7297. char input;
  7298. immedok(logwin, true);
  7299. loginput_mode(8);
  7300. retry:
  7301. wlogprint("\n[L]ongpoll: %s\n", want_longpoll ? "On" : "Off");
  7302. wlogprint("[Q]ueue: %d\n[S]cantime: %d\n[E]xpiry: %d\n[R]etries: %d\n"
  7303. "[W]rite config file\n[B]FGMiner restart\n",
  7304. opt_queue, opt_scantime, opt_expiry, opt_retries);
  7305. wlogprint("Select an option or any other key to return\n");
  7306. logwin_update();
  7307. input = getch();
  7308. if (!strncasecmp(&input, "q", 1)) {
  7309. selected = curses_int("Extra work items to queue");
  7310. if (selected < 0 || selected > 9999) {
  7311. wlogprint("Invalid selection\n");
  7312. goto retry;
  7313. }
  7314. opt_queue = selected;
  7315. goto retry;
  7316. } else if (!strncasecmp(&input, "l", 1)) {
  7317. if (want_longpoll)
  7318. stop_longpoll();
  7319. else
  7320. start_longpoll();
  7321. applog(LOG_WARNING, "Longpoll %s", want_longpoll ? "enabled" : "disabled");
  7322. goto retry;
  7323. } else if (!strncasecmp(&input, "s", 1)) {
  7324. selected = curses_int("Set scantime in seconds");
  7325. if (selected < 0 || selected > 9999) {
  7326. wlogprint("Invalid selection\n");
  7327. goto retry;
  7328. }
  7329. opt_scantime = selected;
  7330. goto retry;
  7331. } else if (!strncasecmp(&input, "e", 1)) {
  7332. selected = curses_int("Set expiry time in seconds");
  7333. if (selected < 0 || selected > 9999) {
  7334. wlogprint("Invalid selection\n");
  7335. goto retry;
  7336. }
  7337. opt_expiry = selected;
  7338. goto retry;
  7339. } else if (!strncasecmp(&input, "r", 1)) {
  7340. selected = curses_int("Retries before failing (-1 infinite)");
  7341. if (selected < -1 || selected > 9999) {
  7342. wlogprint("Invalid selection\n");
  7343. goto retry;
  7344. }
  7345. opt_retries = selected;
  7346. goto retry;
  7347. } else if (!strncasecmp(&input, "w", 1)) {
  7348. FILE *fcfg;
  7349. char *str, filename[PATH_MAX], prompt[PATH_MAX + 50];
  7350. default_save_file(filename);
  7351. snprintf(prompt, sizeof(prompt), "Config filename to write (Enter for default) [%s]", filename);
  7352. str = curses_input(prompt);
  7353. if (str) {
  7354. struct stat statbuf;
  7355. strcpy(filename, str);
  7356. free(str);
  7357. if (!stat(filename, &statbuf)) {
  7358. wlogprint("File exists, overwrite?\n");
  7359. input = getch();
  7360. if (strncasecmp(&input, "y", 1))
  7361. goto retry;
  7362. }
  7363. }
  7364. fcfg = fopen(filename, "w");
  7365. if (!fcfg) {
  7366. wlogprint("Cannot open or create file\n");
  7367. goto retry;
  7368. }
  7369. write_config(fcfg);
  7370. fclose(fcfg);
  7371. goto retry;
  7372. } else if (!strncasecmp(&input, "b", 1)) {
  7373. wlogprint("Are you sure?\n");
  7374. input = getch();
  7375. if (!strncasecmp(&input, "y", 1))
  7376. app_restart();
  7377. else
  7378. clear_logwin();
  7379. } else
  7380. clear_logwin();
  7381. loginput_mode(0);
  7382. immedok(logwin, false);
  7383. }
  7384. int scan_serial(const char *);
  7385. static
  7386. void _managetui_msg(const char *repr, const char **msg)
  7387. {
  7388. if (*msg)
  7389. {
  7390. applog(LOG_DEBUG, "ManageTUI: %"PRIpreprv": %s", repr, *msg);
  7391. wattron(logwin, A_BOLD);
  7392. wlogprint("%s", *msg);
  7393. wattroff(logwin, A_BOLD);
  7394. *msg = NULL;
  7395. }
  7396. logwin_update();
  7397. }
  7398. void manage_device(void)
  7399. {
  7400. char logline[256];
  7401. const char *msg = NULL;
  7402. struct cgpu_info *cgpu;
  7403. const struct device_drv *drv;
  7404. selecting_device = true;
  7405. immedok(logwin, true);
  7406. loginput_mode(12);
  7407. devchange:
  7408. if (unlikely(!total_devices))
  7409. {
  7410. clear_logwin();
  7411. wlogprint("(no devices)\n");
  7412. wlogprint("[Plus] Add device(s) [Enter] Close device manager\n");
  7413. _managetui_msg("(none)", &msg);
  7414. int input = getch();
  7415. switch (input)
  7416. {
  7417. case '+': case '=': // add new device
  7418. goto addnew;
  7419. default:
  7420. goto out;
  7421. }
  7422. }
  7423. cgpu = devices[selected_device];
  7424. drv = cgpu->drv;
  7425. refresh_devstatus();
  7426. refresh:
  7427. clear_logwin();
  7428. wlogprint("Select processor to manage using up/down arrow keys\n");
  7429. get_statline3(logline, sizeof(logline), cgpu, true, true);
  7430. wattron(logwin, A_BOLD);
  7431. wlogprint("%s", logline);
  7432. wattroff(logwin, A_BOLD);
  7433. wlogprint("\n");
  7434. if (cgpu->dev_manufacturer)
  7435. wlogprint(" %s from %s\n", (cgpu->dev_product ?: "Device"), cgpu->dev_manufacturer);
  7436. else
  7437. if (cgpu->dev_product)
  7438. wlogprint(" %s\n", cgpu->dev_product);
  7439. if (cgpu->dev_serial)
  7440. wlogprint("Serial: %s\n", cgpu->dev_serial);
  7441. if (cgpu->kname)
  7442. wlogprint("Kernel: %s\n", cgpu->kname);
  7443. if (drv->proc_wlogprint_status && likely(cgpu->status != LIFE_INIT))
  7444. drv->proc_wlogprint_status(cgpu);
  7445. wlogprint("\n");
  7446. // TODO: Last share at TIMESTAMP on pool N
  7447. // TODO: Custom device info/commands
  7448. if (cgpu->deven != DEV_ENABLED)
  7449. wlogprint("[E]nable ");
  7450. if (cgpu->deven != DEV_DISABLED)
  7451. wlogprint("[D]isable ");
  7452. if (drv->identify_device)
  7453. wlogprint("[I]dentify ");
  7454. if (drv->proc_tui_wlogprint_choices && likely(cgpu->status != LIFE_INIT))
  7455. drv->proc_tui_wlogprint_choices(cgpu);
  7456. wlogprint("\n");
  7457. wlogprint("[Slash] Find processor [Plus] Add device(s) [Enter] Close device manager\n");
  7458. _managetui_msg(cgpu->proc_repr, &msg);
  7459. while (true)
  7460. {
  7461. int input = getch();
  7462. applog(LOG_DEBUG, "ManageTUI: %"PRIpreprv": (choice %d)", cgpu->proc_repr, input);
  7463. switch (input) {
  7464. case 'd': case 'D':
  7465. if (cgpu->deven == DEV_DISABLED)
  7466. msg = "Processor already disabled\n";
  7467. else
  7468. {
  7469. cgpu->deven = DEV_DISABLED;
  7470. msg = "Processor being disabled\n";
  7471. }
  7472. goto refresh;
  7473. case 'e': case 'E':
  7474. if (cgpu->deven == DEV_ENABLED)
  7475. msg = "Processor already enabled\n";
  7476. else
  7477. {
  7478. proc_enable(cgpu);
  7479. msg = "Processor being enabled\n";
  7480. }
  7481. goto refresh;
  7482. case 'i': case 'I':
  7483. if (drv->identify_device && drv->identify_device(cgpu))
  7484. msg = "Identify command sent\n";
  7485. else
  7486. goto key_default;
  7487. goto refresh;
  7488. case KEY_DOWN:
  7489. if (selected_device >= total_devices - 1)
  7490. break;
  7491. ++selected_device;
  7492. goto devchange;
  7493. case KEY_UP:
  7494. if (selected_device <= 0)
  7495. break;
  7496. --selected_device;
  7497. goto devchange;
  7498. case KEY_NPAGE:
  7499. {
  7500. if (selected_device >= total_devices - 1)
  7501. break;
  7502. struct cgpu_info *mdev = devices[selected_device]->device;
  7503. do {
  7504. ++selected_device;
  7505. } while (devices[selected_device]->device == mdev && selected_device < total_devices - 1);
  7506. goto devchange;
  7507. }
  7508. case KEY_PPAGE:
  7509. {
  7510. if (selected_device <= 0)
  7511. break;
  7512. struct cgpu_info *mdev = devices[selected_device]->device;
  7513. do {
  7514. --selected_device;
  7515. } while (devices[selected_device]->device == mdev && selected_device > 0);
  7516. goto devchange;
  7517. }
  7518. case '/': case '?': // find device
  7519. {
  7520. static char *pattern = NULL;
  7521. char *newpattern = curses_input("Enter pattern");
  7522. if (newpattern)
  7523. {
  7524. free(pattern);
  7525. pattern = newpattern;
  7526. }
  7527. else
  7528. if (!pattern)
  7529. pattern = calloc(1, 1);
  7530. int match = cgpu_search(pattern, selected_device + 1);
  7531. if (match == -1)
  7532. {
  7533. msg = "Couldn't find device\n";
  7534. goto refresh;
  7535. }
  7536. selected_device = match;
  7537. goto devchange;
  7538. }
  7539. case '+': case '=': // add new device
  7540. {
  7541. addnew:
  7542. clear_logwin();
  7543. _wlogprint(
  7544. "Enter \"auto\", \"all\", or a serial port to probe for mining devices.\n"
  7545. "Prefix by a driver name and colon to only probe a specific driver.\n"
  7546. "For example: erupter:"
  7547. #ifdef WIN32
  7548. "\\\\.\\COM40"
  7549. #elif defined(__APPLE__)
  7550. "/dev/cu.SLAB_USBtoUART"
  7551. #else
  7552. "/dev/ttyUSB39"
  7553. #endif
  7554. "\n"
  7555. );
  7556. char *scanser = curses_input("Enter target");
  7557. if (scan_serial(scanser))
  7558. {
  7559. selected_device = total_devices - 1;
  7560. msg = "Device scan succeeded\n";
  7561. }
  7562. else
  7563. msg = "No new devices found\n";
  7564. goto devchange;
  7565. }
  7566. case 'Q': case 'q':
  7567. case KEY_BREAK: case KEY_BACKSPACE: case KEY_CANCEL: case KEY_CLOSE: case KEY_EXIT:
  7568. case '\x1b': // ESC
  7569. case KEY_ENTER:
  7570. case '\r': // Ctrl-M on Windows, with nonl
  7571. #ifdef PADENTER
  7572. case PADENTER: // pdcurses, used by Enter key on Windows with nonl
  7573. #endif
  7574. case '\n':
  7575. goto out;
  7576. default:
  7577. ;
  7578. key_default:
  7579. if (drv->proc_tui_handle_choice && likely(drv_ready(cgpu)))
  7580. {
  7581. msg = drv->proc_tui_handle_choice(cgpu, input);
  7582. if (msg)
  7583. goto refresh;
  7584. }
  7585. }
  7586. }
  7587. out:
  7588. selecting_device = false;
  7589. loginput_mode(0);
  7590. immedok(logwin, false);
  7591. }
  7592. void show_help(void)
  7593. {
  7594. loginput_mode(11);
  7595. // NOTE: wlogprint is a macro with a buffer limit
  7596. _wlogprint(
  7597. "LU: oldest explicit work update currently being used for new work\n"
  7598. "ST: work in queue | F: network fails | NB: new blocks detected\n"
  7599. "AS: shares being submitted | BW: bandwidth (up/down)\n"
  7600. "E: # shares * diff per 2kB bw | I: expected income | BS: best share ever found\n"
  7601. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7602. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7603. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7604. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_BTEE
  7605. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7606. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7607. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_BTEE U8_HLINE U8_HLINE U8_HLINE
  7608. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7609. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7610. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7611. "\n"
  7612. "devices/processors hashing (only for totals line), hottest temperature\n"
  7613. );
  7614. wlogprint(
  7615. "hashrates: %ds decaying / all-time average / all-time average (effective)\n"
  7616. , opt_log_interval);
  7617. _wlogprint(
  7618. "A: accepted shares | R: rejected+discarded(% of total)\n"
  7619. "HW: hardware errors / % nonces invalid\n"
  7620. "\n"
  7621. "Press any key to clear"
  7622. );
  7623. logwin_update();
  7624. getch();
  7625. loginput_mode(0);
  7626. }
  7627. static void *input_thread(void __maybe_unused *userdata)
  7628. {
  7629. RenameThread("input");
  7630. if (!curses_active)
  7631. return NULL;
  7632. while (1) {
  7633. int input;
  7634. input = getch();
  7635. switch (input) {
  7636. case 'h': case 'H': case '?':
  7637. case KEY_F(1):
  7638. show_help();
  7639. break;
  7640. case 'q': case 'Q':
  7641. kill_work();
  7642. return NULL;
  7643. case 'd': case 'D':
  7644. display_options();
  7645. break;
  7646. case 'm': case 'M':
  7647. manage_device();
  7648. break;
  7649. case 'p': case 'P':
  7650. display_pools();
  7651. break;
  7652. case 's': case 'S':
  7653. set_options();
  7654. break;
  7655. #ifdef HAVE_CURSES
  7656. case KEY_DOWN:
  7657. {
  7658. const int visible_lines = logcursor - devcursor;
  7659. const int invisible_lines = total_lines - visible_lines;
  7660. if (devsummaryYOffset <= -invisible_lines)
  7661. break;
  7662. devsummaryYOffset -= 2;
  7663. }
  7664. case KEY_UP:
  7665. if (devsummaryYOffset == 0)
  7666. break;
  7667. ++devsummaryYOffset;
  7668. refresh_devstatus();
  7669. break;
  7670. case KEY_NPAGE:
  7671. {
  7672. const int visible_lines = logcursor - devcursor;
  7673. const int invisible_lines = total_lines - visible_lines;
  7674. if (devsummaryYOffset - visible_lines <= -invisible_lines)
  7675. devsummaryYOffset = -invisible_lines;
  7676. else
  7677. devsummaryYOffset -= visible_lines;
  7678. refresh_devstatus();
  7679. break;
  7680. }
  7681. case KEY_PPAGE:
  7682. {
  7683. const int visible_lines = logcursor - devcursor;
  7684. if (devsummaryYOffset + visible_lines >= 0)
  7685. devsummaryYOffset = 0;
  7686. else
  7687. devsummaryYOffset += visible_lines;
  7688. refresh_devstatus();
  7689. break;
  7690. }
  7691. #endif
  7692. }
  7693. if (opt_realquiet) {
  7694. disable_curses();
  7695. break;
  7696. }
  7697. }
  7698. return NULL;
  7699. }
  7700. #endif
  7701. static void *api_thread(void *userdata)
  7702. {
  7703. struct thr_info *mythr = userdata;
  7704. pthread_detach(pthread_self());
  7705. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  7706. RenameThread("rpc");
  7707. api(api_thr_id);
  7708. mythr->has_pth = false;
  7709. return NULL;
  7710. }
  7711. void thread_reportin(struct thr_info *thr)
  7712. {
  7713. cgtime(&thr->last);
  7714. thr->cgpu->status = LIFE_WELL;
  7715. thr->getwork = 0;
  7716. thr->cgpu->device_last_well = time(NULL);
  7717. }
  7718. void thread_reportout(struct thr_info *thr)
  7719. {
  7720. thr->getwork = time(NULL);
  7721. }
  7722. static void hashmeter(int thr_id, struct timeval *diff,
  7723. uint64_t hashes_done)
  7724. {
  7725. char logstatusline[256];
  7726. struct timeval temp_tv_end, total_diff;
  7727. double secs;
  7728. double local_secs;
  7729. static double local_mhashes_done = 0;
  7730. double local_mhashes = (double)hashes_done / 1000000.0;
  7731. bool showlog = false;
  7732. char cHr[ALLOC_H2B_NOUNIT+1], aHr[ALLOC_H2B_NOUNIT+1], uHr[ALLOC_H2B_SPACED+3+1];
  7733. char rejpcbuf[6];
  7734. char bnbuf[6];
  7735. struct thr_info *thr;
  7736. /* Update the last time this thread reported in */
  7737. if (thr_id >= 0) {
  7738. thr = get_thread(thr_id);
  7739. cgtime(&(thr->last));
  7740. thr->cgpu->device_last_well = time(NULL);
  7741. }
  7742. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  7743. /* So we can call hashmeter from a non worker thread */
  7744. if (thr_id >= 0) {
  7745. struct cgpu_info *cgpu = thr->cgpu;
  7746. int threadobj = cgpu->threads ?: 1;
  7747. double thread_rolling = 0.0;
  7748. int i;
  7749. applog(LOG_DEBUG, "[thread %d: %"PRIu64" hashes, %.1f khash/sec]",
  7750. thr_id, hashes_done, hashes_done / 1000 / secs);
  7751. /* Rolling average for each thread and each device */
  7752. decay_time(&thr->rolling, local_mhashes / secs, secs);
  7753. for (i = 0; i < threadobj; i++)
  7754. thread_rolling += cgpu->thr[i]->rolling;
  7755. mutex_lock(&hash_lock);
  7756. decay_time(&cgpu->rolling, thread_rolling, secs);
  7757. cgpu->total_mhashes += local_mhashes;
  7758. mutex_unlock(&hash_lock);
  7759. // If needed, output detailed, per-device stats
  7760. if (want_per_device_stats) {
  7761. struct timeval now;
  7762. struct timeval elapsed;
  7763. struct timeval *last_msg_tv = opt_show_procs ? &thr->cgpu->last_message_tv : &thr->cgpu->device->last_message_tv;
  7764. cgtime(&now);
  7765. timersub(&now, last_msg_tv, &elapsed);
  7766. if (opt_log_interval <= elapsed.tv_sec) {
  7767. struct cgpu_info *cgpu = thr->cgpu;
  7768. char logline[255];
  7769. *last_msg_tv = now;
  7770. get_statline(logline, sizeof(logline), cgpu);
  7771. if (!curses_active) {
  7772. printf("\n%s\r", logline);
  7773. fflush(stdout);
  7774. } else
  7775. applog(LOG_INFO, "%s", logline);
  7776. }
  7777. }
  7778. }
  7779. /* Totals are updated by all threads so can race without locking */
  7780. mutex_lock(&hash_lock);
  7781. cgtime(&temp_tv_end);
  7782. timersub(&temp_tv_end, &total_tv_start, &total_diff);
  7783. total_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  7784. timersub(&temp_tv_end, &total_tv_end, &total_diff);
  7785. total_mhashes_done += local_mhashes;
  7786. local_mhashes_done += local_mhashes;
  7787. /* Only update with opt_log_interval */
  7788. if (total_diff.tv_sec < opt_log_interval)
  7789. goto out_unlock;
  7790. showlog = true;
  7791. cgtime(&total_tv_end);
  7792. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  7793. decay_time(&total_rolling, local_mhashes_done / local_secs, local_secs);
  7794. global_hashrate = ((unsigned long long)lround(total_rolling)) * 1000000;
  7795. double wtotal = (total_diff_accepted + total_diff_rejected + total_diff_stale);
  7796. multi_format_unit_array2(
  7797. ((char*[]){cHr, aHr, uHr}),
  7798. ((size_t[]){sizeof(cHr), sizeof(aHr), sizeof(uHr)}),
  7799. true, "h/s", H2B_SHORT,
  7800. 3,
  7801. 1e6*total_rolling,
  7802. 1e6*total_mhashes_done / total_secs,
  7803. utility_to_hashrate(total_diff1 * (wtotal ? (total_diff_accepted / wtotal) : 1) * 60 / total_secs));
  7804. int ui_accepted, ui_rejected, ui_stale;
  7805. if (opt_weighed_stats)
  7806. {
  7807. ui_accepted = total_diff_accepted;
  7808. ui_rejected = total_diff_rejected;
  7809. ui_stale = total_diff_stale;
  7810. }
  7811. else
  7812. {
  7813. ui_accepted = total_accepted;
  7814. ui_rejected = total_rejected;
  7815. ui_stale = total_stale;
  7816. }
  7817. #ifdef HAVE_CURSES
  7818. if (curses_active_locked()) {
  7819. float temp = 0;
  7820. struct cgpu_info *proc, *last_working_dev = NULL;
  7821. int i, working_devs = 0, working_procs = 0;
  7822. int divx;
  7823. bool bad = false;
  7824. // Find the highest temperature of all processors
  7825. for (i = 0; i < total_devices; ++i)
  7826. {
  7827. proc = get_devices(i);
  7828. if (proc->temp > temp)
  7829. temp = proc->temp;
  7830. if (unlikely(proc->deven == DEV_DISABLED))
  7831. ; // Just need to block it off from both conditions
  7832. else
  7833. if (likely(proc->status == LIFE_WELL && proc->deven == DEV_ENABLED))
  7834. {
  7835. if (proc->rolling > .1)
  7836. {
  7837. ++working_procs;
  7838. if (proc->device != last_working_dev)
  7839. {
  7840. ++working_devs;
  7841. last_working_dev = proc->device;
  7842. }
  7843. }
  7844. }
  7845. else
  7846. bad = true;
  7847. }
  7848. if (working_devs == working_procs)
  7849. snprintf(statusline, sizeof(statusline), "%s%d ", bad ? U8_BAD_START : "", working_devs);
  7850. else
  7851. snprintf(statusline, sizeof(statusline), "%s%d/%d ", bad ? U8_BAD_START : "", working_devs, working_procs);
  7852. divx = 7;
  7853. if (opt_show_procs && !opt_compact)
  7854. divx += max_lpdigits;
  7855. if (bad)
  7856. {
  7857. divx += sizeof(U8_BAD_START)-1;
  7858. strcpy(&statusline[divx], U8_BAD_END);
  7859. divx += sizeof(U8_BAD_END)-1;
  7860. }
  7861. temperature_column(&statusline[divx], sizeof(statusline)-divx, true, &temp);
  7862. format_statline(statusline, sizeof(statusline),
  7863. cHr, aHr,
  7864. uHr,
  7865. ui_accepted,
  7866. ui_rejected,
  7867. ui_stale,
  7868. total_diff_rejected + total_diff_stale, total_diff_accepted,
  7869. hw_errors,
  7870. total_bad_diff1, total_bad_diff1 + total_diff1);
  7871. unlock_curses();
  7872. }
  7873. #endif
  7874. // Add a space
  7875. memmove(&uHr[6], &uHr[5], strlen(&uHr[5]) + 1);
  7876. uHr[5] = ' ';
  7877. percentf4(rejpcbuf, sizeof(rejpcbuf), total_diff_rejected + total_diff_stale, total_diff_accepted);
  7878. percentf4(bnbuf, sizeof(bnbuf), total_bad_diff1, total_diff1);
  7879. snprintf(logstatusline, sizeof(logstatusline),
  7880. "%s%ds:%s avg:%s u:%s | A:%d R:%d+%d(%s) HW:%d/%s",
  7881. want_per_device_stats ? "ALL " : "",
  7882. opt_log_interval,
  7883. cHr, aHr,
  7884. uHr,
  7885. ui_accepted,
  7886. ui_rejected,
  7887. ui_stale,
  7888. rejpcbuf,
  7889. hw_errors,
  7890. bnbuf
  7891. );
  7892. local_mhashes_done = 0;
  7893. out_unlock:
  7894. mutex_unlock(&hash_lock);
  7895. if (showlog) {
  7896. if (!curses_active) {
  7897. if (want_per_device_stats)
  7898. printf("\n%s\r", logstatusline);
  7899. else
  7900. {
  7901. const int logstatusline_len = strlen(logstatusline);
  7902. int padding;
  7903. if (last_logstatusline_len > logstatusline_len)
  7904. padding = (last_logstatusline_len - logstatusline_len);
  7905. else
  7906. {
  7907. padding = 0;
  7908. if (last_logstatusline_len == -1)
  7909. puts("");
  7910. }
  7911. printf("%s%*s\r", logstatusline, padding, "");
  7912. last_logstatusline_len = logstatusline_len;
  7913. }
  7914. fflush(stdout);
  7915. } else
  7916. applog(LOG_INFO, "%s", logstatusline);
  7917. }
  7918. }
  7919. void hashmeter2(struct thr_info *thr)
  7920. {
  7921. struct timeval tv_now, tv_elapsed;
  7922. timerclear(&thr->tv_hashes_done);
  7923. cgtime(&tv_now);
  7924. timersub(&tv_now, &thr->tv_lastupdate, &tv_elapsed);
  7925. /* Update the hashmeter at most 5 times per second */
  7926. if ((thr->hashes_done && (tv_elapsed.tv_sec > 0 || tv_elapsed.tv_usec > 200000)) ||
  7927. tv_elapsed.tv_sec >= opt_log_interval) {
  7928. hashmeter(thr->id, &tv_elapsed, thr->hashes_done);
  7929. thr->hashes_done = 0;
  7930. thr->tv_lastupdate = tv_now;
  7931. }
  7932. }
  7933. static void stratum_share_result(json_t *val, json_t *res_val, json_t *err_val,
  7934. struct stratum_share *sshare)
  7935. {
  7936. struct work *work = sshare->work;
  7937. share_result(val, res_val, err_val, work, false, "");
  7938. }
  7939. /* Parses stratum json responses and tries to find the id that the request
  7940. * matched to and treat it accordingly. */
  7941. bool parse_stratum_response(struct pool *pool, char *s)
  7942. {
  7943. json_t *val = NULL, *err_val, *res_val, *id_val;
  7944. struct stratum_share *sshare;
  7945. json_error_t err;
  7946. bool ret = false;
  7947. int id;
  7948. val = JSON_LOADS(s, &err);
  7949. if (!val) {
  7950. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  7951. goto out;
  7952. }
  7953. res_val = json_object_get(val, "result");
  7954. err_val = json_object_get(val, "error");
  7955. id_val = json_object_get(val, "id");
  7956. if (json_is_null(id_val) || !id_val) {
  7957. char *ss;
  7958. if (err_val)
  7959. ss = json_dumps(err_val, JSON_INDENT(3));
  7960. else
  7961. ss = strdup("(unknown reason)");
  7962. applog(LOG_INFO, "JSON-RPC non method decode failed: %s", ss);
  7963. free(ss);
  7964. goto out;
  7965. }
  7966. if (!json_is_integer(id_val)) {
  7967. if (json_is_string(id_val)
  7968. && !strncmp(json_string_value(id_val), "txlist", 6))
  7969. {
  7970. const bool is_array = json_is_array(res_val);
  7971. applog(LOG_DEBUG, "Received %s for pool %u job %s",
  7972. is_array ? "transaction list" : "no-transaction-list response",
  7973. pool->pool_no, &json_string_value(id_val)[6]);
  7974. if (!is_array)
  7975. {
  7976. // No need to wait for a timeout
  7977. timer_unset(&pool->swork.tv_transparency);
  7978. pool_set_opaque(pool, true);
  7979. goto fishy;
  7980. }
  7981. if (strcmp(json_string_value(id_val) + 6, pool->swork.job_id))
  7982. // We only care about a transaction list for the current job id
  7983. goto fishy;
  7984. // Check that the transactions actually hash to the merkle links
  7985. {
  7986. unsigned maxtx = 1 << pool->swork.merkles;
  7987. unsigned mintx = maxtx >> 1;
  7988. --maxtx;
  7989. unsigned acttx = (unsigned)json_array_size(res_val);
  7990. if (acttx < mintx || acttx > maxtx) {
  7991. applog(LOG_WARNING, "Pool %u is sending mismatched block contents to us (%u is not %u-%u)",
  7992. pool->pool_no, acttx, mintx, maxtx);
  7993. goto fishy;
  7994. }
  7995. // TODO: Check hashes match actual merkle links
  7996. }
  7997. pool_set_opaque(pool, false);
  7998. timer_unset(&pool->swork.tv_transparency);
  7999. fishy:
  8000. ret = true;
  8001. }
  8002. goto out;
  8003. }
  8004. id = json_integer_value(id_val);
  8005. mutex_lock(&sshare_lock);
  8006. HASH_FIND_INT(stratum_shares, &id, sshare);
  8007. if (sshare)
  8008. HASH_DEL(stratum_shares, sshare);
  8009. mutex_unlock(&sshare_lock);
  8010. if (!sshare) {
  8011. double pool_diff;
  8012. /* Since the share is untracked, we can only guess at what the
  8013. * work difficulty is based on the current pool diff. */
  8014. cg_rlock(&pool->data_lock);
  8015. pool_diff = target_diff(pool->swork.target);
  8016. cg_runlock(&pool->data_lock);
  8017. if (json_is_true(res_val)) {
  8018. struct mining_goal_info * const goal = pool->goal;
  8019. applog(LOG_NOTICE, "Accepted untracked stratum share from pool %d", pool->pool_no);
  8020. /* We don't know what device this came from so we can't
  8021. * attribute the work to the relevant cgpu */
  8022. mutex_lock(&stats_lock);
  8023. total_accepted++;
  8024. pool->accepted++;
  8025. total_diff_accepted += pool_diff;
  8026. pool->diff_accepted += pool_diff;
  8027. goal->diff_accepted += pool_diff;
  8028. mutex_unlock(&stats_lock);
  8029. } else {
  8030. applog(LOG_NOTICE, "Rejected untracked stratum share from pool %d", pool->pool_no);
  8031. mutex_lock(&stats_lock);
  8032. total_rejected++;
  8033. pool->rejected++;
  8034. total_diff_rejected += pool_diff;
  8035. pool->diff_rejected += pool_diff;
  8036. mutex_unlock(&stats_lock);
  8037. }
  8038. goto out;
  8039. }
  8040. else {
  8041. mutex_lock(&submitting_lock);
  8042. --total_submitting;
  8043. mutex_unlock(&submitting_lock);
  8044. }
  8045. stratum_share_result(val, res_val, err_val, sshare);
  8046. free_work(sshare->work);
  8047. free(sshare);
  8048. ret = true;
  8049. out:
  8050. if (val)
  8051. json_decref(val);
  8052. return ret;
  8053. }
  8054. static void shutdown_stratum(struct pool *pool)
  8055. {
  8056. // Shut down Stratum as if we never had it
  8057. pool->stratum_active = false;
  8058. pool->stratum_init = false;
  8059. pool->has_stratum = false;
  8060. shutdown(pool->sock, SHUT_RDWR);
  8061. free(pool->stratum_url);
  8062. if (pool->sockaddr_url == pool->stratum_url)
  8063. pool->sockaddr_url = NULL;
  8064. pool->stratum_url = NULL;
  8065. }
  8066. void clear_stratum_shares(struct pool *pool)
  8067. {
  8068. int my_mining_threads = mining_threads; // Cached outside of locking
  8069. struct stratum_share *sshare, *tmpshare;
  8070. struct work *work;
  8071. struct cgpu_info *cgpu;
  8072. double diff_cleared = 0;
  8073. double thr_diff_cleared[my_mining_threads];
  8074. int cleared = 0;
  8075. int thr_cleared[my_mining_threads];
  8076. // NOTE: This is per-thread rather than per-device to avoid getting devices lock in stratum_shares loop
  8077. for (int i = 0; i < my_mining_threads; ++i)
  8078. {
  8079. thr_diff_cleared[i] = 0;
  8080. thr_cleared[i] = 0;
  8081. }
  8082. mutex_lock(&sshare_lock);
  8083. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  8084. work = sshare->work;
  8085. if (sshare->work->pool == pool && work->thr_id < my_mining_threads) {
  8086. HASH_DEL(stratum_shares, sshare);
  8087. sharelog("disconnect", work);
  8088. diff_cleared += sshare->work->work_difficulty;
  8089. thr_diff_cleared[work->thr_id] += work->work_difficulty;
  8090. ++thr_cleared[work->thr_id];
  8091. free_work(sshare->work);
  8092. free(sshare);
  8093. cleared++;
  8094. }
  8095. }
  8096. mutex_unlock(&sshare_lock);
  8097. if (cleared) {
  8098. applog(LOG_WARNING, "Lost %d shares due to stratum disconnect on pool %d", cleared, pool->pool_no);
  8099. mutex_lock(&stats_lock);
  8100. pool->stale_shares += cleared;
  8101. total_stale += cleared;
  8102. pool->diff_stale += diff_cleared;
  8103. total_diff_stale += diff_cleared;
  8104. for (int i = 0; i < my_mining_threads; ++i)
  8105. if (thr_cleared[i])
  8106. {
  8107. cgpu = get_thr_cgpu(i);
  8108. cgpu->diff_stale += thr_diff_cleared[i];
  8109. cgpu->stale += thr_cleared[i];
  8110. }
  8111. mutex_unlock(&stats_lock);
  8112. mutex_lock(&submitting_lock);
  8113. total_submitting -= cleared;
  8114. mutex_unlock(&submitting_lock);
  8115. }
  8116. }
  8117. static void resubmit_stratum_shares(struct pool *pool)
  8118. {
  8119. struct stratum_share *sshare, *tmpshare;
  8120. struct work *work;
  8121. unsigned resubmitted = 0;
  8122. mutex_lock(&sshare_lock);
  8123. mutex_lock(&submitting_lock);
  8124. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  8125. if (sshare->work->pool != pool)
  8126. continue;
  8127. HASH_DEL(stratum_shares, sshare);
  8128. work = sshare->work;
  8129. DL_APPEND(submit_waiting, work);
  8130. free(sshare);
  8131. ++resubmitted;
  8132. }
  8133. mutex_unlock(&submitting_lock);
  8134. mutex_unlock(&sshare_lock);
  8135. if (resubmitted) {
  8136. notifier_wake(submit_waiting_notifier);
  8137. applog(LOG_DEBUG, "Resubmitting %u shares due to stratum disconnect on pool %u", resubmitted, pool->pool_no);
  8138. }
  8139. }
  8140. static void clear_pool_work(struct pool *pool)
  8141. {
  8142. struct work *work, *tmp;
  8143. int cleared = 0;
  8144. mutex_lock(stgd_lock);
  8145. HASH_ITER(hh, staged_work, work, tmp) {
  8146. if (work->pool == pool) {
  8147. unstage_work(work);
  8148. free_work(work);
  8149. cleared++;
  8150. }
  8151. }
  8152. mutex_unlock(stgd_lock);
  8153. }
  8154. static int cp_prio(void)
  8155. {
  8156. int prio;
  8157. cg_rlock(&control_lock);
  8158. prio = currentpool->prio;
  8159. cg_runlock(&control_lock);
  8160. return prio;
  8161. }
  8162. /* We only need to maintain a secondary pool connection when we need the
  8163. * capacity to get work from the backup pools while still on the primary */
  8164. static bool cnx_needed(struct pool *pool)
  8165. {
  8166. struct pool *cp;
  8167. // We want to keep a connection open for rejecting or misbehaving pools, to detect when/if they change their tune
  8168. if (pool->enabled == POOL_DISABLED)
  8169. return false;
  8170. /* Idle stratum pool needs something to kick it alive again */
  8171. if (pool->has_stratum && pool->idle)
  8172. return true;
  8173. /* Getwork pools without opt_fail_only need backup pools up to be able
  8174. * to leak shares */
  8175. cp = current_pool();
  8176. if (pool_actively_desired(pool, cp))
  8177. return true;
  8178. if (!pool_localgen(cp) && (!opt_fail_only || !cp->hdr_path))
  8179. return true;
  8180. /* Keep the connection open to allow any stray shares to be submitted
  8181. * on switching pools for 2 minutes. */
  8182. if (timer_elapsed(&pool->tv_last_work_time, NULL) < 120)
  8183. return true;
  8184. /* If the pool has only just come to life and is higher priority than
  8185. * the current pool keep the connection open so we can fail back to
  8186. * it. */
  8187. if (pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  8188. return true;
  8189. if (pool_unworkable(cp))
  8190. return true;
  8191. /* We've run out of work, bring anything back to life. */
  8192. if (no_work)
  8193. return true;
  8194. // If the current pool lacks its own block change detection, see if we are needed for that
  8195. if (pool_active_lp_pool(cp) == pool)
  8196. return true;
  8197. return false;
  8198. }
  8199. static void wait_lpcurrent(struct pool *pool);
  8200. static void pool_resus(struct pool *pool);
  8201. static void stratum_resumed(struct pool *pool)
  8202. {
  8203. if (!pool->stratum_notify)
  8204. return;
  8205. if (pool_tclear(pool, &pool->idle)) {
  8206. applog(LOG_INFO, "Stratum connection to pool %d resumed", pool->pool_no);
  8207. pool_resus(pool);
  8208. }
  8209. }
  8210. static bool supports_resume(struct pool *pool)
  8211. {
  8212. bool ret;
  8213. cg_rlock(&pool->data_lock);
  8214. ret = (pool->sessionid != NULL);
  8215. cg_runlock(&pool->data_lock);
  8216. return ret;
  8217. }
  8218. static bool pools_active;
  8219. /* One stratum thread per pool that has stratum waits on the socket checking
  8220. * for new messages and for the integrity of the socket connection. We reset
  8221. * the connection based on the integrity of the receive side only as the send
  8222. * side will eventually expire data it fails to send. */
  8223. static void *stratum_thread(void *userdata)
  8224. {
  8225. struct pool *pool = (struct pool *)userdata;
  8226. pthread_detach(pthread_self());
  8227. char threadname[20];
  8228. snprintf(threadname, 20, "stratum%u", pool->pool_no);
  8229. RenameThread(threadname);
  8230. srand(time(NULL) + (intptr_t)userdata);
  8231. while (42) {
  8232. struct timeval timeout;
  8233. int sel_ret;
  8234. fd_set rd;
  8235. char *s;
  8236. int sock;
  8237. if (unlikely(!pool->has_stratum))
  8238. break;
  8239. /* Check to see whether we need to maintain this connection
  8240. * indefinitely or just bring it up when we switch to this
  8241. * pool */
  8242. while (true)
  8243. {
  8244. sock = pool->sock;
  8245. if (sock == INVSOCK)
  8246. applog(LOG_DEBUG, "Pool %u: Invalid socket, suspending",
  8247. pool->pool_no);
  8248. else
  8249. if (!sock_full(pool) && !cnx_needed(pool) && pools_active)
  8250. applog(LOG_DEBUG, "Pool %u: Connection not needed, suspending",
  8251. pool->pool_no);
  8252. else
  8253. break;
  8254. suspend_stratum(pool);
  8255. clear_stratum_shares(pool);
  8256. clear_pool_work(pool);
  8257. wait_lpcurrent(pool);
  8258. if (!restart_stratum(pool)) {
  8259. pool_died(pool);
  8260. while (!restart_stratum(pool)) {
  8261. if (pool->removed)
  8262. goto out;
  8263. cgsleep_ms(30000);
  8264. }
  8265. }
  8266. }
  8267. FD_ZERO(&rd);
  8268. FD_SET(sock, &rd);
  8269. timeout.tv_sec = 120;
  8270. timeout.tv_usec = 0;
  8271. /* If we fail to receive any notify messages for 2 minutes we
  8272. * assume the connection has been dropped and treat this pool
  8273. * as dead */
  8274. if (!sock_full(pool) && (sel_ret = select(sock + 1, &rd, NULL, NULL, &timeout)) < 1) {
  8275. applog(LOG_DEBUG, "Stratum select failed on pool %d with value %d", pool->pool_no, sel_ret);
  8276. s = NULL;
  8277. } else
  8278. s = recv_line(pool);
  8279. if (!s) {
  8280. if (!pool->has_stratum)
  8281. break;
  8282. applog(LOG_NOTICE, "Stratum connection to pool %d interrupted", pool->pool_no);
  8283. pool->getfail_occasions++;
  8284. total_go++;
  8285. mutex_lock(&pool->stratum_lock);
  8286. pool->stratum_active = pool->stratum_notify = false;
  8287. pool->sock = INVSOCK;
  8288. mutex_unlock(&pool->stratum_lock);
  8289. /* If the socket to our stratum pool disconnects, all
  8290. * submissions need to be discarded or resent. */
  8291. if (!supports_resume(pool))
  8292. clear_stratum_shares(pool);
  8293. else
  8294. resubmit_stratum_shares(pool);
  8295. clear_pool_work(pool);
  8296. if (pool == current_pool())
  8297. restart_threads();
  8298. if (restart_stratum(pool))
  8299. continue;
  8300. shutdown_stratum(pool);
  8301. pool_died(pool);
  8302. break;
  8303. }
  8304. /* Check this pool hasn't died while being a backup pool and
  8305. * has not had its idle flag cleared */
  8306. stratum_resumed(pool);
  8307. if (!parse_method(pool, s) && !parse_stratum_response(pool, s))
  8308. applog(LOG_INFO, "Unknown stratum msg: %s", s);
  8309. free(s);
  8310. if (pool->swork.clean) {
  8311. struct work *work = make_work();
  8312. /* Generate a single work item to update the current
  8313. * block database */
  8314. pool->swork.clean = false;
  8315. gen_stratum_work(pool, work);
  8316. /* Try to extract block height from coinbase scriptSig */
  8317. uint8_t *bin_height = &bytes_buf(&pool->swork.coinbase)[4 /*version*/ + 1 /*txin count*/ + 36 /*prevout*/ + 1 /*scriptSig len*/ + 1 /*push opcode*/];
  8318. unsigned char cb_height_sz;
  8319. cb_height_sz = bin_height[-1];
  8320. if (cb_height_sz == 3) {
  8321. // FIXME: The block number will overflow this by AD 2173
  8322. struct mining_goal_info * const goal = pool->goal;
  8323. const void * const prevblkhash = &work->data[4];
  8324. uint32_t height = 0;
  8325. memcpy(&height, bin_height, 3);
  8326. height = le32toh(height);
  8327. have_block_height(goal, prevblkhash, height);
  8328. }
  8329. pool->swork.work_restart_id =
  8330. ++pool->work_restart_id;
  8331. pool_update_work_restart_time(pool);
  8332. if (test_work_current(work)) {
  8333. /* Only accept a work update if this stratum
  8334. * connection is from the current pool */
  8335. struct pool * const cp = current_pool();
  8336. if (pool == cp)
  8337. restart_threads();
  8338. applog(
  8339. ((!opt_quiet_work_updates) && pool_actively_in_use(pool, cp) ? LOG_NOTICE : LOG_DEBUG),
  8340. "Stratum from pool %d requested work update", pool->pool_no);
  8341. } else
  8342. applog(LOG_NOTICE, "Stratum from pool %d detected new block", pool->pool_no);
  8343. free_work(work);
  8344. }
  8345. if (timer_passed(&pool->swork.tv_transparency, NULL)) {
  8346. // More than 4 timmills past since requested transactions
  8347. timer_unset(&pool->swork.tv_transparency);
  8348. pool_set_opaque(pool, true);
  8349. }
  8350. }
  8351. out:
  8352. return NULL;
  8353. }
  8354. static void init_stratum_thread(struct pool *pool)
  8355. {
  8356. struct mining_goal_info * const goal = pool->goal;
  8357. goal->have_longpoll = true;
  8358. if (unlikely(pthread_create(&pool->stratum_thread, NULL, stratum_thread, (void *)pool)))
  8359. quit(1, "Failed to create stratum thread");
  8360. }
  8361. static void *longpoll_thread(void *userdata);
  8362. static bool stratum_works(struct pool *pool)
  8363. {
  8364. applog(LOG_INFO, "Testing pool %d stratum %s", pool->pool_no, pool->stratum_url);
  8365. if (!extract_sockaddr(pool->stratum_url, &pool->sockaddr_url, &pool->stratum_port))
  8366. return false;
  8367. if (pool->stratum_active)
  8368. return true;
  8369. if (!initiate_stratum(pool))
  8370. return false;
  8371. return true;
  8372. }
  8373. static
  8374. bool pool_recently_got_work(struct pool * const pool, const struct timeval * const tvp_now)
  8375. {
  8376. return (timer_isset(&pool->tv_last_work_time) && timer_elapsed(&pool->tv_last_work_time, tvp_now) < 60);
  8377. }
  8378. static bool pool_active(struct pool *pool, bool pinging)
  8379. {
  8380. struct timeval tv_now, tv_getwork, tv_getwork_reply;
  8381. bool ret = false;
  8382. json_t *val;
  8383. CURL *curl = NULL;
  8384. int rolltime;
  8385. char *rpc_req;
  8386. struct work *work;
  8387. enum pool_protocol proto;
  8388. if (pool->stratum_init)
  8389. {
  8390. if (pool->stratum_active)
  8391. return true;
  8392. }
  8393. else
  8394. if (!pool->idle)
  8395. {
  8396. timer_set_now(&tv_now);
  8397. if (pool_recently_got_work(pool, &tv_now))
  8398. return true;
  8399. }
  8400. mutex_lock(&pool->pool_test_lock);
  8401. if (pool->stratum_init)
  8402. {
  8403. ret = pool->stratum_active;
  8404. goto out;
  8405. }
  8406. timer_set_now(&tv_now);
  8407. if (pool->idle)
  8408. {
  8409. if (timer_elapsed(&pool->tv_idle, &tv_now) < 30)
  8410. goto out;
  8411. }
  8412. else
  8413. if (pool_recently_got_work(pool, &tv_now))
  8414. {
  8415. ret = true;
  8416. goto out;
  8417. }
  8418. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  8419. /* This is the central point we activate stratum when we can */
  8420. curl = curl_easy_init();
  8421. if (unlikely(!curl)) {
  8422. applog(LOG_ERR, "CURL initialisation failed");
  8423. goto out;
  8424. }
  8425. if (!(want_gbt || want_getwork))
  8426. goto nohttp;
  8427. work = make_work();
  8428. /* Probe for GBT support on first pass */
  8429. proto = want_gbt ? PLP_GETBLOCKTEMPLATE : PLP_GETWORK;
  8430. tryagain:
  8431. rpc_req = prepare_rpc_req_probe(work, proto, NULL, pool);
  8432. work->pool = pool;
  8433. if (!rpc_req)
  8434. goto out;
  8435. pool->probed = false;
  8436. cgtime(&tv_getwork);
  8437. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  8438. true, false, &rolltime, pool, false);
  8439. cgtime(&tv_getwork_reply);
  8440. free(rpc_req);
  8441. /* Detect if a http getwork pool has an X-Stratum header at startup,
  8442. * and if so, switch to that in preference to getwork if it works */
  8443. if (pool->stratum_url && want_stratum && pool_may_redirect_to(pool, pool->stratum_url) && (pool->has_stratum || stratum_works(pool))) {
  8444. if (!pool->has_stratum) {
  8445. applog(LOG_NOTICE, "Switching pool %d %s to %s", pool->pool_no, pool->rpc_url, pool->stratum_url);
  8446. if (!pool->rpc_url)
  8447. pool_set_uri(pool, strdup(pool->stratum_url));
  8448. pool->has_stratum = true;
  8449. }
  8450. free_work(work);
  8451. if (val)
  8452. json_decref(val);
  8453. retry_stratum:
  8454. ;
  8455. /* We create the stratum thread for each pool just after
  8456. * successful authorisation. Once the init flag has been set
  8457. * we never unset it and the stratum thread is responsible for
  8458. * setting/unsetting the active flag */
  8459. bool init = pool_tset(pool, &pool->stratum_init);
  8460. if (!init) {
  8461. ret = initiate_stratum(pool) && auth_stratum(pool);
  8462. if (ret)
  8463. {
  8464. detect_algo = 2;
  8465. init_stratum_thread(pool);
  8466. }
  8467. else
  8468. {
  8469. pool_tclear(pool, &pool->stratum_init);
  8470. pool->tv_idle = tv_getwork_reply;
  8471. }
  8472. goto out;
  8473. }
  8474. ret = pool->stratum_active;
  8475. goto out;
  8476. }
  8477. else if (pool->has_stratum)
  8478. shutdown_stratum(pool);
  8479. if (val) {
  8480. bool rc;
  8481. json_t *res;
  8482. res = json_object_get(val, "result");
  8483. if ((!json_is_object(res)) || (proto == PLP_GETBLOCKTEMPLATE && !json_object_get(res, "bits")))
  8484. goto badwork;
  8485. work->rolltime = rolltime;
  8486. rc = work_decode(pool, work, val);
  8487. if (rc) {
  8488. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  8489. pool->pool_no, pool->rpc_url);
  8490. work->pool = pool;
  8491. copy_time(&work->tv_getwork, &tv_getwork);
  8492. copy_time(&work->tv_getwork_reply, &tv_getwork_reply);
  8493. work->getwork_mode = GETWORK_MODE_TESTPOOL;
  8494. calc_diff(work, 0);
  8495. update_last_work(work);
  8496. applog(LOG_DEBUG, "Pushing pooltest work to base pool");
  8497. stage_work(work);
  8498. total_getworks++;
  8499. pool->getwork_requested++;
  8500. ret = true;
  8501. pool->tv_idle = tv_getwork_reply;
  8502. } else {
  8503. badwork:
  8504. json_decref(val);
  8505. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher work from pool %u %s",
  8506. pool->pool_no, pool->rpc_url);
  8507. pool->proto = proto = pool_protocol_fallback(proto);
  8508. if (PLP_NONE != proto)
  8509. goto tryagain;
  8510. pool->tv_idle = tv_getwork_reply;
  8511. free_work(work);
  8512. goto out;
  8513. }
  8514. json_decref(val);
  8515. if (proto != pool->proto) {
  8516. pool->proto = proto;
  8517. applog(LOG_INFO, "Selected %s protocol for pool %u", pool_protocol_name(proto), pool->pool_no);
  8518. }
  8519. if (pool->lp_url)
  8520. goto out;
  8521. /* Decipher the longpoll URL, if any, and store it in ->lp_url */
  8522. const struct blktmpl_longpoll_req *lp;
  8523. if (work->tr && (lp = blktmpl_get_longpoll(work->tr->tmpl))) {
  8524. // NOTE: work_decode takes care of lp id
  8525. pool->lp_url = lp->uri ? absolute_uri(lp->uri, pool->rpc_url) : pool->rpc_url;
  8526. if (!pool->lp_url)
  8527. {
  8528. ret = false;
  8529. goto out;
  8530. }
  8531. pool->lp_proto = PLP_GETBLOCKTEMPLATE;
  8532. }
  8533. else
  8534. if (pool->hdr_path && want_getwork) {
  8535. pool->lp_url = absolute_uri(pool->hdr_path, pool->rpc_url);
  8536. if (!pool->lp_url)
  8537. {
  8538. ret = false;
  8539. goto out;
  8540. }
  8541. pool->lp_proto = PLP_GETWORK;
  8542. } else
  8543. pool->lp_url = NULL;
  8544. if (want_longpoll && !pool->lp_started) {
  8545. pool->lp_started = true;
  8546. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  8547. quit(1, "Failed to create pool longpoll thread");
  8548. }
  8549. } else if (PLP_NONE != (proto = pool_protocol_fallback(proto))) {
  8550. pool->proto = proto;
  8551. goto tryagain;
  8552. } else {
  8553. pool->tv_idle = tv_getwork_reply;
  8554. free_work(work);
  8555. nohttp:
  8556. /* If we failed to parse a getwork, this could be a stratum
  8557. * url without the prefix stratum+tcp:// so let's check it */
  8558. if (extract_sockaddr(pool->rpc_url, &pool->sockaddr_url, &pool->stratum_port) && initiate_stratum(pool)) {
  8559. pool->has_stratum = true;
  8560. goto retry_stratum;
  8561. }
  8562. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  8563. pool->pool_no, pool->rpc_url);
  8564. if (!pinging)
  8565. applog(LOG_WARNING, "Pool %u slow/down or URL or credentials invalid", pool->pool_no);
  8566. }
  8567. out:
  8568. if (curl)
  8569. curl_easy_cleanup(curl);
  8570. mutex_unlock(&pool->pool_test_lock);
  8571. return ret;
  8572. }
  8573. static void pool_resus(struct pool *pool)
  8574. {
  8575. if (pool->enabled == POOL_ENABLED && pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  8576. applog(LOG_WARNING, "Pool %d %s alive, testing stability", pool->pool_no, pool->rpc_url);
  8577. else
  8578. applog(LOG_INFO, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  8579. }
  8580. static
  8581. void *cmd_idle_thread(void * const __maybe_unused userp)
  8582. {
  8583. pthread_detach(pthread_self());
  8584. RenameThread("cmd-idle");
  8585. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  8586. sleep(opt_log_interval);
  8587. pthread_testcancel();
  8588. run_cmd(cmd_idle);
  8589. return NULL;
  8590. }
  8591. static struct work *hash_pop(struct cgpu_info * const proc)
  8592. {
  8593. int hc;
  8594. struct work *work, *work_found, *tmp;
  8595. enum {
  8596. HPWS_NONE = 0,
  8597. HPWS_LOWDIFF = 1,
  8598. HPWS_ROLLABLE = 2,
  8599. HPWS_PERFECT = 3,
  8600. } work_score = HPWS_NONE;
  8601. bool did_cmd_idle = false;
  8602. pthread_t cmd_idle_thr;
  8603. retry:
  8604. mutex_lock(stgd_lock);
  8605. while (true)
  8606. {
  8607. work_found = NULL;
  8608. work_score = 0;
  8609. hc = HASH_COUNT(staged_work);
  8610. HASH_ITER(hh, staged_work, work, tmp)
  8611. {
  8612. const struct mining_algorithm * const work_malgo = work_mining_algorithm(work);
  8613. const float min_nonce_diff = drv_min_nonce_diff(proc->drv, proc, work_malgo);
  8614. if (min_nonce_diff < work->work_difficulty)
  8615. {
  8616. if (unlikely(min_nonce_diff >= 0 && work_score < HPWS_LOWDIFF))
  8617. {
  8618. work_found = work;
  8619. work_score = HPWS_LOWDIFF;
  8620. }
  8621. continue;
  8622. }
  8623. if (work->rolltime && hc > staged_rollable)
  8624. {
  8625. if (work_score < HPWS_ROLLABLE)
  8626. {
  8627. work_found = work;
  8628. work_score = HPWS_ROLLABLE;
  8629. }
  8630. continue;
  8631. }
  8632. // Good match
  8633. work_found = work;
  8634. work_score = HPWS_PERFECT;
  8635. break;
  8636. }
  8637. if (work_found)
  8638. {
  8639. work = work_found;
  8640. break;
  8641. }
  8642. // Failed to get a usable work
  8643. if (unlikely(staged_full))
  8644. {
  8645. if (likely(opt_queue < 10 + mining_threads))
  8646. {
  8647. ++opt_queue;
  8648. applog(LOG_WARNING, "Staged work underrun; increasing queue minimum to %d", opt_queue);
  8649. }
  8650. else
  8651. applog(LOG_WARNING, "Staged work underrun; not automatically increasing above %d", opt_queue);
  8652. staged_full = false; // Let it fill up before triggering an underrun again
  8653. no_work = true;
  8654. }
  8655. pthread_cond_signal(&gws_cond);
  8656. if (cmd_idle && !did_cmd_idle)
  8657. {
  8658. if (likely(!pthread_create(&cmd_idle_thr, NULL, cmd_idle_thread, NULL)))
  8659. did_cmd_idle = true;
  8660. }
  8661. pthread_cond_wait(&getq->cond, stgd_lock);
  8662. }
  8663. if (did_cmd_idle)
  8664. pthread_cancel(cmd_idle_thr);
  8665. no_work = false;
  8666. if (can_roll(work) && should_roll(work))
  8667. {
  8668. // Instead of consuming it, force it to be cloned and grab the clone
  8669. mutex_unlock(stgd_lock);
  8670. clone_available();
  8671. goto retry;
  8672. }
  8673. unstage_work(work);
  8674. /* Signal the getwork scheduler to look for more work */
  8675. pthread_cond_signal(&gws_cond);
  8676. /* Signal hash_pop again in case there are mutliple hash_pop waiters */
  8677. pthread_cond_signal(&getq->cond);
  8678. mutex_unlock(stgd_lock);
  8679. work->pool->last_work_time = time(NULL);
  8680. cgtime(&work->pool->tv_last_work_time);
  8681. return work;
  8682. }
  8683. /* Clones work by rolling it if possible, and returning a clone instead of the
  8684. * original work item which gets staged again to possibly be rolled again in
  8685. * the future */
  8686. static struct work *clone_work(struct work *work)
  8687. {
  8688. int mrs = mining_threads + opt_queue - total_staged();
  8689. struct work *work_clone;
  8690. bool cloned;
  8691. if (mrs < 1)
  8692. return work;
  8693. cloned = false;
  8694. work_clone = make_clone(work);
  8695. while (mrs-- > 0 && can_roll(work) && should_roll(work)) {
  8696. applog(LOG_DEBUG, "Pushing rolled converted work to stage thread");
  8697. stage_work(work_clone);
  8698. roll_work(work);
  8699. work_clone = make_clone(work);
  8700. /* Roll it again to prevent duplicates should this be used
  8701. * directly later on */
  8702. roll_work(work);
  8703. cloned = true;
  8704. }
  8705. if (cloned) {
  8706. stage_work(work);
  8707. return work_clone;
  8708. }
  8709. free_work(work_clone);
  8710. return work;
  8711. }
  8712. void gen_hash(unsigned char *data, unsigned char *hash, int len)
  8713. {
  8714. unsigned char hash1[32];
  8715. sha256(data, len, hash1);
  8716. sha256(hash1, 32, hash);
  8717. }
  8718. /* PDiff 1 is a 256 bit unsigned integer of
  8719. * 0x00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff
  8720. * so we use a big endian 32 bit unsigned integer positioned at the Nth byte to
  8721. * cover a huge range of difficulty targets, though not all 256 bits' worth */
  8722. static void pdiff_target_leadzero(void * const target_p, double diff)
  8723. {
  8724. uint8_t *target = target_p;
  8725. diff *= 0x100000000;
  8726. int skip = log2(diff) / 8;
  8727. if (skip)
  8728. {
  8729. if (skip > 0x1c)
  8730. skip = 0x1c;
  8731. diff /= pow(0x100, skip);
  8732. memset(target, 0, skip);
  8733. }
  8734. uint32_t n = 0xffffffff;
  8735. n = (double)n / diff;
  8736. n = htobe32(n);
  8737. memcpy(&target[skip], &n, sizeof(n));
  8738. memset(&target[skip + sizeof(n)], 0xff, 32 - (skip + sizeof(n)));
  8739. }
  8740. void set_target_to_pdiff(void * const dest_target, const double pdiff)
  8741. {
  8742. unsigned char rtarget[32];
  8743. pdiff_target_leadzero(rtarget, pdiff);
  8744. swab256(dest_target, rtarget);
  8745. if (opt_debug) {
  8746. char htarget[65];
  8747. bin2hex(htarget, rtarget, 32);
  8748. applog(LOG_DEBUG, "Generated target %s", htarget);
  8749. }
  8750. }
  8751. void set_target_to_bdiff(void * const dest_target, const double bdiff)
  8752. {
  8753. set_target_to_pdiff(dest_target, bdiff_to_pdiff(bdiff));
  8754. }
  8755. void _test_target(void * const funcp, const char * const funcname, const bool little_endian, const void * const expectp, const double diff)
  8756. {
  8757. uint8_t bufr[32], buf[32], expectr[32], expect[32];
  8758. int off;
  8759. void (*func)(void *, double) = funcp;
  8760. func(little_endian ? bufr : buf, diff);
  8761. if (little_endian)
  8762. swab256(buf, bufr);
  8763. swap32tobe(expect, expectp, 256/32);
  8764. // Fuzzy comparison: the first 32 bits set must match, and the actual target must be >= the expected
  8765. for (off = 0; off < 28 && !buf[off]; ++off)
  8766. {}
  8767. if (memcmp(&buf[off], &expect[off], 4))
  8768. {
  8769. testfail: ;
  8770. ++unittest_failures;
  8771. char hexbuf[65], expectbuf[65];
  8772. bin2hex(hexbuf, buf, 32);
  8773. bin2hex(expectbuf, expect, 32);
  8774. applogr(, LOG_WARNING, "%s test failed: diff %g got %s (expected %s)",
  8775. funcname, diff, hexbuf, expectbuf);
  8776. }
  8777. if (!little_endian)
  8778. swab256(bufr, buf);
  8779. swab256(expectr, expect);
  8780. if (!hash_target_check(expectr, bufr))
  8781. goto testfail;
  8782. }
  8783. #define TEST_TARGET(func, le, expect, diff) \
  8784. _test_target(func, #func, le, expect, diff)
  8785. void test_target()
  8786. {
  8787. uint32_t expect[8] = {0};
  8788. // bdiff 1 should be exactly 00000000ffff0000000006f29cfd29510a6caee84634e86a57257cf03152537f due to floating-point imprecision (pdiff1 / 1.0000152590218966)
  8789. expect[0] = 0x0000ffff;
  8790. TEST_TARGET(set_target_to_bdiff, true, expect, 1./0x10000);
  8791. expect[0] = 0;
  8792. expect[1] = 0xffff0000;
  8793. TEST_TARGET(set_target_to_bdiff, true, expect, 1);
  8794. expect[1] >>= 1;
  8795. TEST_TARGET(set_target_to_bdiff, true, expect, 2);
  8796. expect[1] >>= 3;
  8797. TEST_TARGET(set_target_to_bdiff, true, expect, 0x10);
  8798. expect[1] >>= 4;
  8799. TEST_TARGET(set_target_to_bdiff, true, expect, 0x100);
  8800. memset(&expect[1], '\xff', 28);
  8801. expect[0] = 0x0000ffff;
  8802. TEST_TARGET(set_target_to_pdiff, true, expect, 1./0x10000);
  8803. expect[0] = 0;
  8804. TEST_TARGET(set_target_to_pdiff, true, expect, 1);
  8805. expect[1] >>= 1;
  8806. TEST_TARGET(set_target_to_pdiff, true, expect, 2);
  8807. expect[1] >>= 3;
  8808. TEST_TARGET(set_target_to_pdiff, true, expect, 0x10);
  8809. expect[1] >>= 4;
  8810. TEST_TARGET(set_target_to_pdiff, true, expect, 0x100);
  8811. }
  8812. void stratum_work_cpy(struct stratum_work * const dst, const struct stratum_work * const src)
  8813. {
  8814. *dst = *src;
  8815. if (dst->tr)
  8816. tmpl_incref(dst->tr);
  8817. dst->nonce1 = maybe_strdup(src->nonce1);
  8818. dst->job_id = maybe_strdup(src->job_id);
  8819. bytes_cpy(&dst->coinbase, &src->coinbase);
  8820. bytes_cpy(&dst->merkle_bin, &src->merkle_bin);
  8821. }
  8822. void stratum_work_clean(struct stratum_work * const swork)
  8823. {
  8824. if (swork->tr)
  8825. tmpl_decref(swork->tr);
  8826. free(swork->nonce1);
  8827. free(swork->job_id);
  8828. bytes_free(&swork->coinbase);
  8829. bytes_free(&swork->merkle_bin);
  8830. }
  8831. bool pool_has_usable_swork(const struct pool * const pool)
  8832. {
  8833. if (opt_benchmark)
  8834. return true;
  8835. if (pool->swork.tr)
  8836. {
  8837. // GBT
  8838. struct timeval tv_now;
  8839. timer_set_now(&tv_now);
  8840. return blkmk_time_left(pool->swork.tr->tmpl, tv_now.tv_sec);
  8841. }
  8842. return pool->stratum_notify;
  8843. }
  8844. /* Generates stratum based work based on the most recent notify information
  8845. * from the pool. This will keep generating work while a pool is down so we use
  8846. * other means to detect when the pool has died in stratum_thread */
  8847. static void gen_stratum_work(struct pool *pool, struct work *work)
  8848. {
  8849. clean_work(work);
  8850. cg_wlock(&pool->data_lock);
  8851. pool->swork.data_lock_p = &pool->data_lock;
  8852. const int n2size = pool->swork.n2size;
  8853. bytes_resize(&work->nonce2, n2size);
  8854. if (pool->nonce2sz < n2size)
  8855. memset(&bytes_buf(&work->nonce2)[pool->nonce2sz], 0, n2size - pool->nonce2sz);
  8856. memcpy(bytes_buf(&work->nonce2),
  8857. #ifdef WORDS_BIGENDIAN
  8858. // NOTE: On big endian, the most significant bits are stored at the end, so skip the LSBs
  8859. &((char*)&pool->nonce2)[pool->nonce2off],
  8860. #else
  8861. &pool->nonce2,
  8862. #endif
  8863. pool->nonce2sz);
  8864. pool->nonce2++;
  8865. work->pool = pool;
  8866. work->work_restart_id = pool->swork.work_restart_id;
  8867. gen_stratum_work2(work, &pool->swork);
  8868. cgtime(&work->tv_staged);
  8869. }
  8870. void gen_stratum_work2(struct work *work, struct stratum_work *swork)
  8871. {
  8872. unsigned char *coinbase, merkle_root[32], merkle_sha[64];
  8873. uint8_t *merkle_bin;
  8874. uint32_t *data32, *swap32;
  8875. int i;
  8876. /* Generate coinbase */
  8877. coinbase = bytes_buf(&swork->coinbase);
  8878. memcpy(&coinbase[swork->nonce2_offset], bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  8879. /* Downgrade to a read lock to read off the variables */
  8880. if (swork->data_lock_p)
  8881. cg_dwlock(swork->data_lock_p);
  8882. /* Generate merkle root */
  8883. gen_hash(coinbase, merkle_root, bytes_len(&swork->coinbase));
  8884. memcpy(merkle_sha, merkle_root, 32);
  8885. merkle_bin = bytes_buf(&swork->merkle_bin);
  8886. for (i = 0; i < swork->merkles; ++i, merkle_bin += 32) {
  8887. memcpy(merkle_sha + 32, merkle_bin, 32);
  8888. gen_hash(merkle_sha, merkle_root, 64);
  8889. memcpy(merkle_sha, merkle_root, 32);
  8890. }
  8891. data32 = (uint32_t *)merkle_sha;
  8892. swap32 = (uint32_t *)merkle_root;
  8893. flip32(swap32, data32);
  8894. memcpy(&work->data[0], swork->header1, 36);
  8895. memcpy(&work->data[36], merkle_root, 32);
  8896. *((uint32_t*)&work->data[68]) = htobe32(swork->ntime + timer_elapsed(&swork->tv_received, NULL));
  8897. memcpy(&work->data[72], swork->diffbits, 4);
  8898. memset(&work->data[76], 0, 4); // nonce
  8899. memcpy(&work->data[80], workpadding_bin, 48);
  8900. work->ntime_roll_limits = swork->ntime_roll_limits;
  8901. /* Copy parameters required for share submission */
  8902. memcpy(work->target, swork->target, sizeof(work->target));
  8903. work->job_id = maybe_strdup(swork->job_id);
  8904. work->nonce1 = maybe_strdup(swork->nonce1);
  8905. if (swork->data_lock_p)
  8906. cg_runlock(swork->data_lock_p);
  8907. if (opt_debug)
  8908. {
  8909. char header[161];
  8910. char nonce2hex[(bytes_len(&work->nonce2) * 2) + 1];
  8911. bin2hex(header, work->data, 80);
  8912. bin2hex(nonce2hex, bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  8913. applog(LOG_DEBUG, "Generated stratum header %s", header);
  8914. applog(LOG_DEBUG, "Work job_id %s nonce2 %s", work->job_id, nonce2hex);
  8915. }
  8916. calc_midstate(work);
  8917. local_work++;
  8918. work->stratum = true;
  8919. work->blk.nonce = 0;
  8920. work->id = total_work++;
  8921. work->longpoll = false;
  8922. work->getwork_mode = GETWORK_MODE_STRATUM;
  8923. calc_diff(work, 0);
  8924. }
  8925. void request_work(struct thr_info *thr)
  8926. {
  8927. struct cgpu_info *cgpu = thr->cgpu;
  8928. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  8929. /* Tell the watchdog thread this thread is waiting on getwork and
  8930. * should not be restarted */
  8931. thread_reportout(thr);
  8932. // HACK: Since get_work still blocks, reportout all processors dependent on this thread
  8933. for (struct cgpu_info *proc = thr->cgpu->next_proc; proc; proc = proc->next_proc)
  8934. {
  8935. if (proc->threads)
  8936. break;
  8937. thread_reportout(proc->thr[0]);
  8938. }
  8939. cgtime(&dev_stats->_get_start);
  8940. }
  8941. // FIXME: Make this non-blocking (and remove HACK above)
  8942. struct work *get_work(struct thr_info *thr)
  8943. {
  8944. const int thr_id = thr->id;
  8945. struct cgpu_info *cgpu = thr->cgpu;
  8946. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  8947. struct cgminer_stats *pool_stats;
  8948. struct timeval tv_get;
  8949. struct work *work = NULL;
  8950. applog(LOG_DEBUG, "%"PRIpreprv": Popping work from get queue to get work", cgpu->proc_repr);
  8951. while (!work) {
  8952. work = hash_pop(cgpu);
  8953. if (stale_work(work, false)) {
  8954. staged_full = false; // It wasn't really full, since it was stale :(
  8955. discard_work(work);
  8956. work = NULL;
  8957. wake_gws();
  8958. }
  8959. }
  8960. last_getwork = time(NULL);
  8961. applog(LOG_DEBUG, "%"PRIpreprv": Got work %d from get queue to get work for thread %d",
  8962. cgpu->proc_repr, work->id, thr_id);
  8963. work->thr_id = thr_id;
  8964. thread_reportin(thr);
  8965. // HACK: Since get_work still blocks, reportin all processors dependent on this thread
  8966. for (struct cgpu_info *proc = thr->cgpu->next_proc; proc; proc = proc->next_proc)
  8967. {
  8968. if (proc->threads)
  8969. break;
  8970. thread_reportin(proc->thr[0]);
  8971. }
  8972. work->mined = true;
  8973. work->blk.nonce = 0;
  8974. cgtime(&tv_get);
  8975. timersub(&tv_get, &dev_stats->_get_start, &tv_get);
  8976. timeradd(&tv_get, &dev_stats->getwork_wait, &dev_stats->getwork_wait);
  8977. if (timercmp(&tv_get, &dev_stats->getwork_wait_max, >))
  8978. dev_stats->getwork_wait_max = tv_get;
  8979. if (timercmp(&tv_get, &dev_stats->getwork_wait_min, <))
  8980. dev_stats->getwork_wait_min = tv_get;
  8981. ++dev_stats->getwork_calls;
  8982. pool_stats = &(work->pool->cgminer_stats);
  8983. timeradd(&tv_get, &pool_stats->getwork_wait, &pool_stats->getwork_wait);
  8984. if (timercmp(&tv_get, &pool_stats->getwork_wait_max, >))
  8985. pool_stats->getwork_wait_max = tv_get;
  8986. if (timercmp(&tv_get, &pool_stats->getwork_wait_min, <))
  8987. pool_stats->getwork_wait_min = tv_get;
  8988. ++pool_stats->getwork_calls;
  8989. if (work->work_difficulty < 1)
  8990. {
  8991. const float min_nonce_diff = drv_min_nonce_diff(cgpu->drv, cgpu, work_mining_algorithm(work));
  8992. if (unlikely(work->work_difficulty < min_nonce_diff))
  8993. {
  8994. if (min_nonce_diff - work->work_difficulty > 1./0x10000000)
  8995. applog(LOG_WARNING, "%"PRIpreprv": Using work with lower difficulty than device supports",
  8996. cgpu->proc_repr);
  8997. work->nonce_diff = min_nonce_diff;
  8998. }
  8999. else
  9000. work->nonce_diff = work->work_difficulty;
  9001. }
  9002. else
  9003. work->nonce_diff = 1;
  9004. return work;
  9005. }
  9006. struct dupe_hash_elem {
  9007. uint8_t hash[0x20];
  9008. struct timeval tv_prune;
  9009. UT_hash_handle hh;
  9010. };
  9011. static
  9012. void _submit_work_async(struct work *work)
  9013. {
  9014. applog(LOG_DEBUG, "Pushing submit work to work thread");
  9015. if (opt_benchmark)
  9016. {
  9017. json_t * const jn = json_null(), *result = NULL;
  9018. work_check_for_block(work);
  9019. {
  9020. static struct dupe_hash_elem *dupe_hashes;
  9021. struct dupe_hash_elem *dhe, *dhetmp;
  9022. HASH_FIND(hh, dupe_hashes, &work->hash, sizeof(dhe->hash), dhe);
  9023. if (dhe)
  9024. result = json_string("duplicate");
  9025. else
  9026. {
  9027. struct timeval tv_now;
  9028. timer_set_now(&tv_now);
  9029. // Prune old entries
  9030. HASH_ITER(hh, dupe_hashes, dhe, dhetmp)
  9031. {
  9032. if (!timer_passed(&dhe->tv_prune, &tv_now))
  9033. break;
  9034. HASH_DEL(dupe_hashes, dhe);
  9035. free(dhe);
  9036. }
  9037. dhe = malloc(sizeof(*dhe));
  9038. memcpy(dhe->hash, work->hash, sizeof(dhe->hash));
  9039. timer_set_delay(&dhe->tv_prune, &tv_now, 337500000);
  9040. HASH_ADD(hh, dupe_hashes, hash, sizeof(dhe->hash), dhe);
  9041. }
  9042. }
  9043. if (result)
  9044. {}
  9045. else
  9046. if (stale_work(work, true))
  9047. {
  9048. char stalemsg[0x10];
  9049. snprintf(stalemsg, sizeof(stalemsg), "stale %us", benchmark_update_interval * (work->pool->work_restart_id - work->work_restart_id));
  9050. result = json_string(stalemsg);
  9051. }
  9052. else
  9053. result = json_incref(jn);
  9054. share_result(jn, result, jn, work, false, "");
  9055. free_work(work);
  9056. json_decref(result);
  9057. json_decref(jn);
  9058. return;
  9059. }
  9060. mutex_lock(&submitting_lock);
  9061. ++total_submitting;
  9062. DL_APPEND(submit_waiting, work);
  9063. mutex_unlock(&submitting_lock);
  9064. notifier_wake(submit_waiting_notifier);
  9065. }
  9066. /* Submit a copy of the tested, statistic recorded work item asynchronously */
  9067. static void submit_work_async2(struct work *work, struct timeval *tv_work_found)
  9068. {
  9069. if (tv_work_found)
  9070. copy_time(&work->tv_work_found, tv_work_found);
  9071. _submit_work_async(work);
  9072. }
  9073. void inc_hw_errors3(struct thr_info *thr, const struct work *work, const uint32_t *bad_nonce_p, float nonce_diff)
  9074. {
  9075. struct cgpu_info * const cgpu = thr->cgpu;
  9076. if (bad_nonce_p)
  9077. {
  9078. if (bad_nonce_p == UNKNOWN_NONCE)
  9079. applog(LOG_DEBUG, "%"PRIpreprv": invalid nonce - HW error",
  9080. cgpu->proc_repr);
  9081. else
  9082. applog(LOG_DEBUG, "%"PRIpreprv": invalid nonce (%08lx) - HW error",
  9083. cgpu->proc_repr, (unsigned long)be32toh(*bad_nonce_p));
  9084. }
  9085. mutex_lock(&stats_lock);
  9086. hw_errors++;
  9087. ++cgpu->hw_errors;
  9088. if (bad_nonce_p)
  9089. {
  9090. total_bad_diff1 += nonce_diff;
  9091. cgpu->bad_diff1 += nonce_diff;
  9092. }
  9093. mutex_unlock(&stats_lock);
  9094. if (thr->cgpu->drv->hw_error)
  9095. thr->cgpu->drv->hw_error(thr);
  9096. }
  9097. void work_hash(struct work * const work)
  9098. {
  9099. const struct mining_algorithm * const malgo = work_mining_algorithm(work);
  9100. malgo->hash_data_f(work->hash, work->data);
  9101. }
  9102. static
  9103. bool test_hash(const void * const phash, const float diff)
  9104. {
  9105. const uint32_t * const hash = phash;
  9106. if (diff >= 1.)
  9107. // FIXME: > 1 should check more
  9108. return !hash[7];
  9109. const uint32_t Htarg = (uint32_t)ceil((1. / diff) - 1);
  9110. const uint32_t tmp_hash7 = le32toh(hash[7]);
  9111. applog(LOG_DEBUG, "htarget %08lx hash %08lx",
  9112. (long unsigned int)Htarg,
  9113. (long unsigned int)tmp_hash7);
  9114. return (tmp_hash7 <= Htarg);
  9115. }
  9116. enum test_nonce2_result _test_nonce2(struct work *work, uint32_t nonce, bool checktarget)
  9117. {
  9118. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  9119. *work_nonce = htole32(nonce);
  9120. work_hash(work);
  9121. if (!test_hash(work->hash, work->nonce_diff))
  9122. return TNR_BAD;
  9123. if (checktarget && !hash_target_check_v(work->hash, work->target))
  9124. {
  9125. bool high_hash = true;
  9126. struct pool * const pool = work->pool;
  9127. if (pool->stratum_active)
  9128. {
  9129. // 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
  9130. if (memcmp(pool->next_target, work->target, sizeof(work->target)))
  9131. {
  9132. applog(LOG_DEBUG, "Stratum pool %u target has changed since work job issued, checking that too",
  9133. pool->pool_no);
  9134. if (hash_target_check_v(work->hash, pool->next_target))
  9135. high_hash = false;
  9136. }
  9137. }
  9138. if (high_hash)
  9139. return TNR_HIGH;
  9140. }
  9141. return TNR_GOOD;
  9142. }
  9143. /* Returns true if nonce for work was a valid share */
  9144. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  9145. {
  9146. return submit_noffset_nonce(thr, work, nonce, 0);
  9147. }
  9148. /* Allows drivers to submit work items where the driver has changed the ntime
  9149. * value by noffset. Must be only used with a work protocol that does not ntime
  9150. * roll itself intrinsically to generate work (eg stratum). We do not touch
  9151. * the original work struct, but the copy of it only. */
  9152. bool submit_noffset_nonce(struct thr_info *thr, struct work *work_in, uint32_t nonce,
  9153. int noffset)
  9154. {
  9155. struct work *work = make_work();
  9156. _copy_work(work, work_in, noffset);
  9157. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  9158. struct timeval tv_work_found;
  9159. enum test_nonce2_result res;
  9160. bool ret = true;
  9161. thread_reportout(thr);
  9162. cgtime(&tv_work_found);
  9163. *work_nonce = htole32(nonce);
  9164. work->thr_id = thr->id;
  9165. /* Do one last check before attempting to submit the work */
  9166. /* Side effect: sets work->data and work->hash for us */
  9167. res = test_nonce2(work, nonce);
  9168. if (unlikely(res == TNR_BAD))
  9169. {
  9170. inc_hw_errors(thr, work, nonce);
  9171. ret = false;
  9172. goto out;
  9173. }
  9174. mutex_lock(&stats_lock);
  9175. total_diff1 += work->nonce_diff;
  9176. thr ->cgpu->diff1 += work->nonce_diff;
  9177. work->pool->diff1 += work->nonce_diff;
  9178. thr->cgpu->last_device_valid_work = time(NULL);
  9179. mutex_unlock(&stats_lock);
  9180. if (noncelog_file)
  9181. noncelog(work);
  9182. if (res == TNR_HIGH)
  9183. {
  9184. // Share above target, normal
  9185. /* Check the diff of the share, even if it didn't reach the
  9186. * target, just to set the best share value if it's higher. */
  9187. share_diff(work);
  9188. goto out;
  9189. }
  9190. submit_work_async2(work, &tv_work_found);
  9191. work = NULL; // Taken by submit_work_async2
  9192. out:
  9193. if (work)
  9194. free_work(work);
  9195. thread_reportin(thr);
  9196. return ret;
  9197. }
  9198. // return true of we should stop working on this piece of work
  9199. // returning false means we will keep scanning for a nonce
  9200. // assumptions: work->blk.nonce is the number of nonces completed in the work
  9201. // see minerloop_scanhash comments for more details & usage
  9202. bool abandon_work(struct work *work, struct timeval *wdiff, uint64_t max_hashes)
  9203. {
  9204. if (work->blk.nonce == 0xffffffff || // known we are scanning a full nonce range
  9205. wdiff->tv_sec > opt_scantime || // scan-time has elapsed (user specified, default 60s)
  9206. work->blk.nonce >= 0xfffffffe - max_hashes || // are there enough nonces left in the work
  9207. max_hashes >= 0xfffffffe || // assume we are scanning a full nonce range
  9208. stale_work(work, false)) // work is stale
  9209. return true;
  9210. return false;
  9211. }
  9212. void __thr_being_msg(int prio, struct thr_info *thr, const char *being)
  9213. {
  9214. struct cgpu_info *proc = thr->cgpu;
  9215. if (proc->threads > 1)
  9216. applog(prio, "%"PRIpreprv" (thread %d) %s", proc->proc_repr, thr->id, being);
  9217. else
  9218. applog(prio, "%"PRIpreprv" %s", proc->proc_repr, being);
  9219. }
  9220. // Called by asynchronous minerloops, when they find their processor should be disabled
  9221. void mt_disable_start(struct thr_info *mythr)
  9222. {
  9223. struct cgpu_info *cgpu = mythr->cgpu;
  9224. struct device_drv *drv = cgpu->drv;
  9225. if (drv->thread_disable)
  9226. drv->thread_disable(mythr);
  9227. hashmeter2(mythr);
  9228. __thr_being_msg(LOG_WARNING, mythr, "being disabled");
  9229. mythr->rolling = mythr->cgpu->rolling = 0;
  9230. thread_reportout(mythr);
  9231. mythr->_mt_disable_called = true;
  9232. }
  9233. /* Put a new unqueued work item in cgpu->unqueued_work under cgpu->qlock till
  9234. * the driver tells us it's full so that it may extract the work item using
  9235. * the get_queued() function which adds it to the hashtable on
  9236. * cgpu->queued_work. */
  9237. static void fill_queue(struct thr_info *mythr, struct cgpu_info *cgpu, struct device_drv *drv, const int thr_id)
  9238. {
  9239. thread_reportout(mythr);
  9240. do {
  9241. bool need_work;
  9242. /* Do this lockless just to know if we need more unqueued work. */
  9243. need_work = (!cgpu->unqueued_work);
  9244. /* get_work is a blocking function so do it outside of lock
  9245. * to prevent deadlocks with other locks. */
  9246. if (need_work) {
  9247. struct work *work = get_work(mythr);
  9248. wr_lock(&cgpu->qlock);
  9249. /* Check we haven't grabbed work somehow between
  9250. * checking and picking up the lock. */
  9251. if (likely(!cgpu->unqueued_work))
  9252. cgpu->unqueued_work = work;
  9253. else
  9254. need_work = false;
  9255. wr_unlock(&cgpu->qlock);
  9256. if (unlikely(!need_work))
  9257. discard_work(work);
  9258. }
  9259. /* The queue_full function should be used by the driver to
  9260. * actually place work items on the physical device if it
  9261. * does have a queue. */
  9262. } while (drv->queue_full && !drv->queue_full(cgpu));
  9263. }
  9264. /* Add a work item to a cgpu's queued hashlist */
  9265. void __add_queued(struct cgpu_info *cgpu, struct work *work)
  9266. {
  9267. cgpu->queued_count++;
  9268. HASH_ADD_INT(cgpu->queued_work, id, work);
  9269. }
  9270. /* This function is for retrieving one work item from the unqueued pointer and
  9271. * adding it to the hashtable of queued work. Code using this function must be
  9272. * able to handle NULL as a return which implies there is no work available. */
  9273. struct work *get_queued(struct cgpu_info *cgpu)
  9274. {
  9275. struct work *work = NULL;
  9276. wr_lock(&cgpu->qlock);
  9277. if (cgpu->unqueued_work) {
  9278. work = cgpu->unqueued_work;
  9279. if (unlikely(stale_work(work, false))) {
  9280. discard_work(work);
  9281. work = NULL;
  9282. wake_gws();
  9283. } else
  9284. __add_queued(cgpu, work);
  9285. cgpu->unqueued_work = NULL;
  9286. }
  9287. wr_unlock(&cgpu->qlock);
  9288. return work;
  9289. }
  9290. void add_queued(struct cgpu_info *cgpu, struct work *work)
  9291. {
  9292. wr_lock(&cgpu->qlock);
  9293. __add_queued(cgpu, work);
  9294. wr_unlock(&cgpu->qlock);
  9295. }
  9296. /* Get fresh work and add it to cgpu's queued hashlist */
  9297. struct work *get_queue_work(struct thr_info *thr, struct cgpu_info *cgpu, int thr_id)
  9298. {
  9299. struct work *work = get_work(thr);
  9300. add_queued(cgpu, work);
  9301. return work;
  9302. }
  9303. /* This function is for finding an already queued work item in the
  9304. * given que hashtable. Code using this function must be able
  9305. * to handle NULL as a return which implies there is no matching work.
  9306. * The calling function must lock access to the que if it is required.
  9307. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  9308. struct work *__find_work_bymidstate(struct work *que, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  9309. {
  9310. struct work *work, *tmp, *ret = NULL;
  9311. HASH_ITER(hh, que, work, tmp) {
  9312. if (memcmp(work->midstate, midstate, midstatelen) == 0 &&
  9313. memcmp(work->data + offset, data, datalen) == 0) {
  9314. ret = work;
  9315. break;
  9316. }
  9317. }
  9318. return ret;
  9319. }
  9320. /* This function is for finding an already queued work item in the
  9321. * device's queued_work hashtable. Code using this function must be able
  9322. * to handle NULL as a return which implies there is no matching work.
  9323. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  9324. struct work *find_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  9325. {
  9326. struct work *ret;
  9327. rd_lock(&cgpu->qlock);
  9328. ret = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  9329. rd_unlock(&cgpu->qlock);
  9330. return ret;
  9331. }
  9332. struct work *clone_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  9333. {
  9334. struct work *work, *ret = NULL;
  9335. rd_lock(&cgpu->qlock);
  9336. work = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  9337. if (work)
  9338. ret = copy_work(work);
  9339. rd_unlock(&cgpu->qlock);
  9340. return ret;
  9341. }
  9342. void __work_completed(struct cgpu_info *cgpu, struct work *work)
  9343. {
  9344. cgpu->queued_count--;
  9345. HASH_DEL(cgpu->queued_work, work);
  9346. }
  9347. /* This iterates over a queued hashlist finding work started more than secs
  9348. * seconds ago and discards the work as completed. The driver must set the
  9349. * work->tv_work_start value appropriately. Returns the number of items aged. */
  9350. int age_queued_work(struct cgpu_info *cgpu, double secs)
  9351. {
  9352. struct work *work, *tmp;
  9353. struct timeval tv_now;
  9354. int aged = 0;
  9355. cgtime(&tv_now);
  9356. wr_lock(&cgpu->qlock);
  9357. HASH_ITER(hh, cgpu->queued_work, work, tmp) {
  9358. if (tdiff(&tv_now, &work->tv_work_start) > secs) {
  9359. __work_completed(cgpu, work);
  9360. aged++;
  9361. }
  9362. }
  9363. wr_unlock(&cgpu->qlock);
  9364. return aged;
  9365. }
  9366. /* This function should be used by queued device drivers when they're sure
  9367. * the work struct is no longer in use. */
  9368. void work_completed(struct cgpu_info *cgpu, struct work *work)
  9369. {
  9370. wr_lock(&cgpu->qlock);
  9371. __work_completed(cgpu, work);
  9372. wr_unlock(&cgpu->qlock);
  9373. free_work(work);
  9374. }
  9375. /* Combines find_queued_work_bymidstate and work_completed in one function
  9376. * withOUT destroying the work so the driver must free it. */
  9377. struct work *take_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  9378. {
  9379. struct work *work;
  9380. wr_lock(&cgpu->qlock);
  9381. work = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  9382. if (work)
  9383. __work_completed(cgpu, work);
  9384. wr_unlock(&cgpu->qlock);
  9385. return work;
  9386. }
  9387. void flush_queue(struct cgpu_info *cgpu)
  9388. {
  9389. struct work *work = NULL;
  9390. wr_lock(&cgpu->qlock);
  9391. work = cgpu->unqueued_work;
  9392. cgpu->unqueued_work = NULL;
  9393. wr_unlock(&cgpu->qlock);
  9394. if (work) {
  9395. free_work(work);
  9396. applog(LOG_DEBUG, "Discarded queued work item");
  9397. }
  9398. }
  9399. /* This version of hash work is for devices that are fast enough to always
  9400. * perform a full nonce range and need a queue to maintain the device busy.
  9401. * Work creation and destruction is not done from within this function
  9402. * directly. */
  9403. void hash_queued_work(struct thr_info *mythr)
  9404. {
  9405. const long cycle = opt_log_interval / 5 ? : 1;
  9406. struct timeval tv_start = {0, 0}, tv_end;
  9407. struct cgpu_info *cgpu = mythr->cgpu;
  9408. struct device_drv *drv = cgpu->drv;
  9409. const int thr_id = mythr->id;
  9410. int64_t hashes_done = 0;
  9411. if (unlikely(cgpu->deven != DEV_ENABLED))
  9412. mt_disable(mythr);
  9413. while (likely(!cgpu->shutdown)) {
  9414. struct timeval diff;
  9415. int64_t hashes;
  9416. fill_queue(mythr, cgpu, drv, thr_id);
  9417. thread_reportin(mythr);
  9418. hashes = drv->scanwork(mythr);
  9419. /* Reset the bool here in case the driver looks for it
  9420. * synchronously in the scanwork loop. */
  9421. mythr->work_restart = false;
  9422. if (unlikely(hashes == -1 )) {
  9423. applog(LOG_ERR, "%s %d failure, disabling!", drv->name, cgpu->device_id);
  9424. cgpu->deven = DEV_DISABLED;
  9425. dev_error(cgpu, REASON_THREAD_ZERO_HASH);
  9426. mt_disable(mythr);
  9427. }
  9428. hashes_done += hashes;
  9429. cgtime(&tv_end);
  9430. timersub(&tv_end, &tv_start, &diff);
  9431. if (diff.tv_sec >= cycle) {
  9432. hashmeter(thr_id, &diff, hashes_done);
  9433. hashes_done = 0;
  9434. copy_time(&tv_start, &tv_end);
  9435. }
  9436. if (unlikely(mythr->pause || cgpu->deven != DEV_ENABLED))
  9437. mt_disable(mythr);
  9438. if (unlikely(mythr->work_restart)) {
  9439. flush_queue(cgpu);
  9440. if (drv->flush_work)
  9441. drv->flush_work(cgpu);
  9442. }
  9443. }
  9444. // cgpu->deven = DEV_DISABLED; set in miner_thread
  9445. }
  9446. // Called by minerloop, when it is re-enabling a processor
  9447. void mt_disable_finish(struct thr_info *mythr)
  9448. {
  9449. struct device_drv *drv = mythr->cgpu->drv;
  9450. thread_reportin(mythr);
  9451. __thr_being_msg(LOG_WARNING, mythr, "being re-enabled");
  9452. if (drv->thread_enable)
  9453. drv->thread_enable(mythr);
  9454. mythr->_mt_disable_called = false;
  9455. }
  9456. // Called by synchronous minerloops, when they find their processor should be disabled
  9457. // Calls mt_disable_start, waits until it's re-enabled, then calls mt_disable_finish
  9458. void mt_disable(struct thr_info *mythr)
  9459. {
  9460. const struct cgpu_info * const cgpu = mythr->cgpu;
  9461. mt_disable_start(mythr);
  9462. applog(LOG_DEBUG, "Waiting for wakeup notification in miner thread");
  9463. do {
  9464. notifier_read(mythr->notifier);
  9465. } while (mythr->pause || cgpu->deven != DEV_ENABLED);
  9466. mt_disable_finish(mythr);
  9467. }
  9468. enum {
  9469. STAT_SLEEP_INTERVAL = 1,
  9470. STAT_CTR_INTERVAL = 10000000,
  9471. FAILURE_INTERVAL = 30,
  9472. };
  9473. /* Stage another work item from the work returned in a longpoll */
  9474. 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)
  9475. {
  9476. bool rc;
  9477. work->rolltime = rolltime;
  9478. rc = work_decode(pool, work, val);
  9479. if (unlikely(!rc)) {
  9480. applog(LOG_ERR, "Could not convert longpoll data to work");
  9481. free_work(work);
  9482. return;
  9483. }
  9484. total_getworks++;
  9485. pool->getwork_requested++;
  9486. work->pool = pool;
  9487. copy_time(&work->tv_getwork, tv_lp);
  9488. copy_time(&work->tv_getwork_reply, tv_lp_reply);
  9489. calc_diff(work, 0);
  9490. if (pool->enabled == POOL_REJECTING)
  9491. work->mandatory = true;
  9492. work->longpoll = true;
  9493. work->getwork_mode = GETWORK_MODE_LP;
  9494. update_last_work(work);
  9495. /* We'll be checking this work item twice, but we already know it's
  9496. * from a new block so explicitly force the new block detection now
  9497. * rather than waiting for it to hit the stage thread. This also
  9498. * allows testwork to know whether LP discovered the block or not. */
  9499. test_work_current(work);
  9500. /* Don't use backup LPs as work if we have failover-only enabled. Use
  9501. * the longpoll work from a pool that has been rejecting shares as a
  9502. * way to detect when the pool has recovered.
  9503. */
  9504. if (pool != current_pool() && opt_fail_only && pool->enabled != POOL_REJECTING) {
  9505. free_work(work);
  9506. return;
  9507. }
  9508. work = clone_work(work);
  9509. applog(LOG_DEBUG, "Pushing converted work to stage thread");
  9510. stage_work(work);
  9511. applog(LOG_DEBUG, "Converted longpoll data to work");
  9512. }
  9513. /* If we want longpoll, enable it for the chosen default pool, or, if
  9514. * the pool does not support longpoll, find the first one that does
  9515. * and use its longpoll support */
  9516. static
  9517. struct pool *_select_longpoll_pool(struct pool *cp, bool(*func)(struct pool *))
  9518. {
  9519. int i;
  9520. if (func(cp))
  9521. return cp;
  9522. for (i = 0; i < total_pools; i++) {
  9523. struct pool *pool = pools[i];
  9524. if (cp->goal != pool->goal)
  9525. continue;
  9526. if (func(pool))
  9527. return pool;
  9528. }
  9529. return NULL;
  9530. }
  9531. /* This will make the longpoll thread wait till it's the current pool, or it
  9532. * has been flagged as rejecting, before attempting to open any connections.
  9533. */
  9534. static void wait_lpcurrent(struct pool *pool)
  9535. {
  9536. mutex_lock(&lp_lock);
  9537. while (!cnx_needed(pool))
  9538. {
  9539. pool->lp_active = false;
  9540. pthread_cond_wait(&lp_cond, &lp_lock);
  9541. }
  9542. mutex_unlock(&lp_lock);
  9543. }
  9544. static curl_socket_t save_curl_socket(void *vpool, __maybe_unused curlsocktype purpose, struct curl_sockaddr *addr) {
  9545. struct pool *pool = vpool;
  9546. curl_socket_t sock = bfg_socket(addr->family, addr->socktype, addr->protocol);
  9547. pool->lp_socket = sock;
  9548. return sock;
  9549. }
  9550. static void *longpoll_thread(void *userdata)
  9551. {
  9552. struct pool *cp = (struct pool *)userdata;
  9553. /* This *pool is the source of the actual longpoll, not the pool we've
  9554. * tied it to */
  9555. struct timeval start, reply, end;
  9556. struct pool *pool = NULL;
  9557. char threadname[20];
  9558. CURL *curl = NULL;
  9559. int failures = 0;
  9560. char *lp_url;
  9561. int rolltime;
  9562. #ifndef HAVE_PTHREAD_CANCEL
  9563. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  9564. #endif
  9565. snprintf(threadname, 20, "longpoll%u", cp->pool_no);
  9566. RenameThread(threadname);
  9567. curl = curl_easy_init();
  9568. if (unlikely(!curl)) {
  9569. applog(LOG_ERR, "CURL initialisation failed");
  9570. return NULL;
  9571. }
  9572. retry_pool:
  9573. pool = select_longpoll_pool(cp);
  9574. if (!pool) {
  9575. applog(LOG_WARNING, "No suitable long-poll found for %s", cp->rpc_url);
  9576. while (!pool) {
  9577. cgsleep_ms(60000);
  9578. pool = select_longpoll_pool(cp);
  9579. }
  9580. }
  9581. if (pool->has_stratum) {
  9582. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  9583. cp->rpc_url, pool->rpc_url);
  9584. goto out;
  9585. }
  9586. /* Any longpoll from any pool is enough for this to be true */
  9587. pool->goal->have_longpoll = true;
  9588. wait_lpcurrent(cp);
  9589. {
  9590. lp_url = pool->lp_url;
  9591. if (cp == pool)
  9592. applog(LOG_WARNING, "Long-polling activated for %s (%s)", lp_url, pool_protocol_name(pool->lp_proto));
  9593. else
  9594. applog(LOG_WARNING, "Long-polling activated for %s via %s (%s)", cp->rpc_url, lp_url, pool_protocol_name(pool->lp_proto));
  9595. }
  9596. while (42) {
  9597. json_t *val, *soval;
  9598. struct work *work = make_work();
  9599. char *lpreq;
  9600. lpreq = prepare_rpc_req(work, pool->lp_proto, pool->lp_id, pool);
  9601. work->pool = pool;
  9602. if (!lpreq)
  9603. {
  9604. free_work(work);
  9605. goto lpfail;
  9606. }
  9607. wait_lpcurrent(cp);
  9608. cgtime(&start);
  9609. /* Longpoll connections can be persistent for a very long time
  9610. * and any number of issues could have come up in the meantime
  9611. * so always establish a fresh connection instead of relying on
  9612. * a persistent one. */
  9613. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  9614. curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, save_curl_socket);
  9615. curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, pool);
  9616. val = json_rpc_call(curl, lp_url, pool->rpc_userpass,
  9617. lpreq, false, true, &rolltime, pool, false);
  9618. pool->lp_socket = CURL_SOCKET_BAD;
  9619. cgtime(&reply);
  9620. free(lpreq);
  9621. if (likely(val)) {
  9622. soval = json_object_get(json_object_get(val, "result"), "submitold");
  9623. if (soval)
  9624. pool->submit_old = json_is_true(soval);
  9625. else
  9626. pool->submit_old = false;
  9627. convert_to_work(val, rolltime, pool, work, &start, &reply);
  9628. failures = 0;
  9629. json_decref(val);
  9630. } else {
  9631. /* Some pools regularly drop the longpoll request so
  9632. * only see this as longpoll failure if it happens
  9633. * immediately and just restart it the rest of the
  9634. * time. */
  9635. cgtime(&end);
  9636. free_work(work);
  9637. if (end.tv_sec - start.tv_sec <= 30)
  9638. {
  9639. if (failures == 1)
  9640. applog(LOG_WARNING, "longpoll failed for %s, retrying every 30s", lp_url);
  9641. lpfail:
  9642. cgsleep_ms(30000);
  9643. }
  9644. }
  9645. if (pool != cp) {
  9646. pool = select_longpoll_pool(cp);
  9647. if (pool->has_stratum) {
  9648. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  9649. cp->rpc_url, pool->rpc_url);
  9650. break;
  9651. }
  9652. if (unlikely(!pool))
  9653. goto retry_pool;
  9654. }
  9655. if (unlikely(pool->removed))
  9656. break;
  9657. }
  9658. out:
  9659. pool->lp_active = false;
  9660. curl_easy_cleanup(curl);
  9661. return NULL;
  9662. }
  9663. static void stop_longpoll(void)
  9664. {
  9665. int i;
  9666. want_longpoll = false;
  9667. for (i = 0; i < total_pools; ++i)
  9668. {
  9669. struct pool *pool = pools[i];
  9670. if (unlikely(!pool->lp_started))
  9671. continue;
  9672. pool->lp_started = false;
  9673. pthread_cancel(pool->longpoll_thread);
  9674. }
  9675. struct mining_goal_info *goal, *tmpgoal;
  9676. HASH_ITER(hh, mining_goals, goal, tmpgoal)
  9677. {
  9678. goal->have_longpoll = false;
  9679. }
  9680. }
  9681. static void start_longpoll(void)
  9682. {
  9683. int i;
  9684. want_longpoll = true;
  9685. for (i = 0; i < total_pools; ++i)
  9686. {
  9687. struct pool *pool = pools[i];
  9688. if (unlikely(pool->removed || pool->lp_started || !pool->lp_url))
  9689. continue;
  9690. pool->lp_started = true;
  9691. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  9692. quit(1, "Failed to create pool longpoll thread");
  9693. }
  9694. }
  9695. void reinit_device(struct cgpu_info *cgpu)
  9696. {
  9697. if (cgpu->drv->reinit_device)
  9698. cgpu->drv->reinit_device(cgpu);
  9699. }
  9700. static struct timeval rotate_tv;
  9701. /* We reap curls if they are unused for over a minute */
  9702. static void reap_curl(struct pool *pool)
  9703. {
  9704. struct curl_ent *ent, *iter;
  9705. struct timeval now;
  9706. int reaped = 0;
  9707. cgtime(&now);
  9708. mutex_lock(&pool->pool_lock);
  9709. LL_FOREACH_SAFE(pool->curllist, ent, iter) {
  9710. if (pool->curls < 2)
  9711. break;
  9712. if (now.tv_sec - ent->tv.tv_sec > 300) {
  9713. reaped++;
  9714. pool->curls--;
  9715. LL_DELETE(pool->curllist, ent);
  9716. curl_easy_cleanup(ent->curl);
  9717. free(ent);
  9718. }
  9719. }
  9720. mutex_unlock(&pool->pool_lock);
  9721. if (reaped)
  9722. applog(LOG_DEBUG, "Reaped %d curl%s from pool %d", reaped, reaped > 1 ? "s" : "", pool->pool_no);
  9723. }
  9724. static void *watchpool_thread(void __maybe_unused *userdata)
  9725. {
  9726. int intervals = 0;
  9727. #ifndef HAVE_PTHREAD_CANCEL
  9728. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  9729. #endif
  9730. RenameThread("watchpool");
  9731. while (42) {
  9732. struct timeval now;
  9733. int i;
  9734. if (++intervals > 20)
  9735. intervals = 0;
  9736. cgtime(&now);
  9737. for (i = 0; i < total_pools; i++) {
  9738. struct pool *pool = pools[i];
  9739. if (!opt_benchmark)
  9740. reap_curl(pool);
  9741. /* Get a rolling utility per pool over 10 mins */
  9742. if (intervals > 19) {
  9743. int shares = pool->diff1 - pool->last_shares;
  9744. pool->last_shares = pool->diff1;
  9745. pool->utility = (pool->utility + (double)shares * 0.63) / 1.63;
  9746. pool->shares = pool->utility;
  9747. }
  9748. if (pool->enabled == POOL_DISABLED)
  9749. continue;
  9750. /* Don't start testing any pools if the test threads
  9751. * from startup are still doing their first attempt. */
  9752. if (unlikely(pool->testing)) {
  9753. pthread_join(pool->test_thread, NULL);
  9754. }
  9755. /* Test pool is idle once every minute */
  9756. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 30) {
  9757. if (pool_active(pool, true) && pool_tclear(pool, &pool->idle))
  9758. pool_resus(pool);
  9759. }
  9760. /* Only switch pools if the failback pool has been
  9761. * alive for more than 5 minutes (default) to prevent
  9762. * intermittently failing pools from being used. */
  9763. 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)
  9764. {
  9765. if (opt_fail_switch_delay % 60)
  9766. applog(LOG_WARNING, "Pool %d %s stable for %d second%s",
  9767. pool->pool_no, pool->rpc_url,
  9768. opt_fail_switch_delay,
  9769. (opt_fail_switch_delay == 1 ? "" : "s"));
  9770. else
  9771. applog(LOG_WARNING, "Pool %d %s stable for %d minute%s",
  9772. pool->pool_no, pool->rpc_url,
  9773. opt_fail_switch_delay / 60,
  9774. (opt_fail_switch_delay == 60 ? "" : "s"));
  9775. switch_pools(NULL);
  9776. }
  9777. }
  9778. if (current_pool()->idle)
  9779. switch_pools(NULL);
  9780. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  9781. cgtime(&rotate_tv);
  9782. switch_pools(NULL);
  9783. }
  9784. cgsleep_ms(30000);
  9785. }
  9786. return NULL;
  9787. }
  9788. void mt_enable(struct thr_info *thr)
  9789. {
  9790. applog(LOG_DEBUG, "Waking up thread %d", thr->id);
  9791. notifier_wake(thr->notifier);
  9792. }
  9793. void proc_enable(struct cgpu_info *cgpu)
  9794. {
  9795. int j;
  9796. cgpu->deven = DEV_ENABLED;
  9797. for (j = cgpu->threads ?: 1; j--; )
  9798. mt_enable(cgpu->thr[j]);
  9799. }
  9800. #define device_recovered(cgpu) proc_enable(cgpu)
  9801. void cgpu_set_defaults(struct cgpu_info * const cgpu)
  9802. {
  9803. struct string_elist *setstr_elist;
  9804. const char *p, *p2;
  9805. char replybuf[0x2000];
  9806. size_t L;
  9807. DL_FOREACH(opt_set_device_list, setstr_elist)
  9808. {
  9809. const char * const setstr = setstr_elist->string;
  9810. p = strchr(setstr, ':');
  9811. if (!p)
  9812. p = setstr;
  9813. {
  9814. L = p - setstr;
  9815. char pattern[L + 1];
  9816. if (L)
  9817. memcpy(pattern, setstr, L);
  9818. pattern[L] = '\0';
  9819. if (!cgpu_match(pattern, cgpu))
  9820. continue;
  9821. }
  9822. applog(LOG_DEBUG, "%"PRIpreprv": %s: Matched with set default: %s",
  9823. cgpu->proc_repr, __func__, setstr);
  9824. if (p[0] == ':')
  9825. ++p;
  9826. p2 = strchr(p, '=');
  9827. if (!p2)
  9828. {
  9829. L = strlen(p);
  9830. p2 = "";
  9831. }
  9832. else
  9833. {
  9834. L = p2 - p;
  9835. ++p2;
  9836. }
  9837. char opt[L + 1];
  9838. if (L)
  9839. memcpy(opt, p, L);
  9840. opt[L] = '\0';
  9841. L = strlen(p2);
  9842. char setval[L + 1];
  9843. if (L)
  9844. memcpy(setval, p2, L);
  9845. setval[L] = '\0';
  9846. enum bfg_set_device_replytype success;
  9847. p = proc_set_device(cgpu, opt, setval, replybuf, &success);
  9848. switch (success)
  9849. {
  9850. case SDR_OK:
  9851. applog(LOG_DEBUG, "%"PRIpreprv": Applied rule %s%s%s",
  9852. cgpu->proc_repr, setstr,
  9853. p ? ": " : "", p ?: "");
  9854. break;
  9855. case SDR_ERR:
  9856. case SDR_HELP:
  9857. case SDR_UNKNOWN:
  9858. applog(LOG_DEBUG, "%"PRIpreprv": Applying rule %s: %s",
  9859. cgpu->proc_repr, setstr, p);
  9860. break;
  9861. case SDR_AUTO:
  9862. case SDR_NOSUPP:
  9863. applog(LOG_DEBUG, "%"PRIpreprv": set_device is not implemented (trying to apply rule: %s)",
  9864. cgpu->proc_repr, setstr);
  9865. }
  9866. }
  9867. cgpu->already_set_defaults = true;
  9868. }
  9869. 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)
  9870. {
  9871. struct device_drv dummy_drv = *drv;
  9872. struct cgpu_info dummy_cgpu = {
  9873. .drv = &dummy_drv,
  9874. .device = &dummy_cgpu,
  9875. .device_id = -1,
  9876. .proc_id = -1,
  9877. .device_data = userp,
  9878. .device_path = devpath,
  9879. .dev_serial = serial,
  9880. };
  9881. strcpy(dummy_cgpu.proc_repr, drv->name);
  9882. switch (mode)
  9883. {
  9884. case 0:
  9885. dummy_drv.set_device = datap;
  9886. break;
  9887. case 1:
  9888. dummy_drv.set_device = NULL;
  9889. dummy_cgpu.set_device_funcs = datap;
  9890. break;
  9891. }
  9892. cgpu_set_defaults(&dummy_cgpu);
  9893. }
  9894. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  9895. * the screen at regular intervals, and restarts threads if they appear to have
  9896. * died. */
  9897. #define WATCHDOG_SICK_TIME 60
  9898. #define WATCHDOG_DEAD_TIME 600
  9899. #define WATCHDOG_SICK_COUNT (WATCHDOG_SICK_TIME/WATCHDOG_INTERVAL)
  9900. #define WATCHDOG_DEAD_COUNT (WATCHDOG_DEAD_TIME/WATCHDOG_INTERVAL)
  9901. static void *watchdog_thread(void __maybe_unused *userdata)
  9902. {
  9903. const unsigned int interval = WATCHDOG_INTERVAL;
  9904. struct timeval zero_tv;
  9905. #ifndef HAVE_PTHREAD_CANCEL
  9906. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  9907. #endif
  9908. RenameThread("watchdog");
  9909. memset(&zero_tv, 0, sizeof(struct timeval));
  9910. cgtime(&rotate_tv);
  9911. while (1) {
  9912. int i;
  9913. struct timeval now;
  9914. sleep(interval);
  9915. discard_stale();
  9916. hashmeter(-1, &zero_tv, 0);
  9917. #ifdef HAVE_CURSES
  9918. const int ts = total_staged();
  9919. if (curses_active_locked()) {
  9920. change_logwinsize();
  9921. curses_print_status(ts);
  9922. _refresh_devstatus(true);
  9923. touchwin(logwin);
  9924. wrefresh(logwin);
  9925. unlock_curses();
  9926. }
  9927. #endif
  9928. cgtime(&now);
  9929. if (!sched_paused && !should_run()) {
  9930. applog(LOG_WARNING, "Pausing execution as per stop time %02d:%02d scheduled",
  9931. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  9932. if (!schedstart.enable) {
  9933. quit(0, "Terminating execution as planned");
  9934. break;
  9935. }
  9936. applog(LOG_WARNING, "Will restart execution as scheduled at %02d:%02d",
  9937. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  9938. sched_paused = true;
  9939. rd_lock(&mining_thr_lock);
  9940. for (i = 0; i < mining_threads; i++)
  9941. mining_thr[i]->pause = true;
  9942. rd_unlock(&mining_thr_lock);
  9943. } else if (sched_paused && should_run()) {
  9944. applog(LOG_WARNING, "Restarting execution as per start time %02d:%02d scheduled",
  9945. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  9946. if (schedstop.enable)
  9947. applog(LOG_WARNING, "Will pause execution as scheduled at %02d:%02d",
  9948. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  9949. sched_paused = false;
  9950. for (i = 0; i < mining_threads; i++) {
  9951. struct thr_info *thr;
  9952. thr = get_thread(i);
  9953. thr->pause = false;
  9954. }
  9955. for (i = 0; i < total_devices; ++i)
  9956. {
  9957. struct cgpu_info *cgpu = get_devices(i);
  9958. /* Don't touch disabled devices */
  9959. if (cgpu->deven == DEV_DISABLED)
  9960. continue;
  9961. proc_enable(cgpu);
  9962. }
  9963. }
  9964. for (i = 0; i < total_devices; ++i) {
  9965. struct cgpu_info *cgpu = get_devices(i);
  9966. if (!cgpu->disable_watchdog)
  9967. bfg_watchdog(cgpu, &now);
  9968. }
  9969. }
  9970. return NULL;
  9971. }
  9972. void bfg_watchdog(struct cgpu_info * const cgpu, struct timeval * const tvp_now)
  9973. {
  9974. struct thr_info *thr = cgpu->thr[0];
  9975. enum dev_enable *denable;
  9976. char *dev_str = cgpu->proc_repr;
  9977. if (likely(drv_ready(cgpu)))
  9978. {
  9979. if (unlikely(!cgpu->already_set_defaults))
  9980. cgpu_set_defaults(cgpu);
  9981. if (cgpu->drv->get_stats)
  9982. cgpu->drv->get_stats(cgpu);
  9983. }
  9984. denable = &cgpu->deven;
  9985. if (cgpu->drv->watchdog)
  9986. cgpu->drv->watchdog(cgpu, tvp_now);
  9987. /* Thread is disabled */
  9988. if (*denable == DEV_DISABLED)
  9989. return;
  9990. else
  9991. if (*denable == DEV_RECOVER_ERR) {
  9992. if (opt_restart && timer_elapsed(&cgpu->tv_device_last_not_well, NULL) > cgpu->reinit_backoff) {
  9993. applog(LOG_NOTICE, "Attempting to reinitialize %s",
  9994. dev_str);
  9995. if (cgpu->reinit_backoff < 300)
  9996. cgpu->reinit_backoff *= 2;
  9997. device_recovered(cgpu);
  9998. }
  9999. return;
  10000. }
  10001. else
  10002. if (*denable == DEV_RECOVER) {
  10003. if (opt_restart && cgpu->temp < cgpu->targettemp) {
  10004. applog(LOG_NOTICE, "%s recovered to temperature below target, re-enabling",
  10005. dev_str);
  10006. device_recovered(cgpu);
  10007. }
  10008. dev_error_update(cgpu, REASON_DEV_THERMAL_CUTOFF);
  10009. return;
  10010. }
  10011. else
  10012. if (cgpu->temp > cgpu->cutofftemp)
  10013. {
  10014. applog(LOG_WARNING, "%s hit thermal cutoff limit at %dC, disabling!",
  10015. dev_str, (int)cgpu->temp);
  10016. *denable = DEV_RECOVER;
  10017. dev_error(cgpu, REASON_DEV_THERMAL_CUTOFF);
  10018. run_cmd(cmd_idle);
  10019. }
  10020. if (thr->getwork) {
  10021. if (cgpu->status == LIFE_WELL && thr->getwork < tvp_now->tv_sec - opt_log_interval) {
  10022. int thrid;
  10023. bool cgpu_idle = true;
  10024. thr->rolling = 0;
  10025. for (thrid = 0; thrid < cgpu->threads; ++thrid)
  10026. if (!cgpu->thr[thrid]->getwork)
  10027. cgpu_idle = false;
  10028. if (cgpu_idle) {
  10029. cgpu->rolling = 0;
  10030. cgpu->status = LIFE_WAIT;
  10031. }
  10032. }
  10033. return;
  10034. }
  10035. else if (cgpu->status == LIFE_WAIT)
  10036. cgpu->status = LIFE_WELL;
  10037. #ifdef WANT_CPUMINE
  10038. if (!strcmp(cgpu->drv->dname, "cpu"))
  10039. return;
  10040. #endif
  10041. if (cgpu->status != LIFE_WELL && (tvp_now->tv_sec - thr->last.tv_sec < WATCHDOG_SICK_TIME)) {
  10042. if (likely(cgpu->status != LIFE_INIT && cgpu->status != LIFE_INIT2))
  10043. applog(LOG_ERR, "%s: Recovered, declaring WELL!", dev_str);
  10044. cgpu->status = LIFE_WELL;
  10045. cgpu->device_last_well = time(NULL);
  10046. } else if (cgpu->status == LIFE_WELL && (tvp_now->tv_sec - thr->last.tv_sec > WATCHDOG_SICK_TIME)) {
  10047. thr->rolling = cgpu->rolling = 0;
  10048. cgpu->status = LIFE_SICK;
  10049. applog(LOG_ERR, "%s: Idle for more than 60 seconds, declaring SICK!", dev_str);
  10050. cgtime(&thr->sick);
  10051. dev_error(cgpu, REASON_DEV_SICK_IDLE_60);
  10052. run_cmd(cmd_sick);
  10053. if (opt_restart && cgpu->drv->reinit_device) {
  10054. applog(LOG_ERR, "%s: Attempting to restart", dev_str);
  10055. reinit_device(cgpu);
  10056. }
  10057. } else if (cgpu->status == LIFE_SICK && (tvp_now->tv_sec - thr->last.tv_sec > WATCHDOG_DEAD_TIME)) {
  10058. cgpu->status = LIFE_DEAD;
  10059. applog(LOG_ERR, "%s: Not responded for more than 10 minutes, declaring DEAD!", dev_str);
  10060. cgtime(&thr->sick);
  10061. dev_error(cgpu, REASON_DEV_DEAD_IDLE_600);
  10062. run_cmd(cmd_dead);
  10063. } else if (tvp_now->tv_sec - thr->sick.tv_sec > 60 &&
  10064. (cgpu->status == LIFE_SICK || cgpu->status == LIFE_DEAD)) {
  10065. /* Attempt to restart a GPU that's sick or dead once every minute */
  10066. cgtime(&thr->sick);
  10067. if (opt_restart)
  10068. reinit_device(cgpu);
  10069. }
  10070. }
  10071. static void log_print_status(struct cgpu_info *cgpu)
  10072. {
  10073. char logline[255];
  10074. get_statline(logline, sizeof(logline), cgpu);
  10075. applog(LOG_WARNING, "%s", logline);
  10076. }
  10077. void print_summary(void)
  10078. {
  10079. struct timeval diff;
  10080. int hours, mins, secs, i;
  10081. double utility, efficiency = 0.0;
  10082. char xfer[(ALLOC_H2B_SPACED*2)+4+1], bw[(ALLOC_H2B_SPACED*2)+6+1];
  10083. int pool_secs;
  10084. timersub(&total_tv_end, &total_tv_start, &diff);
  10085. hours = diff.tv_sec / 3600;
  10086. mins = (diff.tv_sec % 3600) / 60;
  10087. secs = diff.tv_sec % 60;
  10088. utility = total_accepted / total_secs * 60;
  10089. efficiency = total_bytes_xfer ? total_diff_accepted * 2048. / total_bytes_xfer : 0.0;
  10090. applog(LOG_WARNING, "\nSummary of runtime statistics:\n");
  10091. applog(LOG_WARNING, "Started at %s", datestamp);
  10092. if (total_pools == 1)
  10093. applog(LOG_WARNING, "Pool: %s", pools[0]->rpc_url);
  10094. #ifdef WANT_CPUMINE
  10095. if (opt_n_threads > 0)
  10096. applog(LOG_WARNING, "CPU hasher algorithm used: %s", algo_names[opt_algo]);
  10097. #endif
  10098. applog(LOG_WARNING, "Runtime: %d hrs : %d mins : %d secs", hours, mins, secs);
  10099. applog(LOG_WARNING, "Average hashrate: %.1f Megahash/s", total_mhashes_done / total_secs);
  10100. applog(LOG_WARNING, "Solved blocks: %d", found_blocks);
  10101. applog(LOG_WARNING, "Best share difficulty: %s", best_share);
  10102. applog(LOG_WARNING, "Share submissions: %d", total_accepted + total_rejected);
  10103. applog(LOG_WARNING, "Accepted shares: %d", total_accepted);
  10104. applog(LOG_WARNING, "Rejected shares: %d + %d stale (%.2f%%)",
  10105. total_rejected, total_stale,
  10106. (float)(total_rejected + total_stale) / (float)(total_rejected + total_stale + total_accepted)
  10107. );
  10108. applog(LOG_WARNING, "Accepted difficulty shares: %1.f", total_diff_accepted);
  10109. applog(LOG_WARNING, "Rejected difficulty shares: %1.f", total_diff_rejected);
  10110. applog(LOG_WARNING, "Hardware errors: %d", hw_errors);
  10111. applog(LOG_WARNING, "Network transfer: %s (%s)",
  10112. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  10113. (float)total_bytes_rcvd,
  10114. (float)total_bytes_sent),
  10115. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  10116. (float)(total_bytes_rcvd / total_secs),
  10117. (float)(total_bytes_sent / total_secs)));
  10118. applog(LOG_WARNING, "Efficiency (accepted shares * difficulty / 2 KB): %.2f", efficiency);
  10119. applog(LOG_WARNING, "Utility (accepted shares / min): %.2f/min\n", utility);
  10120. applog(LOG_WARNING, "Unable to get work from server occasions: %d", total_go);
  10121. applog(LOG_WARNING, "Work items generated locally: %d", local_work);
  10122. applog(LOG_WARNING, "Submitting work remotely delay occasions: %d", total_ro);
  10123. applog(LOG_WARNING, "New blocks detected on network: %d\n", new_blocks);
  10124. if (total_pools > 1) {
  10125. for (i = 0; i < total_pools; i++) {
  10126. struct pool *pool = pools[i];
  10127. applog(LOG_WARNING, "Pool: %s", pool->rpc_url);
  10128. if (pool->solved)
  10129. applog(LOG_WARNING, "SOLVED %d BLOCK%s!", pool->solved, pool->solved > 1 ? "S" : "");
  10130. applog(LOG_WARNING, " Share submissions: %d", pool->accepted + pool->rejected);
  10131. applog(LOG_WARNING, " Accepted shares: %d", pool->accepted);
  10132. applog(LOG_WARNING, " Rejected shares: %d + %d stale (%.2f%%)",
  10133. pool->rejected, pool->stale_shares,
  10134. (float)(pool->rejected + pool->stale_shares) / (float)(pool->rejected + pool->stale_shares + pool->accepted)
  10135. );
  10136. applog(LOG_WARNING, " Accepted difficulty shares: %1.f", pool->diff_accepted);
  10137. applog(LOG_WARNING, " Rejected difficulty shares: %1.f", pool->diff_rejected);
  10138. pool_secs = timer_elapsed(&pool->cgminer_stats.start_tv, NULL);
  10139. applog(LOG_WARNING, " Network transfer: %s (%s)",
  10140. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  10141. (float)pool->cgminer_pool_stats.net_bytes_received,
  10142. (float)pool->cgminer_pool_stats.net_bytes_sent),
  10143. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  10144. (float)(pool->cgminer_pool_stats.net_bytes_received / pool_secs),
  10145. (float)(pool->cgminer_pool_stats.net_bytes_sent / pool_secs)));
  10146. uint64_t pool_bytes_xfer = pool->cgminer_pool_stats.net_bytes_received + pool->cgminer_pool_stats.net_bytes_sent;
  10147. efficiency = pool_bytes_xfer ? pool->diff_accepted * 2048. / pool_bytes_xfer : 0.0;
  10148. applog(LOG_WARNING, " Efficiency (accepted * difficulty / 2 KB): %.2f", efficiency);
  10149. applog(LOG_WARNING, " Items worked on: %d", pool->works);
  10150. applog(LOG_WARNING, " Unable to get work from server occasions: %d", pool->getfail_occasions);
  10151. applog(LOG_WARNING, " Submitting work remotely delay occasions: %d\n", pool->remotefail_occasions);
  10152. }
  10153. }
  10154. if (opt_quit_summary != BQS_NONE)
  10155. {
  10156. if (opt_quit_summary == BQS_DEFAULT)
  10157. {
  10158. if (total_devices < 25)
  10159. opt_quit_summary = BQS_PROCS;
  10160. else
  10161. opt_quit_summary = BQS_DEVS;
  10162. }
  10163. if (opt_quit_summary == BQS_DETAILED)
  10164. include_serial_in_statline = true;
  10165. applog(LOG_WARNING, "Summary of per device statistics:\n");
  10166. for (i = 0; i < total_devices; ++i) {
  10167. struct cgpu_info *cgpu = get_devices(i);
  10168. if (!cgpu->proc_id)
  10169. {
  10170. // Device summary line
  10171. opt_show_procs = false;
  10172. log_print_status(cgpu);
  10173. opt_show_procs = true;
  10174. }
  10175. if ((opt_quit_summary == BQS_PROCS || opt_quit_summary == BQS_DETAILED) && cgpu->procs > 1)
  10176. log_print_status(cgpu);
  10177. }
  10178. }
  10179. if (opt_shares) {
  10180. applog(LOG_WARNING, "Mined %g accepted shares of %g requested\n", total_diff_accepted, opt_shares);
  10181. if (opt_shares > total_diff_accepted)
  10182. applog(LOG_WARNING, "WARNING - Mined only %g shares of %g requested.", total_diff_accepted, opt_shares);
  10183. }
  10184. applog(LOG_WARNING, " ");
  10185. fflush(stderr);
  10186. fflush(stdout);
  10187. }
  10188. void _bfg_clean_up(bool restarting)
  10189. {
  10190. #ifdef HAVE_OPENCL
  10191. clear_adl(nDevs);
  10192. #endif
  10193. #ifdef HAVE_LIBUSB
  10194. if (likely(have_libusb))
  10195. libusb_exit(NULL);
  10196. #endif
  10197. cgtime(&total_tv_end);
  10198. #ifdef WIN32
  10199. timeEndPeriod(1);
  10200. #endif
  10201. if (!restarting) {
  10202. /* Attempting to disable curses or print a summary during a
  10203. * restart can lead to a deadlock. */
  10204. #ifdef HAVE_CURSES
  10205. disable_curses();
  10206. #endif
  10207. if (!opt_realquiet && successful_connect)
  10208. print_summary();
  10209. }
  10210. if (opt_n_threads > 0)
  10211. free(cpus);
  10212. curl_global_cleanup();
  10213. #ifdef WIN32
  10214. WSACleanup();
  10215. #endif
  10216. }
  10217. void _quit(int status)
  10218. {
  10219. if (status) {
  10220. const char *ev = getenv("__BFGMINER_SEGFAULT_ERRQUIT");
  10221. if (unlikely(ev && ev[0] && ev[0] != '0')) {
  10222. int *p = NULL;
  10223. // NOTE debugger can bypass with: p = &p
  10224. *p = status; // Segfault, hopefully dumping core
  10225. }
  10226. }
  10227. #if defined(unix) || defined(__APPLE__)
  10228. if (forkpid > 0) {
  10229. kill(forkpid, SIGTERM);
  10230. forkpid = 0;
  10231. }
  10232. #endif
  10233. exit(status);
  10234. }
  10235. #ifdef HAVE_CURSES
  10236. char *curses_input(const char *query)
  10237. {
  10238. char *input;
  10239. echo();
  10240. input = malloc(255);
  10241. if (!input)
  10242. quit(1, "Failed to malloc input");
  10243. leaveok(logwin, false);
  10244. wlogprint("%s:\n", query);
  10245. wgetnstr(logwin, input, 255);
  10246. if (!strlen(input))
  10247. {
  10248. free(input);
  10249. input = NULL;
  10250. }
  10251. leaveok(logwin, true);
  10252. noecho();
  10253. return input;
  10254. }
  10255. #endif
  10256. static void *test_pool_thread(void *arg)
  10257. {
  10258. struct pool *pool = (struct pool *)arg;
  10259. if (pool_active(pool, false)) {
  10260. pool_tset(pool, &pool->lagging);
  10261. pool_tclear(pool, &pool->idle);
  10262. bool first_pool = false;
  10263. cg_wlock(&control_lock);
  10264. if (!pools_active) {
  10265. currentpool = pool;
  10266. if (pool->pool_no != 0)
  10267. first_pool = true;
  10268. pools_active = true;
  10269. }
  10270. cg_wunlock(&control_lock);
  10271. if (unlikely(first_pool))
  10272. applog(LOG_NOTICE, "Switching to pool %d %s - first alive pool", pool->pool_no, pool->rpc_url);
  10273. else
  10274. applog(LOG_NOTICE, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  10275. switch_pools(NULL);
  10276. } else
  10277. pool_died(pool);
  10278. pool->testing = false;
  10279. return NULL;
  10280. }
  10281. /* Always returns true that the pool details were added unless we are not
  10282. * live, implying this is the only pool being added, so if no pools are
  10283. * active it returns false. */
  10284. bool add_pool_details(struct pool *pool, bool live, char *url, char *user, char *pass)
  10285. {
  10286. size_t siz;
  10287. pool_set_uri(pool, url);
  10288. pool->rpc_user = user;
  10289. pool->rpc_pass = pass;
  10290. siz = strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2;
  10291. pool->rpc_userpass = malloc(siz);
  10292. if (!pool->rpc_userpass)
  10293. quit(1, "Failed to malloc userpass");
  10294. snprintf(pool->rpc_userpass, siz, "%s:%s", pool->rpc_user, pool->rpc_pass);
  10295. pool->testing = true;
  10296. pool->idle = true;
  10297. enable_pool(pool);
  10298. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  10299. if (!live) {
  10300. pthread_join(pool->test_thread, NULL);
  10301. return pools_active;
  10302. }
  10303. return true;
  10304. }
  10305. #ifdef HAVE_CURSES
  10306. static bool input_pool(bool live)
  10307. {
  10308. char *url = NULL, *user = NULL, *pass = NULL;
  10309. struct pool *pool;
  10310. bool ret = false;
  10311. immedok(logwin, true);
  10312. wlogprint("Input server details.\n");
  10313. url = curses_input("URL");
  10314. if (!url)
  10315. goto out;
  10316. user = curses_input("Username");
  10317. if (!user)
  10318. goto out;
  10319. pass = curses_input("Password");
  10320. if (!pass)
  10321. pass = calloc(1, 1);
  10322. pool = add_pool();
  10323. if (!detect_stratum(pool, url) && strncmp(url, "http://", 7) &&
  10324. strncmp(url, "https://", 8)) {
  10325. char *httpinput;
  10326. httpinput = malloc(256);
  10327. if (!httpinput)
  10328. quit(1, "Failed to malloc httpinput");
  10329. strcpy(httpinput, "http://");
  10330. strncat(httpinput, url, 248);
  10331. free(url);
  10332. url = httpinput;
  10333. }
  10334. ret = add_pool_details(pool, live, url, user, pass);
  10335. out:
  10336. immedok(logwin, false);
  10337. if (!ret) {
  10338. if (url)
  10339. free(url);
  10340. if (user)
  10341. free(user);
  10342. if (pass)
  10343. free(pass);
  10344. }
  10345. return ret;
  10346. }
  10347. #endif
  10348. #if BLKMAKER_VERSION > 1
  10349. static
  10350. bool _add_local_gbt(const char * const filepath, void *userp)
  10351. {
  10352. const bool * const live_p = userp;
  10353. struct pool *pool;
  10354. char buf[0x100];
  10355. char *rpcuser = NULL, *rpcpass = NULL, *rpcconnect = NULL;
  10356. int rpcport = 0, rpcssl = -101;
  10357. FILE * const F = fopen(filepath, "r");
  10358. if (!F)
  10359. applogr(false, LOG_WARNING, "%s: Failed to open %s for reading", "add_local_gbt", filepath);
  10360. while (fgets(buf, sizeof(buf), F))
  10361. {
  10362. if (!strncasecmp(buf, "rpcuser=", 8))
  10363. rpcuser = trimmed_strdup(&buf[8]);
  10364. else
  10365. if (!strncasecmp(buf, "rpcpassword=", 12))
  10366. rpcpass = trimmed_strdup(&buf[12]);
  10367. else
  10368. if (!strncasecmp(buf, "rpcport=", 8))
  10369. rpcport = atoi(&buf[8]);
  10370. else
  10371. if (!strncasecmp(buf, "rpcssl=", 7))
  10372. rpcssl = atoi(&buf[7]);
  10373. else
  10374. if (!strncasecmp(buf, "rpcconnect=", 11))
  10375. rpcconnect = trimmed_strdup(&buf[11]);
  10376. else
  10377. continue;
  10378. if (rpcuser && rpcpass && rpcport && rpcssl != -101 && rpcconnect)
  10379. break;
  10380. }
  10381. fclose(F);
  10382. if (!rpcpass)
  10383. {
  10384. applog(LOG_DEBUG, "%s: Did not find rpcpassword in %s", "add_local_gbt", filepath);
  10385. err:
  10386. free(rpcuser);
  10387. free(rpcpass);
  10388. goto out;
  10389. }
  10390. if (!rpcport)
  10391. rpcport = 8332;
  10392. if (rpcssl == -101)
  10393. rpcssl = 0;
  10394. const bool have_cbaddr = get_mining_goal("default")->generation_script;
  10395. const int uri_sz = 0x30;
  10396. char * const uri = malloc(uri_sz);
  10397. snprintf(uri, uri_sz, "http%s://%s:%d/%s#allblocks", rpcssl ? "s" : "", rpcconnect ?: "localhost", rpcport, have_cbaddr ? "" : "#getcbaddr");
  10398. char hfuri[0x40];
  10399. if (rpcconnect)
  10400. snprintf(hfuri, sizeof(hfuri), "%s:%d", rpcconnect, rpcport);
  10401. else
  10402. snprintf(hfuri, sizeof(hfuri), "port %d", rpcport);
  10403. applog(LOG_DEBUG, "Local bitcoin RPC server on %s found in %s", hfuri, filepath);
  10404. for (int i = 0; i < total_pools; ++i)
  10405. {
  10406. struct pool *pool = pools[i];
  10407. if (!(strcmp(pool->rpc_url, uri) || strcmp(pool->rpc_pass, rpcpass)))
  10408. {
  10409. applog(LOG_DEBUG, "Server on %s is already configured, not adding as failover", hfuri);
  10410. free(uri);
  10411. goto err;
  10412. }
  10413. }
  10414. pool = add_pool();
  10415. if (!pool)
  10416. {
  10417. applog(LOG_ERR, "%s: Error adding pool for bitcoin configured in %s", "add_local_gbt", filepath);
  10418. goto err;
  10419. }
  10420. if (!rpcuser)
  10421. rpcuser = "";
  10422. pool->quota = 0;
  10423. adjust_quota_gcd();
  10424. pool->failover_only = true;
  10425. add_pool_details(pool, *live_p, uri, rpcuser, rpcpass);
  10426. applog(LOG_NOTICE, "Added local bitcoin RPC server on %s as pool %d", hfuri, pool->pool_no);
  10427. out:
  10428. return false;
  10429. }
  10430. static
  10431. void add_local_gbt(bool live)
  10432. {
  10433. appdata_file_call("Bitcoin", "bitcoin.conf", _add_local_gbt, &live);
  10434. }
  10435. #endif
  10436. #if defined(unix) || defined(__APPLE__)
  10437. static void fork_monitor()
  10438. {
  10439. // Make a pipe: [readFD, writeFD]
  10440. int pfd[2];
  10441. int r = pipe(pfd);
  10442. if (r < 0) {
  10443. perror("pipe - failed to create pipe for --monitor");
  10444. exit(1);
  10445. }
  10446. // Make stderr write end of pipe
  10447. fflush(stderr);
  10448. r = dup2(pfd[1], 2);
  10449. if (r < 0) {
  10450. perror("dup2 - failed to alias stderr to write end of pipe for --monitor");
  10451. exit(1);
  10452. }
  10453. r = close(pfd[1]);
  10454. if (r < 0) {
  10455. perror("close - failed to close write end of pipe for --monitor");
  10456. exit(1);
  10457. }
  10458. // Don't allow a dying monitor to kill the main process
  10459. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  10460. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  10461. if (SIG_ERR == sr0 || SIG_ERR == sr1) {
  10462. perror("signal - failed to edit signal mask for --monitor");
  10463. exit(1);
  10464. }
  10465. // Fork a child process
  10466. forkpid = fork();
  10467. if (forkpid < 0) {
  10468. perror("fork - failed to fork child process for --monitor");
  10469. exit(1);
  10470. }
  10471. // Child: launch monitor command
  10472. if (0 == forkpid) {
  10473. // Make stdin read end of pipe
  10474. r = dup2(pfd[0], 0);
  10475. if (r < 0) {
  10476. perror("dup2 - in child, failed to alias read end of pipe to stdin for --monitor");
  10477. exit(1);
  10478. }
  10479. close(pfd[0]);
  10480. if (r < 0) {
  10481. perror("close - in child, failed to close read end of pipe for --monitor");
  10482. exit(1);
  10483. }
  10484. // Launch user specified command
  10485. execl("/bin/bash", "/bin/bash", "-c", opt_stderr_cmd, (char*)NULL);
  10486. perror("execl - in child failed to exec user specified command for --monitor");
  10487. exit(1);
  10488. }
  10489. // Parent: clean up unused fds and bail
  10490. r = close(pfd[0]);
  10491. if (r < 0) {
  10492. perror("close - failed to close read end of pipe for --monitor");
  10493. exit(1);
  10494. }
  10495. }
  10496. #endif // defined(unix)
  10497. #ifdef HAVE_CURSES
  10498. #ifdef USE_UNICODE
  10499. static
  10500. wchar_t select_unicode_char(const wchar_t *opt)
  10501. {
  10502. for ( ; *opt; ++opt)
  10503. if (iswprint(*opt))
  10504. return *opt;
  10505. return '?';
  10506. }
  10507. #endif
  10508. void enable_curses(void) {
  10509. int x;
  10510. __maybe_unused int y;
  10511. lock_curses();
  10512. if (curses_active) {
  10513. unlock_curses();
  10514. return;
  10515. }
  10516. #ifdef USE_UNICODE
  10517. if (use_unicode)
  10518. {
  10519. setlocale(LC_CTYPE, "");
  10520. if (iswprint(0xb0))
  10521. have_unicode_degrees = true;
  10522. unicode_micro = select_unicode_char(L"\xb5\u03bcu");
  10523. }
  10524. #endif
  10525. mainwin = initscr();
  10526. start_color();
  10527. #if defined(PDCURSES) || defined(NCURSES_VERSION)
  10528. if (ERR != use_default_colors())
  10529. default_bgcolor = -1;
  10530. #endif
  10531. if (has_colors() && ERR != init_pair(1, COLOR_WHITE, COLOR_BLUE))
  10532. {
  10533. menu_attr = COLOR_PAIR(1);
  10534. if (ERR != init_pair(2, COLOR_RED, default_bgcolor))
  10535. attr_bad |= COLOR_PAIR(2);
  10536. }
  10537. keypad(mainwin, true);
  10538. getmaxyx(mainwin, y, x);
  10539. statuswin = newwin(logstart, x, 0, 0);
  10540. leaveok(statuswin, true);
  10541. // For whatever reason, PDCurses crashes if the logwin is initialized to height y-logcursor
  10542. // We resize the window later anyway, so just start it off at 1 :)
  10543. logwin = newwin(1, 0, logcursor, 0);
  10544. idlok(logwin, true);
  10545. scrollok(logwin, true);
  10546. leaveok(logwin, true);
  10547. cbreak();
  10548. noecho();
  10549. nonl();
  10550. curses_active = true;
  10551. statusy = logstart;
  10552. unlock_curses();
  10553. }
  10554. #endif
  10555. /* TODO: fix need a dummy CPU device_drv even if no support for CPU mining */
  10556. #ifndef WANT_CPUMINE
  10557. struct device_drv cpu_drv;
  10558. struct device_drv cpu_drv = {
  10559. .name = "CPU",
  10560. };
  10561. #endif
  10562. static int cgminer_id_count = 0;
  10563. static int device_line_id_count;
  10564. void register_device(struct cgpu_info *cgpu)
  10565. {
  10566. cgpu->deven = DEV_ENABLED;
  10567. wr_lock(&devices_lock);
  10568. devices[cgpu->cgminer_id = cgminer_id_count++] = cgpu;
  10569. wr_unlock(&devices_lock);
  10570. if (!cgpu->proc_id)
  10571. cgpu->device_line_id = device_line_id_count++;
  10572. int thr_objs = cgpu->threads ?: 1;
  10573. mining_threads += thr_objs;
  10574. base_queue += thr_objs + cgpu->extra_work_queue;
  10575. {
  10576. const struct device_drv * const drv = cgpu->drv;
  10577. struct mining_algorithm *malgo;
  10578. LL_FOREACH(mining_algorithms, malgo)
  10579. {
  10580. if (drv_min_nonce_diff(drv, cgpu, malgo) < 0)
  10581. continue;
  10582. malgo->base_queue += thr_objs + cgpu->extra_work_queue;
  10583. }
  10584. }
  10585. #ifdef HAVE_CURSES
  10586. adj_width(mining_threads, &dev_width);
  10587. #endif
  10588. rwlock_init(&cgpu->qlock);
  10589. cgpu->queued_work = NULL;
  10590. }
  10591. struct _cgpu_devid_counter {
  10592. char name[4];
  10593. int lastid;
  10594. UT_hash_handle hh;
  10595. };
  10596. void renumber_cgpu(struct cgpu_info *cgpu)
  10597. {
  10598. static struct _cgpu_devid_counter *devids = NULL;
  10599. struct _cgpu_devid_counter *d;
  10600. HASH_FIND_STR(devids, cgpu->drv->name, d);
  10601. if (d)
  10602. cgpu->device_id = ++d->lastid;
  10603. else {
  10604. d = malloc(sizeof(*d));
  10605. memcpy(d->name, cgpu->drv->name, sizeof(d->name));
  10606. cgpu->device_id = d->lastid = 0;
  10607. HASH_ADD_STR(devids, name, d);
  10608. }
  10609. // Build repr strings
  10610. sprintf(cgpu->dev_repr, "%s%2u", cgpu->drv->name, cgpu->device_id % 100);
  10611. sprintf(cgpu->dev_repr_ns, "%s%u", cgpu->drv->name, cgpu->device_id % 100);
  10612. strcpy(cgpu->proc_repr, cgpu->dev_repr);
  10613. sprintf(cgpu->proc_repr_ns, "%s%u", cgpu->drv->name, cgpu->device_id);
  10614. const int lpcount = cgpu->procs;
  10615. if (lpcount > 1)
  10616. {
  10617. int ns;
  10618. struct cgpu_info *slave;
  10619. int lpdigits = 1;
  10620. for (int i = lpcount; i > 26 && lpdigits < 3; i /= 26)
  10621. ++lpdigits;
  10622. if (lpdigits > max_lpdigits)
  10623. max_lpdigits = lpdigits;
  10624. memset(&cgpu->proc_repr[5], 'a', lpdigits);
  10625. cgpu->proc_repr[5 + lpdigits] = '\0';
  10626. ns = strlen(cgpu->proc_repr_ns);
  10627. strcpy(&cgpu->proc_repr_ns[ns], &cgpu->proc_repr[5]);
  10628. slave = cgpu;
  10629. for (int i = 1; i < lpcount; ++i)
  10630. {
  10631. slave = slave->next_proc;
  10632. strcpy(slave->proc_repr, cgpu->proc_repr);
  10633. strcpy(slave->proc_repr_ns, cgpu->proc_repr_ns);
  10634. for (int x = i, y = lpdigits; --y, x; x /= 26)
  10635. {
  10636. slave->proc_repr_ns[ns + y] =
  10637. slave->proc_repr[5 + y] += (x % 26);
  10638. }
  10639. }
  10640. }
  10641. }
  10642. static bool my_blkmaker_sha256_callback(void *digest, const void *buffer, size_t length)
  10643. {
  10644. sha256(buffer, length, digest);
  10645. return true;
  10646. }
  10647. static
  10648. bool drv_algo_check(const struct device_drv * const drv)
  10649. {
  10650. struct mining_goal_info *goal, *tmpgoal;
  10651. HASH_ITER(hh, mining_goals, goal, tmpgoal)
  10652. {
  10653. if (drv_min_nonce_diff(drv, NULL, goal->malgo) >= 0)
  10654. return true;
  10655. }
  10656. return false;
  10657. }
  10658. #ifndef HAVE_PTHREAD_CANCEL
  10659. extern void setup_pthread_cancel_workaround();
  10660. extern struct sigaction pcwm_orig_term_handler;
  10661. #endif
  10662. bool bfg_need_detect_rescan;
  10663. extern void probe_device(struct lowlevel_device_info *);
  10664. static void schedule_rescan(const struct timeval *);
  10665. static
  10666. void drv_detect_all()
  10667. {
  10668. bool rescanning = false;
  10669. rescan:
  10670. bfg_need_detect_rescan = false;
  10671. #ifdef HAVE_BFG_LOWLEVEL
  10672. struct lowlevel_device_info * const infolist = lowlevel_scan(), *info, *infotmp;
  10673. LL_FOREACH_SAFE(infolist, info, infotmp)
  10674. probe_device(info);
  10675. LL_FOREACH_SAFE(infolist, info, infotmp)
  10676. pthread_join(info->probe_pth, NULL);
  10677. #endif
  10678. struct driver_registration *reg, *tmp;
  10679. BFG_FOREACH_DRIVER_BY_PRIORITY(reg, tmp)
  10680. {
  10681. const struct device_drv * const drv = reg->drv;
  10682. if (!(drv_algo_check(drv) && drv->drv_detect))
  10683. continue;
  10684. drv->drv_detect();
  10685. }
  10686. #ifdef HAVE_BFG_LOWLEVEL
  10687. lowlevel_scan_free();
  10688. #endif
  10689. if (bfg_need_detect_rescan)
  10690. {
  10691. if (rescanning)
  10692. {
  10693. applog(LOG_DEBUG, "Device rescan requested a second time, delaying");
  10694. struct timeval tv_when;
  10695. timer_set_delay_from_now(&tv_when, rescan_delay_ms * 1000);
  10696. schedule_rescan(&tv_when);
  10697. }
  10698. else
  10699. {
  10700. rescanning = true;
  10701. applog(LOG_DEBUG, "Device rescan requested");
  10702. goto rescan;
  10703. }
  10704. }
  10705. }
  10706. static
  10707. void allocate_cgpu(struct cgpu_info *cgpu, unsigned int *kp)
  10708. {
  10709. struct thr_info *thr;
  10710. int j;
  10711. struct device_drv *api = cgpu->drv;
  10712. cgpu->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  10713. int threadobj = cgpu->threads;
  10714. if (!threadobj)
  10715. // Create a fake thread object to handle hashmeter etc
  10716. threadobj = 1;
  10717. cgpu->thr = calloc(threadobj + 1, sizeof(*cgpu->thr));
  10718. cgpu->thr[threadobj] = NULL;
  10719. cgpu->status = LIFE_INIT;
  10720. if (opt_devices_enabled_list)
  10721. {
  10722. struct string_elist *enablestr_elist;
  10723. cgpu->deven = DEV_DISABLED;
  10724. DL_FOREACH(opt_devices_enabled_list, enablestr_elist)
  10725. {
  10726. const char * const enablestr = enablestr_elist->string;
  10727. if (cgpu_match(enablestr, cgpu))
  10728. {
  10729. cgpu->deven = DEV_ENABLED;
  10730. break;
  10731. }
  10732. }
  10733. }
  10734. cgpu->max_hashes = 0;
  10735. BFGINIT(cgpu->cutofftemp, opt_cutofftemp);
  10736. BFGINIT(cgpu->targettemp, cgpu->cutofftemp - 6);
  10737. // Setup thread structs before starting any of the threads, in case they try to interact
  10738. for (j = 0; j < threadobj; ++j, ++*kp) {
  10739. thr = get_thread(*kp);
  10740. thr->id = *kp;
  10741. thr->cgpu = cgpu;
  10742. thr->device_thread = j;
  10743. thr->work_restart_notifier[1] = INVSOCK;
  10744. thr->mutex_request[1] = INVSOCK;
  10745. thr->_job_transition_in_progress = true;
  10746. timerclear(&thr->tv_morework);
  10747. thr->scanhash_working = true;
  10748. thr->hashes_done = 0;
  10749. timerclear(&thr->tv_hashes_done);
  10750. cgtime(&thr->tv_lastupdate);
  10751. thr->tv_poll.tv_sec = -1;
  10752. thr->_max_nonce = api->can_limit_work ? api->can_limit_work(thr) : 0xffffffff;
  10753. cgpu->thr[j] = thr;
  10754. }
  10755. if (!cgpu->device->threads)
  10756. notifier_init_invalid(cgpu->thr[0]->notifier);
  10757. else
  10758. if (!cgpu->threads)
  10759. memcpy(&cgpu->thr[0]->notifier, &cgpu->device->thr[0]->notifier, sizeof(cgpu->thr[0]->notifier));
  10760. else
  10761. for (j = 0; j < cgpu->threads; ++j)
  10762. {
  10763. thr = cgpu->thr[j];
  10764. notifier_init(thr->notifier);
  10765. }
  10766. }
  10767. static
  10768. void start_cgpu(struct cgpu_info *cgpu)
  10769. {
  10770. struct thr_info *thr;
  10771. int j;
  10772. for (j = 0; j < cgpu->threads; ++j) {
  10773. thr = cgpu->thr[j];
  10774. /* Enable threads for devices set not to mine but disable
  10775. * their queue in case we wish to enable them later */
  10776. if (cgpu->drv->thread_prepare && !cgpu->drv->thread_prepare(thr))
  10777. continue;
  10778. thread_reportout(thr);
  10779. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  10780. quit(1, "thread %d create failed", thr->id);
  10781. notifier_wake(thr->notifier);
  10782. }
  10783. if (cgpu->deven == DEV_ENABLED)
  10784. proc_enable(cgpu);
  10785. }
  10786. static
  10787. void _scan_serial(void *p)
  10788. {
  10789. const char *s = p;
  10790. struct string_elist *iter, *tmp;
  10791. struct string_elist *orig_scan_devices = scan_devices;
  10792. if (s)
  10793. {
  10794. // Make temporary scan_devices list
  10795. scan_devices = NULL;
  10796. string_elist_add("noauto", &scan_devices);
  10797. add_serial(s);
  10798. }
  10799. drv_detect_all();
  10800. if (s)
  10801. {
  10802. DL_FOREACH_SAFE(scan_devices, iter, tmp)
  10803. {
  10804. string_elist_del(&scan_devices, iter);
  10805. }
  10806. scan_devices = orig_scan_devices;
  10807. }
  10808. }
  10809. #ifdef HAVE_BFG_LOWLEVEL
  10810. static
  10811. bool _probe_device_match(const struct lowlevel_device_info * const info, const char * const ser)
  10812. {
  10813. if (!(false
  10814. || (info->serial && !strcasecmp(ser, info->serial))
  10815. || (info->path && !strcasecmp(ser, info->path ))
  10816. || (info->devid && !strcasecmp(ser, info->devid ))
  10817. ))
  10818. {
  10819. char *devid = devpath_to_devid(ser);
  10820. if (!devid)
  10821. return false;
  10822. const bool different = strcmp(info->devid, devid);
  10823. free(devid);
  10824. if (different)
  10825. return false;
  10826. }
  10827. return true;
  10828. }
  10829. static
  10830. const struct device_drv *_probe_device_find_drv(const char * const _dname, const size_t dnamelen)
  10831. {
  10832. struct driver_registration *dreg;
  10833. char dname[dnamelen];
  10834. int i;
  10835. for (i = 0; i < dnamelen; ++i)
  10836. dname[i] = tolower(_dname[i]);
  10837. BFG_FIND_DRV_BY_DNAME(dreg, dname, dnamelen);
  10838. if (!dreg)
  10839. {
  10840. for (i = 0; i < dnamelen; ++i)
  10841. dname[i] = toupper(_dname[i]);
  10842. BFG_FIND_DRV_BY_NAME(dreg, dname, dnamelen);
  10843. if (!dreg)
  10844. return NULL;
  10845. }
  10846. if (!drv_algo_check(dreg->drv))
  10847. return NULL;
  10848. return dreg->drv;
  10849. }
  10850. static
  10851. bool _probe_device_do_probe(const struct device_drv * const drv, const struct lowlevel_device_info * const info, bool * const request_rescan_p)
  10852. {
  10853. bfg_probe_result_flags = 0;
  10854. if (drv->lowl_probe(info))
  10855. {
  10856. if (!(bfg_probe_result_flags & BPR_CONTINUE_PROBES))
  10857. return true;
  10858. }
  10859. else
  10860. if (request_rescan_p && opt_hotplug && !(bfg_probe_result_flags & BPR_DONT_RESCAN))
  10861. *request_rescan_p = true;
  10862. return false;
  10863. }
  10864. bool dummy_check_never_true = false;
  10865. static
  10866. void *probe_device_thread(void *p)
  10867. {
  10868. struct lowlevel_device_info * const infolist = p;
  10869. struct lowlevel_device_info *info = infolist;
  10870. bool request_rescan = false;
  10871. {
  10872. char threadname[5 + strlen(info->devid) + 1];
  10873. sprintf(threadname, "probe_%s", info->devid);
  10874. RenameThread(threadname);
  10875. }
  10876. // If already in use, ignore
  10877. if (bfg_claim_any(NULL, NULL, info->devid))
  10878. applogr(NULL, LOG_DEBUG, "%s: \"%s\" already in use",
  10879. __func__, info->product);
  10880. // if lowlevel device matches specific user assignment, probe requested driver(s)
  10881. struct string_elist *sd_iter, *sd_tmp;
  10882. struct driver_registration *dreg, *dreg_tmp;
  10883. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  10884. {
  10885. const char * const dname = sd_iter->string;
  10886. const char * const colon = strpbrk(dname, ":@");
  10887. if (!(colon && colon != dname))
  10888. continue;
  10889. const char * const ser = &colon[1];
  10890. LL_FOREACH2(infolist, info, same_devid_next)
  10891. {
  10892. if (!_probe_device_match(info, ser))
  10893. continue;
  10894. const size_t dnamelen = (colon - dname);
  10895. const struct device_drv * const drv = _probe_device_find_drv(dname, dnamelen);
  10896. if (!(drv && drv->lowl_probe && drv_algo_check(drv)))
  10897. continue;
  10898. if (_probe_device_do_probe(drv, info, &request_rescan))
  10899. return NULL;
  10900. }
  10901. }
  10902. // probe driver(s) with auto enabled and matching VID/PID/Product/etc of device
  10903. BFG_FOREACH_DRIVER_BY_PRIORITY(dreg, dreg_tmp)
  10904. {
  10905. const struct device_drv * const drv = dreg->drv;
  10906. if (!drv_algo_check(drv))
  10907. continue;
  10908. // Check for "noauto" flag
  10909. // NOTE: driver-specific configuration overrides general
  10910. bool doauto = true;
  10911. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  10912. {
  10913. const char * const dname = sd_iter->string;
  10914. // NOTE: Only checking flags here, NOT path/serial, so @ is unacceptable
  10915. const char *colon = strchr(dname, ':');
  10916. if (!colon)
  10917. colon = &dname[-1];
  10918. if (strcasecmp("noauto", &colon[1]) && strcasecmp("auto", &colon[1]))
  10919. continue;
  10920. const ssize_t dnamelen = (colon - dname);
  10921. if (dnamelen >= 0 && _probe_device_find_drv(dname, dnamelen) != drv)
  10922. continue;
  10923. doauto = (tolower(colon[1]) == 'a');
  10924. if (dnamelen != -1)
  10925. break;
  10926. }
  10927. if (doauto && drv->lowl_match)
  10928. {
  10929. LL_FOREACH2(infolist, info, same_devid_next)
  10930. {
  10931. /*
  10932. The below call to applog is absolutely necessary
  10933. Starting with commit 76d0cc183b1c9ddcc0ef34d2e43bc696ef9de92e installing BFGMiner on
  10934. Mac OS X using Homebrew results in a binary that segfaults on startup
  10935. There are two unresolved issues:
  10936. 1) The BFGMiner authors cannot find a way to install BFGMiner with Homebrew that results
  10937. in debug symbols being available to help troubleshoot the issue
  10938. 2) The issue disappears when unrelated code changes are made, such as adding the following
  10939. call to applog with infolist and / or p
  10940. We would encourage revisiting this in the future to come up with a more concrete solution
  10941. Reproducing should only require commenting / removing the following line and installing
  10942. BFGMiner using "brew install bfgminer --HEAD"
  10943. */
  10944. if (dummy_check_never_true)
  10945. applog(LOG_DEBUG, "lowl_match: %p(%s) %p %p %p", drv, drv->dname, info, infolist, p);
  10946. if (!drv->lowl_match(info))
  10947. continue;
  10948. if (_probe_device_do_probe(drv, info, &request_rescan))
  10949. return NULL;
  10950. }
  10951. }
  10952. }
  10953. // probe driver(s) with 'all' enabled
  10954. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  10955. {
  10956. const char * const dname = sd_iter->string;
  10957. // NOTE: Only checking flags here, NOT path/serial, so @ is unacceptable
  10958. const char * const colon = strchr(dname, ':');
  10959. if (!colon)
  10960. {
  10961. LL_FOREACH2(infolist, info, same_devid_next)
  10962. {
  10963. if (
  10964. #ifdef NEED_BFG_LOWL_VCOM
  10965. (info->lowl == &lowl_vcom && !strcasecmp(dname, "all")) ||
  10966. #endif
  10967. _probe_device_match(info, (dname[0] == '@') ? &dname[1] : dname))
  10968. {
  10969. bool dont_rescan = false;
  10970. BFG_FOREACH_DRIVER_BY_PRIORITY(dreg, dreg_tmp)
  10971. {
  10972. const struct device_drv * const drv = dreg->drv;
  10973. if (!drv_algo_check(drv))
  10974. continue;
  10975. if (drv->lowl_probe_by_name_only)
  10976. continue;
  10977. if (!drv->lowl_probe)
  10978. continue;
  10979. if (_probe_device_do_probe(drv, info, NULL))
  10980. return NULL;
  10981. if (bfg_probe_result_flags & BPR_DONT_RESCAN)
  10982. dont_rescan = true;
  10983. }
  10984. if (opt_hotplug && !dont_rescan)
  10985. request_rescan = true;
  10986. break;
  10987. }
  10988. }
  10989. continue;
  10990. }
  10991. if (strcasecmp(&colon[1], "all"))
  10992. continue;
  10993. const size_t dnamelen = (colon - dname);
  10994. const struct device_drv * const drv = _probe_device_find_drv(dname, dnamelen);
  10995. if (!(drv && drv->lowl_probe && drv_algo_check(drv)))
  10996. continue;
  10997. LL_FOREACH2(infolist, info, same_devid_next)
  10998. {
  10999. if (info->lowl->exclude_from_all)
  11000. continue;
  11001. if (_probe_device_do_probe(drv, info, NULL))
  11002. return NULL;
  11003. }
  11004. }
  11005. // Only actually request a rescan if we never found any cgpu
  11006. if (request_rescan)
  11007. bfg_need_detect_rescan = true;
  11008. return NULL;
  11009. }
  11010. void probe_device(struct lowlevel_device_info * const info)
  11011. {
  11012. pthread_create(&info->probe_pth, NULL, probe_device_thread, info);
  11013. }
  11014. #endif
  11015. int create_new_cgpus(void (*addfunc)(void*), void *arg)
  11016. {
  11017. static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  11018. int devcount, i, mining_threads_new = 0;
  11019. unsigned int k;
  11020. struct cgpu_info *cgpu;
  11021. struct thr_info *thr;
  11022. void *p;
  11023. mutex_lock(&mutex);
  11024. devcount = total_devices;
  11025. addfunc(arg);
  11026. if (!total_devices_new)
  11027. goto out;
  11028. wr_lock(&devices_lock);
  11029. p = realloc(devices, sizeof(struct cgpu_info *) * (total_devices + total_devices_new + 1));
  11030. if (unlikely(!p))
  11031. {
  11032. wr_unlock(&devices_lock);
  11033. applog(LOG_ERR, "scan_serial: realloc failed trying to grow devices array");
  11034. goto out;
  11035. }
  11036. devices = p;
  11037. wr_unlock(&devices_lock);
  11038. for (i = 0; i < total_devices_new; ++i)
  11039. {
  11040. cgpu = devices_new[i];
  11041. mining_threads_new += cgpu->threads ?: 1;
  11042. }
  11043. wr_lock(&mining_thr_lock);
  11044. mining_threads_new += mining_threads;
  11045. p = realloc(mining_thr, sizeof(struct thr_info *) * mining_threads_new);
  11046. if (unlikely(!p))
  11047. {
  11048. wr_unlock(&mining_thr_lock);
  11049. applog(LOG_ERR, "scan_serial: realloc failed trying to grow mining_thr");
  11050. goto out;
  11051. }
  11052. mining_thr = p;
  11053. wr_unlock(&mining_thr_lock);
  11054. for (i = mining_threads; i < mining_threads_new; ++i) {
  11055. mining_thr[i] = calloc(1, sizeof(*thr));
  11056. if (!mining_thr[i])
  11057. {
  11058. applog(LOG_ERR, "scan_serial: Failed to calloc mining_thr[%d]", i);
  11059. for ( ; --i >= mining_threads; )
  11060. free(mining_thr[i]);
  11061. goto out;
  11062. }
  11063. }
  11064. k = mining_threads;
  11065. for (i = 0; i < total_devices_new; ++i)
  11066. {
  11067. cgpu = devices_new[i];
  11068. allocate_cgpu(cgpu, &k);
  11069. }
  11070. for (i = 0; i < total_devices_new; ++i)
  11071. {
  11072. cgpu = devices_new[i];
  11073. start_cgpu(cgpu);
  11074. register_device(cgpu);
  11075. ++total_devices;
  11076. }
  11077. #ifdef HAVE_CURSES
  11078. switch_logsize();
  11079. #endif
  11080. out:
  11081. total_devices_new = 0;
  11082. devcount = total_devices - devcount;
  11083. mutex_unlock(&mutex);
  11084. return devcount;
  11085. }
  11086. int scan_serial(const char *s)
  11087. {
  11088. return create_new_cgpus(_scan_serial, (void*)s);
  11089. }
  11090. static pthread_mutex_t rescan_mutex = PTHREAD_MUTEX_INITIALIZER;
  11091. static bool rescan_active;
  11092. static struct timeval tv_rescan;
  11093. static notifier_t rescan_notifier;
  11094. static
  11095. void *rescan_thread(__maybe_unused void *p)
  11096. {
  11097. pthread_detach(pthread_self());
  11098. RenameThread("rescan");
  11099. struct timeval tv_timeout, tv_now;
  11100. fd_set rfds;
  11101. while (true)
  11102. {
  11103. mutex_lock(&rescan_mutex);
  11104. tv_timeout = tv_rescan;
  11105. if (!timer_isset(&tv_timeout))
  11106. {
  11107. rescan_active = false;
  11108. mutex_unlock(&rescan_mutex);
  11109. break;
  11110. }
  11111. mutex_unlock(&rescan_mutex);
  11112. FD_ZERO(&rfds);
  11113. FD_SET(rescan_notifier[0], &rfds);
  11114. const int maxfd = rescan_notifier[0];
  11115. timer_set_now(&tv_now);
  11116. if (select(maxfd+1, &rfds, NULL, NULL, select_timeout(&tv_timeout, &tv_now)) > 0)
  11117. notifier_read(rescan_notifier);
  11118. mutex_lock(&rescan_mutex);
  11119. if (timer_passed(&tv_rescan, NULL))
  11120. {
  11121. timer_unset(&tv_rescan);
  11122. mutex_unlock(&rescan_mutex);
  11123. applog(LOG_DEBUG, "Rescan timer expired, triggering");
  11124. scan_serial(NULL);
  11125. }
  11126. else
  11127. mutex_unlock(&rescan_mutex);
  11128. }
  11129. return NULL;
  11130. }
  11131. static
  11132. void _schedule_rescan(const struct timeval * const tvp_when)
  11133. {
  11134. if (rescan_active)
  11135. {
  11136. if (timercmp(tvp_when, &tv_rescan, <))
  11137. applog(LOG_DEBUG, "schedule_rescan: New schedule is before current, waiting it out");
  11138. else
  11139. {
  11140. applog(LOG_DEBUG, "schedule_rescan: New schedule is after current, delaying rescan");
  11141. tv_rescan = *tvp_when;
  11142. }
  11143. return;
  11144. }
  11145. applog(LOG_DEBUG, "schedule_rescan: Scheduling rescan (no rescans currently pending)");
  11146. tv_rescan = *tvp_when;
  11147. rescan_active = true;
  11148. static pthread_t pth;
  11149. if (unlikely(pthread_create(&pth, NULL, rescan_thread, NULL)))
  11150. applog(LOG_ERR, "Failed to start rescan thread");
  11151. }
  11152. static
  11153. void schedule_rescan(const struct timeval * const tvp_when)
  11154. {
  11155. mutex_lock(&rescan_mutex);
  11156. _schedule_rescan(tvp_when);
  11157. mutex_unlock(&rescan_mutex);
  11158. }
  11159. #ifdef HAVE_BFG_HOTPLUG
  11160. static
  11161. void hotplug_trigger()
  11162. {
  11163. applog(LOG_DEBUG, "%s: Scheduling rescan immediately", __func__);
  11164. struct timeval tv_now;
  11165. timer_set_now(&tv_now);
  11166. schedule_rescan(&tv_now);
  11167. }
  11168. #endif
  11169. #if defined(HAVE_LIBUDEV) && defined(HAVE_SYS_EPOLL_H)
  11170. static
  11171. void *hotplug_thread(__maybe_unused void *p)
  11172. {
  11173. pthread_detach(pthread_self());
  11174. RenameThread("hotplug");
  11175. struct udev * const udev = udev_new();
  11176. if (unlikely(!udev))
  11177. applogfailr(NULL, LOG_ERR, "udev_new");
  11178. struct udev_monitor * const mon = udev_monitor_new_from_netlink(udev, "udev");
  11179. if (unlikely(!mon))
  11180. applogfailr(NULL, LOG_ERR, "udev_monitor_new_from_netlink");
  11181. if (unlikely(udev_monitor_enable_receiving(mon)))
  11182. applogfailr(NULL, LOG_ERR, "udev_monitor_enable_receiving");
  11183. const int epfd = epoll_create(1);
  11184. if (unlikely(epfd == -1))
  11185. applogfailr(NULL, LOG_ERR, "epoll_create");
  11186. {
  11187. const int fd = udev_monitor_get_fd(mon);
  11188. struct epoll_event ev = {
  11189. .events = EPOLLIN | EPOLLPRI,
  11190. .data.fd = fd,
  11191. };
  11192. if (epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev))
  11193. applogfailr(NULL, LOG_ERR, "epoll_ctl");
  11194. }
  11195. struct epoll_event ev;
  11196. int rv;
  11197. bool pending = false;
  11198. while (true)
  11199. {
  11200. rv = epoll_wait(epfd, &ev, 1, pending ? hotplug_delay_ms : -1);
  11201. if (rv == -1)
  11202. {
  11203. if (errno == EAGAIN || errno == EINTR)
  11204. continue;
  11205. break;
  11206. }
  11207. if (!rv)
  11208. {
  11209. hotplug_trigger();
  11210. pending = false;
  11211. continue;
  11212. }
  11213. struct udev_device * const device = udev_monitor_receive_device(mon);
  11214. if (!device)
  11215. continue;
  11216. const char * const action = udev_device_get_action(device);
  11217. applog(LOG_DEBUG, "%s: Received %s event", __func__, action);
  11218. if (!strcmp(action, "add"))
  11219. pending = true;
  11220. udev_device_unref(device);
  11221. }
  11222. applogfailr(NULL, LOG_ERR, "epoll_wait");
  11223. }
  11224. #elif defined(WIN32)
  11225. static UINT_PTR _hotplug_wintimer_id;
  11226. VOID CALLBACK hotplug_win_timer(HWND hwnd, UINT msg, UINT_PTR idEvent, DWORD dwTime)
  11227. {
  11228. KillTimer(NULL, _hotplug_wintimer_id);
  11229. _hotplug_wintimer_id = 0;
  11230. hotplug_trigger();
  11231. }
  11232. LRESULT CALLBACK hotplug_win_callback(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
  11233. {
  11234. if (msg == WM_DEVICECHANGE && wParam == DBT_DEVNODES_CHANGED)
  11235. {
  11236. applog(LOG_DEBUG, "%s: Received DBT_DEVNODES_CHANGED event", __func__);
  11237. _hotplug_wintimer_id = SetTimer(NULL, _hotplug_wintimer_id, hotplug_delay_ms, hotplug_win_timer);
  11238. }
  11239. return DefWindowProc(hwnd, msg, wParam, lParam);
  11240. }
  11241. static
  11242. void *hotplug_thread(__maybe_unused void *p)
  11243. {
  11244. pthread_detach(pthread_self());
  11245. WNDCLASS DummyWinCls = {
  11246. .lpszClassName = "BFGDummyWinCls",
  11247. .lpfnWndProc = hotplug_win_callback,
  11248. };
  11249. ATOM a = RegisterClass(&DummyWinCls);
  11250. if (unlikely(!a))
  11251. applogfailinfor(NULL, LOG_ERR, "RegisterClass", "%d", (int)GetLastError());
  11252. HWND hwnd = CreateWindow((void*)(intptr_t)a, NULL, WS_OVERLAPPED, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, NULL, NULL);
  11253. if (unlikely(!hwnd))
  11254. applogfailinfor(NULL, LOG_ERR, "CreateWindow", "%d", (int)GetLastError());
  11255. MSG msg;
  11256. while (GetMessage(&msg, NULL, 0, 0))
  11257. {
  11258. TranslateMessage(&msg);
  11259. DispatchMessage(&msg);
  11260. }
  11261. quit(0, "WM_QUIT received");
  11262. return NULL;
  11263. }
  11264. #endif
  11265. #ifdef HAVE_BFG_HOTPLUG
  11266. static
  11267. void hotplug_start()
  11268. {
  11269. pthread_t pth;
  11270. if (unlikely(pthread_create(&pth, NULL, hotplug_thread, NULL)))
  11271. applog(LOG_ERR, "Failed to start hotplug thread");
  11272. }
  11273. #endif
  11274. static void probe_pools(void)
  11275. {
  11276. int i;
  11277. for (i = 0; i < total_pools; i++) {
  11278. struct pool *pool = pools[i];
  11279. pool->testing = true;
  11280. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  11281. }
  11282. }
  11283. static void raise_fd_limits(void)
  11284. {
  11285. #ifdef HAVE_SETRLIMIT
  11286. struct rlimit fdlimit;
  11287. rlim_t old_soft_limit;
  11288. char frombuf[0x10] = "unlimited";
  11289. char hardbuf[0x10] = "unlimited";
  11290. if (getrlimit(RLIMIT_NOFILE, &fdlimit))
  11291. applogr(, LOG_DEBUG, "setrlimit: Failed to getrlimit(RLIMIT_NOFILE)");
  11292. old_soft_limit = fdlimit.rlim_cur;
  11293. if (fdlimit.rlim_max > FD_SETSIZE || fdlimit.rlim_max == RLIM_INFINITY)
  11294. fdlimit.rlim_cur = FD_SETSIZE;
  11295. else
  11296. fdlimit.rlim_cur = fdlimit.rlim_max;
  11297. if (fdlimit.rlim_max != RLIM_INFINITY)
  11298. snprintf(hardbuf, sizeof(hardbuf), "%lu", (unsigned long)fdlimit.rlim_max);
  11299. if (old_soft_limit != RLIM_INFINITY)
  11300. snprintf(frombuf, sizeof(frombuf), "%lu", (unsigned long)old_soft_limit);
  11301. if (fdlimit.rlim_cur == old_soft_limit)
  11302. applogr(, LOG_DEBUG, "setrlimit: Soft fd limit not being changed from %lu (FD_SETSIZE=%lu; hard limit=%s)",
  11303. (unsigned long)old_soft_limit, (unsigned long)FD_SETSIZE, hardbuf);
  11304. if (setrlimit(RLIMIT_NOFILE, &fdlimit))
  11305. applogr(, LOG_DEBUG, "setrlimit: Failed to change soft fd limit from %s to %lu (FD_SETSIZE=%lu; hard limit=%s)",
  11306. frombuf, (unsigned long)fdlimit.rlim_cur, (unsigned long)FD_SETSIZE, hardbuf);
  11307. applog(LOG_DEBUG, "setrlimit: Changed soft fd limit from %s to %lu (FD_SETSIZE=%lu; hard limit=%s)",
  11308. frombuf, (unsigned long)fdlimit.rlim_cur, (unsigned long)FD_SETSIZE, hardbuf);
  11309. #else
  11310. applog(LOG_DEBUG, "setrlimit: Not supported by platform");
  11311. #endif
  11312. }
  11313. static
  11314. void bfg_atexit(void)
  11315. {
  11316. puts("");
  11317. }
  11318. extern void bfg_init_threadlocal();
  11319. extern void stratumsrv_start();
  11320. extern void test_aan_pll(void);
  11321. int main(int argc, char *argv[])
  11322. {
  11323. struct sigaction handler;
  11324. struct thr_info *thr;
  11325. unsigned int k;
  11326. int i;
  11327. int rearrange_pools = 0;
  11328. char *s;
  11329. #ifdef WIN32
  11330. LoadLibrary("backtrace.dll");
  11331. #endif
  11332. atexit(bfg_atexit);
  11333. b58_sha256_impl = my_blkmaker_sha256_callback;
  11334. blkmk_sha256_impl = my_blkmaker_sha256_callback;
  11335. bfg_init_threadlocal();
  11336. #ifndef HAVE_PTHREAD_CANCEL
  11337. setup_pthread_cancel_workaround();
  11338. #endif
  11339. bfg_init_checksums();
  11340. #ifdef WIN32
  11341. {
  11342. WSADATA wsa;
  11343. i = WSAStartup(MAKEWORD(2, 2), &wsa);
  11344. if (i)
  11345. quit(1, "Failed to initialise Winsock: %s", bfg_strerror(i, BST_SOCKET));
  11346. }
  11347. #endif
  11348. /* This dangerous functions tramples random dynamically allocated
  11349. * variables so do it before anything at all */
  11350. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  11351. quit(1, "Failed to curl_global_init");
  11352. initial_args = malloc(sizeof(char *) * (argc + 1));
  11353. for (i = 0; i < argc; i++)
  11354. initial_args[i] = strdup(argv[i]);
  11355. initial_args[argc] = NULL;
  11356. mutex_init(&hash_lock);
  11357. mutex_init(&console_lock);
  11358. cglock_init(&control_lock);
  11359. mutex_init(&stats_lock);
  11360. mutex_init(&sharelog_lock);
  11361. cglock_init(&ch_lock);
  11362. mutex_init(&sshare_lock);
  11363. rwlock_init(&blk_lock);
  11364. rwlock_init(&netacc_lock);
  11365. rwlock_init(&mining_thr_lock);
  11366. rwlock_init(&devices_lock);
  11367. mutex_init(&lp_lock);
  11368. if (unlikely(pthread_cond_init(&lp_cond, bfg_condattr)))
  11369. quit(1, "Failed to pthread_cond_init lp_cond");
  11370. if (unlikely(pthread_cond_init(&gws_cond, bfg_condattr)))
  11371. quit(1, "Failed to pthread_cond_init gws_cond");
  11372. notifier_init(submit_waiting_notifier);
  11373. timer_unset(&tv_rescan);
  11374. notifier_init(rescan_notifier);
  11375. /* Create a unique get work queue */
  11376. getq = tq_new();
  11377. if (!getq)
  11378. quit(1, "Failed to create getq");
  11379. /* We use the getq mutex as the staged lock */
  11380. stgd_lock = &getq->mutex;
  11381. snprintf(packagename, sizeof(packagename), "%s %s", PACKAGE, VERSION);
  11382. #ifdef WANT_CPUMINE
  11383. init_max_name_len();
  11384. #endif
  11385. handler.sa_handler = &sighandler;
  11386. handler.sa_flags = 0;
  11387. sigemptyset(&handler.sa_mask);
  11388. #ifdef HAVE_PTHREAD_CANCEL
  11389. sigaction(SIGTERM, &handler, &termhandler);
  11390. #else
  11391. // Need to let pthread_cancel emulation handle SIGTERM first
  11392. termhandler = pcwm_orig_term_handler;
  11393. pcwm_orig_term_handler = handler;
  11394. #endif
  11395. sigaction(SIGINT, &handler, &inthandler);
  11396. #ifndef WIN32
  11397. signal(SIGPIPE, SIG_IGN);
  11398. #else
  11399. timeBeginPeriod(1);
  11400. #endif
  11401. opt_kernel_path = CGMINER_PREFIX;
  11402. cgminer_path = alloca(PATH_MAX);
  11403. s = strdup(argv[0]);
  11404. strcpy(cgminer_path, dirname(s));
  11405. free(s);
  11406. strcat(cgminer_path, "/");
  11407. #if defined(WANT_CPUMINE) && defined(WIN32)
  11408. {
  11409. char buf[32];
  11410. int gev = GetEnvironmentVariable("BFGMINER_BENCH_ALGO", buf, sizeof(buf));
  11411. if (gev > 0 && gev < sizeof(buf))
  11412. {
  11413. setup_benchmark_pool();
  11414. double rate = bench_algo_stage3(atoi(buf));
  11415. // Write result to shared memory for parent
  11416. char unique_name[64];
  11417. if (GetEnvironmentVariable("BFGMINER_SHARED_MEM", unique_name, 32))
  11418. {
  11419. HANDLE map_handle = CreateFileMapping(
  11420. INVALID_HANDLE_VALUE, // use paging file
  11421. NULL, // default security attributes
  11422. PAGE_READWRITE, // read/write access
  11423. 0, // size: high 32-bits
  11424. 4096, // size: low 32-bits
  11425. unique_name // name of map object
  11426. );
  11427. if (NULL != map_handle) {
  11428. void *shared_mem = MapViewOfFile(
  11429. map_handle, // object to map view of
  11430. FILE_MAP_WRITE, // read/write access
  11431. 0, // high offset: map from
  11432. 0, // low offset: beginning
  11433. 0 // default: map entire file
  11434. );
  11435. if (NULL != shared_mem)
  11436. CopyMemory(shared_mem, &rate, sizeof(rate));
  11437. (void)UnmapViewOfFile(shared_mem);
  11438. }
  11439. (void)CloseHandle(map_handle);
  11440. }
  11441. exit(0);
  11442. }
  11443. }
  11444. #endif
  11445. #ifdef HAVE_CURSES
  11446. devcursor = 8;
  11447. logstart = devcursor;
  11448. logcursor = logstart;
  11449. #endif
  11450. mutex_init(&submitting_lock);
  11451. #ifdef HAVE_OPENCL
  11452. opencl_early_init();
  11453. #endif
  11454. schedstart.tm.tm_sec = 1;
  11455. schedstop .tm.tm_sec = 1;
  11456. opt_register_table(opt_early_table, NULL);
  11457. opt_register_table(opt_config_table, NULL);
  11458. opt_register_table(opt_cmdline_table, NULL);
  11459. opt_early_parse(argc, argv, applog_and_exit);
  11460. if (!config_loaded)
  11461. {
  11462. load_default_config();
  11463. rearrange_pools = total_pools;
  11464. }
  11465. opt_free_table();
  11466. /* parse command line */
  11467. opt_register_table(opt_config_table,
  11468. "Options for both config file and command line");
  11469. opt_register_table(opt_cmdline_table,
  11470. "Options for command line only");
  11471. opt_parse(&argc, argv, applog_and_exit);
  11472. if (argc != 1)
  11473. quit(1, "Unexpected extra commandline arguments");
  11474. if (rearrange_pools && rearrange_pools < total_pools)
  11475. {
  11476. // Prioritise commandline pools before default-config pools
  11477. for (i = 0; i < rearrange_pools; ++i)
  11478. pools[i]->prio += rearrange_pools;
  11479. for ( ; i < total_pools; ++i)
  11480. pools[i]->prio -= rearrange_pools;
  11481. }
  11482. #ifndef HAVE_PTHREAD_CANCEL
  11483. // Can't do this any earlier, or config isn't loaded
  11484. applog(LOG_DEBUG, "pthread_cancel workaround in use");
  11485. #endif
  11486. #ifdef HAVE_PWD_H
  11487. struct passwd *user_info = NULL;
  11488. if (opt_setuid != NULL) {
  11489. if ((user_info = getpwnam(opt_setuid)) == NULL) {
  11490. quit(1, "Unable to find setuid user information");
  11491. }
  11492. }
  11493. #endif
  11494. #ifdef HAVE_CHROOT
  11495. if (chroot_dir != NULL) {
  11496. #ifdef HAVE_PWD_H
  11497. if (user_info == NULL && getuid() == 0) {
  11498. applog(LOG_WARNING, "Running as root inside chroot");
  11499. }
  11500. #endif
  11501. if (chroot(chroot_dir) != 0) {
  11502. quit(1, "Unable to chroot");
  11503. }
  11504. if (chdir("/"))
  11505. quit(1, "Unable to chdir to chroot");
  11506. }
  11507. #endif
  11508. #ifdef HAVE_PWD_H
  11509. if (user_info != NULL) {
  11510. if (setgid((*user_info).pw_gid) != 0)
  11511. quit(1, "Unable to setgid");
  11512. if (setuid((*user_info).pw_uid) != 0)
  11513. quit(1, "Unable to setuid");
  11514. }
  11515. #endif
  11516. raise_fd_limits();
  11517. if (opt_benchmark) {
  11518. while (total_pools)
  11519. remove_pool(pools[0]);
  11520. setup_benchmark_pool();
  11521. }
  11522. if (opt_unittest) {
  11523. test_cgpu_match();
  11524. test_intrange();
  11525. test_decimal_width();
  11526. test_domain_funcs();
  11527. #ifdef USE_SCRYPT
  11528. test_scrypt();
  11529. #endif
  11530. test_target();
  11531. test_uri_get_param();
  11532. utf8_test();
  11533. #ifdef USE_JINGTIAN
  11534. test_aan_pll();
  11535. #endif
  11536. if (unittest_failures)
  11537. quit(1, "Unit tests failed");
  11538. }
  11539. #ifdef HAVE_CURSES
  11540. if (opt_realquiet || opt_display_devs)
  11541. use_curses = false;
  11542. setlocale(LC_ALL, "C");
  11543. if (use_curses)
  11544. enable_curses();
  11545. #endif
  11546. #ifdef HAVE_LIBUSB
  11547. int err = libusb_init(NULL);
  11548. if (err)
  11549. applog(LOG_WARNING, "libusb_init() failed err %d", err);
  11550. else
  11551. have_libusb = true;
  11552. #endif
  11553. applog(LOG_WARNING, "Started %s", packagename);
  11554. {
  11555. struct bfg_loaded_configfile *configfile;
  11556. LL_FOREACH(bfg_loaded_configfiles, configfile)
  11557. {
  11558. char * const cnfbuf = configfile->filename;
  11559. int fileconf_load = configfile->fileconf_load;
  11560. applog(LOG_NOTICE, "Loaded configuration file %s", cnfbuf);
  11561. switch (fileconf_load) {
  11562. case 0:
  11563. applog(LOG_WARNING, "Fatal JSON error in configuration file.");
  11564. applog(LOG_WARNING, "Configuration file could not be used.");
  11565. break;
  11566. case -1:
  11567. applog(LOG_WARNING, "Error in configuration file, partially loaded.");
  11568. if (use_curses)
  11569. applog(LOG_WARNING, "Start BFGMiner with -T to see what failed to load.");
  11570. break;
  11571. default:
  11572. break;
  11573. }
  11574. }
  11575. }
  11576. i = strlen(opt_kernel_path) + 2;
  11577. char __kernel_path[i];
  11578. snprintf(__kernel_path, i, "%s/", opt_kernel_path);
  11579. opt_kernel_path = __kernel_path;
  11580. if (want_per_device_stats)
  11581. opt_log_output = true;
  11582. bfg_devapi_init();
  11583. drv_detect_all();
  11584. total_devices = total_devices_new;
  11585. devices = devices_new;
  11586. total_devices_new = 0;
  11587. devices_new = NULL;
  11588. if (opt_display_devs) {
  11589. int devcount = 0;
  11590. applog(LOG_ERR, "Devices detected:");
  11591. for (i = 0; i < total_devices; ++i) {
  11592. struct cgpu_info *cgpu = devices[i];
  11593. char buf[0x100];
  11594. if (cgpu->device != cgpu)
  11595. continue;
  11596. if (cgpu->name)
  11597. snprintf(buf, sizeof(buf), " %s", cgpu->name);
  11598. else
  11599. if (cgpu->dev_manufacturer)
  11600. snprintf(buf, sizeof(buf), " %s by %s", (cgpu->dev_product ?: "Device"), cgpu->dev_manufacturer);
  11601. else
  11602. if (cgpu->dev_product)
  11603. snprintf(buf, sizeof(buf), " %s", cgpu->dev_product);
  11604. else
  11605. strcpy(buf, " Device");
  11606. tailsprintf(buf, sizeof(buf), " (driver=%s; procs=%d", cgpu->drv->dname, cgpu->procs);
  11607. if (cgpu->dev_serial)
  11608. tailsprintf(buf, sizeof(buf), "; serial=%s", cgpu->dev_serial);
  11609. if (cgpu->device_path)
  11610. tailsprintf(buf, sizeof(buf), "; path=%s", cgpu->device_path);
  11611. tailsprintf(buf, sizeof(buf), ")");
  11612. _applog(LOG_NOTICE, buf);
  11613. ++devcount;
  11614. }
  11615. quit(0, "%d devices listed", devcount);
  11616. }
  11617. mining_threads = 0;
  11618. for (i = 0; i < total_devices; ++i)
  11619. register_device(devices[i]);
  11620. if (!total_devices) {
  11621. applog(LOG_WARNING, "No devices detected!");
  11622. if (use_curses)
  11623. applog(LOG_WARNING, "Waiting for devices; press 'M+' to add, or 'Q' to quit");
  11624. else
  11625. applog(LOG_WARNING, "Waiting for devices");
  11626. }
  11627. #ifdef HAVE_CURSES
  11628. switch_logsize();
  11629. #endif
  11630. #if BLKMAKER_VERSION > 1
  11631. if (opt_load_bitcoin_conf && !(opt_scrypt || opt_benchmark))
  11632. add_local_gbt(total_pools);
  11633. #endif
  11634. if (!total_pools) {
  11635. applog(LOG_WARNING, "Need to specify at least one pool server.");
  11636. #ifdef HAVE_CURSES
  11637. if (!use_curses || !input_pool(false))
  11638. #endif
  11639. quit(1, "Pool setup failed");
  11640. }
  11641. for (i = 0; i < total_pools; i++) {
  11642. struct pool *pool = pools[i];
  11643. size_t siz;
  11644. if (!pool->rpc_url)
  11645. quit(1, "No URI supplied for pool %u", i);
  11646. if (!pool->rpc_userpass) {
  11647. if (!pool->rpc_user || !pool->rpc_pass)
  11648. quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  11649. siz = strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2;
  11650. pool->rpc_userpass = malloc(siz);
  11651. if (!pool->rpc_userpass)
  11652. quit(1, "Failed to malloc userpass");
  11653. snprintf(pool->rpc_userpass, siz, "%s:%s", pool->rpc_user, pool->rpc_pass);
  11654. }
  11655. }
  11656. /* Set the currentpool to pool with priority 0 */
  11657. validate_pool_priorities();
  11658. for (i = 0; i < total_pools; i++) {
  11659. struct pool *pool = pools[i];
  11660. if (!pool->prio)
  11661. currentpool = pool;
  11662. }
  11663. #ifdef HAVE_SYSLOG_H
  11664. if (use_syslog)
  11665. openlog(PACKAGE, LOG_PID, LOG_USER);
  11666. #endif
  11667. #if defined(unix) || defined(__APPLE__)
  11668. if (opt_stderr_cmd)
  11669. fork_monitor();
  11670. #endif // defined(unix)
  11671. mining_thr = calloc(mining_threads, sizeof(thr));
  11672. if (!mining_thr)
  11673. quit(1, "Failed to calloc mining_thr");
  11674. for (i = 0; i < mining_threads; i++) {
  11675. mining_thr[i] = calloc(1, sizeof(*thr));
  11676. if (!mining_thr[i])
  11677. quit(1, "Failed to calloc mining_thr[%d]", i);
  11678. }
  11679. total_control_threads = 6;
  11680. control_thr = calloc(total_control_threads, sizeof(*thr));
  11681. if (!control_thr)
  11682. quit(1, "Failed to calloc control_thr");
  11683. if (opt_benchmark)
  11684. goto begin_bench;
  11685. applog(LOG_NOTICE, "Probing for an alive pool");
  11686. do {
  11687. bool still_testing;
  11688. int i;
  11689. /* Look for at least one active pool before starting */
  11690. probe_pools();
  11691. do {
  11692. sleep(1);
  11693. if (pools_active)
  11694. break;
  11695. still_testing = false;
  11696. for (int i = 0; i < total_pools; ++i)
  11697. if (pools[i]->testing)
  11698. still_testing = true;
  11699. } while (still_testing);
  11700. if (!pools_active) {
  11701. applog(LOG_ERR, "No servers were found that could be used to get work from.");
  11702. applog(LOG_ERR, "Please check the details from the list below of the servers you have input");
  11703. applog(LOG_ERR, "Most likely you have input the wrong URL, forgotten to add a port, or have not set up workers");
  11704. for (i = 0; i < total_pools; i++) {
  11705. struct pool *pool;
  11706. pool = pools[i];
  11707. applog(LOG_WARNING, "Pool: %d URL: %s User: %s Password: %s",
  11708. i, pool->rpc_url, pool->rpc_user, pool->rpc_pass);
  11709. }
  11710. #ifdef HAVE_CURSES
  11711. if (use_curses) {
  11712. halfdelay(150);
  11713. applog(LOG_ERR, "Press any key to exit, or BFGMiner will try again in 15s.");
  11714. if (getch() != ERR)
  11715. quit(0, "No servers could be used! Exiting.");
  11716. cbreak();
  11717. } else
  11718. #endif
  11719. quit(0, "No servers could be used! Exiting.");
  11720. }
  11721. } while (!pools_active);
  11722. #ifdef USE_SCRYPT
  11723. if (detect_algo == 1 && !opt_scrypt) {
  11724. applog(LOG_NOTICE, "Detected scrypt algorithm");
  11725. set_malgo_scrypt();
  11726. }
  11727. #endif
  11728. detect_algo = 0;
  11729. begin_bench:
  11730. total_mhashes_done = 0;
  11731. for (i = 0; i < total_devices; i++) {
  11732. struct cgpu_info *cgpu = devices[i];
  11733. cgpu->rolling = cgpu->total_mhashes = 0;
  11734. }
  11735. cgtime(&total_tv_start);
  11736. cgtime(&total_tv_end);
  11737. miner_started = total_tv_start;
  11738. time_t miner_start_ts = time(NULL);
  11739. if (schedstart.tm.tm_sec)
  11740. localtime_r(&miner_start_ts, &schedstart.tm);
  11741. if (schedstop.tm.tm_sec)
  11742. localtime_r(&miner_start_ts, &schedstop .tm);
  11743. get_datestamp(datestamp, sizeof(datestamp), miner_start_ts);
  11744. // Initialise processors and threads
  11745. k = 0;
  11746. for (i = 0; i < total_devices; ++i) {
  11747. struct cgpu_info *cgpu = devices[i];
  11748. allocate_cgpu(cgpu, &k);
  11749. }
  11750. // Start threads
  11751. for (i = 0; i < total_devices; ++i) {
  11752. struct cgpu_info *cgpu = devices[i];
  11753. start_cgpu(cgpu);
  11754. }
  11755. #ifdef HAVE_OPENCL
  11756. for (i = 0; i < nDevs; i++)
  11757. pause_dynamic_threads(i);
  11758. #endif
  11759. #ifdef WANT_CPUMINE
  11760. if (opt_n_threads > 0)
  11761. applog(LOG_INFO, "%d cpu miner threads started, using '%s' algorithm.",
  11762. opt_n_threads, algo_names[opt_algo]);
  11763. #endif
  11764. cgtime(&total_tv_start);
  11765. cgtime(&total_tv_end);
  11766. if (!opt_benchmark)
  11767. {
  11768. pthread_t submit_thread;
  11769. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, NULL)))
  11770. quit(1, "submit_work thread create failed");
  11771. }
  11772. watchpool_thr_id = 1;
  11773. thr = &control_thr[watchpool_thr_id];
  11774. /* start watchpool thread */
  11775. if (thr_info_create(thr, NULL, watchpool_thread, NULL))
  11776. quit(1, "watchpool thread create failed");
  11777. pthread_detach(thr->pth);
  11778. watchdog_thr_id = 2;
  11779. thr = &control_thr[watchdog_thr_id];
  11780. /* start watchdog thread */
  11781. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  11782. quit(1, "watchdog thread create failed");
  11783. pthread_detach(thr->pth);
  11784. #ifdef HAVE_OPENCL
  11785. /* Create reinit gpu thread */
  11786. gpur_thr_id = 3;
  11787. thr = &control_thr[gpur_thr_id];
  11788. thr->q = tq_new();
  11789. if (!thr->q)
  11790. quit(1, "tq_new failed for gpur_thr_id");
  11791. if (thr_info_create(thr, NULL, reinit_gpu, thr))
  11792. quit(1, "reinit_gpu thread create failed");
  11793. #endif
  11794. /* Create API socket thread */
  11795. api_thr_id = 4;
  11796. thr = &control_thr[api_thr_id];
  11797. if (thr_info_create(thr, NULL, api_thread, thr))
  11798. quit(1, "API thread create failed");
  11799. #ifdef USE_LIBMICROHTTPD
  11800. if (httpsrv_port != -1)
  11801. httpsrv_start(httpsrv_port);
  11802. #endif
  11803. #ifdef USE_LIBEVENT
  11804. if (stratumsrv_port != -1)
  11805. stratumsrv_start();
  11806. #endif
  11807. #ifdef HAVE_BFG_HOTPLUG
  11808. if (opt_hotplug)
  11809. hotplug_start();
  11810. #endif
  11811. #ifdef HAVE_CURSES
  11812. /* Create curses input thread for keyboard input. Create this last so
  11813. * that we know all threads are created since this can call kill_work
  11814. * to try and shut down ll previous threads. */
  11815. input_thr_id = 5;
  11816. thr = &control_thr[input_thr_id];
  11817. if (thr_info_create(thr, NULL, input_thread, thr))
  11818. quit(1, "input thread create failed");
  11819. pthread_detach(thr->pth);
  11820. #endif
  11821. /* Just to be sure */
  11822. if (total_control_threads != 6)
  11823. quit(1, "incorrect total_control_threads (%d) should be 7", total_control_threads);
  11824. /* Once everything is set up, main() becomes the getwork scheduler */
  11825. while (42) {
  11826. int ts, max_staged = opt_queue;
  11827. struct pool *pool, *cp;
  11828. bool lagging = false;
  11829. struct curl_ent *ce;
  11830. struct work *work;
  11831. struct mining_algorithm *malgo = NULL;
  11832. cp = current_pool();
  11833. // Generally, each processor needs a new work, and all at once during work restarts
  11834. max_staged += base_queue;
  11835. mutex_lock(stgd_lock);
  11836. ts = __total_staged();
  11837. if (!pool_localgen(cp) && !ts && !opt_fail_only)
  11838. lagging = true;
  11839. /* Wait until hash_pop tells us we need to create more work */
  11840. if (ts > max_staged) {
  11841. {
  11842. LL_FOREACH(mining_algorithms, malgo)
  11843. {
  11844. if (!malgo->goal_refs)
  11845. continue;
  11846. if (malgo->staged < malgo->base_queue + opt_queue)
  11847. {
  11848. mutex_unlock(stgd_lock);
  11849. goto need_malgo_queued;
  11850. }
  11851. }
  11852. malgo = NULL;
  11853. }
  11854. staged_full = true;
  11855. pthread_cond_wait(&gws_cond, stgd_lock);
  11856. ts = __total_staged();
  11857. }
  11858. mutex_unlock(stgd_lock);
  11859. if (ts > max_staged)
  11860. continue;
  11861. need_malgo_queued: ;
  11862. work = make_work();
  11863. if (lagging && !pool_tset(cp, &cp->lagging)) {
  11864. applog(LOG_WARNING, "Pool %d not providing work fast enough", cp->pool_no);
  11865. cp->getfail_occasions++;
  11866. total_go++;
  11867. }
  11868. pool = select_pool(lagging, malgo);
  11869. retry:
  11870. if (pool->has_stratum) {
  11871. while (!pool->stratum_active || !pool->stratum_notify) {
  11872. struct pool *altpool = select_pool(true, malgo);
  11873. if (altpool == pool && pool->has_stratum)
  11874. cgsleep_ms(5000);
  11875. pool = altpool;
  11876. goto retry;
  11877. }
  11878. gen_stratum_work(pool, work);
  11879. applog(LOG_DEBUG, "Generated stratum work");
  11880. stage_work(work);
  11881. continue;
  11882. }
  11883. if (pool->last_work_copy) {
  11884. mutex_lock(&pool->last_work_lock);
  11885. struct work *last_work = pool->last_work_copy;
  11886. if (!last_work)
  11887. {}
  11888. else
  11889. if (can_roll(last_work) && should_roll(last_work)) {
  11890. struct timeval tv_now;
  11891. cgtime(&tv_now);
  11892. free_work(work);
  11893. work = make_clone(pool->last_work_copy);
  11894. mutex_unlock(&pool->last_work_lock);
  11895. roll_work(work);
  11896. 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));
  11897. stage_work(work);
  11898. continue;
  11899. } else if (last_work->tr && pool->proto == PLP_GETBLOCKTEMPLATE && blkmk_work_left(last_work->tr->tmpl) > (unsigned long)mining_threads) {
  11900. // Don't free last_work_copy, since it is used to detect upstream provides plenty of work per template
  11901. } else {
  11902. free_work(last_work);
  11903. pool->last_work_copy = NULL;
  11904. }
  11905. mutex_unlock(&pool->last_work_lock);
  11906. }
  11907. if (clone_available()) {
  11908. applog(LOG_DEBUG, "Cloned getwork work");
  11909. free_work(work);
  11910. continue;
  11911. }
  11912. if (opt_benchmark) {
  11913. get_benchmark_work(work, opt_benchmark_intense);
  11914. applog(LOG_DEBUG, "Generated benchmark work");
  11915. stage_work(work);
  11916. continue;
  11917. }
  11918. work->pool = pool;
  11919. ce = pop_curl_entry3(pool, 2);
  11920. /* obtain new work from bitcoin via JSON-RPC */
  11921. if (!get_upstream_work(work, ce->curl)) {
  11922. struct pool *next_pool;
  11923. /* Make sure the pool just hasn't stopped serving
  11924. * requests but is up as we'll keep hammering it */
  11925. push_curl_entry(ce, pool);
  11926. ++pool->seq_getfails;
  11927. pool_died(pool);
  11928. next_pool = select_pool(!opt_fail_only, malgo);
  11929. if (pool == next_pool) {
  11930. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, retrying in 5s", pool->pool_no);
  11931. cgsleep_ms(5000);
  11932. } else {
  11933. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, failover activated", pool->pool_no);
  11934. pool = next_pool;
  11935. }
  11936. goto retry;
  11937. }
  11938. if (ts >= max_staged)
  11939. pool_tclear(pool, &pool->lagging);
  11940. if (pool_tclear(pool, &pool->idle))
  11941. pool_resus(pool);
  11942. applog(LOG_DEBUG, "Generated getwork work");
  11943. stage_work(work);
  11944. push_curl_entry(ce, pool);
  11945. }
  11946. return 0;
  11947. }