miner.c 309 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157
  1. /*
  2. * Copyright 2011-2013 Con Kolivas
  3. * Copyright 2011-2013 Luke Dashjr
  4. * Copyright 2012-2013 Andrew Smith
  5. * Copyright 2010 Jeff Garzik
  6. *
  7. * This program is free software; you can redistribute it and/or modify it
  8. * under the terms of the GNU General Public License as published by the Free
  9. * Software Foundation; either version 3 of the License, or (at your option)
  10. * any later version. See COPYING for more details.
  11. */
  12. #include "config.h"
  13. #ifdef HAVE_CURSES
  14. #ifdef USE_UNICODE
  15. #define PDC_WIDE
  16. #endif
  17. // Must be before stdbool, since pdcurses typedefs bool :/
  18. #include <curses.h>
  19. #endif
  20. #include <ctype.h>
  21. #include <float.h>
  22. #include <limits.h>
  23. #include <locale.h>
  24. #include <stdio.h>
  25. #include <stdlib.h>
  26. #include <string.h>
  27. #include <stdbool.h>
  28. #include <stdint.h>
  29. #include <unistd.h>
  30. #include <sys/time.h>
  31. #include <time.h>
  32. #include <math.h>
  33. #include <stdarg.h>
  34. #include <assert.h>
  35. #include <signal.h>
  36. #include <wctype.h>
  37. #include <sys/stat.h>
  38. #include <sys/types.h>
  39. #include <dirent.h>
  40. #ifdef HAVE_PWD_H
  41. #include <pwd.h>
  42. #endif
  43. #ifndef WIN32
  44. #include <sys/resource.h>
  45. #include <sys/socket.h>
  46. #if defined(HAVE_LIBUDEV) && defined(HAVE_SYS_EPOLL_H)
  47. #include <libudev.h>
  48. #include <sys/epoll.h>
  49. #define HAVE_BFG_HOTPLUG
  50. #endif
  51. #else
  52. #include <winsock2.h>
  53. #include <windows.h>
  54. #include <dbt.h>
  55. #define HAVE_BFG_HOTPLUG
  56. #endif
  57. #include <ccan/opt/opt.h>
  58. #include <jansson.h>
  59. #include <curl/curl.h>
  60. #include <libgen.h>
  61. #include <sha2.h>
  62. #include <utlist.h>
  63. #include <blkmaker.h>
  64. #include <blkmaker_jansson.h>
  65. #include <blktemplate.h>
  66. #include "compat.h"
  67. #include "deviceapi.h"
  68. #include "logging.h"
  69. #include "miner.h"
  70. #include "adl.h"
  71. #include "driver-cpu.h"
  72. #include "driver-opencl.h"
  73. #include "scrypt.h"
  74. #ifdef USE_AVALON
  75. #include "driver-avalon.h"
  76. #endif
  77. #ifdef HAVE_BFG_LOWLEVEL
  78. #include "lowlevel.h"
  79. #endif
  80. #if defined(unix) || defined(__APPLE__)
  81. #include <errno.h>
  82. #include <fcntl.h>
  83. #include <sys/wait.h>
  84. #endif
  85. #ifdef USE_SCRYPT
  86. #include "scrypt.h"
  87. #endif
  88. #if defined(USE_AVALON) || defined(USE_BITFORCE) || defined(USE_ICARUS) || defined(USE_MODMINER) || defined(USE_NANOFURY) || defined(USE_X6500) || defined(USE_ZTEX)
  89. # define USE_FPGA
  90. #endif
  91. enum bfg_quit_summary {
  92. BQS_DEFAULT,
  93. BQS_NONE,
  94. BQS_DEVS,
  95. BQS_PROCS,
  96. BQS_DETAILED,
  97. };
  98. struct strategies strategies[] = {
  99. { "Failover" },
  100. { "Round Robin" },
  101. { "Rotate" },
  102. { "Load Balance" },
  103. { "Balance" },
  104. };
  105. static char packagename[256];
  106. bool opt_protocol;
  107. bool opt_dev_protocol;
  108. static bool opt_benchmark;
  109. static bool want_longpoll = true;
  110. static bool want_gbt = true;
  111. static bool want_getwork = true;
  112. #if BLKMAKER_VERSION > 1
  113. struct _cbscript_t {
  114. char *data;
  115. size_t sz;
  116. };
  117. static struct _cbscript_t opt_coinbase_script;
  118. static uint32_t template_nonce;
  119. #endif
  120. #if BLKMAKER_VERSION > 0
  121. char *opt_coinbase_sig;
  122. #endif
  123. static enum bfg_quit_summary opt_quit_summary = BQS_DEFAULT;
  124. static bool include_serial_in_statline;
  125. char *request_target_str;
  126. float request_pdiff = 1.0;
  127. double request_bdiff;
  128. static bool want_stratum = true;
  129. bool have_longpoll;
  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 long global_quota_gcd = 1;
  151. time_t last_getwork;
  152. #ifdef HAVE_OPENCL
  153. int opt_dynamic_interval = 7;
  154. int nDevs;
  155. int opt_g_threads = -1;
  156. #endif
  157. #ifdef USE_SCRYPT
  158. static char detect_algo = 1;
  159. bool opt_scrypt;
  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 num_processors;
  193. #ifdef HAVE_CURSES
  194. bool use_curses = true;
  195. #else
  196. bool use_curses;
  197. #endif
  198. #ifdef HAVE_LIBUSB
  199. bool have_libusb;
  200. #endif
  201. static bool opt_submit_stale = true;
  202. static float opt_shares;
  203. static int opt_submit_threads = 0x40;
  204. bool opt_fail_only;
  205. bool opt_autofan;
  206. bool opt_autoengine;
  207. bool opt_noadl;
  208. char *opt_api_allow = NULL;
  209. char *opt_api_groups;
  210. char *opt_api_description = PACKAGE_STRING;
  211. int opt_api_port = 4028;
  212. bool opt_api_listen;
  213. bool opt_api_mcast;
  214. char *opt_api_mcast_addr = API_MCAST_ADDR;
  215. char *opt_api_mcast_code = API_MCAST_CODE;
  216. char *opt_api_mcast_des = "";
  217. int opt_api_mcast_port = 4028;
  218. bool opt_api_network;
  219. bool opt_delaynet;
  220. bool opt_disable_pool;
  221. bool opt_disable_client_reconnect = false;
  222. static bool no_work;
  223. bool opt_worktime;
  224. bool opt_weighed_stats;
  225. char *opt_kernel_path;
  226. char *cgminer_path;
  227. #if defined(USE_BITFORCE)
  228. bool opt_bfl_noncerange;
  229. #endif
  230. #define QUIET (opt_quiet || opt_realquiet)
  231. struct thr_info *control_thr;
  232. struct thr_info **mining_thr;
  233. static int gwsched_thr_id;
  234. static int watchpool_thr_id;
  235. static int watchdog_thr_id;
  236. #ifdef HAVE_CURSES
  237. static int input_thr_id;
  238. #endif
  239. int gpur_thr_id;
  240. static int api_thr_id;
  241. static int total_control_threads;
  242. pthread_mutex_t hash_lock;
  243. static pthread_mutex_t *stgd_lock;
  244. pthread_mutex_t console_lock;
  245. cglock_t ch_lock;
  246. static pthread_rwlock_t blk_lock;
  247. static pthread_mutex_t sshare_lock;
  248. pthread_rwlock_t netacc_lock;
  249. pthread_rwlock_t mining_thr_lock;
  250. pthread_rwlock_t devices_lock;
  251. static pthread_mutex_t lp_lock;
  252. static pthread_cond_t lp_cond;
  253. pthread_cond_t gws_cond;
  254. bool shutting_down;
  255. double total_rolling;
  256. double total_mhashes_done;
  257. static struct timeval total_tv_start, total_tv_end;
  258. static struct timeval miner_started;
  259. cglock_t control_lock;
  260. pthread_mutex_t stats_lock;
  261. static pthread_mutex_t submitting_lock;
  262. static int total_submitting;
  263. static struct work *submit_waiting;
  264. notifier_t submit_waiting_notifier;
  265. int hw_errors;
  266. int total_accepted, total_rejected;
  267. int total_getworks, total_stale, total_discarded;
  268. uint64_t total_bytes_rcvd, total_bytes_sent;
  269. double total_diff1, total_bad_diff1;
  270. double total_diff_accepted, total_diff_rejected, total_diff_stale;
  271. static int staged_rollable;
  272. unsigned int new_blocks;
  273. unsigned int found_blocks;
  274. unsigned int local_work;
  275. unsigned int total_go, total_ro;
  276. struct pool **pools;
  277. static struct pool *currentpool = NULL;
  278. int total_pools, enabled_pools;
  279. enum pool_strategy pool_strategy = POOL_FAILOVER;
  280. int opt_rotate_period;
  281. static int total_urls, total_users, total_passes;
  282. static
  283. #ifndef HAVE_CURSES
  284. const
  285. #endif
  286. bool curses_active;
  287. #ifdef HAVE_CURSES
  288. #if !(defined(PDCURSES) || defined(NCURSES_VERSION))
  289. const
  290. #endif
  291. short default_bgcolor = COLOR_BLACK;
  292. static int attr_title = A_BOLD;
  293. #endif
  294. static
  295. #if defined(HAVE_CURSES) && defined(USE_UNICODE)
  296. bool use_unicode;
  297. static
  298. bool have_unicode_degrees;
  299. static
  300. wchar_t unicode_micro = 'u';
  301. #else
  302. const bool use_unicode;
  303. static
  304. const bool have_unicode_degrees;
  305. static
  306. const char unicode_micro = 'u';
  307. #endif
  308. #ifdef HAVE_CURSES
  309. #define U8_BAD_START "\xef\x80\x81"
  310. #define U8_BAD_END "\xef\x80\x80"
  311. #define AS_BAD(x) U8_BAD_START x U8_BAD_END
  312. bool selecting_device;
  313. unsigned selected_device;
  314. #endif
  315. static char current_block[40];
  316. /* Protected by ch_lock */
  317. static char *current_hash;
  318. static uint32_t current_block_id;
  319. char *current_fullhash;
  320. static char datestamp[40];
  321. static char blocktime[32];
  322. time_t block_time;
  323. static char best_share[ALLOC_H2B_SHORTV] = "0";
  324. double current_diff = 0xFFFFFFFFFFFFFFFFULL;
  325. static char block_diff[ALLOC_H2B_SHORTV];
  326. static char net_hashrate[ALLOC_H2B_SHORT];
  327. double best_diff = 0;
  328. static bool known_blkheight_current;
  329. static uint32_t known_blkheight;
  330. static uint32_t known_blkheight_blkid;
  331. static uint64_t block_subsidy;
  332. struct block {
  333. char hash[40];
  334. UT_hash_handle hh;
  335. int block_no;
  336. };
  337. static struct block *blocks = NULL;
  338. int swork_id;
  339. /* For creating a hash database of stratum shares submitted that have not had
  340. * a response yet */
  341. struct stratum_share {
  342. UT_hash_handle hh;
  343. bool block;
  344. struct work *work;
  345. int id;
  346. };
  347. static struct stratum_share *stratum_shares = NULL;
  348. char *opt_socks_proxy = NULL;
  349. static const char def_conf[] = "bfgminer.conf";
  350. static bool config_loaded;
  351. static int include_count;
  352. #define JSON_INCLUDE_CONF "include"
  353. #define JSON_LOAD_ERROR "JSON decode of file '%s' failed\n %s"
  354. #define JSON_LOAD_ERROR_LEN strlen(JSON_LOAD_ERROR)
  355. #define JSON_MAX_DEPTH 10
  356. #define JSON_MAX_DEPTH_ERR "Too many levels of JSON includes (limit 10) or a loop"
  357. char *cmd_idle, *cmd_sick, *cmd_dead;
  358. #if defined(unix) || defined(__APPLE__)
  359. static char *opt_stderr_cmd = NULL;
  360. static int forkpid;
  361. #endif // defined(unix)
  362. #ifdef HAVE_CHROOT
  363. char *chroot_dir;
  364. #endif
  365. #ifdef HAVE_PWD_H
  366. char *opt_setuid;
  367. #endif
  368. struct sigaction termhandler, inthandler;
  369. struct thread_q *getq;
  370. static int total_work;
  371. static bool staged_full;
  372. struct work *staged_work = NULL;
  373. struct schedtime {
  374. bool enable;
  375. struct tm tm;
  376. };
  377. struct schedtime schedstart;
  378. struct schedtime schedstop;
  379. bool sched_paused;
  380. static bool time_before(struct tm *tm1, struct tm *tm2)
  381. {
  382. if (tm1->tm_hour < tm2->tm_hour)
  383. return true;
  384. if (tm1->tm_hour == tm2->tm_hour && tm1->tm_min < tm2->tm_min)
  385. return true;
  386. return false;
  387. }
  388. static bool should_run(void)
  389. {
  390. struct tm tm;
  391. time_t tt;
  392. bool within_range;
  393. if (!schedstart.enable && !schedstop.enable)
  394. return true;
  395. tt = time(NULL);
  396. localtime_r(&tt, &tm);
  397. // NOTE: This is delicately balanced so that should_run is always false if schedstart==schedstop
  398. if (time_before(&schedstop.tm, &schedstart.tm))
  399. within_range = (time_before(&tm, &schedstop.tm) || !time_before(&tm, &schedstart.tm));
  400. else
  401. within_range = (time_before(&tm, &schedstop.tm) && !time_before(&tm, &schedstart.tm));
  402. if (within_range && !schedstop.enable)
  403. /* This is a once off event with no stop time set */
  404. schedstart.enable = false;
  405. return within_range;
  406. }
  407. void get_datestamp(char *f, size_t fsiz, time_t tt)
  408. {
  409. struct tm _tm;
  410. struct tm *tm = &_tm;
  411. if (tt == INVALID_TIMESTAMP)
  412. tt = time(NULL);
  413. localtime_r(&tt, tm);
  414. snprintf(f, fsiz, "[%d-%02d-%02d %02d:%02d:%02d]",
  415. tm->tm_year + 1900,
  416. tm->tm_mon + 1,
  417. tm->tm_mday,
  418. tm->tm_hour,
  419. tm->tm_min,
  420. tm->tm_sec);
  421. }
  422. static
  423. void get_timestamp(char *f, size_t fsiz, time_t tt)
  424. {
  425. struct tm _tm;
  426. struct tm *tm = &_tm;
  427. localtime_r(&tt, tm);
  428. snprintf(f, fsiz, "[%02d:%02d:%02d]",
  429. tm->tm_hour,
  430. tm->tm_min,
  431. tm->tm_sec);
  432. }
  433. static void applog_and_exit(const char *fmt, ...) FORMAT_SYNTAX_CHECK(printf, 1, 2);
  434. static char exit_buf[512];
  435. static void applog_and_exit(const char *fmt, ...)
  436. {
  437. va_list ap;
  438. va_start(ap, fmt);
  439. vsnprintf(exit_buf, sizeof(exit_buf), fmt, ap);
  440. va_end(ap);
  441. _applog(LOG_ERR, exit_buf);
  442. exit(1);
  443. }
  444. char *devpath_to_devid(const char *devpath)
  445. {
  446. #ifndef WIN32
  447. struct stat my_stat;
  448. if (stat(devpath, &my_stat))
  449. return NULL;
  450. char *devs = malloc(6 + (sizeof(dev_t) * 2) + 1);
  451. memcpy(devs, "dev_t:", 6);
  452. bin2hex(&devs[6], &my_stat.st_rdev, sizeof(dev_t));
  453. #else
  454. if (!strncmp(devpath, "\\\\.\\", 4))
  455. devpath += 4;
  456. if (strncasecmp(devpath, "COM", 3) || !devpath[3])
  457. return NULL;
  458. devpath += 3;
  459. char *p;
  460. strtol(devpath, &p, 10);
  461. if (p[0])
  462. return NULL;
  463. const int sz = (p - devpath);
  464. char *devs = malloc(4 + sz + 1);
  465. sprintf(devs, "com:%s", devpath);
  466. #endif
  467. return devs;
  468. }
  469. static
  470. bool devpaths_match(const char * const ap, const char * const bp)
  471. {
  472. char * const a = devpath_to_devid(ap);
  473. if (!a)
  474. return false;
  475. char * const b = devpath_to_devid(bp);
  476. bool rv = false;
  477. if (b)
  478. {
  479. rv = !strcmp(a, b);
  480. free(b);
  481. }
  482. free(a);
  483. return rv;
  484. }
  485. static
  486. int proc_letter_to_number(const char *s, const char ** const rem)
  487. {
  488. int n = 0, c;
  489. for ( ; s[0]; ++s)
  490. {
  491. if (unlikely(n > INT_MAX / 26))
  492. break;
  493. c = tolower(s[0]) - 'a';
  494. if (unlikely(c < 0 || c > 25))
  495. break;
  496. if (unlikely(INT_MAX - c < n))
  497. break;
  498. n = (n * 26) + c;
  499. }
  500. *rem = s;
  501. return n;
  502. }
  503. static
  504. bool cgpu_match(const char * const pattern, const struct cgpu_info * const cgpu)
  505. {
  506. // all - matches anything
  507. // d0 - matches all processors of device 0
  508. // d0-3 - matches all processors of device 0, 1, 2, or 3
  509. // d0a - matches first processor of device 0
  510. // 0 - matches processor 0
  511. // 0-4 - matches processors 0, 1, 2, 3, or 4
  512. // ___ - matches all processors on all devices using driver/name ___
  513. // ___0 - matches all processors of 0th device using driver/name ___
  514. // ___0a - matches first processor of 0th device using driver/name ___
  515. // @* - matches device with serial or path *
  516. // @*@a - matches first processor of device with serial or path *
  517. // ___@* - matches device with serial or path * using driver/name ___
  518. if (!strcasecmp(pattern, "all"))
  519. return true;
  520. const struct device_drv * const drv = cgpu->drv;
  521. const char *p = pattern, *p2;
  522. size_t L;
  523. int n, i, c = -1;
  524. int n2;
  525. int proc_first = -1, proc_last = -1;
  526. struct cgpu_info *device;
  527. if (!(strncasecmp(drv->dname, p, (L = strlen(drv->dname)))
  528. && strncasecmp(drv-> name, p, (L = strlen(drv-> name)))))
  529. // dname or name
  530. p = &pattern[L];
  531. else
  532. if (p[0] == 'd' && (isdigit(p[1]) || p[1] == '-'))
  533. // d#
  534. ++p;
  535. else
  536. if (isdigit(p[0]) || p[0] == '@' || p[0] == '-')
  537. // # or @
  538. {}
  539. else
  540. return false;
  541. L = p - pattern;
  542. while (isspace(p[0]))
  543. ++p;
  544. if (p[0] == '@')
  545. {
  546. // Serial/path
  547. const char * const ser = &p[1];
  548. for (p = ser; p[0] != '@' && p[0] != '\0'; ++p)
  549. {}
  550. p2 = (p[0] == '@') ? &p[1] : p;
  551. const size_t serlen = (p - ser);
  552. p = "";
  553. n = n2 = 0;
  554. const char * const devpath = cgpu->device_path ?: "";
  555. const char * const devser = cgpu->dev_serial ?: "";
  556. if ((!strncmp(devpath, ser, serlen)) && devpath[serlen] == '\0')
  557. {} // Match
  558. else
  559. if ((!strncmp(devser, ser, serlen)) && devser[serlen] == '\0')
  560. {} // Match
  561. else
  562. {
  563. char devpath2[serlen + 1];
  564. memcpy(devpath2, ser, serlen);
  565. devpath2[serlen] = '\0';
  566. if (!devpaths_match(devpath, ser))
  567. return false;
  568. }
  569. }
  570. else
  571. {
  572. if (isdigit(p[0]))
  573. n = strtol(p, (void*)&p2, 0);
  574. else
  575. {
  576. n = 0;
  577. p2 = p;
  578. }
  579. if (p2[0] == '-')
  580. {
  581. ++p2;
  582. if (p2[0] && isdigit(p2[0]))
  583. n2 = strtol(p2, (void*)&p2, 0);
  584. else
  585. n2 = INT_MAX;
  586. }
  587. else
  588. n2 = n;
  589. if (p == pattern)
  590. {
  591. if (!p[0])
  592. return true;
  593. if (p2 && p2[0])
  594. goto invsyntax;
  595. for (i = n; i <= n2; ++i)
  596. {
  597. if (i >= total_devices)
  598. break;
  599. if (cgpu == devices[i])
  600. return true;
  601. }
  602. return false;
  603. }
  604. }
  605. if (p2[0])
  606. {
  607. proc_first = proc_letter_to_number(&p2[0], &p2);
  608. if (p2[0] == '-')
  609. {
  610. ++p2;
  611. if (p2[0])
  612. proc_last = proc_letter_to_number(p2, &p2);
  613. else
  614. proc_last = INT_MAX;
  615. }
  616. else
  617. proc_last = proc_first;
  618. if (p2[0])
  619. goto invsyntax;
  620. }
  621. if (L > 1 || tolower(pattern[0]) != 'd' || !p[0])
  622. {
  623. if ((L == 3 && !strncasecmp(pattern, drv->name, 3)) ||
  624. (!L) ||
  625. (L == strlen(drv->dname) && !strncasecmp(pattern, drv->dname, L)))
  626. {} // Matched name or dname
  627. else
  628. return false;
  629. if (p[0] && (cgpu->device_id < n || cgpu->device_id > n2))
  630. return false;
  631. if (proc_first != -1 && (cgpu->proc_id < proc_first || cgpu->proc_id > proc_last))
  632. return false;
  633. return true;
  634. }
  635. // d#
  636. c = -1;
  637. for (i = 0; ; ++i)
  638. {
  639. if (i == total_devices)
  640. return false;
  641. if (devices[i]->device != devices[i])
  642. continue;
  643. ++c;
  644. if (c < n)
  645. continue;
  646. if (c > n2)
  647. break;
  648. for (device = devices[i]; device; device = device->next_proc)
  649. {
  650. if (proc_first != -1 && (device->proc_id < proc_first || device->proc_id > proc_last))
  651. continue;
  652. if (device == cgpu)
  653. return true;
  654. }
  655. }
  656. return false;
  657. invsyntax:
  658. applog(LOG_WARNING, "%s: Invalid syntax: %s", __func__, pattern);
  659. return false;
  660. }
  661. #define TEST_CGPU_MATCH(pattern) \
  662. if (!cgpu_match(pattern, &cgpu)) \
  663. applog(LOG_ERR, "%s: Pattern \"%s\" should have matched!", __func__, pattern); \
  664. // END TEST_CGPU_MATCH
  665. #define TEST_CGPU_NOMATCH(pattern) \
  666. if (cgpu_match(pattern, &cgpu)) \
  667. applog(LOG_ERR, "%s: Pattern \"%s\" should NOT have matched!", __func__, pattern); \
  668. // END TEST_CGPU_MATCH
  669. static __maybe_unused
  670. void test_cgpu_match()
  671. {
  672. struct device_drv drv = {
  673. .dname = "test",
  674. .name = "TST",
  675. };
  676. struct cgpu_info cgpu = {
  677. .drv = &drv,
  678. .device = &cgpu,
  679. .device_id = 1,
  680. .proc_id = 1,
  681. .proc_repr = "TST 1b",
  682. }, cgpu0a = {
  683. .drv = &drv,
  684. .device = &cgpu0a,
  685. .device_id = 0,
  686. .proc_id = 0,
  687. .proc_repr = "TST 0a",
  688. }, cgpu1a = {
  689. .drv = &drv,
  690. .device = &cgpu0a,
  691. .device_id = 1,
  692. .proc_id = 0,
  693. .proc_repr = "TST 1a",
  694. };
  695. struct cgpu_info *devices_list[3] = {&cgpu0a, &cgpu1a, &cgpu,};
  696. devices = devices_list;
  697. total_devices = 3;
  698. TEST_CGPU_MATCH("all")
  699. TEST_CGPU_MATCH("d1")
  700. TEST_CGPU_NOMATCH("d2")
  701. TEST_CGPU_MATCH("d0-5")
  702. TEST_CGPU_NOMATCH("d0-0")
  703. TEST_CGPU_NOMATCH("d2-5")
  704. TEST_CGPU_MATCH("d-1")
  705. TEST_CGPU_MATCH("d1-")
  706. TEST_CGPU_NOMATCH("d-0")
  707. TEST_CGPU_NOMATCH("d2-")
  708. TEST_CGPU_MATCH("2")
  709. TEST_CGPU_NOMATCH("3")
  710. TEST_CGPU_MATCH("1-2")
  711. TEST_CGPU_MATCH("2-3")
  712. TEST_CGPU_NOMATCH("1-1")
  713. TEST_CGPU_NOMATCH("3-4")
  714. TEST_CGPU_MATCH("TST")
  715. TEST_CGPU_MATCH("test")
  716. TEST_CGPU_MATCH("tst")
  717. TEST_CGPU_MATCH("TEST")
  718. TEST_CGPU_NOMATCH("TSF")
  719. TEST_CGPU_NOMATCH("TS")
  720. TEST_CGPU_NOMATCH("TSTF")
  721. TEST_CGPU_MATCH("TST1")
  722. TEST_CGPU_MATCH("test1")
  723. TEST_CGPU_MATCH("TST0-1")
  724. TEST_CGPU_MATCH("TST 1")
  725. TEST_CGPU_MATCH("TST 1-2")
  726. TEST_CGPU_MATCH("TEST 1-2")
  727. TEST_CGPU_NOMATCH("TST2")
  728. TEST_CGPU_NOMATCH("TST2-3")
  729. TEST_CGPU_NOMATCH("TST0-0")
  730. TEST_CGPU_MATCH("TST1b")
  731. TEST_CGPU_MATCH("tst1b")
  732. TEST_CGPU_NOMATCH("TST1c")
  733. TEST_CGPU_NOMATCH("TST1bb")
  734. TEST_CGPU_MATCH("TST0-1b")
  735. TEST_CGPU_NOMATCH("TST0-1c")
  736. TEST_CGPU_MATCH("TST1a-d")
  737. TEST_CGPU_NOMATCH("TST1a-a")
  738. TEST_CGPU_NOMATCH("TST1-a")
  739. TEST_CGPU_NOMATCH("TST1c-z")
  740. TEST_CGPU_NOMATCH("TST1c-")
  741. TEST_CGPU_MATCH("@")
  742. TEST_CGPU_NOMATCH("@abc")
  743. TEST_CGPU_MATCH("@@b")
  744. TEST_CGPU_NOMATCH("@@c")
  745. TEST_CGPU_MATCH("TST@")
  746. TEST_CGPU_NOMATCH("TST@abc")
  747. TEST_CGPU_MATCH("TST@@b")
  748. TEST_CGPU_NOMATCH("TST@@c")
  749. TEST_CGPU_MATCH("TST@@b-f")
  750. TEST_CGPU_NOMATCH("TST@@c-f")
  751. TEST_CGPU_NOMATCH("TST@@-a")
  752. cgpu.device_path = "/dev/test";
  753. cgpu.dev_serial = "testy";
  754. TEST_CGPU_MATCH("TST@/dev/test")
  755. TEST_CGPU_MATCH("TST@testy")
  756. TEST_CGPU_NOMATCH("TST@")
  757. TEST_CGPU_NOMATCH("TST@/dev/test5@b")
  758. TEST_CGPU_NOMATCH("TST@testy3@b")
  759. TEST_CGPU_MATCH("TST@/dev/test@b")
  760. TEST_CGPU_MATCH("TST@testy@b")
  761. TEST_CGPU_NOMATCH("TST@/dev/test@c")
  762. TEST_CGPU_NOMATCH("TST@testy@c")
  763. cgpu.device_path = "usb:000:999";
  764. TEST_CGPU_MATCH("TST@usb:000:999")
  765. drv.dname = "test7";
  766. TEST_CGPU_MATCH("test7")
  767. TEST_CGPU_MATCH("TEST7")
  768. TEST_CGPU_NOMATCH("test&")
  769. TEST_CGPU_MATCH("test7 1-2")
  770. TEST_CGPU_MATCH("test7@testy@b")
  771. }
  772. static
  773. int cgpu_search(const char * const pattern, const int first)
  774. {
  775. int i;
  776. struct cgpu_info *cgpu;
  777. #define CHECK_CGPU_SEARCH do{ \
  778. cgpu = get_devices(i); \
  779. if (cgpu_match(pattern, cgpu)) \
  780. return i; \
  781. }while(0)
  782. for (i = first; i < total_devices; ++i)
  783. CHECK_CGPU_SEARCH;
  784. for (i = 0; i < first; ++i)
  785. CHECK_CGPU_SEARCH;
  786. #undef CHECK_CGPU_SEARCH
  787. return -1;
  788. }
  789. static pthread_mutex_t sharelog_lock;
  790. static FILE *sharelog_file = NULL;
  791. struct thr_info *get_thread(int thr_id)
  792. {
  793. struct thr_info *thr;
  794. rd_lock(&mining_thr_lock);
  795. thr = mining_thr[thr_id];
  796. rd_unlock(&mining_thr_lock);
  797. return thr;
  798. }
  799. static struct cgpu_info *get_thr_cgpu(int thr_id)
  800. {
  801. struct thr_info *thr = get_thread(thr_id);
  802. return thr->cgpu;
  803. }
  804. struct cgpu_info *get_devices(int id)
  805. {
  806. struct cgpu_info *cgpu;
  807. rd_lock(&devices_lock);
  808. cgpu = devices[id];
  809. rd_unlock(&devices_lock);
  810. return cgpu;
  811. }
  812. static pthread_mutex_t noncelog_lock = PTHREAD_MUTEX_INITIALIZER;
  813. static FILE *noncelog_file = NULL;
  814. static
  815. void noncelog(const struct work * const work)
  816. {
  817. const int thr_id = work->thr_id;
  818. const struct cgpu_info *proc = get_thr_cgpu(thr_id);
  819. char buf[0x200], hash[65], data[161], midstate[65];
  820. int rv;
  821. size_t ret;
  822. bin2hex(hash, work->hash, 32);
  823. bin2hex(data, work->data, 80);
  824. bin2hex(midstate, work->midstate, 32);
  825. // timestamp,proc,hash,data,midstate
  826. rv = snprintf(buf, sizeof(buf), "%lu,%s,%s,%s,%s\n",
  827. (unsigned long)time(NULL), proc->proc_repr_ns,
  828. hash, data, midstate);
  829. if (unlikely(rv < 1))
  830. {
  831. applog(LOG_ERR, "noncelog printf error");
  832. return;
  833. }
  834. mutex_lock(&noncelog_lock);
  835. ret = fwrite(buf, rv, 1, noncelog_file);
  836. fflush(noncelog_file);
  837. mutex_unlock(&noncelog_lock);
  838. if (ret != 1)
  839. applog(LOG_ERR, "noncelog fwrite error");
  840. }
  841. static void sharelog(const char*disposition, const struct work*work)
  842. {
  843. char target[(sizeof(work->target) * 2) + 1];
  844. char hash[(sizeof(work->hash) * 2) + 1];
  845. char data[(sizeof(work->data) * 2) + 1];
  846. struct cgpu_info *cgpu;
  847. unsigned long int t;
  848. struct pool *pool;
  849. int thr_id, rv;
  850. char s[1024];
  851. size_t ret;
  852. if (!sharelog_file)
  853. return;
  854. thr_id = work->thr_id;
  855. cgpu = get_thr_cgpu(thr_id);
  856. pool = work->pool;
  857. t = work->ts_getwork + timer_elapsed(&work->tv_getwork, &work->tv_work_found);
  858. bin2hex(target, work->target, sizeof(work->target));
  859. bin2hex(hash, work->hash, sizeof(work->hash));
  860. bin2hex(data, work->data, sizeof(work->data));
  861. // timestamp,disposition,target,pool,dev,thr,sharehash,sharedata
  862. 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);
  863. if (rv >= (int)(sizeof(s)))
  864. s[sizeof(s) - 1] = '\0';
  865. else if (rv < 0) {
  866. applog(LOG_ERR, "sharelog printf error");
  867. return;
  868. }
  869. mutex_lock(&sharelog_lock);
  870. ret = fwrite(s, rv, 1, sharelog_file);
  871. fflush(sharelog_file);
  872. mutex_unlock(&sharelog_lock);
  873. if (ret != 1)
  874. applog(LOG_ERR, "sharelog fwrite error");
  875. }
  876. static char *getwork_req = "{\"method\": \"getwork\", \"params\": [], \"id\":0}\n";
  877. /* Adjust all the pools' quota to the greatest common denominator after a pool
  878. * has been added or the quotas changed. */
  879. void adjust_quota_gcd(void)
  880. {
  881. unsigned long gcd, lowest_quota = ~0UL, quota;
  882. struct pool *pool;
  883. int i;
  884. for (i = 0; i < total_pools; i++) {
  885. pool = pools[i];
  886. quota = pool->quota;
  887. if (!quota)
  888. continue;
  889. if (quota < lowest_quota)
  890. lowest_quota = quota;
  891. }
  892. if (likely(lowest_quota < ~0UL)) {
  893. gcd = lowest_quota;
  894. for (i = 0; i < total_pools; i++) {
  895. pool = pools[i];
  896. quota = pool->quota;
  897. if (!quota)
  898. continue;
  899. while (quota % gcd)
  900. gcd--;
  901. }
  902. } else
  903. gcd = 1;
  904. for (i = 0; i < total_pools; i++) {
  905. pool = pools[i];
  906. pool->quota_used *= global_quota_gcd;
  907. pool->quota_used /= gcd;
  908. pool->quota_gcd = pool->quota / gcd;
  909. }
  910. global_quota_gcd = gcd;
  911. applog(LOG_DEBUG, "Global quota greatest common denominator set to %lu", gcd);
  912. }
  913. /* Return value is ignored if not called from add_pool_details */
  914. struct pool *add_pool(void)
  915. {
  916. struct pool *pool;
  917. pool = calloc(sizeof(struct pool), 1);
  918. if (!pool)
  919. quit(1, "Failed to malloc pool in add_pool");
  920. pool->pool_no = pool->prio = total_pools;
  921. mutex_init(&pool->last_work_lock);
  922. mutex_init(&pool->pool_lock);
  923. if (unlikely(pthread_cond_init(&pool->cr_cond, NULL)))
  924. quit(1, "Failed to pthread_cond_init in add_pool");
  925. cglock_init(&pool->data_lock);
  926. mutex_init(&pool->stratum_lock);
  927. timer_unset(&pool->swork.tv_transparency);
  928. /* Make sure the pool doesn't think we've been idle since time 0 */
  929. pool->tv_idle.tv_sec = ~0UL;
  930. cgtime(&pool->cgminer_stats.start_tv);
  931. pool->rpc_proxy = NULL;
  932. pool->quota = 1;
  933. pool->sock = INVSOCK;
  934. pool->lp_socket = CURL_SOCKET_BAD;
  935. if (opt_benchmark)
  936. {
  937. // Don't add to pools array, but immediately remove it
  938. remove_pool(pool);
  939. return pool;
  940. }
  941. pools = realloc(pools, sizeof(struct pool *) * (total_pools + 2));
  942. pools[total_pools++] = pool;
  943. adjust_quota_gcd();
  944. return pool;
  945. }
  946. /* Pool variant of test and set */
  947. static bool pool_tset(struct pool *pool, bool *var)
  948. {
  949. bool ret;
  950. mutex_lock(&pool->pool_lock);
  951. ret = *var;
  952. *var = true;
  953. mutex_unlock(&pool->pool_lock);
  954. return ret;
  955. }
  956. bool pool_tclear(struct pool *pool, bool *var)
  957. {
  958. bool ret;
  959. mutex_lock(&pool->pool_lock);
  960. ret = *var;
  961. *var = false;
  962. mutex_unlock(&pool->pool_lock);
  963. return ret;
  964. }
  965. struct pool *current_pool(void)
  966. {
  967. struct pool *pool;
  968. cg_rlock(&control_lock);
  969. pool = currentpool;
  970. cg_runlock(&control_lock);
  971. return pool;
  972. }
  973. // Copied from ccan/opt/helpers.c
  974. static char *arg_bad(const char *fmt, const char *arg)
  975. {
  976. char *str = malloc(strlen(fmt) + strlen(arg));
  977. sprintf(str, fmt, arg);
  978. return str;
  979. }
  980. static
  981. char *opt_set_floatval(const char *arg, float *f)
  982. {
  983. char *endp;
  984. errno = 0;
  985. *f = strtof(arg, &endp);
  986. if (*endp || !arg[0])
  987. return arg_bad("'%s' is not a number", arg);
  988. if (errno)
  989. return arg_bad("'%s' is out of range", arg);
  990. return NULL;
  991. }
  992. static
  993. void opt_show_floatval(char buf[OPT_SHOW_LEN], const float *f)
  994. {
  995. snprintf(buf, OPT_SHOW_LEN, "%.1f", *f);
  996. }
  997. static
  998. char *set_bool_ignore_arg(const char * const arg, bool * const b)
  999. {
  1000. return opt_set_bool(b);
  1001. }
  1002. char *set_int_range(const char *arg, int *i, int min, int max)
  1003. {
  1004. char *err = opt_set_intval(arg, i);
  1005. if (err)
  1006. return err;
  1007. if (*i < min || *i > max)
  1008. return "Value out of range";
  1009. return NULL;
  1010. }
  1011. static char *set_int_0_to_9999(const char *arg, int *i)
  1012. {
  1013. return set_int_range(arg, i, 0, 9999);
  1014. }
  1015. static char *set_int_1_to_65535(const char *arg, int *i)
  1016. {
  1017. return set_int_range(arg, i, 1, 65535);
  1018. }
  1019. static char *set_int_0_to_10(const char *arg, int *i)
  1020. {
  1021. return set_int_range(arg, i, 0, 10);
  1022. }
  1023. static char *set_int_1_to_10(const char *arg, int *i)
  1024. {
  1025. return set_int_range(arg, i, 1, 10);
  1026. }
  1027. char *set_strdup(const char *arg, char **p)
  1028. {
  1029. *p = strdup((char *)arg);
  1030. return NULL;
  1031. }
  1032. #if BLKMAKER_VERSION > 1
  1033. static char *set_b58addr(const char *arg, struct _cbscript_t *p)
  1034. {
  1035. size_t scriptsz = blkmk_address_to_script(NULL, 0, arg);
  1036. if (!scriptsz)
  1037. return "Invalid address";
  1038. char *script = malloc(scriptsz);
  1039. if (blkmk_address_to_script(script, scriptsz, arg) != scriptsz) {
  1040. free(script);
  1041. return "Failed to convert address to script";
  1042. }
  1043. p->data = script;
  1044. p->sz = scriptsz;
  1045. return NULL;
  1046. }
  1047. #endif
  1048. static
  1049. char *set_quit_summary(const char * const arg)
  1050. {
  1051. if (!(strcasecmp(arg, "none") && strcasecmp(arg, "no")))
  1052. opt_quit_summary = BQS_NONE;
  1053. else
  1054. if (!(strcasecmp(arg, "devs") && strcasecmp(arg, "devices")))
  1055. opt_quit_summary = BQS_DEVS;
  1056. else
  1057. if (!(strcasecmp(arg, "procs") && strcasecmp(arg, "processors") && strcasecmp(arg, "chips") && strcasecmp(arg, "cores")))
  1058. opt_quit_summary = BQS_PROCS;
  1059. else
  1060. if (!(strcasecmp(arg, "detailed") && strcasecmp(arg, "detail") && strcasecmp(arg, "all")))
  1061. opt_quit_summary = BQS_DETAILED;
  1062. else
  1063. return "Quit summary must be one of none/devs/procs/detailed";
  1064. return NULL;
  1065. }
  1066. static void bdiff_target_leadzero(unsigned char *target, double diff);
  1067. char *set_request_diff(const char *arg, float *p)
  1068. {
  1069. unsigned char target[32];
  1070. char *e = opt_set_floatval(arg, p);
  1071. if (e)
  1072. return e;
  1073. request_bdiff = (double)*p * 0.9999847412109375;
  1074. bdiff_target_leadzero(target, request_bdiff);
  1075. request_target_str = malloc(65);
  1076. bin2hex(request_target_str, target, 32);
  1077. return NULL;
  1078. }
  1079. #ifdef NEED_BFG_LOWL_VCOM
  1080. extern struct lowlevel_device_info *_vcom_devinfo_findorcreate(struct lowlevel_device_info **, const char *);
  1081. #ifdef WIN32
  1082. void _vcom_devinfo_scan_querydosdevice(struct lowlevel_device_info ** const devinfo_list)
  1083. {
  1084. char dev[PATH_MAX];
  1085. char *devp = dev;
  1086. size_t bufLen = 0x100;
  1087. tryagain: ;
  1088. char buf[bufLen];
  1089. if (!QueryDosDevice(NULL, buf, bufLen)) {
  1090. if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
  1091. bufLen *= 2;
  1092. applog(LOG_DEBUG, "QueryDosDevice returned insufficent buffer error; enlarging to %lx", (unsigned long)bufLen);
  1093. goto tryagain;
  1094. }
  1095. applogr(, LOG_WARNING, "Error occurred trying to enumerate COM ports with QueryDosDevice");
  1096. }
  1097. size_t tLen;
  1098. memcpy(devp, "\\\\.\\", 4);
  1099. devp = &devp[4];
  1100. for (char *t = buf; *t; t += tLen) {
  1101. tLen = strlen(t) + 1;
  1102. if (strncmp("COM", t, 3))
  1103. continue;
  1104. memcpy(devp, t, tLen);
  1105. // NOTE: We depend on _vcom_devinfo_findorcreate to further check that there's a number (and only a number) on the end
  1106. _vcom_devinfo_findorcreate(devinfo_list, dev);
  1107. }
  1108. }
  1109. #else
  1110. void _vcom_devinfo_scan_lsdev(struct lowlevel_device_info ** const devinfo_list)
  1111. {
  1112. char dev[PATH_MAX];
  1113. char *devp = dev;
  1114. DIR *D;
  1115. struct dirent *de;
  1116. const char devdir[] = "/dev";
  1117. const size_t devdirlen = sizeof(devdir) - 1;
  1118. char *devpath = devp;
  1119. char *devfile = devpath + devdirlen + 1;
  1120. D = opendir(devdir);
  1121. if (!D)
  1122. applogr(, LOG_DEBUG, "No /dev directory to look for VCOM devices in");
  1123. memcpy(devpath, devdir, devdirlen);
  1124. devpath[devdirlen] = '/';
  1125. while ( (de = readdir(D)) ) {
  1126. if (!strncmp(de->d_name, "cu.", 3)
  1127. //don't probe Bluetooth devices - causes bus errors and segfaults
  1128. && strncmp(de->d_name, "cu.Bluetooth", 12))
  1129. goto trydev;
  1130. if (strncmp(de->d_name, "tty", 3))
  1131. continue;
  1132. if (strncmp(&de->d_name[3], "USB", 3) && strncmp(&de->d_name[3], "ACM", 3))
  1133. continue;
  1134. trydev:
  1135. strcpy(devfile, de->d_name);
  1136. _vcom_devinfo_findorcreate(devinfo_list, dev);
  1137. }
  1138. closedir(D);
  1139. }
  1140. #endif
  1141. #endif
  1142. static char *add_serial(const char *arg)
  1143. {
  1144. string_elist_add(arg, &scan_devices);
  1145. return NULL;
  1146. }
  1147. static
  1148. char *opt_string_elist_add(const char *arg, struct string_elist **elist)
  1149. {
  1150. string_elist_add(arg, elist);
  1151. return NULL;
  1152. }
  1153. bool get_intrange(const char *arg, int *val1, int *val2)
  1154. {
  1155. // NOTE: This could be done with sscanf, but its %n is broken in strange ways on Windows
  1156. char *p, *p2;
  1157. *val1 = strtol(arg, &p, 0);
  1158. if (arg == p)
  1159. // Zero-length ending number, invalid
  1160. return false;
  1161. while (true)
  1162. {
  1163. if (!p[0])
  1164. {
  1165. *val2 = *val1;
  1166. return true;
  1167. }
  1168. if (p[0] == '-')
  1169. break;
  1170. if (!isspace(p[0]))
  1171. // Garbage, invalid
  1172. return false;
  1173. ++p;
  1174. }
  1175. p2 = &p[1];
  1176. *val2 = strtol(p2, &p, 0);
  1177. if (p2 == p)
  1178. // Zero-length ending number, invalid
  1179. return false;
  1180. while (true)
  1181. {
  1182. if (!p[0])
  1183. return true;
  1184. if (!isspace(p[0]))
  1185. // Garbage, invalid
  1186. return false;
  1187. ++p;
  1188. }
  1189. }
  1190. static
  1191. void _test_intrange(const char *s, const int v[2])
  1192. {
  1193. int a[2];
  1194. if (!get_intrange(s, &a[0], &a[1]))
  1195. applog(LOG_ERR, "Test \"%s\" failed: returned false", s);
  1196. for (int i = 0; i < 2; ++i)
  1197. if (unlikely(a[i] != v[i]))
  1198. applog(LOG_ERR, "Test \"%s\" failed: value %d should be %d but got %d", s, i, v[i], a[i]);
  1199. }
  1200. #define _test_intrange(s, ...) _test_intrange(s, (int[]){ __VA_ARGS__ })
  1201. static
  1202. void _test_intrange_fail(const char *s)
  1203. {
  1204. int a[2];
  1205. if (get_intrange(s, &a[0], &a[1]))
  1206. applog(LOG_ERR, "Test !\"%s\" failed: returned true with %d and %d", s, a[0], a[1]);
  1207. }
  1208. static
  1209. void test_intrange()
  1210. {
  1211. _test_intrange("-1--2", -1, -2);
  1212. _test_intrange("-1-2", -1, 2);
  1213. _test_intrange("1--2", 1, -2);
  1214. _test_intrange("1-2", 1, 2);
  1215. _test_intrange("111-222", 111, 222);
  1216. _test_intrange(" 11 - 22 ", 11, 22);
  1217. _test_intrange("+11-+22", 11, 22);
  1218. _test_intrange("-1", -1, -1);
  1219. _test_intrange_fail("all");
  1220. _test_intrange_fail("1-");
  1221. _test_intrange_fail("");
  1222. _test_intrange_fail("1-54x");
  1223. }
  1224. static char *set_devices(char *arg)
  1225. {
  1226. if (*arg) {
  1227. if (*arg == '?') {
  1228. opt_display_devs = true;
  1229. return NULL;
  1230. }
  1231. } else
  1232. return "Invalid device parameters";
  1233. string_elist_add(arg, &opt_devices_enabled_list);
  1234. return NULL;
  1235. }
  1236. static char *set_balance(enum pool_strategy *strategy)
  1237. {
  1238. *strategy = POOL_BALANCE;
  1239. return NULL;
  1240. }
  1241. static char *set_loadbalance(enum pool_strategy *strategy)
  1242. {
  1243. *strategy = POOL_LOADBALANCE;
  1244. return NULL;
  1245. }
  1246. static char *set_rotate(const char *arg, int *i)
  1247. {
  1248. pool_strategy = POOL_ROTATE;
  1249. return set_int_range(arg, i, 0, 9999);
  1250. }
  1251. static char *set_rr(enum pool_strategy *strategy)
  1252. {
  1253. *strategy = POOL_ROUNDROBIN;
  1254. return NULL;
  1255. }
  1256. /* Detect that url is for a stratum protocol either via the presence of
  1257. * stratum+tcp or by detecting a stratum server response */
  1258. bool detect_stratum(struct pool *pool, char *url)
  1259. {
  1260. if (!extract_sockaddr(url, &pool->sockaddr_url, &pool->stratum_port))
  1261. return false;
  1262. if (!strncasecmp(url, "stratum+tcp://", 14)) {
  1263. pool->rpc_url = strdup(url);
  1264. pool->has_stratum = true;
  1265. pool->stratum_url = pool->sockaddr_url;
  1266. return true;
  1267. }
  1268. return false;
  1269. }
  1270. static struct pool *add_url(void)
  1271. {
  1272. total_urls++;
  1273. if (total_urls > total_pools)
  1274. add_pool();
  1275. return pools[total_urls - 1];
  1276. }
  1277. static void setup_url(struct pool *pool, char *arg)
  1278. {
  1279. if (detect_stratum(pool, arg))
  1280. return;
  1281. opt_set_charp(arg, &pool->rpc_url);
  1282. if (strncmp(arg, "http://", 7) &&
  1283. strncmp(arg, "https://", 8)) {
  1284. const size_t L = strlen(arg);
  1285. char *httpinput;
  1286. httpinput = malloc(8 + L);
  1287. if (!httpinput)
  1288. quit(1, "Failed to malloc httpinput");
  1289. sprintf(httpinput, "http://%s", arg);
  1290. pool->rpc_url = httpinput;
  1291. }
  1292. }
  1293. static char *set_url(char *arg)
  1294. {
  1295. struct pool *pool = add_url();
  1296. setup_url(pool, arg);
  1297. return NULL;
  1298. }
  1299. static char *set_quota(char *arg)
  1300. {
  1301. char *semicolon = strchr(arg, ';'), *url;
  1302. int len, qlen, quota;
  1303. struct pool *pool;
  1304. if (!semicolon)
  1305. return "No semicolon separated quota;URL pair found";
  1306. len = strlen(arg);
  1307. *semicolon = '\0';
  1308. qlen = strlen(arg);
  1309. if (!qlen)
  1310. return "No parameter for quota found";
  1311. len -= qlen + 1;
  1312. if (len < 1)
  1313. return "No parameter for URL found";
  1314. quota = atoi(arg);
  1315. if (quota < 0)
  1316. return "Invalid negative parameter for quota set";
  1317. url = arg + qlen + 1;
  1318. pool = add_url();
  1319. setup_url(pool, url);
  1320. pool->quota = quota;
  1321. applog(LOG_INFO, "Setting pool %d to quota %d", pool->pool_no, pool->quota);
  1322. adjust_quota_gcd();
  1323. return NULL;
  1324. }
  1325. static char *set_user(const char *arg)
  1326. {
  1327. struct pool *pool;
  1328. total_users++;
  1329. if (total_users > total_pools)
  1330. add_pool();
  1331. pool = pools[total_users - 1];
  1332. opt_set_charp(arg, &pool->rpc_user);
  1333. return NULL;
  1334. }
  1335. static char *set_pass(const char *arg)
  1336. {
  1337. struct pool *pool;
  1338. total_passes++;
  1339. if (total_passes > total_pools)
  1340. add_pool();
  1341. pool = pools[total_passes - 1];
  1342. opt_set_charp(arg, &pool->rpc_pass);
  1343. return NULL;
  1344. }
  1345. static char *set_userpass(const char *arg)
  1346. {
  1347. struct pool *pool;
  1348. char *updup;
  1349. if (total_users != total_passes)
  1350. return "User + pass options must be balanced before userpass";
  1351. ++total_users;
  1352. ++total_passes;
  1353. if (total_users > total_pools)
  1354. add_pool();
  1355. pool = pools[total_users - 1];
  1356. updup = strdup(arg);
  1357. opt_set_charp(arg, &pool->rpc_userpass);
  1358. pool->rpc_user = strtok(updup, ":");
  1359. if (!pool->rpc_user)
  1360. return "Failed to find : delimited user info";
  1361. pool->rpc_pass = strtok(NULL, ":");
  1362. if (!pool->rpc_pass)
  1363. pool->rpc_pass = "";
  1364. return NULL;
  1365. }
  1366. static char *set_pool_priority(const char *arg)
  1367. {
  1368. struct pool *pool;
  1369. if (!total_pools)
  1370. return "Usage of --pool-priority before pools are defined does not make sense";
  1371. pool = pools[total_pools - 1];
  1372. opt_set_intval(arg, &pool->prio);
  1373. return NULL;
  1374. }
  1375. static char *set_pool_proxy(const char *arg)
  1376. {
  1377. struct pool *pool;
  1378. if (!total_pools)
  1379. return "Usage of --pool-proxy before pools are defined does not make sense";
  1380. if (!our_curl_supports_proxy_uris())
  1381. return "Your installed cURL library does not support proxy URIs. At least version 7.21.7 is required.";
  1382. pool = pools[total_pools - 1];
  1383. opt_set_charp(arg, &pool->rpc_proxy);
  1384. return NULL;
  1385. }
  1386. static char *set_pool_force_rollntime(const char *arg)
  1387. {
  1388. struct pool *pool;
  1389. if (!total_pools)
  1390. return "Usage of --force-rollntime before pools are defined does not make sense";
  1391. pool = pools[total_pools - 1];
  1392. opt_set_intval(arg, &pool->force_rollntime);
  1393. return NULL;
  1394. }
  1395. static char *enable_debug(bool *flag)
  1396. {
  1397. *flag = true;
  1398. opt_debug_console = true;
  1399. /* Turn on verbose output, too. */
  1400. opt_log_output = true;
  1401. return NULL;
  1402. }
  1403. static char *set_schedtime(const char *arg, struct schedtime *st)
  1404. {
  1405. if (sscanf(arg, "%d:%d", &st->tm.tm_hour, &st->tm.tm_min) != 2)
  1406. {
  1407. if (strcasecmp(arg, "now"))
  1408. return "Invalid time set, should be HH:MM";
  1409. } else
  1410. schedstop.tm.tm_sec = 0;
  1411. if (st->tm.tm_hour > 23 || st->tm.tm_min > 59 || st->tm.tm_hour < 0 || st->tm.tm_min < 0)
  1412. return "Invalid time set.";
  1413. st->enable = true;
  1414. return NULL;
  1415. }
  1416. static
  1417. char *set_log_file(char *arg)
  1418. {
  1419. char *r = "";
  1420. long int i = strtol(arg, &r, 10);
  1421. int fd, stderr_fd = fileno(stderr);
  1422. if ((!*r) && i >= 0 && i <= INT_MAX)
  1423. fd = i;
  1424. else
  1425. if (!strcmp(arg, "-"))
  1426. {
  1427. fd = fileno(stdout);
  1428. if (unlikely(fd == -1))
  1429. return "Standard output missing for log-file";
  1430. }
  1431. else
  1432. {
  1433. fd = open(arg, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR);
  1434. if (unlikely(fd == -1))
  1435. return "Failed to open log-file";
  1436. }
  1437. close(stderr_fd);
  1438. if (unlikely(-1 == dup2(fd, stderr_fd)))
  1439. return "Failed to dup2 for log-file";
  1440. close(fd);
  1441. return NULL;
  1442. }
  1443. static
  1444. char *_bfgopt_set_file(const char *arg, FILE **F, const char *mode, const char *purpose)
  1445. {
  1446. char *r = "";
  1447. long int i = strtol(arg, &r, 10);
  1448. static char *err = NULL;
  1449. const size_t errbufsz = 0x100;
  1450. free(err);
  1451. err = NULL;
  1452. if ((!*r) && i >= 0 && i <= INT_MAX) {
  1453. *F = fdopen((int)i, mode);
  1454. if (!*F)
  1455. {
  1456. err = malloc(errbufsz);
  1457. snprintf(err, errbufsz, "Failed to open fd %d for %s",
  1458. (int)i, purpose);
  1459. return err;
  1460. }
  1461. } else if (!strcmp(arg, "-")) {
  1462. *F = (mode[0] == 'a') ? stdout : stdin;
  1463. if (!*F)
  1464. {
  1465. err = malloc(errbufsz);
  1466. snprintf(err, errbufsz, "Standard %sput missing for %s",
  1467. (mode[0] == 'a') ? "out" : "in", purpose);
  1468. return err;
  1469. }
  1470. } else {
  1471. *F = fopen(arg, mode);
  1472. if (!*F)
  1473. {
  1474. err = malloc(errbufsz);
  1475. snprintf(err, errbufsz, "Failed to open %s for %s",
  1476. arg, purpose);
  1477. return err;
  1478. }
  1479. }
  1480. return NULL;
  1481. }
  1482. static char *set_noncelog(char *arg)
  1483. {
  1484. return _bfgopt_set_file(arg, &noncelog_file, "a", "nonce log");
  1485. }
  1486. static char *set_sharelog(char *arg)
  1487. {
  1488. return _bfgopt_set_file(arg, &sharelog_file, "a", "share log");
  1489. }
  1490. static
  1491. void _add_set_device_option(const char * const func, const char * const buf)
  1492. {
  1493. applog(LOG_DEBUG, "%s: Using --set-device %s", func, buf);
  1494. string_elist_add(buf, &opt_set_device_list);
  1495. }
  1496. #define add_set_device_option(...) do{ \
  1497. char _tmp1718[0x100]; \
  1498. snprintf(_tmp1718, sizeof(_tmp1718), __VA_ARGS__); \
  1499. _add_set_device_option(__func__, _tmp1718); \
  1500. }while(0)
  1501. char *set_temp_cutoff(char *arg)
  1502. {
  1503. if (strchr(arg, ','))
  1504. return "temp-cutoff no longer supports comma-delimited syntax, use --set-device for better control";
  1505. applog(LOG_WARNING, "temp-cutoff is deprecated! Use --set-device for better control");
  1506. add_set_device_option("all:temp-cutoff=%s", arg);
  1507. return NULL;
  1508. }
  1509. char *set_temp_target(char *arg)
  1510. {
  1511. if (strchr(arg, ','))
  1512. return "temp-target no longer supports comma-delimited syntax, use --set-device for better control";
  1513. applog(LOG_WARNING, "temp-target is deprecated! Use --set-device for better control");
  1514. add_set_device_option("all:temp-target=%s", arg);
  1515. return NULL;
  1516. }
  1517. static
  1518. char *set_no_opencl_binaries(__maybe_unused void * const dummy)
  1519. {
  1520. applog(LOG_WARNING, "The --no-opencl-binaries option is deprecated! Use --set-device OCL:binary=no");
  1521. add_set_device_option("OCL:binary=no");
  1522. return NULL;
  1523. }
  1524. static
  1525. char *disable_pool_redirect(__maybe_unused void * const dummy)
  1526. {
  1527. opt_disable_client_reconnect = true;
  1528. want_stratum = false;
  1529. return NULL;
  1530. }
  1531. static char *set_api_allow(const char *arg)
  1532. {
  1533. opt_set_charp(arg, &opt_api_allow);
  1534. return NULL;
  1535. }
  1536. static char *set_api_groups(const char *arg)
  1537. {
  1538. opt_set_charp(arg, &opt_api_groups);
  1539. return NULL;
  1540. }
  1541. static char *set_api_description(const char *arg)
  1542. {
  1543. opt_set_charp(arg, &opt_api_description);
  1544. return NULL;
  1545. }
  1546. static char *set_api_mcast_des(const char *arg)
  1547. {
  1548. opt_set_charp(arg, &opt_api_mcast_des);
  1549. return NULL;
  1550. }
  1551. #ifdef USE_ICARUS
  1552. extern const struct bfg_set_device_definition icarus_set_device_funcs[];
  1553. static char *set_icarus_options(const char *arg)
  1554. {
  1555. if (strchr(arg, ','))
  1556. return "icarus-options no longer supports comma-delimited syntax, see README.FPGA for better control";
  1557. applog(LOG_WARNING, "icarus-options is deprecated! See README.FPGA for better control");
  1558. char *opts = strdup(arg), *argdup;
  1559. argdup = opts;
  1560. const struct bfg_set_device_definition *sdf = icarus_set_device_funcs;
  1561. const char *drivers[] = {"antminer", "cairnsmore", "erupter", "icarus"};
  1562. char *saveptr, *opt;
  1563. for (int i = 0; i < 4; ++i, ++sdf)
  1564. {
  1565. opt = strtok_r(opts, ":", &saveptr);
  1566. opts = NULL;
  1567. if (!opt)
  1568. break;
  1569. if (!opt[0])
  1570. continue;
  1571. for (int j = 0; j < 4; ++j)
  1572. add_set_device_option("%s:%s=%s", drivers[j], sdf->optname, opt);
  1573. }
  1574. free(argdup);
  1575. return NULL;
  1576. }
  1577. static char *set_icarus_timing(const char *arg)
  1578. {
  1579. if (strchr(arg, ','))
  1580. return "icarus-timing no longer supports comma-delimited syntax, see README.FPGA for better control";
  1581. applog(LOG_WARNING, "icarus-timing is deprecated! See README.FPGA for better control");
  1582. const char *drivers[] = {"antminer", "cairnsmore", "erupter", "icarus"};
  1583. for (int j = 0; j < 4; ++j)
  1584. add_set_device_option("%s:timing=%s", drivers[j], arg);
  1585. return NULL;
  1586. }
  1587. #endif
  1588. #ifdef USE_AVALON
  1589. extern const struct bfg_set_device_definition avalon_set_device_funcs[];
  1590. static char *set_avalon_options(const char *arg)
  1591. {
  1592. if (strchr(arg, ','))
  1593. return "avalon-options no longer supports comma-delimited syntax, see README.FPGA for better control";
  1594. applog(LOG_WARNING, "avalon-options is deprecated! See README.FPGA for better control");
  1595. char *opts = strdup(arg), *argdup;
  1596. argdup = opts;
  1597. const struct bfg_set_device_definition *sdf = avalon_set_device_funcs;
  1598. char *saveptr, *opt;
  1599. for (int i = 0; i < 5; ++i, ++sdf)
  1600. {
  1601. opt = strtok_r(opts, ":", &saveptr);
  1602. opts = NULL;
  1603. if (!opt)
  1604. break;
  1605. if (!opt[0])
  1606. continue;
  1607. add_set_device_option("avalon:%s=%s", sdf->optname, opt);
  1608. }
  1609. free(argdup);
  1610. return NULL;
  1611. }
  1612. #endif
  1613. #ifdef USE_KLONDIKE
  1614. static char *set_klondike_options(const char *arg)
  1615. {
  1616. int hashclock;
  1617. double temptarget;
  1618. switch (sscanf(arg, "%d:%lf", &hashclock, &temptarget))
  1619. {
  1620. default:
  1621. return "Unrecognised --klondike-options";
  1622. case 2:
  1623. add_set_device_option("klondike:temp-target=%lf", temptarget);
  1624. // fallthru
  1625. case 1:
  1626. add_set_device_option("klondike:clock=%d", hashclock);
  1627. }
  1628. applog(LOG_WARNING, "klondike-options is deprecated! Use --set-device for better control");
  1629. return NULL;
  1630. }
  1631. #endif
  1632. __maybe_unused
  1633. static char *set_null(const char __maybe_unused *arg)
  1634. {
  1635. return NULL;
  1636. }
  1637. /* These options are available from config file or commandline */
  1638. static struct opt_table opt_config_table[] = {
  1639. #ifdef WANT_CPUMINE
  1640. OPT_WITH_ARG("--algo",
  1641. set_algo, show_algo, &opt_algo,
  1642. "Specify sha256 implementation for CPU mining:\n"
  1643. "\tfastauto*\tQuick benchmark at startup to pick a working algorithm\n"
  1644. "\tauto\t\tBenchmark at startup and pick fastest algorithm"
  1645. "\n\tc\t\tLinux kernel sha256, implemented in C"
  1646. #ifdef WANT_SSE2_4WAY
  1647. "\n\t4way\t\ttcatm's 4-way SSE2 implementation"
  1648. #endif
  1649. #ifdef WANT_VIA_PADLOCK
  1650. "\n\tvia\t\tVIA padlock implementation"
  1651. #endif
  1652. "\n\tcryptopp\tCrypto++ C/C++ implementation"
  1653. #ifdef WANT_CRYPTOPP_ASM32
  1654. "\n\tcryptopp_asm32\tCrypto++ 32-bit assembler implementation"
  1655. #endif
  1656. #ifdef WANT_X8632_SSE2
  1657. "\n\tsse2_32\t\tSSE2 32 bit implementation for i386 machines"
  1658. #endif
  1659. #ifdef WANT_X8664_SSE2
  1660. "\n\tsse2_64\t\tSSE2 64 bit implementation for x86_64 machines"
  1661. #endif
  1662. #ifdef WANT_X8664_SSE4
  1663. "\n\tsse4_64\t\tSSE4.1 64 bit implementation for x86_64 machines"
  1664. #endif
  1665. #ifdef WANT_ALTIVEC_4WAY
  1666. "\n\taltivec_4way\tAltivec implementation for PowerPC G4 and G5 machines"
  1667. #endif
  1668. ),
  1669. OPT_WITH_ARG("-a",
  1670. set_algo, show_algo, &opt_algo,
  1671. opt_hidden),
  1672. #endif
  1673. OPT_WITH_ARG("--api-allow",
  1674. set_api_allow, NULL, NULL,
  1675. "Allow API access only to the given list of [G:]IP[/Prefix] addresses[/subnets]"),
  1676. OPT_WITH_ARG("--api-description",
  1677. set_api_description, NULL, NULL,
  1678. "Description placed in the API status header, default: BFGMiner version"),
  1679. OPT_WITH_ARG("--api-groups",
  1680. set_api_groups, NULL, NULL,
  1681. "API one letter groups G:cmd:cmd[,P:cmd:*...] defining the cmds a groups can use"),
  1682. OPT_WITHOUT_ARG("--api-listen",
  1683. opt_set_bool, &opt_api_listen,
  1684. "Enable API, default: disabled"),
  1685. OPT_WITHOUT_ARG("--api-mcast",
  1686. opt_set_bool, &opt_api_mcast,
  1687. "Enable API Multicast listener, default: disabled"),
  1688. OPT_WITH_ARG("--api-mcast-addr",
  1689. opt_set_charp, opt_show_charp, &opt_api_mcast_addr,
  1690. "API Multicast listen address"),
  1691. OPT_WITH_ARG("--api-mcast-code",
  1692. opt_set_charp, opt_show_charp, &opt_api_mcast_code,
  1693. "Code expected in the API Multicast message, don't use '-'"),
  1694. OPT_WITH_ARG("--api-mcast-des",
  1695. set_api_mcast_des, NULL, NULL,
  1696. "Description appended to the API Multicast reply, default: ''"),
  1697. OPT_WITH_ARG("--api-mcast-port",
  1698. set_int_1_to_65535, opt_show_intval, &opt_api_mcast_port,
  1699. "API Multicast listen port"),
  1700. OPT_WITHOUT_ARG("--api-network",
  1701. opt_set_bool, &opt_api_network,
  1702. "Allow API (if enabled) to listen on/for any address, default: only 127.0.0.1"),
  1703. OPT_WITH_ARG("--api-port",
  1704. set_int_1_to_65535, opt_show_intval, &opt_api_port,
  1705. "Port number of miner API"),
  1706. #ifdef HAVE_ADL
  1707. OPT_WITHOUT_ARG("--auto-fan",
  1708. opt_set_bool, &opt_autofan,
  1709. opt_hidden),
  1710. OPT_WITHOUT_ARG("--auto-gpu",
  1711. opt_set_bool, &opt_autoengine,
  1712. opt_hidden),
  1713. #endif
  1714. OPT_WITHOUT_ARG("--balance",
  1715. set_balance, &pool_strategy,
  1716. "Change multipool strategy from failover to even share balance"),
  1717. OPT_WITHOUT_ARG("--benchmark",
  1718. opt_set_bool, &opt_benchmark,
  1719. "Run BFGMiner in benchmark mode - produces no shares"),
  1720. #if defined(USE_BITFORCE)
  1721. OPT_WITHOUT_ARG("--bfl-range",
  1722. opt_set_bool, &opt_bfl_noncerange,
  1723. "Use nonce range on bitforce devices if supported"),
  1724. #endif
  1725. #ifdef HAVE_CHROOT
  1726. OPT_WITH_ARG("--chroot-dir",
  1727. opt_set_charp, NULL, &chroot_dir,
  1728. "Chroot to a directory right after startup"),
  1729. #endif
  1730. OPT_WITH_ARG("--cmd-idle",
  1731. opt_set_charp, NULL, &cmd_idle,
  1732. "Execute a command when a device is allowed to be idle (rest or wait)"),
  1733. OPT_WITH_ARG("--cmd-sick",
  1734. opt_set_charp, NULL, &cmd_sick,
  1735. "Execute a command when a device is declared sick"),
  1736. OPT_WITH_ARG("--cmd-dead",
  1737. opt_set_charp, NULL, &cmd_dead,
  1738. "Execute a command when a device is declared dead"),
  1739. #if BLKMAKER_VERSION > 1
  1740. OPT_WITH_ARG("--coinbase-addr",
  1741. set_b58addr, NULL, &opt_coinbase_script,
  1742. "Set coinbase payout address for solo mining"),
  1743. OPT_WITH_ARG("--coinbase-address|--coinbase-payout|--cbaddress|--cbaddr|--cb-address|--cb-addr|--payout",
  1744. set_b58addr, NULL, &opt_coinbase_script,
  1745. opt_hidden),
  1746. #endif
  1747. #if BLKMAKER_VERSION > 0
  1748. OPT_WITH_ARG("--coinbase-sig",
  1749. set_strdup, NULL, &opt_coinbase_sig,
  1750. "Set coinbase signature when possible"),
  1751. OPT_WITH_ARG("--coinbase|--cbsig|--cb-sig|--cb|--prayer",
  1752. set_strdup, NULL, &opt_coinbase_sig,
  1753. opt_hidden),
  1754. #endif
  1755. #ifdef HAVE_CURSES
  1756. OPT_WITHOUT_ARG("--compact",
  1757. opt_set_bool, &opt_compact,
  1758. "Use compact display without per device statistics"),
  1759. #endif
  1760. #ifdef WANT_CPUMINE
  1761. OPT_WITH_ARG("--cpu-threads",
  1762. force_nthreads_int, opt_show_intval, &opt_n_threads,
  1763. "Number of miner CPU threads"),
  1764. OPT_WITH_ARG("-t",
  1765. force_nthreads_int, opt_show_intval, &opt_n_threads,
  1766. opt_hidden),
  1767. #endif
  1768. OPT_WITHOUT_ARG("--debug|-D",
  1769. enable_debug, &opt_debug,
  1770. "Enable debug output"),
  1771. OPT_WITHOUT_ARG("--debuglog",
  1772. opt_set_bool, &opt_debug,
  1773. "Enable debug logging"),
  1774. OPT_WITHOUT_ARG("--device-protocol-dump",
  1775. opt_set_bool, &opt_dev_protocol,
  1776. "Verbose dump of device protocol-level activities"),
  1777. OPT_WITH_ARG("--device|-d",
  1778. set_devices, NULL, NULL,
  1779. "Enable only devices matching pattern (default: all)"),
  1780. OPT_WITHOUT_ARG("--disable-rejecting",
  1781. opt_set_bool, &opt_disable_pool,
  1782. "Automatically disable pools that continually reject shares"),
  1783. #ifdef USE_LIBMICROHTTPD
  1784. OPT_WITH_ARG("--http-port",
  1785. opt_set_intval, opt_show_intval, &httpsrv_port,
  1786. "Port number to listen on for HTTP getwork miners (-1 means disabled)"),
  1787. #endif
  1788. OPT_WITH_ARG("--expiry",
  1789. set_int_0_to_9999, opt_show_intval, &opt_expiry,
  1790. "Upper bound on how many seconds after getting work we consider a share from it stale (w/o longpoll active)"),
  1791. OPT_WITH_ARG("-E",
  1792. set_int_0_to_9999, opt_show_intval, &opt_expiry,
  1793. opt_hidden),
  1794. OPT_WITH_ARG("--expiry-lp",
  1795. set_int_0_to_9999, opt_show_intval, &opt_expiry_lp,
  1796. "Upper bound on how many seconds after getting work we consider a share from it stale (with longpoll active)"),
  1797. OPT_WITHOUT_ARG("--failover-only",
  1798. opt_set_bool, &opt_fail_only,
  1799. "Don't leak work to backup pools when primary pool is lagging"),
  1800. #ifdef USE_FPGA
  1801. OPT_WITHOUT_ARG("--force-dev-init",
  1802. opt_set_bool, &opt_force_dev_init,
  1803. "Always initialize devices when possible (such as bitstream uploads to some FPGAs)"),
  1804. #endif
  1805. #ifdef HAVE_OPENCL
  1806. OPT_WITH_ARG("--gpu-dyninterval",
  1807. set_int_1_to_65535, opt_show_intval, &opt_dynamic_interval,
  1808. opt_hidden),
  1809. OPT_WITH_ARG("--gpu-platform",
  1810. set_int_0_to_9999, opt_show_intval, &opt_platform_id,
  1811. "Select OpenCL platform ID to use for GPU mining"),
  1812. OPT_WITH_ARG("--gpu-threads|-g",
  1813. set_gpu_threads, opt_show_intval, &opt_g_threads,
  1814. opt_hidden),
  1815. #ifdef HAVE_ADL
  1816. OPT_WITH_ARG("--gpu-engine",
  1817. set_gpu_engine, NULL, NULL,
  1818. opt_hidden),
  1819. OPT_WITH_ARG("--gpu-fan",
  1820. set_gpu_fan, NULL, NULL,
  1821. opt_hidden),
  1822. OPT_WITH_ARG("--gpu-map",
  1823. set_gpu_map, NULL, NULL,
  1824. "Map OpenCL to ADL device order manually, paired CSV (e.g. 1:0,2:1 maps OpenCL 1 to ADL 0, 2 to 1)"),
  1825. OPT_WITH_ARG("--gpu-memclock",
  1826. set_gpu_memclock, NULL, NULL,
  1827. opt_hidden),
  1828. OPT_WITH_ARG("--gpu-memdiff",
  1829. set_gpu_memdiff, NULL, NULL,
  1830. opt_hidden),
  1831. OPT_WITH_ARG("--gpu-powertune",
  1832. set_gpu_powertune, NULL, NULL,
  1833. opt_hidden),
  1834. OPT_WITHOUT_ARG("--gpu-reorder",
  1835. opt_set_bool, &opt_reorder,
  1836. "Attempt to reorder GPU devices according to PCI Bus ID"),
  1837. OPT_WITH_ARG("--gpu-vddc",
  1838. set_gpu_vddc, NULL, NULL,
  1839. opt_hidden),
  1840. #endif
  1841. #ifdef USE_SCRYPT
  1842. OPT_WITH_ARG("--lookup-gap",
  1843. set_lookup_gap, NULL, NULL,
  1844. opt_hidden),
  1845. #endif
  1846. OPT_WITH_ARG("--intensity|-I",
  1847. set_intensity, NULL, NULL,
  1848. opt_hidden),
  1849. #endif
  1850. #if defined(HAVE_OPENCL) || defined(USE_MODMINER) || defined(USE_X6500) || defined(USE_ZTEX)
  1851. OPT_WITH_ARG("--kernel-path",
  1852. opt_set_charp, opt_show_charp, &opt_kernel_path,
  1853. "Specify a path to where bitstream and kernel files are"),
  1854. OPT_WITH_ARG("-K",
  1855. opt_set_charp, opt_show_charp, &opt_kernel_path,
  1856. opt_hidden),
  1857. #endif
  1858. #ifdef HAVE_OPENCL
  1859. OPT_WITH_ARG("--kernel|-k",
  1860. set_kernel, NULL, NULL,
  1861. opt_hidden),
  1862. #endif
  1863. #ifdef USE_ICARUS
  1864. OPT_WITH_ARG("--icarus-options",
  1865. set_icarus_options, NULL, NULL,
  1866. opt_hidden),
  1867. OPT_WITH_ARG("--icarus-timing",
  1868. set_icarus_timing, NULL, NULL,
  1869. opt_hidden),
  1870. #endif
  1871. #ifdef USE_AVALON
  1872. OPT_WITH_ARG("--avalon-options",
  1873. set_avalon_options, NULL, NULL,
  1874. opt_hidden),
  1875. #endif
  1876. #ifdef USE_KLONDIKE
  1877. OPT_WITH_ARG("--klondike-options",
  1878. set_klondike_options, NULL, NULL,
  1879. "Set klondike options clock:temptarget"),
  1880. #endif
  1881. OPT_WITHOUT_ARG("--load-balance",
  1882. set_loadbalance, &pool_strategy,
  1883. "Change multipool strategy from failover to quota based balance"),
  1884. OPT_WITH_ARG("--log|-l",
  1885. set_int_0_to_9999, opt_show_intval, &opt_log_interval,
  1886. "Interval in seconds between log output"),
  1887. OPT_WITH_ARG("--log-file|-L",
  1888. set_log_file, NULL, NULL,
  1889. "Append log file for output messages"),
  1890. OPT_WITH_ARG("--logfile",
  1891. set_log_file, NULL, NULL,
  1892. opt_hidden),
  1893. OPT_WITHOUT_ARG("--log-microseconds",
  1894. opt_set_bool, &opt_log_microseconds,
  1895. "Include microseconds in log output"),
  1896. #if defined(unix) || defined(__APPLE__)
  1897. OPT_WITH_ARG("--monitor|-m",
  1898. opt_set_charp, NULL, &opt_stderr_cmd,
  1899. "Use custom pipe cmd for output messages"),
  1900. #endif // defined(unix)
  1901. OPT_WITHOUT_ARG("--net-delay",
  1902. opt_set_bool, &opt_delaynet,
  1903. "Impose small delays in networking to avoid overloading slow routers"),
  1904. OPT_WITHOUT_ARG("--no-adl",
  1905. opt_set_bool, &opt_noadl,
  1906. #ifdef HAVE_ADL
  1907. "Disable the ATI display library used for monitoring and setting GPU parameters"
  1908. #else
  1909. opt_hidden
  1910. #endif
  1911. ),
  1912. OPT_WITHOUT_ARG("--no-gbt",
  1913. opt_set_invbool, &want_gbt,
  1914. "Disable getblocktemplate support"),
  1915. OPT_WITHOUT_ARG("--no-getwork",
  1916. opt_set_invbool, &want_getwork,
  1917. "Disable getwork support"),
  1918. OPT_WITHOUT_ARG("--no-hotplug",
  1919. #ifdef HAVE_BFG_HOTPLUG
  1920. opt_set_invbool, &opt_hotplug,
  1921. "Disable hotplug detection"
  1922. #else
  1923. set_null, &opt_hotplug,
  1924. opt_hidden
  1925. #endif
  1926. ),
  1927. OPT_WITHOUT_ARG("--no-longpoll",
  1928. opt_set_invbool, &want_longpoll,
  1929. "Disable X-Long-Polling support"),
  1930. OPT_WITHOUT_ARG("--no-pool-disable",
  1931. opt_set_invbool, &opt_disable_pool,
  1932. opt_hidden),
  1933. OPT_WITHOUT_ARG("--no-client-reconnect",
  1934. opt_set_invbool, &opt_disable_client_reconnect,
  1935. opt_hidden),
  1936. OPT_WITHOUT_ARG("--no-pool-redirect",
  1937. disable_pool_redirect, NULL,
  1938. "Ignore pool requests to redirect to another server"),
  1939. OPT_WITHOUT_ARG("--no-restart",
  1940. opt_set_invbool, &opt_restart,
  1941. "Do not attempt to restart devices that hang"
  1942. ),
  1943. OPT_WITHOUT_ARG("--no-show-processors",
  1944. opt_set_invbool, &opt_show_procs,
  1945. opt_hidden),
  1946. OPT_WITHOUT_ARG("--no-show-procs",
  1947. opt_set_invbool, &opt_show_procs,
  1948. opt_hidden),
  1949. OPT_WITHOUT_ARG("--no-stratum",
  1950. opt_set_invbool, &want_stratum,
  1951. "Disable Stratum detection"),
  1952. OPT_WITHOUT_ARG("--no-submit-stale",
  1953. opt_set_invbool, &opt_submit_stale,
  1954. "Don't submit shares if they are detected as stale"),
  1955. #ifdef HAVE_OPENCL
  1956. OPT_WITHOUT_ARG("--no-opencl-binaries",
  1957. set_no_opencl_binaries, NULL,
  1958. opt_hidden),
  1959. #endif
  1960. OPT_WITHOUT_ARG("--no-unicode",
  1961. #ifdef USE_UNICODE
  1962. opt_set_invbool, &use_unicode,
  1963. "Don't use Unicode characters in TUI"
  1964. #else
  1965. set_null, &use_unicode,
  1966. opt_hidden
  1967. #endif
  1968. ),
  1969. OPT_WITH_ARG("--noncelog",
  1970. set_noncelog, NULL, NULL,
  1971. "Create log of all nonces found"),
  1972. OPT_WITH_ARG("--pass|-p",
  1973. set_pass, NULL, NULL,
  1974. "Password for bitcoin JSON-RPC server"),
  1975. OPT_WITHOUT_ARG("--per-device-stats",
  1976. opt_set_bool, &want_per_device_stats,
  1977. "Force verbose mode and output per-device statistics"),
  1978. OPT_WITH_ARG("--userpass|-O", // duplicate to ensure config loads it before pool-priority
  1979. set_userpass, NULL, NULL,
  1980. opt_hidden),
  1981. OPT_WITH_ARG("--pool-priority",
  1982. set_pool_priority, NULL, NULL,
  1983. "Priority for just the previous-defined pool"),
  1984. OPT_WITH_ARG("--pool-proxy|-x",
  1985. set_pool_proxy, NULL, NULL,
  1986. "Proxy URI to use for connecting to just the previous-defined pool"),
  1987. OPT_WITH_ARG("--force-rollntime", // NOTE: must be after --pass for config file ordering
  1988. set_pool_force_rollntime, NULL, NULL,
  1989. opt_hidden),
  1990. OPT_WITHOUT_ARG("--protocol-dump|-P",
  1991. opt_set_bool, &opt_protocol,
  1992. "Verbose dump of protocol-level activities"),
  1993. OPT_WITH_ARG("--queue|-Q",
  1994. set_int_0_to_9999, opt_show_intval, &opt_queue,
  1995. "Minimum number of work items to have queued (0+)"),
  1996. OPT_WITHOUT_ARG("--quiet|-q",
  1997. opt_set_bool, &opt_quiet,
  1998. "Disable logging output, display status and errors"),
  1999. OPT_WITHOUT_ARG("--quiet-work-updates|--quiet-work-update",
  2000. opt_set_bool, &opt_quiet_work_updates,
  2001. opt_hidden),
  2002. OPT_WITH_ARG("--quit-summary",
  2003. set_quit_summary, NULL, NULL,
  2004. "Summary printed when you quit: none/devs/procs/detailed"),
  2005. OPT_WITH_ARG("--quota|-U",
  2006. set_quota, NULL, NULL,
  2007. "quota;URL combination for server with load-balance strategy quotas"),
  2008. OPT_WITHOUT_ARG("--real-quiet",
  2009. opt_set_bool, &opt_realquiet,
  2010. "Disable all output"),
  2011. OPT_WITH_ARG("--request-diff",
  2012. set_request_diff, opt_show_floatval, &request_pdiff,
  2013. "Request a specific difficulty from pools"),
  2014. OPT_WITH_ARG("--retries",
  2015. opt_set_intval, opt_show_intval, &opt_retries,
  2016. "Number of times to retry failed submissions before giving up (-1 means never)"),
  2017. OPT_WITH_ARG("--retry-pause",
  2018. set_null, NULL, NULL,
  2019. opt_hidden),
  2020. OPT_WITH_ARG("--rotate",
  2021. set_rotate, opt_show_intval, &opt_rotate_period,
  2022. "Change multipool strategy from failover to regularly rotate at N minutes"),
  2023. OPT_WITHOUT_ARG("--round-robin",
  2024. set_rr, &pool_strategy,
  2025. "Change multipool strategy from failover to round robin on failure"),
  2026. OPT_WITH_ARG("--scan|-S",
  2027. add_serial, NULL, NULL,
  2028. "Configure how to scan for mining devices"),
  2029. OPT_WITH_ARG("--scan-device|--scan-serial|--devscan",
  2030. add_serial, NULL, NULL,
  2031. opt_hidden),
  2032. OPT_WITH_ARG("--scan-time",
  2033. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  2034. "Upper bound on time spent scanning current work, in seconds"),
  2035. OPT_WITH_ARG("-s",
  2036. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  2037. opt_hidden),
  2038. OPT_WITH_ARG("--scantime",
  2039. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  2040. opt_hidden),
  2041. OPT_WITH_ARG("--sched-start",
  2042. set_schedtime, NULL, &schedstart,
  2043. "Set a time of day in HH:MM to start mining (a once off without a stop time)"),
  2044. OPT_WITH_ARG("--sched-stop",
  2045. set_schedtime, NULL, &schedstop,
  2046. "Set a time of day in HH:MM to stop mining (will quit without a start time)"),
  2047. #ifdef USE_SCRYPT
  2048. OPT_WITHOUT_ARG("--scrypt",
  2049. opt_set_bool, &opt_scrypt,
  2050. "Use the scrypt algorithm for mining (non-bitcoin)"),
  2051. #endif
  2052. OPT_WITH_ARG("--set-device|--set",
  2053. opt_string_elist_add, NULL, &opt_set_device_list,
  2054. "Set default parameters on devices; eg, NFY:osc6_bits=50"),
  2055. #if defined(USE_SCRYPT) && defined(HAVE_OPENCL)
  2056. OPT_WITH_ARG("--shaders",
  2057. set_shaders, NULL, NULL,
  2058. opt_hidden),
  2059. #endif
  2060. #ifdef HAVE_PWD_H
  2061. OPT_WITH_ARG("--setuid",
  2062. opt_set_charp, NULL, &opt_setuid,
  2063. "Username of an unprivileged user to run as"),
  2064. #endif
  2065. OPT_WITH_ARG("--sharelog",
  2066. set_sharelog, NULL, NULL,
  2067. "Append share log to file"),
  2068. OPT_WITH_ARG("--shares",
  2069. opt_set_floatval, NULL, &opt_shares,
  2070. "Quit after mining 2^32 * N hashes worth of shares (default: unlimited)"),
  2071. OPT_WITHOUT_ARG("--show-processors",
  2072. opt_set_bool, &opt_show_procs,
  2073. "Show per processor statistics in summary"),
  2074. OPT_WITHOUT_ARG("--show-procs",
  2075. opt_set_bool, &opt_show_procs,
  2076. opt_hidden),
  2077. OPT_WITH_ARG("--skip-security-checks",
  2078. set_int_0_to_9999, NULL, &opt_skip_checks,
  2079. "Skip security checks sometimes to save bandwidth; only check 1/<arg>th of the time (default: never skip)"),
  2080. OPT_WITH_ARG("--socks-proxy",
  2081. opt_set_charp, NULL, &opt_socks_proxy,
  2082. "Set socks proxy (host:port)"),
  2083. #ifdef USE_LIBEVENT
  2084. OPT_WITH_ARG("--stratum-port",
  2085. opt_set_intval, opt_show_intval, &stratumsrv_port,
  2086. "Port number to listen on for stratum miners (-1 means disabled)"),
  2087. #endif
  2088. OPT_WITHOUT_ARG("--submit-stale",
  2089. opt_set_bool, &opt_submit_stale,
  2090. opt_hidden),
  2091. OPT_WITH_ARG("--submit-threads",
  2092. opt_set_intval, opt_show_intval, &opt_submit_threads,
  2093. "Minimum number of concurrent share submissions (default: 64)"),
  2094. #ifdef HAVE_SYSLOG_H
  2095. OPT_WITHOUT_ARG("--syslog",
  2096. opt_set_bool, &use_syslog,
  2097. "Use system log for output messages (default: standard error)"),
  2098. #endif
  2099. OPT_WITH_ARG("--temp-cutoff",
  2100. set_temp_cutoff, NULL, &opt_cutofftemp,
  2101. opt_hidden),
  2102. OPT_WITH_ARG("--temp-hysteresis",
  2103. set_int_1_to_10, opt_show_intval, &opt_hysteresis,
  2104. "Set how much the temperature can fluctuate outside limits when automanaging speeds"),
  2105. #ifdef HAVE_ADL
  2106. OPT_WITH_ARG("--temp-overheat",
  2107. set_temp_overheat, opt_show_intval, &opt_overheattemp,
  2108. opt_hidden),
  2109. #endif
  2110. OPT_WITH_ARG("--temp-target",
  2111. set_temp_target, NULL, NULL,
  2112. opt_hidden),
  2113. OPT_WITHOUT_ARG("--text-only|-T",
  2114. opt_set_invbool, &use_curses,
  2115. #ifdef HAVE_CURSES
  2116. "Disable ncurses formatted screen output"
  2117. #else
  2118. opt_hidden
  2119. #endif
  2120. ),
  2121. #if defined(USE_SCRYPT) && defined(HAVE_OPENCL)
  2122. OPT_WITH_ARG("--thread-concurrency",
  2123. set_thread_concurrency, NULL, NULL,
  2124. opt_hidden),
  2125. #endif
  2126. #ifdef USE_UNICODE
  2127. OPT_WITHOUT_ARG("--unicode",
  2128. opt_set_bool, &use_unicode,
  2129. "Use Unicode characters in TUI"),
  2130. #endif
  2131. OPT_WITH_ARG("--url|-o",
  2132. set_url, NULL, NULL,
  2133. "URL for bitcoin JSON-RPC server"),
  2134. OPT_WITH_ARG("--user|-u",
  2135. set_user, NULL, NULL,
  2136. "Username for bitcoin JSON-RPC server"),
  2137. #ifdef HAVE_OPENCL
  2138. OPT_WITH_ARG("--vectors|-v",
  2139. set_vector, NULL, NULL,
  2140. opt_hidden),
  2141. #endif
  2142. OPT_WITHOUT_ARG("--verbose",
  2143. opt_set_bool, &opt_log_output,
  2144. "Log verbose output to stderr as well as status output"),
  2145. OPT_WITHOUT_ARG("--verbose-work-updates|--verbose-work-update",
  2146. opt_set_invbool, &opt_quiet_work_updates,
  2147. opt_hidden),
  2148. OPT_WITHOUT_ARG("--weighed-stats",
  2149. opt_set_bool, &opt_weighed_stats,
  2150. "Display statistics weighed to difficulty 1"),
  2151. #ifdef HAVE_OPENCL
  2152. OPT_WITH_ARG("--worksize|-w",
  2153. set_worksize, NULL, NULL,
  2154. opt_hidden),
  2155. #endif
  2156. OPT_WITHOUT_ARG("--unittest",
  2157. opt_set_bool, &opt_unittest, opt_hidden),
  2158. OPT_WITH_ARG("--userpass|-O",
  2159. set_userpass, NULL, NULL,
  2160. "Username:Password pair for bitcoin JSON-RPC server"),
  2161. OPT_WITHOUT_ARG("--worktime",
  2162. opt_set_bool, &opt_worktime,
  2163. "Display extra work time debug information"),
  2164. OPT_WITH_ARG("--pools",
  2165. opt_set_bool, NULL, NULL, opt_hidden),
  2166. OPT_ENDTABLE
  2167. };
  2168. static char *load_config(const char *arg, void __maybe_unused *unused);
  2169. static int fileconf_load;
  2170. static char *parse_config(json_t *config, bool fileconf)
  2171. {
  2172. static char err_buf[200];
  2173. struct opt_table *opt;
  2174. json_t *val;
  2175. if (fileconf && !fileconf_load)
  2176. fileconf_load = 1;
  2177. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  2178. char *p, *name, *sp;
  2179. /* We don't handle subtables. */
  2180. assert(!(opt->type & OPT_SUBTABLE));
  2181. if (!opt->names)
  2182. continue;
  2183. /* Pull apart the option name(s). */
  2184. name = strdup(opt->names);
  2185. for (p = strtok_r(name, "|", &sp); p; p = strtok_r(NULL, "|", &sp)) {
  2186. char *err = "Invalid value";
  2187. /* Ignore short options. */
  2188. if (p[1] != '-')
  2189. continue;
  2190. val = json_object_get(config, p+2);
  2191. if (!val)
  2192. continue;
  2193. if (opt->type & OPT_HASARG) {
  2194. if (json_is_string(val)) {
  2195. err = opt->cb_arg(json_string_value(val),
  2196. opt->u.arg);
  2197. } else if (json_is_number(val)) {
  2198. char buf[256], *p, *q;
  2199. snprintf(buf, 256, "%f", json_number_value(val));
  2200. if ( (p = strchr(buf, '.')) ) {
  2201. // Trim /\.0*$/ to work properly with integer-only arguments
  2202. q = p;
  2203. while (*(++q) == '0') {}
  2204. if (*q == '\0')
  2205. *p = '\0';
  2206. }
  2207. err = opt->cb_arg(buf, opt->u.arg);
  2208. } else if (json_is_array(val)) {
  2209. int n, size = json_array_size(val);
  2210. err = NULL;
  2211. for (n = 0; n < size && !err; n++) {
  2212. if (json_is_string(json_array_get(val, n)))
  2213. err = opt->cb_arg(json_string_value(json_array_get(val, n)), opt->u.arg);
  2214. else if (json_is_object(json_array_get(val, n)))
  2215. err = parse_config(json_array_get(val, n), false);
  2216. }
  2217. }
  2218. } else if (opt->type & OPT_NOARG) {
  2219. if (json_is_true(val))
  2220. err = opt->cb(opt->u.arg);
  2221. else if (json_is_boolean(val)) {
  2222. if (opt->cb == (void*)opt_set_bool)
  2223. err = opt_set_invbool(opt->u.arg);
  2224. else if (opt->cb == (void*)opt_set_invbool)
  2225. err = opt_set_bool(opt->u.arg);
  2226. }
  2227. }
  2228. if (err) {
  2229. /* Allow invalid values to be in configuration
  2230. * file, just skipping over them provided the
  2231. * JSON is still valid after that. */
  2232. if (fileconf) {
  2233. applog(LOG_ERR, "Invalid config option %s: %s", p, err);
  2234. fileconf_load = -1;
  2235. } else {
  2236. snprintf(err_buf, sizeof(err_buf), "Parsing JSON option %s: %s",
  2237. p, err);
  2238. return err_buf;
  2239. }
  2240. }
  2241. }
  2242. free(name);
  2243. }
  2244. val = json_object_get(config, JSON_INCLUDE_CONF);
  2245. if (val && json_is_string(val))
  2246. return load_config(json_string_value(val), NULL);
  2247. return NULL;
  2248. }
  2249. char *cnfbuf = NULL;
  2250. static char *load_config(const char *arg, void __maybe_unused *unused)
  2251. {
  2252. json_error_t err;
  2253. json_t *config;
  2254. char *json_error;
  2255. size_t siz;
  2256. if (!cnfbuf)
  2257. cnfbuf = strdup(arg);
  2258. if (++include_count > JSON_MAX_DEPTH)
  2259. return JSON_MAX_DEPTH_ERR;
  2260. #if JANSSON_MAJOR_VERSION > 1
  2261. config = json_load_file(arg, 0, &err);
  2262. #else
  2263. config = json_load_file(arg, &err);
  2264. #endif
  2265. if (!json_is_object(config)) {
  2266. siz = JSON_LOAD_ERROR_LEN + strlen(arg) + strlen(err.text);
  2267. json_error = malloc(siz);
  2268. if (!json_error)
  2269. quit(1, "Malloc failure in json error");
  2270. snprintf(json_error, siz, JSON_LOAD_ERROR, arg, err.text);
  2271. return json_error;
  2272. }
  2273. config_loaded = true;
  2274. /* Parse the config now, so we can override it. That can keep pointers
  2275. * so don't free config object. */
  2276. return parse_config(config, true);
  2277. }
  2278. static void load_default_config(void)
  2279. {
  2280. cnfbuf = malloc(PATH_MAX);
  2281. #if defined(unix)
  2282. if (getenv("HOME") && *getenv("HOME")) {
  2283. strcpy(cnfbuf, getenv("HOME"));
  2284. strcat(cnfbuf, "/");
  2285. } else
  2286. strcpy(cnfbuf, "");
  2287. char *dirp = cnfbuf + strlen(cnfbuf);
  2288. strcpy(dirp, ".bfgminer/");
  2289. strcat(dirp, def_conf);
  2290. if (access(cnfbuf, R_OK))
  2291. // No BFGMiner config, try Cgminer's...
  2292. strcpy(dirp, ".cgminer/cgminer.conf");
  2293. #else
  2294. strcpy(cnfbuf, "");
  2295. strcat(cnfbuf, def_conf);
  2296. #endif
  2297. if (!access(cnfbuf, R_OK))
  2298. load_config(cnfbuf, NULL);
  2299. else {
  2300. free(cnfbuf);
  2301. cnfbuf = NULL;
  2302. }
  2303. }
  2304. extern const char *opt_argv0;
  2305. static char *opt_verusage_and_exit(const char *extra)
  2306. {
  2307. puts(packagename);
  2308. printf(" Lowlevel:%s\n", BFG_LOWLLIST);
  2309. printf(" Drivers:%s\n", BFG_DRIVERLIST);
  2310. printf(" Algorithms:%s\n", BFG_ALGOLIST);
  2311. printf(" Options:%s\n", BFG_OPTLIST);
  2312. printf("%s", opt_usage(opt_argv0, extra));
  2313. fflush(stdout);
  2314. exit(0);
  2315. }
  2316. /* These options are parsed before anything else */
  2317. static struct opt_table opt_early_table[] = {
  2318. OPT_EARLY_WITH_ARG("--config|-c",
  2319. set_bool_ignore_arg, NULL, &config_loaded,
  2320. opt_hidden),
  2321. OPT_EARLY_WITHOUT_ARG("--no-config",
  2322. opt_set_bool, &config_loaded,
  2323. "Inhibit loading default config file"),
  2324. OPT_ENDTABLE
  2325. };
  2326. /* These options are available from commandline only */
  2327. static struct opt_table opt_cmdline_table[] = {
  2328. OPT_WITH_ARG("--config|-c",
  2329. load_config, NULL, NULL,
  2330. "Load a JSON-format configuration file\n"
  2331. "See example.conf for an example configuration."),
  2332. OPT_EARLY_WITHOUT_ARG("--no-config",
  2333. opt_set_bool, &config_loaded,
  2334. "Inhibit loading default config file"),
  2335. OPT_WITHOUT_ARG("--help|-h",
  2336. opt_verusage_and_exit, NULL,
  2337. "Print this message"),
  2338. #ifdef HAVE_OPENCL
  2339. OPT_WITHOUT_ARG("--ndevs|-n",
  2340. print_ndevs_and_exit, &nDevs,
  2341. opt_hidden),
  2342. #endif
  2343. OPT_WITHOUT_ARG("--version|-V",
  2344. opt_version_and_exit, packagename,
  2345. "Display version and exit"),
  2346. OPT_ENDTABLE
  2347. };
  2348. static bool jobj_binary(const json_t *obj, const char *key,
  2349. void *buf, size_t buflen, bool required)
  2350. {
  2351. const char *hexstr;
  2352. json_t *tmp;
  2353. tmp = json_object_get(obj, key);
  2354. if (unlikely(!tmp)) {
  2355. if (unlikely(required))
  2356. applog(LOG_ERR, "JSON key '%s' not found", key);
  2357. return false;
  2358. }
  2359. hexstr = json_string_value(tmp);
  2360. if (unlikely(!hexstr)) {
  2361. applog(LOG_ERR, "JSON key '%s' is not a string", key);
  2362. return false;
  2363. }
  2364. if (!hex2bin(buf, hexstr, buflen))
  2365. return false;
  2366. return true;
  2367. }
  2368. static void calc_midstate(struct work *work)
  2369. {
  2370. union {
  2371. unsigned char c[64];
  2372. uint32_t i[16];
  2373. } data;
  2374. swap32yes(&data.i[0], work->data, 16);
  2375. sha256_ctx ctx;
  2376. sha256_init(&ctx);
  2377. sha256_update(&ctx, data.c, 64);
  2378. memcpy(work->midstate, ctx.h, sizeof(work->midstate));
  2379. swap32tole(work->midstate, work->midstate, 8);
  2380. }
  2381. static struct work *make_work(void)
  2382. {
  2383. struct work *work = calloc(1, sizeof(struct work));
  2384. if (unlikely(!work))
  2385. quit(1, "Failed to calloc work in make_work");
  2386. cg_wlock(&control_lock);
  2387. work->id = total_work++;
  2388. cg_wunlock(&control_lock);
  2389. return work;
  2390. }
  2391. /* This is the central place all work that is about to be retired should be
  2392. * cleaned to remove any dynamically allocated arrays within the struct */
  2393. void clean_work(struct work *work)
  2394. {
  2395. free(work->job_id);
  2396. bytes_free(&work->nonce2);
  2397. free(work->nonce1);
  2398. if (work->device_data_free_func)
  2399. work->device_data_free_func(work);
  2400. if (work->tmpl) {
  2401. struct pool *pool = work->pool;
  2402. mutex_lock(&pool->pool_lock);
  2403. bool free_tmpl = !--*work->tmpl_refcount;
  2404. mutex_unlock(&pool->pool_lock);
  2405. if (free_tmpl) {
  2406. blktmpl_free(work->tmpl);
  2407. free(work->tmpl_refcount);
  2408. }
  2409. }
  2410. memset(work, 0, sizeof(struct work));
  2411. }
  2412. /* All dynamically allocated work structs should be freed here to not leak any
  2413. * ram from arrays allocated within the work struct */
  2414. void free_work(struct work *work)
  2415. {
  2416. clean_work(work);
  2417. free(work);
  2418. }
  2419. static const char *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";
  2420. // Must only be called with ch_lock held!
  2421. static
  2422. void __update_block_title(const unsigned char *hash_swap)
  2423. {
  2424. if (hash_swap) {
  2425. char tmp[17];
  2426. // Only provided when the block has actually changed
  2427. free(current_hash);
  2428. current_hash = malloc(3 /* ... */ + 16 /* block hash segment */ + 1);
  2429. bin2hex(tmp, &hash_swap[24], 8);
  2430. memset(current_hash, '.', 3);
  2431. memcpy(&current_hash[3], tmp, 17);
  2432. known_blkheight_current = false;
  2433. } else if (likely(known_blkheight_current)) {
  2434. return;
  2435. }
  2436. if (current_block_id == known_blkheight_blkid) {
  2437. // FIXME: The block number will overflow this sometime around AD 2025-2027
  2438. if (known_blkheight < 1000000) {
  2439. memmove(&current_hash[3], &current_hash[11], 8);
  2440. snprintf(&current_hash[11], 20-11, " #%6u", known_blkheight);
  2441. }
  2442. known_blkheight_current = true;
  2443. }
  2444. }
  2445. static
  2446. void have_block_height(uint32_t block_id, uint32_t blkheight)
  2447. {
  2448. if (known_blkheight == blkheight)
  2449. return;
  2450. applog(LOG_DEBUG, "Learned that block id %08" PRIx32 " is height %" PRIu32, (uint32_t)be32toh(block_id), blkheight);
  2451. cg_wlock(&ch_lock);
  2452. known_blkheight = blkheight;
  2453. known_blkheight_blkid = block_id;
  2454. block_subsidy = 5000000000LL >> (blkheight / 210000);
  2455. if (block_id == current_block_id)
  2456. __update_block_title(NULL);
  2457. cg_wunlock(&ch_lock);
  2458. }
  2459. static
  2460. void pool_set_opaque(struct pool *pool, bool opaque)
  2461. {
  2462. if (pool->swork.opaque == opaque)
  2463. return;
  2464. pool->swork.opaque = opaque;
  2465. if (opaque)
  2466. applog(LOG_WARNING, "Pool %u is hiding block contents from us",
  2467. pool->pool_no);
  2468. else
  2469. applog(LOG_NOTICE, "Pool %u now providing block contents to us",
  2470. pool->pool_no);
  2471. }
  2472. static bool work_decode(struct pool *pool, struct work *work, json_t *val)
  2473. {
  2474. json_t *res_val = json_object_get(val, "result");
  2475. json_t *tmp_val;
  2476. bool ret = false;
  2477. if (unlikely(detect_algo == 1)) {
  2478. json_t *tmp = json_object_get(res_val, "algorithm");
  2479. const char *v = tmp ? json_string_value(tmp) : "";
  2480. if (strncasecmp(v, "scrypt", 6))
  2481. detect_algo = 2;
  2482. }
  2483. if (work->tmpl) {
  2484. struct timeval tv_now;
  2485. cgtime(&tv_now);
  2486. const char *err = blktmpl_add_jansson(work->tmpl, res_val, tv_now.tv_sec);
  2487. if (err) {
  2488. applog(LOG_ERR, "blktmpl error: %s", err);
  2489. return false;
  2490. }
  2491. work->rolltime = blkmk_time_left(work->tmpl, tv_now.tv_sec);
  2492. #if BLKMAKER_VERSION > 1
  2493. if (opt_coinbase_script.sz)
  2494. {
  2495. bool newcb;
  2496. #if BLKMAKER_VERSION > 2
  2497. blkmk_init_generation2(work->tmpl, opt_coinbase_script.data, opt_coinbase_script.sz, &newcb);
  2498. #else
  2499. newcb = !work->tmpl->cbtxn;
  2500. blkmk_init_generation(work->tmpl, opt_coinbase_script.data, opt_coinbase_script.sz);
  2501. #endif
  2502. if (newcb)
  2503. {
  2504. ssize_t ae = blkmk_append_coinbase_safe(work->tmpl, &template_nonce, sizeof(template_nonce));
  2505. if (ae < (ssize_t)sizeof(template_nonce))
  2506. 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);
  2507. ++template_nonce;
  2508. }
  2509. }
  2510. #endif
  2511. #if BLKMAKER_VERSION > 0
  2512. {
  2513. ssize_t ae = blkmk_append_coinbase_safe(work->tmpl, opt_coinbase_sig, 101);
  2514. static bool appenderr = false;
  2515. if (ae <= 0) {
  2516. if (opt_coinbase_sig) {
  2517. applog((appenderr ? LOG_DEBUG : LOG_WARNING), "Cannot append coinbase signature at all on pool %u (%"PRId64")", pool->pool_no, (int64_t)ae);
  2518. appenderr = true;
  2519. }
  2520. } else if (ae >= 3 || opt_coinbase_sig) {
  2521. const char *cbappend = opt_coinbase_sig;
  2522. const char full[] = PACKAGE " " VERSION;
  2523. if (!cbappend) {
  2524. if ((size_t)ae >= sizeof(full) - 1)
  2525. cbappend = full;
  2526. else if ((size_t)ae >= sizeof(PACKAGE) - 1)
  2527. cbappend = PACKAGE;
  2528. else
  2529. cbappend = "BFG";
  2530. }
  2531. size_t cbappendsz = strlen(cbappend);
  2532. static bool truncatewarning = false;
  2533. if (cbappendsz <= (size_t)ae) {
  2534. if (cbappendsz < (size_t)ae)
  2535. // If we have space, include the trailing \0
  2536. ++cbappendsz;
  2537. ae = cbappendsz;
  2538. truncatewarning = false;
  2539. } else {
  2540. char *tmp = malloc(ae + 1);
  2541. memcpy(tmp, opt_coinbase_sig, ae);
  2542. tmp[ae] = '\0';
  2543. applog((truncatewarning ? LOG_DEBUG : LOG_WARNING),
  2544. "Pool %u truncating appended coinbase signature at %"PRId64" bytes: %s(%s)",
  2545. pool->pool_no, (int64_t)ae, tmp, &opt_coinbase_sig[ae]);
  2546. free(tmp);
  2547. truncatewarning = true;
  2548. }
  2549. ae = blkmk_append_coinbase_safe(work->tmpl, cbappend, ae);
  2550. if (ae <= 0) {
  2551. applog((appenderr ? LOG_DEBUG : LOG_WARNING), "Error appending coinbase signature (%"PRId64")", (int64_t)ae);
  2552. appenderr = true;
  2553. } else
  2554. appenderr = false;
  2555. }
  2556. }
  2557. #endif
  2558. if (blkmk_get_data(work->tmpl, work->data, 80, tv_now.tv_sec, NULL, &work->dataid) < 76)
  2559. return false;
  2560. swap32yes(work->data, work->data, 80 / 4);
  2561. memcpy(&work->data[80], workpadding_bin, 48);
  2562. const struct blktmpl_longpoll_req *lp;
  2563. if ((lp = blktmpl_get_longpoll(work->tmpl)) && ((!pool->lp_id) || strcmp(lp->id, pool->lp_id))) {
  2564. free(pool->lp_id);
  2565. pool->lp_id = strdup(lp->id);
  2566. #if 0 /* This just doesn't work :( */
  2567. curl_socket_t sock = pool->lp_socket;
  2568. if (sock != CURL_SOCKET_BAD) {
  2569. pool->lp_socket = CURL_SOCKET_BAD;
  2570. applog(LOG_WARNING, "Pool %u long poll request hanging, reconnecting", pool->pool_no);
  2571. shutdown(sock, SHUT_RDWR);
  2572. }
  2573. #endif
  2574. }
  2575. }
  2576. else
  2577. if (unlikely(!jobj_binary(res_val, "data", work->data, sizeof(work->data), true))) {
  2578. applog(LOG_ERR, "JSON inval data");
  2579. return false;
  2580. }
  2581. if (!jobj_binary(res_val, "midstate", work->midstate, sizeof(work->midstate), false)) {
  2582. // Calculate it ourselves
  2583. applog(LOG_DEBUG, "Calculating midstate locally");
  2584. calc_midstate(work);
  2585. }
  2586. if (unlikely(!jobj_binary(res_val, "target", work->target, sizeof(work->target), true))) {
  2587. applog(LOG_ERR, "JSON inval target");
  2588. return false;
  2589. }
  2590. if (work->tmpl) {
  2591. for (size_t i = 0; i < sizeof(work->target) / 2; ++i)
  2592. {
  2593. int p = (sizeof(work->target) - 1) - i;
  2594. unsigned char c = work->target[i];
  2595. work->target[i] = work->target[p];
  2596. work->target[p] = c;
  2597. }
  2598. }
  2599. if ( (tmp_val = json_object_get(res_val, "height")) ) {
  2600. uint32_t blkheight = json_number_value(tmp_val);
  2601. uint32_t block_id = ((uint32_t*)work->data)[1];
  2602. have_block_height(block_id, blkheight);
  2603. }
  2604. memset(work->hash, 0, sizeof(work->hash));
  2605. cgtime(&work->tv_staged);
  2606. pool_set_opaque(pool, !work->tmpl);
  2607. ret = true;
  2608. return ret;
  2609. }
  2610. /* Returns whether the pool supports local work generation or not. */
  2611. static bool pool_localgen(struct pool *pool)
  2612. {
  2613. return (pool->last_work_copy || pool->has_stratum);
  2614. }
  2615. int dev_from_id(int thr_id)
  2616. {
  2617. struct cgpu_info *cgpu = get_thr_cgpu(thr_id);
  2618. return cgpu->device_id;
  2619. }
  2620. /* Create an exponentially decaying average over the opt_log_interval */
  2621. void decay_time(double *f, double fadd, double fsecs)
  2622. {
  2623. double ftotal, fprop;
  2624. fprop = 1.0 - 1 / (exp(fsecs / (double)opt_log_interval));
  2625. ftotal = 1.0 + fprop;
  2626. *f += (fadd * fprop);
  2627. *f /= ftotal;
  2628. }
  2629. static int __total_staged(void)
  2630. {
  2631. return HASH_COUNT(staged_work);
  2632. }
  2633. static int total_staged(void)
  2634. {
  2635. int ret;
  2636. mutex_lock(stgd_lock);
  2637. ret = __total_staged();
  2638. mutex_unlock(stgd_lock);
  2639. return ret;
  2640. }
  2641. #ifdef HAVE_CURSES
  2642. WINDOW *mainwin, *statuswin, *logwin;
  2643. #endif
  2644. double total_secs = 1.0;
  2645. static char statusline[256];
  2646. /* logstart is where the log window should start */
  2647. static int devcursor, logstart, logcursor;
  2648. #ifdef HAVE_CURSES
  2649. /* statusy is where the status window goes up to in cases where it won't fit at startup */
  2650. static int statusy;
  2651. static int devsummaryYOffset;
  2652. static int total_lines;
  2653. #endif
  2654. #ifdef HAVE_OPENCL
  2655. struct cgpu_info gpus[MAX_GPUDEVICES]; /* Maximum number apparently possible */
  2656. #endif
  2657. struct cgpu_info *cpus;
  2658. bool _bfg_console_cancel_disabled;
  2659. int _bfg_console_prev_cancelstate;
  2660. #ifdef HAVE_CURSES
  2661. #define lock_curses() bfg_console_lock()
  2662. #define unlock_curses() bfg_console_unlock()
  2663. static bool curses_active_locked(void)
  2664. {
  2665. bool ret;
  2666. lock_curses();
  2667. ret = curses_active;
  2668. if (!ret)
  2669. unlock_curses();
  2670. return ret;
  2671. }
  2672. // Cancellable getch
  2673. int my_cancellable_getch(void)
  2674. {
  2675. // This only works because the macro only hits direct getch() calls
  2676. typedef int (*real_getch_t)(void);
  2677. const real_getch_t real_getch = __real_getch;
  2678. int type, rv;
  2679. bool sct;
  2680. sct = !pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &type);
  2681. rv = real_getch();
  2682. if (sct)
  2683. pthread_setcanceltype(type, &type);
  2684. return rv;
  2685. }
  2686. #ifdef PDCURSES
  2687. static
  2688. int bfg_wresize(WINDOW *win, int lines, int columns)
  2689. {
  2690. int rv = wresize(win, lines, columns);
  2691. int x, y;
  2692. getyx(win, y, x);
  2693. if (unlikely(y >= lines || x >= columns))
  2694. {
  2695. if (y >= lines)
  2696. y = lines - 1;
  2697. if (x >= columns)
  2698. x = columns - 1;
  2699. wmove(win, y, x);
  2700. }
  2701. return rv;
  2702. }
  2703. #else
  2704. # define bfg_wresize wresize
  2705. #endif
  2706. #endif
  2707. void tailsprintf(char *buf, size_t bufsz, const char *fmt, ...)
  2708. {
  2709. va_list ap;
  2710. size_t presz = strlen(buf);
  2711. va_start(ap, fmt);
  2712. vsnprintf(&buf[presz], bufsz - presz, fmt, ap);
  2713. va_end(ap);
  2714. }
  2715. double stats_elapsed(struct cgminer_stats *stats)
  2716. {
  2717. struct timeval now;
  2718. double elapsed;
  2719. if (stats->start_tv.tv_sec == 0)
  2720. elapsed = total_secs;
  2721. else {
  2722. cgtime(&now);
  2723. elapsed = tdiff(&now, &stats->start_tv);
  2724. }
  2725. if (elapsed < 1.0)
  2726. elapsed = 1.0;
  2727. return elapsed;
  2728. }
  2729. bool drv_ready(struct cgpu_info *cgpu)
  2730. {
  2731. switch (cgpu->status) {
  2732. case LIFE_INIT:
  2733. case LIFE_DEAD2:
  2734. return false;
  2735. default:
  2736. return true;
  2737. }
  2738. }
  2739. double cgpu_utility(struct cgpu_info *cgpu)
  2740. {
  2741. double dev_runtime = cgpu_runtime(cgpu);
  2742. return cgpu->utility = cgpu->accepted / dev_runtime * 60;
  2743. }
  2744. #define suffix_string(val, buf, bufsiz, sigdigits) do{ \
  2745. _Static_assert(sigdigits == 0, "suffix_string only supported with sigdigits==0"); \
  2746. format_unit3(buf, bufsiz, FUP_DIFF, "", H2B_SHORTV, val, -1); \
  2747. }while(0)
  2748. static float
  2749. utility_to_hashrate(double utility)
  2750. {
  2751. return utility * 0x4444444;
  2752. }
  2753. static const char*_unitchar = "pn\xb5m kMGTPEZY?";
  2754. static const int _unitbase = 4;
  2755. static
  2756. void pick_unit(float hashrate, unsigned char *unit)
  2757. {
  2758. unsigned char i;
  2759. if (hashrate == 0)
  2760. {
  2761. if (*unit < _unitbase)
  2762. *unit = _unitbase;
  2763. return;
  2764. }
  2765. hashrate *= 1e12;
  2766. for (i = 0; i < *unit; ++i)
  2767. hashrate /= 1e3;
  2768. // 1000 but with tolerance for floating-point rounding, avoid showing "1000.0"
  2769. while (hashrate >= 999.95)
  2770. {
  2771. hashrate /= 1e3;
  2772. if (likely(_unitchar[*unit] != '?'))
  2773. ++*unit;
  2774. }
  2775. }
  2776. #define hashrate_pick_unit(hashrate, unit) pick_unit(hashrate, unit)
  2777. enum h2bs_fmt {
  2778. H2B_NOUNIT, // "xxx.x"
  2779. H2B_SHORT, // "xxx.xMH/s"
  2780. H2B_SPACED, // "xxx.x MH/s"
  2781. H2B_SHORTV, // Like H2B_SHORT, but omit space for base unit
  2782. };
  2783. enum bfu_floatprec {
  2784. FUP_INTEGER,
  2785. FUP_HASHES,
  2786. FUP_BTC,
  2787. FUP_DIFF,
  2788. };
  2789. static
  2790. int format_unit3(char *buf, size_t sz, enum bfu_floatprec fprec, const char *measurement, enum h2bs_fmt fmt, float hashrate, signed char unitin)
  2791. {
  2792. char *s = buf;
  2793. unsigned char prec, i, unit;
  2794. int rv = 0;
  2795. if (unitin == -1)
  2796. {
  2797. unit = 0;
  2798. hashrate_pick_unit(hashrate, &unit);
  2799. }
  2800. else
  2801. unit = unitin;
  2802. hashrate *= 1e12;
  2803. for (i = 0; i < unit; ++i)
  2804. hashrate /= 1000;
  2805. switch (fprec)
  2806. {
  2807. case FUP_HASHES:
  2808. // 100 but with tolerance for floating-point rounding, max "99.99" then "100.0"
  2809. if (hashrate >= 99.995 || unit < 6)
  2810. prec = 1;
  2811. else
  2812. prec = 2;
  2813. _SNP("%5.*f", prec, hashrate);
  2814. break;
  2815. case FUP_INTEGER:
  2816. _SNP("%3d", (int)hashrate);
  2817. break;
  2818. case FUP_BTC:
  2819. if (hashrate >= 99.995)
  2820. prec = 0;
  2821. else
  2822. prec = 2;
  2823. _SNP("%5.*f", prec, hashrate);
  2824. break;
  2825. case FUP_DIFF:
  2826. if (unit > _unitbase)
  2827. _SNP("%.3g", hashrate);
  2828. else
  2829. _SNP("%u", (unsigned int)hashrate);
  2830. }
  2831. if (fmt != H2B_NOUNIT)
  2832. {
  2833. char uc[3] = {_unitchar[unit], '\0'};
  2834. switch (fmt) {
  2835. case H2B_SPACED:
  2836. _SNP(" ");
  2837. default:
  2838. break;
  2839. case H2B_SHORTV:
  2840. if (isspace(uc[0]))
  2841. uc[0] = '\0';
  2842. }
  2843. if (uc[0] == '\xb5')
  2844. // Convert to UTF-8
  2845. snprintf(uc, sizeof(uc), "%s", U8_MICRO);
  2846. _SNP("%s%s", uc, measurement);
  2847. }
  2848. return rv;
  2849. }
  2850. #define format_unit2(buf, sz, floatprec, measurement, fmt, n, unit) \
  2851. format_unit3(buf, sz, floatprec ? FUP_HASHES : FUP_INTEGER, measurement, fmt, n, unit)
  2852. static
  2853. 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)
  2854. {
  2855. unsigned char unit = 0;
  2856. bool allzero = true;
  2857. int i;
  2858. size_t delimsz = 0;
  2859. char *buf = buflist[0];
  2860. size_t bufsz = bufszlist[0];
  2861. size_t itemwidth = (floatprec ? 5 : 3);
  2862. if (!isarray)
  2863. delimsz = strlen(delim);
  2864. for (i = 0; i < count; ++i)
  2865. if (numbers[i] != 0)
  2866. {
  2867. pick_unit(numbers[i], &unit);
  2868. allzero = false;
  2869. }
  2870. if (allzero)
  2871. unit = _unitbase;
  2872. --count;
  2873. for (i = 0; i < count; ++i)
  2874. {
  2875. format_unit2(buf, bufsz, floatprec, NULL, H2B_NOUNIT, numbers[i], unit);
  2876. if (isarray)
  2877. {
  2878. buf = buflist[i + 1];
  2879. bufsz = bufszlist[i + 1];
  2880. }
  2881. else
  2882. {
  2883. buf += itemwidth;
  2884. bufsz -= itemwidth;
  2885. if (delimsz > bufsz)
  2886. delimsz = bufsz;
  2887. memcpy(buf, delim, delimsz);
  2888. buf += delimsz;
  2889. bufsz -= delimsz;
  2890. }
  2891. }
  2892. // Last entry has the unit
  2893. format_unit2(buf, bufsz, floatprec, measurement, fmt, numbers[count], unit);
  2894. return buflist[0];
  2895. }
  2896. #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)
  2897. #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)
  2898. static
  2899. int percentf3(char * const buf, size_t sz, double p, const double t)
  2900. {
  2901. char *s = buf;
  2902. int rv = 0;
  2903. if (!p)
  2904. _SNP("none");
  2905. else
  2906. if (t <= p)
  2907. _SNP("100%%");
  2908. else
  2909. {
  2910. p /= t;
  2911. if (p < 0.00995) // 0.01 but with tolerance for floating-point rounding, max ".99%"
  2912. _SNP(".%02.0f%%", p * 10000); // ".01%"
  2913. else
  2914. if (p < 0.0995) // 0.1 but with tolerance for floating-point rounding, max "9.9%"
  2915. _SNP("%.1f%%", p * 100); // "9.1%"
  2916. else
  2917. _SNP("%3.0f%%", p * 100); // " 99%"
  2918. }
  2919. return rv;
  2920. }
  2921. #define percentf4(buf, bufsz, p, t) percentf3(buf, bufsz, p, p + t)
  2922. static
  2923. void test_decimal_width()
  2924. {
  2925. // The pipe character at end of each line should perfectly line up
  2926. char printbuf[512];
  2927. char testbuf1[64];
  2928. char testbuf2[64];
  2929. char testbuf3[64];
  2930. char testbuf4[64];
  2931. double testn;
  2932. int width;
  2933. int saved;
  2934. // Hotspots around 0.1 and 0.01
  2935. saved = -1;
  2936. for (testn = 0.09; testn <= 0.11; testn += 0.000001) {
  2937. percentf3(testbuf1, sizeof(testbuf1), testn, 1.0);
  2938. percentf3(testbuf2, sizeof(testbuf2), testn, 10.0);
  2939. width = snprintf(printbuf, sizeof(printbuf), "%10g %s %s |", testn, testbuf1, testbuf2);
  2940. if (unlikely((saved != -1) && (width != saved))) {
  2941. applog(LOG_ERR, "Test width mismatch in percentf3! %d not %d at %10g", width, saved, testn);
  2942. applog(LOG_ERR, "%s", printbuf);
  2943. }
  2944. saved = width;
  2945. }
  2946. // Hotspot around 100 (but test this in several units because format_unit2 also has unit<2 check)
  2947. saved = -1;
  2948. for (testn = 99.0; testn <= 101.0; testn += 0.0001) {
  2949. format_unit2(testbuf1, sizeof(testbuf1), true, "x", H2B_SHORT, testn , -1);
  2950. format_unit2(testbuf2, sizeof(testbuf2), true, "x", H2B_SHORT, testn * 1e3, -1);
  2951. format_unit2(testbuf3, sizeof(testbuf3), true, "x", H2B_SHORT, testn * 1e6, -1);
  2952. snprintf(printbuf, sizeof(printbuf), "%10g %s %s %s |", testn, testbuf1, testbuf2, testbuf3);
  2953. width = utf8_strlen(printbuf);
  2954. if (unlikely((saved != -1) && (width != saved))) {
  2955. applog(LOG_ERR, "Test width mismatch in format_unit2! %d not %d at %10g", width, saved, testn);
  2956. applog(LOG_ERR, "%s", printbuf);
  2957. }
  2958. saved = width;
  2959. }
  2960. // Hotspot around unit transition boundary in pick_unit
  2961. saved = -1;
  2962. for (testn = 999.0; testn <= 1001.0; testn += 0.0001) {
  2963. format_unit2(testbuf1, sizeof(testbuf1), true, "x", H2B_SHORT, testn , -1);
  2964. format_unit2(testbuf2, sizeof(testbuf2), true, "x", H2B_SHORT, testn * 1e3, -1);
  2965. format_unit2(testbuf3, sizeof(testbuf3), true, "x", H2B_SHORT, testn * 1e6, -1);
  2966. format_unit2(testbuf4, sizeof(testbuf4), true, "x", H2B_SHORT, testn * 1e9, -1);
  2967. snprintf(printbuf, sizeof(printbuf), "%10g %s %s %s %s |", testn, testbuf1, testbuf2, testbuf3, testbuf4);
  2968. width = utf8_strlen(printbuf);
  2969. if (unlikely((saved != -1) && (width != saved))) {
  2970. applog(LOG_ERR, "Test width mismatch in pick_unit! %d not %d at %10g", width, saved, testn);
  2971. applog(LOG_ERR, "%s", printbuf);
  2972. }
  2973. saved = width;
  2974. }
  2975. }
  2976. #ifdef HAVE_CURSES
  2977. static void adj_width(int var, int *length);
  2978. #endif
  2979. #ifdef HAVE_CURSES
  2980. static int awidth = 1, rwidth = 1, swidth = 1, hwwidth = 1;
  2981. static
  2982. void format_statline(char *buf, size_t bufsz, const char *cHr, const char *aHr, const char *uHr, int accepted, int rejected, int stale, int wnotaccepted, int waccepted, int hwerrs, int bad_diff1, int allnonces)
  2983. {
  2984. char rejpcbuf[6];
  2985. char bnbuf[6];
  2986. adj_width(accepted, &awidth);
  2987. adj_width(rejected, &rwidth);
  2988. adj_width(stale, &swidth);
  2989. adj_width(hwerrs, &hwwidth);
  2990. percentf4(rejpcbuf, sizeof(rejpcbuf), wnotaccepted, waccepted);
  2991. percentf3(bnbuf, sizeof(bnbuf), bad_diff1, allnonces);
  2992. tailsprintf(buf, bufsz, "%s/%s/%s | A:%*d R:%*d+%*d(%s) HW:%*d/%s",
  2993. cHr, aHr, uHr,
  2994. awidth, accepted,
  2995. rwidth, rejected,
  2996. swidth, stale,
  2997. rejpcbuf,
  2998. hwwidth, hwerrs,
  2999. bnbuf
  3000. );
  3001. }
  3002. static
  3003. const char *pool_proto_str(const struct pool * const pool)
  3004. {
  3005. if (pool->idle)
  3006. return "Dead ";
  3007. if (pool->has_stratum)
  3008. return "Strtm";
  3009. if (pool->lp_url && pool->proto != pool->lp_proto)
  3010. return "Mixed";
  3011. switch (pool->proto)
  3012. {
  3013. case PLP_GETBLOCKTEMPLATE:
  3014. return " GBT ";
  3015. case PLP_GETWORK:
  3016. return "GWork";
  3017. default:
  3018. return "Alive";
  3019. }
  3020. }
  3021. #endif
  3022. static inline
  3023. void temperature_column(char *buf, size_t bufsz, bool maybe_unicode, const float * const temp)
  3024. {
  3025. if (!(use_unicode && have_unicode_degrees))
  3026. maybe_unicode = false;
  3027. if (temp && *temp > 0.)
  3028. if (maybe_unicode)
  3029. snprintf(buf, bufsz, "%4.1f"U8_DEGREE"C", *temp);
  3030. else
  3031. snprintf(buf, bufsz, "%4.1fC", *temp);
  3032. else
  3033. {
  3034. if (temp)
  3035. snprintf(buf, bufsz, " ");
  3036. if (maybe_unicode)
  3037. tailsprintf(buf, bufsz, " ");
  3038. }
  3039. tailsprintf(buf, bufsz, " | ");
  3040. }
  3041. void get_statline3(char *buf, size_t bufsz, struct cgpu_info *cgpu, bool for_curses, bool opt_show_procs)
  3042. {
  3043. #ifndef HAVE_CURSES
  3044. assert(for_curses == false);
  3045. #endif
  3046. struct device_drv *drv = cgpu->drv;
  3047. enum h2bs_fmt hashrate_style = for_curses ? H2B_SHORT : H2B_SPACED;
  3048. char cHr[ALLOC_H2B_NOUNIT+1], aHr[ALLOC_H2B_NOUNIT+1], uHr[max(ALLOC_H2B_SHORT, ALLOC_H2B_SPACED)+3+1];
  3049. char rejpcbuf[6];
  3050. char bnbuf[6];
  3051. double dev_runtime;
  3052. if (!opt_show_procs)
  3053. cgpu = cgpu->device;
  3054. dev_runtime = cgpu_runtime(cgpu);
  3055. double rolling, mhashes;
  3056. int accepted, rejected, stale;
  3057. double waccepted;
  3058. double wnotaccepted;
  3059. int hwerrs;
  3060. double bad_diff1, good_diff1;
  3061. rolling = mhashes = waccepted = wnotaccepted = 0;
  3062. accepted = rejected = stale = hwerrs = bad_diff1 = good_diff1 = 0;
  3063. {
  3064. struct cgpu_info *slave = cgpu;
  3065. for (int i = 0; i < cgpu->procs; ++i, (slave = slave->next_proc))
  3066. {
  3067. slave->utility = slave->accepted / dev_runtime * 60;
  3068. slave->utility_diff1 = slave->diff_accepted / dev_runtime * 60;
  3069. rolling += slave->rolling;
  3070. mhashes += slave->total_mhashes;
  3071. if (opt_weighed_stats)
  3072. {
  3073. accepted += slave->diff_accepted;
  3074. rejected += slave->diff_rejected;
  3075. stale += slave->diff_stale;
  3076. }
  3077. else
  3078. {
  3079. accepted += slave->accepted;
  3080. rejected += slave->rejected;
  3081. stale += slave->stale;
  3082. }
  3083. waccepted += slave->diff_accepted;
  3084. wnotaccepted += slave->diff_rejected + slave->diff_stale;
  3085. hwerrs += slave->hw_errors;
  3086. bad_diff1 += slave->bad_diff1;
  3087. good_diff1 += slave->diff1;
  3088. if (opt_show_procs)
  3089. break;
  3090. }
  3091. }
  3092. double wtotal = (waccepted + wnotaccepted);
  3093. multi_format_unit_array2(
  3094. ((char*[]){cHr, aHr, uHr}),
  3095. ((size_t[]){sizeof(cHr), sizeof(aHr), sizeof(uHr)}),
  3096. true, "h/s", hashrate_style,
  3097. 3,
  3098. 1e6*rolling,
  3099. 1e6*mhashes / dev_runtime,
  3100. utility_to_hashrate(good_diff1 * (wtotal ? (waccepted / wtotal) : 1) * 60 / dev_runtime));
  3101. // Processor representation
  3102. #ifdef HAVE_CURSES
  3103. if (for_curses)
  3104. {
  3105. if (opt_show_procs)
  3106. snprintf(buf, bufsz, " %"PRIprepr": ", cgpu->proc_repr);
  3107. else
  3108. snprintf(buf, bufsz, " %s: ", cgpu->dev_repr);
  3109. }
  3110. else
  3111. #endif
  3112. snprintf(buf, bufsz, "%s ", opt_show_procs ? cgpu->proc_repr_ns : cgpu->dev_repr_ns);
  3113. if (include_serial_in_statline && cgpu->dev_serial)
  3114. tailsprintf(buf, bufsz, "[serial=%s] ", cgpu->dev_serial);
  3115. if (unlikely(cgpu->status == LIFE_INIT))
  3116. {
  3117. tailsprintf(buf, bufsz, "Initializing...");
  3118. return;
  3119. }
  3120. {
  3121. const size_t bufln = strlen(buf);
  3122. const size_t abufsz = (bufln >= bufsz) ? 0 : (bufsz - bufln);
  3123. if (likely(cgpu->status != LIFE_DEAD2) && drv->override_statline_temp2 && drv->override_statline_temp2(buf, bufsz, cgpu, opt_show_procs))
  3124. temperature_column(&buf[bufln], abufsz, for_curses, NULL);
  3125. else
  3126. {
  3127. float temp = cgpu->temp;
  3128. if (!opt_show_procs)
  3129. {
  3130. // Find the highest temperature of all processors
  3131. struct cgpu_info *proc = cgpu;
  3132. for (int i = 0; i < cgpu->procs; ++i, (proc = proc->next_proc))
  3133. if (proc->temp > temp)
  3134. temp = proc->temp;
  3135. }
  3136. temperature_column(&buf[bufln], abufsz, for_curses, &temp);
  3137. }
  3138. }
  3139. #ifdef HAVE_CURSES
  3140. if (for_curses)
  3141. {
  3142. const char *cHrStatsOpt[] = {AS_BAD("DEAD "), AS_BAD("SICK "), "OFF ", AS_BAD("REST "), AS_BAD(" ERR "), AS_BAD("WAIT "), cHr};
  3143. const char *cHrStats;
  3144. int cHrStatsI = (sizeof(cHrStatsOpt) / sizeof(*cHrStatsOpt)) - 1;
  3145. bool all_dead = true, all_off = true, all_rdrv = true;
  3146. struct cgpu_info *proc = cgpu;
  3147. for (int i = 0; i < cgpu->procs; ++i, (proc = proc->next_proc))
  3148. {
  3149. switch (cHrStatsI) {
  3150. default:
  3151. if (proc->status == LIFE_WAIT)
  3152. cHrStatsI = 5;
  3153. case 5:
  3154. if (proc->deven == DEV_RECOVER_ERR)
  3155. cHrStatsI = 4;
  3156. case 4:
  3157. if (proc->deven == DEV_RECOVER)
  3158. cHrStatsI = 3;
  3159. case 3:
  3160. if (proc->status == LIFE_SICK || proc->status == LIFE_DEAD || proc->status == LIFE_DEAD2)
  3161. {
  3162. cHrStatsI = 1;
  3163. all_off = false;
  3164. }
  3165. else
  3166. {
  3167. if (likely(proc->deven == DEV_ENABLED))
  3168. all_off = false;
  3169. if (proc->deven != DEV_RECOVER_DRV)
  3170. all_rdrv = false;
  3171. }
  3172. case 1:
  3173. break;
  3174. }
  3175. if (likely(proc->status != LIFE_DEAD && proc->status != LIFE_DEAD2))
  3176. all_dead = false;
  3177. if (opt_show_procs)
  3178. break;
  3179. }
  3180. if (unlikely(all_dead))
  3181. cHrStatsI = 0;
  3182. else
  3183. if (unlikely(all_off))
  3184. cHrStatsI = 2;
  3185. cHrStats = cHrStatsOpt[cHrStatsI];
  3186. if (cHrStatsI == 2 && all_rdrv)
  3187. cHrStats = " RST ";
  3188. format_statline(buf, bufsz,
  3189. cHrStats,
  3190. aHr, uHr,
  3191. accepted, rejected, stale,
  3192. wnotaccepted, waccepted,
  3193. hwerrs,
  3194. bad_diff1, bad_diff1 + good_diff1);
  3195. }
  3196. else
  3197. #endif
  3198. {
  3199. percentf4(rejpcbuf, sizeof(rejpcbuf), wnotaccepted, waccepted);
  3200. percentf4(bnbuf, sizeof(bnbuf), bad_diff1, good_diff1);
  3201. tailsprintf(buf, bufsz, "%ds:%s avg:%s u:%s | A:%d R:%d+%d(%s) HW:%d/%s",
  3202. opt_log_interval,
  3203. cHr, aHr, uHr,
  3204. accepted,
  3205. rejected,
  3206. stale,
  3207. rejpcbuf,
  3208. hwerrs,
  3209. bnbuf
  3210. );
  3211. }
  3212. }
  3213. #define get_statline(buf, bufsz, cgpu) get_statline3(buf, bufsz, cgpu, false, opt_show_procs)
  3214. #define get_statline2(buf, bufsz, cgpu, for_curses) get_statline3(buf, bufsz, cgpu, for_curses, opt_show_procs)
  3215. static void text_print_status(int thr_id)
  3216. {
  3217. struct cgpu_info *cgpu;
  3218. char logline[256];
  3219. cgpu = get_thr_cgpu(thr_id);
  3220. if (cgpu) {
  3221. get_statline(logline, sizeof(logline), cgpu);
  3222. printf("%s\n", logline);
  3223. }
  3224. }
  3225. #ifdef HAVE_CURSES
  3226. static int attr_bad = A_BOLD;
  3227. #ifdef WIN32
  3228. #define swprintf snwprintf
  3229. #endif
  3230. static
  3231. void bfg_waddstr(WINDOW *win, const char *s)
  3232. {
  3233. const char *p = s;
  3234. int32_t w;
  3235. int wlen;
  3236. unsigned char stop_ascii = (use_unicode ? '|' : 0x80);
  3237. while (true)
  3238. {
  3239. while (likely(p[0] == '\n' || (p[0] >= 0x20 && p[0] < stop_ascii)))
  3240. {
  3241. // Printable ASCII
  3242. ++p;
  3243. }
  3244. if (p != s)
  3245. waddnstr(win, s, p - s);
  3246. w = utf8_decode(p, &wlen);
  3247. s = p += wlen;
  3248. switch(w)
  3249. {
  3250. // NOTE: U+F000-U+F7FF are reserved for font hacks
  3251. case '\0':
  3252. return;
  3253. case 0xb5: // micro symbol
  3254. w = unicode_micro;
  3255. goto default_addch;
  3256. case 0xf000: // "bad" off
  3257. wattroff(win, attr_bad);
  3258. break;
  3259. case 0xf001: // "bad" on
  3260. wattron(win, attr_bad);
  3261. break;
  3262. #ifdef USE_UNICODE
  3263. case '|':
  3264. wadd_wch(win, WACS_VLINE);
  3265. break;
  3266. #endif
  3267. case 0x2500: // BOX DRAWINGS LIGHT HORIZONTAL
  3268. case 0x2534: // BOX DRAWINGS LIGHT UP AND HORIZONTAL
  3269. if (!use_unicode)
  3270. {
  3271. waddch(win, '-');
  3272. break;
  3273. }
  3274. #ifdef USE_UNICODE
  3275. wadd_wch(win, (w == 0x2500) ? WACS_HLINE : WACS_BTEE);
  3276. break;
  3277. #endif
  3278. case 0x2022:
  3279. if (w > WCHAR_MAX || !iswprint(w))
  3280. w = '*';
  3281. default:
  3282. default_addch:
  3283. if (w > WCHAR_MAX || !(iswprint(w) || w == '\n'))
  3284. {
  3285. #if REPLACEMENT_CHAR <= WCHAR_MAX
  3286. if (iswprint(REPLACEMENT_CHAR))
  3287. w = REPLACEMENT_CHAR;
  3288. else
  3289. #endif
  3290. w = '?';
  3291. }
  3292. {
  3293. #ifdef USE_UNICODE
  3294. wchar_t wbuf[0x10];
  3295. int wbuflen = sizeof(wbuf) / sizeof(*wbuf);
  3296. wbuflen = swprintf(wbuf, wbuflen, L"%lc", (wint_t)w);
  3297. waddnwstr(win, wbuf, wbuflen);
  3298. #else
  3299. wprintw(win, "%lc", (wint_t)w);
  3300. #endif
  3301. }
  3302. }
  3303. }
  3304. }
  3305. static inline
  3306. void bfg_hline(WINDOW *win, int y)
  3307. {
  3308. int maxx, __maybe_unused maxy;
  3309. getmaxyx(win, maxy, maxx);
  3310. #ifdef USE_UNICODE
  3311. if (use_unicode)
  3312. mvwhline_set(win, y, 0, WACS_HLINE, maxx);
  3313. else
  3314. #endif
  3315. mvwhline(win, y, 0, '-', maxx);
  3316. }
  3317. // Spaces until end of line, using current attributes (ie, not completely clear)
  3318. static
  3319. void bfg_wspctoeol(WINDOW * const win, const int offset)
  3320. {
  3321. int x, maxx;
  3322. int __maybe_unused y;
  3323. getmaxyx(win, y, maxx);
  3324. getyx(win, y, x);
  3325. const int space_count = (maxx - x) - offset;
  3326. // Check for negative - terminal too narrow
  3327. if (space_count <= 0)
  3328. return;
  3329. char buf[space_count];
  3330. memset(buf, ' ', space_count);
  3331. waddnstr(win, buf, space_count);
  3332. }
  3333. static int menu_attr = A_REVERSE;
  3334. #define CURBUFSIZ 256
  3335. #define cg_mvwprintw(win, y, x, fmt, ...) do { \
  3336. char tmp42[CURBUFSIZ]; \
  3337. snprintf(tmp42, sizeof(tmp42), fmt, ##__VA_ARGS__); \
  3338. wmove(win, y, x); \
  3339. bfg_waddstr(win, tmp42); \
  3340. } while (0)
  3341. #define cg_wprintw(win, fmt, ...) do { \
  3342. char tmp42[CURBUFSIZ]; \
  3343. snprintf(tmp42, sizeof(tmp42), fmt, ##__VA_ARGS__); \
  3344. bfg_waddstr(win, tmp42); \
  3345. } while (0)
  3346. static bool pool_unworkable(const struct pool *);
  3347. /* Must be called with curses mutex lock held and curses_active */
  3348. static void curses_print_status(const int ts)
  3349. {
  3350. struct pool *pool = currentpool;
  3351. struct timeval now, tv;
  3352. float efficiency;
  3353. double income;
  3354. int logdiv;
  3355. efficiency = total_bytes_xfer ? total_diff_accepted * 2048. / total_bytes_xfer : 0.0;
  3356. wattron(statuswin, attr_title);
  3357. cg_mvwprintw(statuswin, 0, 0, " " PACKAGE " version " VERSION " - Started: %s", datestamp);
  3358. timer_set_now(&now);
  3359. {
  3360. unsigned int days, hours;
  3361. div_t d;
  3362. timersub(&now, &miner_started, &tv);
  3363. d = div(tv.tv_sec, 86400);
  3364. days = d.quot;
  3365. d = div(d.rem, 3600);
  3366. hours = d.quot;
  3367. d = div(d.rem, 60);
  3368. cg_wprintw(statuswin, " - [%3u day%c %02d:%02d:%02d]"
  3369. , days
  3370. , (days == 1) ? ' ' : 's'
  3371. , hours
  3372. , d.quot
  3373. , d.rem
  3374. );
  3375. }
  3376. bfg_wspctoeol(statuswin, 0);
  3377. wattroff(statuswin, attr_title);
  3378. wattron(statuswin, menu_attr);
  3379. wmove(statuswin, 1, 0);
  3380. bfg_waddstr(statuswin, " [M]anage devices [P]ool management [S]ettings [D]isplay options ");
  3381. bfg_wspctoeol(statuswin, 14);
  3382. bfg_waddstr(statuswin, "[H]elp [Q]uit ");
  3383. wattroff(statuswin, menu_attr);
  3384. if ((pool_strategy == POOL_LOADBALANCE || pool_strategy == POOL_BALANCE) && enabled_pools > 1) {
  3385. char poolinfo[20], poolinfo2[20];
  3386. int poolinfooff = 0, poolinfo2off, workable_pools = 0;
  3387. double lowdiff = DBL_MAX, highdiff = -1;
  3388. struct pool *lowdiff_pool = pools[0], *highdiff_pool = pools[0];
  3389. time_t oldest_work_restart = time(NULL) + 1;
  3390. struct pool *oldest_work_restart_pool = pools[0];
  3391. for (int i = 0; i < total_pools; ++i)
  3392. {
  3393. if (pool_unworkable(pools[i]))
  3394. continue;
  3395. // NOTE: Only set pool var when it's workable; if only one is, it gets used by single-pool code
  3396. pool = pools[i];
  3397. ++workable_pools;
  3398. if (poolinfooff < sizeof(poolinfo))
  3399. poolinfooff += snprintf(&poolinfo[poolinfooff], sizeof(poolinfo) - poolinfooff, "%u,", pool->pool_no);
  3400. struct cgminer_pool_stats * const pool_stats = &pool->cgminer_pool_stats;
  3401. if (pool_stats->last_diff < lowdiff)
  3402. {
  3403. lowdiff = pool_stats->last_diff;
  3404. lowdiff_pool = pool;
  3405. }
  3406. if (pool_stats->last_diff > highdiff)
  3407. {
  3408. highdiff = pool_stats->last_diff;
  3409. highdiff_pool = pool;
  3410. }
  3411. if (oldest_work_restart >= pool->work_restart_time)
  3412. {
  3413. oldest_work_restart = pool->work_restart_time;
  3414. oldest_work_restart_pool = pool;
  3415. }
  3416. }
  3417. if (workable_pools == 1)
  3418. goto one_workable_pool;
  3419. poolinfo2off = snprintf(poolinfo2, sizeof(poolinfo2), "%u (", workable_pools);
  3420. if (poolinfooff > sizeof(poolinfo2) - poolinfo2off - 1)
  3421. snprintf(&poolinfo2[poolinfo2off], sizeof(poolinfo2) - poolinfo2off, "%.*s...)", sizeof(poolinfo2) - poolinfo2off - 5, poolinfo);
  3422. else
  3423. snprintf(&poolinfo2[poolinfo2off], sizeof(poolinfo2) - poolinfo2off, "%.*s)%*s", poolinfooff - 1, poolinfo, sizeof(poolinfo2), "");
  3424. cg_mvwprintw(statuswin, 2, 0, " Pools: %s Diff:%s%s%s %c LU:%s",
  3425. poolinfo2,
  3426. lowdiff_pool->diff,
  3427. (lowdiff == highdiff) ? "" : "-",
  3428. (lowdiff == highdiff) ? "" : highdiff_pool->diff,
  3429. have_longpoll ? '+' : '-',
  3430. oldest_work_restart_pool->work_restart_timestamp);
  3431. }
  3432. else
  3433. {
  3434. one_workable_pool: ;
  3435. char pooladdr[19];
  3436. {
  3437. const char *rawaddr = pool->sockaddr_url;
  3438. BFGINIT(rawaddr, pool->rpc_url);
  3439. size_t pooladdrlen = strlen(rawaddr);
  3440. if (pooladdrlen > 20)
  3441. snprintf(pooladdr, sizeof(pooladdr), "...%s", &rawaddr[pooladdrlen - (sizeof(pooladdr) - 4)]);
  3442. else
  3443. snprintf(pooladdr, sizeof(pooladdr), "%*s", -(sizeof(pooladdr) - 1), rawaddr);
  3444. }
  3445. cg_mvwprintw(statuswin, 2, 0, " Pool%2u: %s Diff:%s %c%s LU:%s User:%s",
  3446. pool->pool_no, pooladdr, pool->diff,
  3447. have_longpoll ? '+' : '-', pool_proto_str(pool),
  3448. pool->work_restart_timestamp,
  3449. pool->rpc_user);
  3450. }
  3451. wclrtoeol(statuswin);
  3452. cg_mvwprintw(statuswin, 3, 0, " Block: %s Diff:%s (%s) Started: %s",
  3453. current_hash, block_diff, net_hashrate, blocktime);
  3454. income = total_diff_accepted * 3600 * block_subsidy / total_secs / current_diff;
  3455. char bwstr[(ALLOC_H2B_SHORT*2)+3+1], incomestr[ALLOC_H2B_SHORT+6+1];
  3456. format_unit3(incomestr, sizeof(incomestr), FUP_BTC, "BTC/hr", H2B_SHORT, income/1e8, -1);
  3457. cg_mvwprintw(statuswin, 4, 0, " ST:%d F:%d NB:%d AS:%d BW:[%s] E:%.2f I:%s BS:%s",
  3458. ts,
  3459. total_go + total_ro,
  3460. new_blocks,
  3461. total_submitting,
  3462. multi_format_unit2(bwstr, sizeof(bwstr),
  3463. false, "B/s", H2B_SHORT, "/", 2,
  3464. (float)(total_bytes_rcvd / total_secs),
  3465. (float)(total_bytes_sent / total_secs)),
  3466. efficiency,
  3467. incomestr,
  3468. best_share);
  3469. wclrtoeol(statuswin);
  3470. mvwaddstr(statuswin, 5, 0, " ");
  3471. bfg_waddstr(statuswin, statusline);
  3472. wclrtoeol(statuswin);
  3473. logdiv = statusy - 1;
  3474. bfg_hline(statuswin, 6);
  3475. bfg_hline(statuswin, logdiv);
  3476. #ifdef USE_UNICODE
  3477. if (use_unicode)
  3478. {
  3479. int offset = 8 /* device */ + 5 /* temperature */ + 1 /* padding space */;
  3480. if (opt_show_procs && !opt_compact)
  3481. ++offset; // proc letter
  3482. if (have_unicode_degrees)
  3483. ++offset; // degrees symbol
  3484. mvwadd_wch(statuswin, 6, offset, WACS_PLUS);
  3485. mvwadd_wch(statuswin, logdiv, offset, WACS_BTEE);
  3486. offset += 24; // hashrates etc
  3487. mvwadd_wch(statuswin, 6, offset, WACS_PLUS);
  3488. mvwadd_wch(statuswin, logdiv, offset, WACS_BTEE);
  3489. }
  3490. #endif
  3491. }
  3492. static void adj_width(int var, int *length)
  3493. {
  3494. if ((int)(log10(var) + 1) > *length)
  3495. (*length)++;
  3496. }
  3497. static int dev_width;
  3498. static void curses_print_devstatus(struct cgpu_info *cgpu)
  3499. {
  3500. char logline[256];
  3501. int ypos;
  3502. if (opt_compact)
  3503. return;
  3504. /* Check this isn't out of the window size */
  3505. if (opt_show_procs)
  3506. ypos = cgpu->cgminer_id;
  3507. else
  3508. {
  3509. if (cgpu->proc_id)
  3510. return;
  3511. ypos = cgpu->device_line_id;
  3512. }
  3513. ypos += devsummaryYOffset;
  3514. if (ypos < 0)
  3515. return;
  3516. ypos += devcursor - 1;
  3517. if (ypos >= statusy - 1)
  3518. return;
  3519. if (wmove(statuswin, ypos, 0) == ERR)
  3520. return;
  3521. get_statline2(logline, sizeof(logline), cgpu, true);
  3522. if (selecting_device && (opt_show_procs ? (selected_device == cgpu->cgminer_id) : (devices[selected_device]->device == cgpu)))
  3523. wattron(statuswin, A_REVERSE);
  3524. bfg_waddstr(statuswin, logline);
  3525. wattroff(statuswin, A_REVERSE);
  3526. wclrtoeol(statuswin);
  3527. }
  3528. static
  3529. void _refresh_devstatus(const bool already_have_lock) {
  3530. if ((!opt_compact) && (already_have_lock || curses_active_locked())) {
  3531. int i;
  3532. if (unlikely(!total_devices))
  3533. {
  3534. const int ypos = devcursor - 1;
  3535. if (ypos < statusy - 1 && wmove(statuswin, ypos, 0) != ERR)
  3536. {
  3537. wattron(statuswin, attr_bad);
  3538. bfg_waddstr(statuswin, "NO DEVICES FOUND: Press 'M' and '+' to add");
  3539. wclrtoeol(statuswin);
  3540. wattroff(statuswin, attr_bad);
  3541. }
  3542. }
  3543. for (i = 0; i < total_devices; i++)
  3544. curses_print_devstatus(get_devices(i));
  3545. touchwin(statuswin);
  3546. wrefresh(statuswin);
  3547. if (!already_have_lock)
  3548. unlock_curses();
  3549. }
  3550. }
  3551. #define refresh_devstatus() _refresh_devstatus(false)
  3552. #endif
  3553. static void print_status(int thr_id)
  3554. {
  3555. if (!curses_active)
  3556. text_print_status(thr_id);
  3557. }
  3558. #ifdef HAVE_CURSES
  3559. static
  3560. bool set_statusy(int maxy)
  3561. {
  3562. if (loginput_size)
  3563. {
  3564. maxy -= loginput_size;
  3565. if (maxy < 0)
  3566. maxy = 0;
  3567. }
  3568. if (logstart < maxy)
  3569. maxy = logstart;
  3570. if (statusy == maxy)
  3571. return false;
  3572. statusy = maxy;
  3573. logcursor = statusy;
  3574. return true;
  3575. }
  3576. /* Check for window resize. Called with curses mutex locked */
  3577. static inline void change_logwinsize(void)
  3578. {
  3579. int x, y, logx, logy;
  3580. getmaxyx(mainwin, y, x);
  3581. if (x < 80 || y < 25)
  3582. return;
  3583. if (y > statusy + 2 && statusy < logstart) {
  3584. set_statusy(y - 2);
  3585. mvwin(logwin, logcursor, 0);
  3586. bfg_wresize(statuswin, statusy, x);
  3587. }
  3588. y -= logcursor;
  3589. getmaxyx(logwin, logy, logx);
  3590. /* Detect screen size change */
  3591. if (x != logx || y != logy)
  3592. bfg_wresize(logwin, y, x);
  3593. }
  3594. static void check_winsizes(void)
  3595. {
  3596. if (!use_curses)
  3597. return;
  3598. if (curses_active_locked()) {
  3599. int y, x;
  3600. x = getmaxx(statuswin);
  3601. if (set_statusy(LINES - 2))
  3602. {
  3603. erase();
  3604. bfg_wresize(statuswin, statusy, x);
  3605. getmaxyx(mainwin, y, x);
  3606. y -= logcursor;
  3607. bfg_wresize(logwin, y, x);
  3608. mvwin(logwin, logcursor, 0);
  3609. }
  3610. unlock_curses();
  3611. }
  3612. }
  3613. static int device_line_id_count;
  3614. static void switch_logsize(void)
  3615. {
  3616. if (curses_active_locked()) {
  3617. if (opt_compact) {
  3618. logstart = devcursor - 1;
  3619. logcursor = logstart + 1;
  3620. } else {
  3621. total_lines = (opt_show_procs ? total_devices : device_line_id_count) ?: 1;
  3622. logstart = devcursor + total_lines;
  3623. logcursor = logstart;
  3624. }
  3625. unlock_curses();
  3626. }
  3627. check_winsizes();
  3628. }
  3629. /* For mandatory printing when mutex is already locked */
  3630. void _wlog(const char *str)
  3631. {
  3632. static bool newline;
  3633. size_t end = strlen(str) - 1;
  3634. if (newline)
  3635. bfg_waddstr(logwin, "\n");
  3636. if (str[end] == '\n')
  3637. {
  3638. char *s;
  3639. newline = true;
  3640. s = alloca(end + 1);
  3641. memcpy(s, str, end);
  3642. s[end] = '\0';
  3643. str = s;
  3644. }
  3645. else
  3646. newline = false;
  3647. bfg_waddstr(logwin, str);
  3648. }
  3649. /* Mandatory printing */
  3650. void _wlogprint(const char *str)
  3651. {
  3652. if (curses_active_locked()) {
  3653. _wlog(str);
  3654. unlock_curses();
  3655. }
  3656. }
  3657. #endif
  3658. #ifdef HAVE_CURSES
  3659. bool _log_curses_only(int prio, const char *datetime, const char *str)
  3660. {
  3661. bool high_prio;
  3662. high_prio = (prio == LOG_WARNING || prio == LOG_ERR);
  3663. if (curses_active)
  3664. {
  3665. if (!loginput_size || high_prio) {
  3666. wlog(" %s %s\n", datetime, str);
  3667. if (high_prio) {
  3668. touchwin(logwin);
  3669. wrefresh(logwin);
  3670. }
  3671. }
  3672. return true;
  3673. }
  3674. return false;
  3675. }
  3676. void clear_logwin(void)
  3677. {
  3678. if (curses_active_locked()) {
  3679. wclear(logwin);
  3680. unlock_curses();
  3681. }
  3682. }
  3683. void logwin_update(void)
  3684. {
  3685. if (curses_active_locked()) {
  3686. touchwin(logwin);
  3687. wrefresh(logwin);
  3688. unlock_curses();
  3689. }
  3690. }
  3691. #endif
  3692. static void enable_pool(struct pool *pool)
  3693. {
  3694. if (pool->enabled != POOL_ENABLED) {
  3695. enabled_pools++;
  3696. pool->enabled = POOL_ENABLED;
  3697. }
  3698. }
  3699. #ifdef HAVE_CURSES
  3700. static void disable_pool(struct pool *pool)
  3701. {
  3702. if (pool->enabled == POOL_ENABLED)
  3703. enabled_pools--;
  3704. pool->enabled = POOL_DISABLED;
  3705. }
  3706. #endif
  3707. static void reject_pool(struct pool *pool)
  3708. {
  3709. if (pool->enabled == POOL_ENABLED)
  3710. enabled_pools--;
  3711. pool->enabled = POOL_REJECTING;
  3712. }
  3713. static double share_diff(const struct work *);
  3714. static
  3715. void share_result_msg(const struct work *work, const char *disp, const char *reason, bool resubmit, const char *worktime) {
  3716. struct cgpu_info *cgpu;
  3717. const unsigned char *hashpart = &work->hash[opt_scrypt ? 26 : 24];
  3718. char shrdiffdisp[ALLOC_H2B_SHORTV];
  3719. const double tgtdiff = work->work_difficulty;
  3720. char tgtdiffdisp[ALLOC_H2B_SHORTV];
  3721. char where[20];
  3722. cgpu = get_thr_cgpu(work->thr_id);
  3723. suffix_string(work->share_diff, shrdiffdisp, sizeof(shrdiffdisp), 0);
  3724. suffix_string(tgtdiff, tgtdiffdisp, sizeof(tgtdiffdisp), 0);
  3725. if (total_pools > 1)
  3726. snprintf(where, sizeof(where), " pool %d", work->pool->pool_no);
  3727. else
  3728. where[0] = '\0';
  3729. applog(LOG_NOTICE, "%s %02x%02x%02x%02x %"PRIprepr"%s Diff %s/%s%s %s%s",
  3730. disp,
  3731. (unsigned)hashpart[3], (unsigned)hashpart[2], (unsigned)hashpart[1], (unsigned)hashpart[0],
  3732. cgpu->proc_repr,
  3733. where,
  3734. shrdiffdisp, tgtdiffdisp,
  3735. reason,
  3736. resubmit ? "(resubmit)" : "",
  3737. worktime
  3738. );
  3739. }
  3740. static bool test_work_current(struct work *);
  3741. static void _submit_work_async(struct work *);
  3742. static
  3743. void maybe_local_submit(const struct work *work)
  3744. {
  3745. #if BLKMAKER_VERSION > 3
  3746. if (unlikely(work->block && work->tmpl))
  3747. {
  3748. // This is a block with a full template (GBT)
  3749. // Regardless of the result, submit to local bitcoind(s) as well
  3750. struct work *work_cp;
  3751. char *p;
  3752. for (int i = 0; i < total_pools; ++i)
  3753. {
  3754. p = strchr(pools[i]->rpc_url, '#');
  3755. if (likely(!(p && strstr(&p[1], "allblocks"))))
  3756. continue;
  3757. applog(LOG_DEBUG, "Attempting submission of full block to pool %d", pools[i]->pool_no);
  3758. work_cp = copy_work(work);
  3759. work_cp->pool = pools[i];
  3760. work_cp->do_foreign_submit = true;
  3761. _submit_work_async(work_cp);
  3762. }
  3763. }
  3764. #endif
  3765. }
  3766. /* Theoretically threads could race when modifying accepted and
  3767. * rejected values but the chance of two submits completing at the
  3768. * same time is zero so there is no point adding extra locking */
  3769. static void
  3770. share_result(json_t *val, json_t *res, json_t *err, const struct work *work,
  3771. /*char *hashshow,*/ bool resubmit, char *worktime)
  3772. {
  3773. struct pool *pool = work->pool;
  3774. struct cgpu_info *cgpu;
  3775. cgpu = get_thr_cgpu(work->thr_id);
  3776. if ((json_is_null(err) || !err) && (json_is_null(res) || json_is_true(res))) {
  3777. mutex_lock(&stats_lock);
  3778. cgpu->accepted++;
  3779. total_accepted++;
  3780. pool->accepted++;
  3781. cgpu->diff_accepted += work->work_difficulty;
  3782. total_diff_accepted += work->work_difficulty;
  3783. pool->diff_accepted += work->work_difficulty;
  3784. mutex_unlock(&stats_lock);
  3785. pool->seq_rejects = 0;
  3786. cgpu->last_share_pool = pool->pool_no;
  3787. cgpu->last_share_pool_time = time(NULL);
  3788. cgpu->last_share_diff = work->work_difficulty;
  3789. pool->last_share_time = cgpu->last_share_pool_time;
  3790. pool->last_share_diff = work->work_difficulty;
  3791. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  3792. if (!QUIET) {
  3793. share_result_msg(work, "Accepted", "", resubmit, worktime);
  3794. }
  3795. sharelog("accept", work);
  3796. if (opt_shares && total_diff_accepted >= opt_shares) {
  3797. applog(LOG_WARNING, "Successfully mined %g accepted shares as requested and exiting.", opt_shares);
  3798. kill_work();
  3799. return;
  3800. }
  3801. /* Detect if a pool that has been temporarily disabled for
  3802. * continually rejecting shares has started accepting shares.
  3803. * This will only happen with the work returned from a
  3804. * longpoll */
  3805. if (unlikely(pool->enabled == POOL_REJECTING)) {
  3806. applog(LOG_WARNING, "Rejecting pool %d now accepting shares, re-enabling!", pool->pool_no);
  3807. enable_pool(pool);
  3808. switch_pools(NULL);
  3809. }
  3810. if (unlikely(work->block)) {
  3811. // Force moving on to this new block :)
  3812. struct work fakework;
  3813. memset(&fakework, 0, sizeof(fakework));
  3814. fakework.pool = work->pool;
  3815. // Copy block version, bits, and time from share
  3816. memcpy(&fakework.data[ 0], &work->data[ 0], 4);
  3817. memcpy(&fakework.data[68], &work->data[68], 8);
  3818. // Set prevblock to winning hash (swap32'd)
  3819. swap32yes(&fakework.data[4], &work->hash[0], 32 / 4);
  3820. test_work_current(&fakework);
  3821. }
  3822. } else {
  3823. mutex_lock(&stats_lock);
  3824. cgpu->rejected++;
  3825. total_rejected++;
  3826. pool->rejected++;
  3827. cgpu->diff_rejected += work->work_difficulty;
  3828. total_diff_rejected += work->work_difficulty;
  3829. pool->diff_rejected += work->work_difficulty;
  3830. pool->seq_rejects++;
  3831. mutex_unlock(&stats_lock);
  3832. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  3833. if (!QUIET) {
  3834. char where[20];
  3835. char disposition[36] = "reject";
  3836. char reason[32];
  3837. strcpy(reason, "");
  3838. if (total_pools > 1)
  3839. snprintf(where, sizeof(where), "pool %d", work->pool->pool_no);
  3840. else
  3841. strcpy(where, "");
  3842. if (!json_is_string(res))
  3843. res = json_object_get(val, "reject-reason");
  3844. if (res) {
  3845. const char *reasontmp = json_string_value(res);
  3846. size_t reasonLen = strlen(reasontmp);
  3847. if (reasonLen > 28)
  3848. reasonLen = 28;
  3849. reason[0] = ' '; reason[1] = '(';
  3850. memcpy(2 + reason, reasontmp, reasonLen);
  3851. reason[reasonLen + 2] = ')'; reason[reasonLen + 3] = '\0';
  3852. memcpy(disposition + 7, reasontmp, reasonLen);
  3853. disposition[6] = ':'; disposition[reasonLen + 7] = '\0';
  3854. } else if (work->stratum && err && json_is_array(err)) {
  3855. json_t *reason_val = json_array_get(err, 1);
  3856. char *reason_str;
  3857. if (reason_val && json_is_string(reason_val)) {
  3858. reason_str = (char *)json_string_value(reason_val);
  3859. snprintf(reason, 31, " (%s)", reason_str);
  3860. }
  3861. }
  3862. share_result_msg(work, "Rejected", reason, resubmit, worktime);
  3863. sharelog(disposition, work);
  3864. }
  3865. /* Once we have more than a nominal amount of sequential rejects,
  3866. * at least 10 and more than 3 mins at the current utility,
  3867. * disable the pool because some pool error is likely to have
  3868. * ensued. Do not do this if we know the share just happened to
  3869. * be stale due to networking delays.
  3870. */
  3871. if (pool->seq_rejects > 10 && !work->stale && opt_disable_pool && enabled_pools > 1) {
  3872. double utility = total_accepted / total_secs * 60;
  3873. if (pool->seq_rejects > utility * 3) {
  3874. applog(LOG_WARNING, "Pool %d rejected %d sequential shares, disabling!",
  3875. pool->pool_no, pool->seq_rejects);
  3876. reject_pool(pool);
  3877. if (pool == current_pool())
  3878. switch_pools(NULL);
  3879. pool->seq_rejects = 0;
  3880. }
  3881. }
  3882. }
  3883. maybe_local_submit(work);
  3884. }
  3885. static char *submit_upstream_work_request(struct work *work)
  3886. {
  3887. char *hexstr = NULL;
  3888. char *s, *sd;
  3889. struct pool *pool = work->pool;
  3890. if (work->tmpl) {
  3891. json_t *req;
  3892. unsigned char data[80];
  3893. swap32yes(data, work->data, 80 / 4);
  3894. #if BLKMAKER_VERSION > 3
  3895. if (work->do_foreign_submit)
  3896. req = blkmk_submit_foreign_jansson(work->tmpl, data, work->dataid, le32toh(*((uint32_t*)&work->data[76])));
  3897. else
  3898. #endif
  3899. req = blkmk_submit_jansson(work->tmpl, data, work->dataid, le32toh(*((uint32_t*)&work->data[76])));
  3900. s = json_dumps(req, 0);
  3901. json_decref(req);
  3902. sd = malloc(161);
  3903. bin2hex(sd, data, 80);
  3904. } else {
  3905. /* build hex string */
  3906. hexstr = malloc((sizeof(work->data) * 2) + 1);
  3907. bin2hex(hexstr, work->data, sizeof(work->data));
  3908. /* build JSON-RPC request */
  3909. s = strdup("{\"method\": \"getwork\", \"params\": [ \"");
  3910. s = realloc_strcat(s, hexstr);
  3911. s = realloc_strcat(s, "\" ], \"id\":1}");
  3912. free(hexstr);
  3913. sd = s;
  3914. }
  3915. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->rpc_url, sd);
  3916. if (work->tmpl)
  3917. free(sd);
  3918. else
  3919. s = realloc_strcat(s, "\n");
  3920. return s;
  3921. }
  3922. static bool submit_upstream_work_completed(struct work *work, bool resubmit, struct timeval *ptv_submit, json_t *val) {
  3923. json_t *res, *err;
  3924. bool rc = false;
  3925. int thr_id = work->thr_id;
  3926. struct pool *pool = work->pool;
  3927. struct timeval tv_submit_reply;
  3928. time_t ts_submit_reply;
  3929. char worktime[200] = "";
  3930. cgtime(&tv_submit_reply);
  3931. ts_submit_reply = time(NULL);
  3932. if (unlikely(!val)) {
  3933. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  3934. if (!pool_tset(pool, &pool->submit_fail)) {
  3935. total_ro++;
  3936. pool->remotefail_occasions++;
  3937. applog(LOG_WARNING, "Pool %d communication failure, caching submissions", pool->pool_no);
  3938. }
  3939. goto out;
  3940. } else if (pool_tclear(pool, &pool->submit_fail))
  3941. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  3942. res = json_object_get(val, "result");
  3943. err = json_object_get(val, "error");
  3944. if (!QUIET) {
  3945. if (opt_worktime) {
  3946. char workclone[20];
  3947. struct tm _tm;
  3948. struct tm *tm, tm_getwork, tm_submit_reply;
  3949. tm = &_tm;
  3950. double getwork_time = tdiff((struct timeval *)&(work->tv_getwork_reply),
  3951. (struct timeval *)&(work->tv_getwork));
  3952. double getwork_to_work = tdiff((struct timeval *)&(work->tv_work_start),
  3953. (struct timeval *)&(work->tv_getwork_reply));
  3954. double work_time = tdiff((struct timeval *)&(work->tv_work_found),
  3955. (struct timeval *)&(work->tv_work_start));
  3956. double work_to_submit = tdiff(ptv_submit,
  3957. (struct timeval *)&(work->tv_work_found));
  3958. double submit_time = tdiff(&tv_submit_reply, ptv_submit);
  3959. int diffplaces = 3;
  3960. localtime_r(&work->ts_getwork, tm);
  3961. memcpy(&tm_getwork, tm, sizeof(struct tm));
  3962. localtime_r(&ts_submit_reply, tm);
  3963. memcpy(&tm_submit_reply, tm, sizeof(struct tm));
  3964. if (work->clone) {
  3965. snprintf(workclone, sizeof(workclone), "C:%1.3f",
  3966. tdiff((struct timeval *)&(work->tv_cloned),
  3967. (struct timeval *)&(work->tv_getwork_reply)));
  3968. }
  3969. else
  3970. strcpy(workclone, "O");
  3971. if (work->work_difficulty < 1)
  3972. diffplaces = 6;
  3973. snprintf(worktime, sizeof(worktime),
  3974. " <-%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",
  3975. (unsigned long)be32toh(*(uint32_t *)&(work->data[opt_scrypt ? 32 : 28])),
  3976. (unsigned long)be32toh(*(uint32_t *)&(work->data[opt_scrypt ? 28 : 24])),
  3977. work->getwork_mode, diffplaces, work->work_difficulty,
  3978. tm_getwork.tm_hour, tm_getwork.tm_min,
  3979. tm_getwork.tm_sec, getwork_time, workclone,
  3980. getwork_to_work, work_time, work_to_submit, submit_time,
  3981. tm_submit_reply.tm_hour, tm_submit_reply.tm_min,
  3982. tm_submit_reply.tm_sec);
  3983. }
  3984. }
  3985. share_result(val, res, err, work, resubmit, worktime);
  3986. if (!opt_realquiet)
  3987. print_status(thr_id);
  3988. if (!want_per_device_stats) {
  3989. char logline[256];
  3990. struct cgpu_info *cgpu;
  3991. cgpu = get_thr_cgpu(thr_id);
  3992. get_statline(logline, sizeof(logline), cgpu);
  3993. applog(LOG_INFO, "%s", logline);
  3994. }
  3995. json_decref(val);
  3996. rc = true;
  3997. out:
  3998. return rc;
  3999. }
  4000. /* Specifies whether we can use this pool for work or not. */
  4001. static bool pool_unworkable(const struct pool * const pool)
  4002. {
  4003. if (pool->idle)
  4004. return true;
  4005. if (pool->enabled != POOL_ENABLED)
  4006. return true;
  4007. if (pool->has_stratum && !pool->stratum_active)
  4008. return true;
  4009. return false;
  4010. }
  4011. static
  4012. bool pool_actively_desired(const struct pool * const pool, const struct pool *cp)
  4013. {
  4014. if (pool->enabled != POOL_ENABLED)
  4015. return false;
  4016. if (pool_strategy == POOL_LOADBALANCE || pool_strategy == POOL_BALANCE)
  4017. return true;
  4018. if (!cp)
  4019. cp = current_pool();
  4020. return (pool == cp);
  4021. }
  4022. static
  4023. bool pool_actively_in_use(const struct pool * const pool, const struct pool *cp)
  4024. {
  4025. return (!pool_unworkable(pool)) && pool_actively_desired(pool, cp);
  4026. }
  4027. /* In balanced mode, the amount of diff1 solutions per pool is monitored as a
  4028. * rolling average per 10 minutes and if pools start getting more, it biases
  4029. * away from them to distribute work evenly. The share count is reset to the
  4030. * rolling average every 10 minutes to not send all work to one pool after it
  4031. * has been disabled/out for an extended period. */
  4032. static struct pool *select_balanced(struct pool *cp)
  4033. {
  4034. int i, lowest = cp->shares;
  4035. struct pool *ret = cp;
  4036. for (i = 0; i < total_pools; i++) {
  4037. struct pool *pool = pools[i];
  4038. if (pool_unworkable(pool))
  4039. continue;
  4040. if (pool->shares < lowest) {
  4041. lowest = pool->shares;
  4042. ret = pool;
  4043. }
  4044. }
  4045. ret->shares++;
  4046. return ret;
  4047. }
  4048. static bool pool_active(struct pool *, bool pinging);
  4049. static void pool_died(struct pool *);
  4050. static struct pool *priority_pool(int choice);
  4051. static bool pool_unusable(struct pool *pool);
  4052. /* Select any active pool in a rotating fashion when loadbalance is chosen if
  4053. * it has any quota left. */
  4054. static inline struct pool *select_pool(bool lagging)
  4055. {
  4056. static int rotating_pool = 0;
  4057. struct pool *pool, *cp;
  4058. bool avail = false;
  4059. int tested, i;
  4060. cp = current_pool();
  4061. retry:
  4062. if (pool_strategy == POOL_BALANCE) {
  4063. pool = select_balanced(cp);
  4064. goto out;
  4065. }
  4066. if (pool_strategy != POOL_LOADBALANCE && (!lagging || opt_fail_only)) {
  4067. pool = cp;
  4068. goto out;
  4069. } else
  4070. pool = NULL;
  4071. for (i = 0; i < total_pools; i++) {
  4072. struct pool *tp = pools[i];
  4073. if (tp->quota_used < tp->quota_gcd) {
  4074. avail = true;
  4075. break;
  4076. }
  4077. }
  4078. /* There are no pools with quota, so reset them. */
  4079. if (!avail) {
  4080. for (i = 0; i < total_pools; i++)
  4081. pools[i]->quota_used = 0;
  4082. if (++rotating_pool >= total_pools)
  4083. rotating_pool = 0;
  4084. }
  4085. /* Try to find the first pool in the rotation that is usable */
  4086. tested = 0;
  4087. while (!pool && tested++ < total_pools) {
  4088. pool = pools[rotating_pool];
  4089. if (pool->quota_used++ < pool->quota_gcd) {
  4090. if (!pool_unworkable(pool))
  4091. break;
  4092. /* Failover-only flag for load-balance means distribute
  4093. * unused quota to priority pool 0. */
  4094. if (opt_fail_only)
  4095. priority_pool(0)->quota_used--;
  4096. }
  4097. pool = NULL;
  4098. if (++rotating_pool >= total_pools)
  4099. rotating_pool = 0;
  4100. }
  4101. /* If there are no alive pools with quota, choose according to
  4102. * priority. */
  4103. if (!pool) {
  4104. for (i = 0; i < total_pools; i++) {
  4105. struct pool *tp = priority_pool(i);
  4106. if (!pool_unusable(tp)) {
  4107. pool = tp;
  4108. break;
  4109. }
  4110. }
  4111. }
  4112. /* If still nothing is usable, use the current pool */
  4113. if (!pool)
  4114. pool = cp;
  4115. out:
  4116. if (!pool_actively_in_use(pool, cp))
  4117. {
  4118. if (!pool_active(pool, false))
  4119. {
  4120. pool_died(pool);
  4121. goto retry;
  4122. }
  4123. pool_tclear(pool, &pool->idle);
  4124. }
  4125. applog(LOG_DEBUG, "Selecting pool %d for work", pool->pool_no);
  4126. return pool;
  4127. }
  4128. static double DIFFEXACTONE = 26959946667150639794667015087019630673637144422540572481103610249215.0;
  4129. static const uint64_t diffone = 0xFFFF000000000000ull;
  4130. static double target_diff(const unsigned char *target)
  4131. {
  4132. double targ = 0;
  4133. signed int i;
  4134. for (i = 31; i >= 0; --i)
  4135. targ = (targ * 0x100) + target[i];
  4136. return DIFFEXACTONE / (targ ?: 1);
  4137. }
  4138. /*
  4139. * Calculate the work share difficulty
  4140. */
  4141. static void calc_diff(struct work *work, int known)
  4142. {
  4143. struct cgminer_pool_stats *pool_stats = &(work->pool->cgminer_pool_stats);
  4144. double difficulty;
  4145. if (!known) {
  4146. work->work_difficulty = target_diff(work->target);
  4147. } else
  4148. work->work_difficulty = known;
  4149. difficulty = work->work_difficulty;
  4150. pool_stats->last_diff = difficulty;
  4151. suffix_string(difficulty, work->pool->diff, sizeof(work->pool->diff), 0);
  4152. if (difficulty == pool_stats->min_diff)
  4153. pool_stats->min_diff_count++;
  4154. else if (difficulty < pool_stats->min_diff || pool_stats->min_diff == 0) {
  4155. pool_stats->min_diff = difficulty;
  4156. pool_stats->min_diff_count = 1;
  4157. }
  4158. if (difficulty == pool_stats->max_diff)
  4159. pool_stats->max_diff_count++;
  4160. else if (difficulty > pool_stats->max_diff) {
  4161. pool_stats->max_diff = difficulty;
  4162. pool_stats->max_diff_count = 1;
  4163. }
  4164. }
  4165. static
  4166. void setup_benchmark_pool()
  4167. {
  4168. struct pool *pool;
  4169. want_longpoll = false;
  4170. // Temporarily disable opt_benchmark to avoid auto-removal
  4171. opt_benchmark = false;
  4172. pool = add_pool();
  4173. opt_benchmark = true;
  4174. pool->rpc_url = malloc(255);
  4175. strcpy(pool->rpc_url, "Benchmark");
  4176. pool->rpc_user = pool->rpc_url;
  4177. pool->rpc_pass = pool->rpc_url;
  4178. enable_pool(pool);
  4179. pool->idle = false;
  4180. successful_connect = true;
  4181. }
  4182. void get_benchmark_work(struct work *work)
  4183. {
  4184. static uint32_t blkhdr[20];
  4185. for (int i = 18; i >= 0; --i)
  4186. if (++blkhdr[i])
  4187. break;
  4188. memcpy(&work->data[ 0], blkhdr, 80);
  4189. memcpy(&work->data[80], workpadding_bin, 48);
  4190. calc_midstate(work);
  4191. set_target(work->target, 1.0);
  4192. work->mandatory = true;
  4193. work->pool = pools[0];
  4194. cgtime(&work->tv_getwork);
  4195. copy_time(&work->tv_getwork_reply, &work->tv_getwork);
  4196. copy_time(&work->tv_staged, &work->tv_getwork);
  4197. work->getwork_mode = GETWORK_MODE_BENCHMARK;
  4198. calc_diff(work, 0);
  4199. }
  4200. static void wake_gws(void);
  4201. static void update_last_work(struct work *work)
  4202. {
  4203. if (!work->tmpl)
  4204. // Only save GBT jobs, since rollntime isn't coordinated well yet
  4205. return;
  4206. struct pool *pool = work->pool;
  4207. mutex_lock(&pool->last_work_lock);
  4208. if (pool->last_work_copy)
  4209. free_work(pool->last_work_copy);
  4210. pool->last_work_copy = copy_work(work);
  4211. pool->last_work_copy->work_restart_id = pool->work_restart_id;
  4212. mutex_unlock(&pool->last_work_lock);
  4213. }
  4214. static
  4215. void gbt_req_target(json_t *req)
  4216. {
  4217. json_t *j;
  4218. json_t *n;
  4219. if (!request_target_str)
  4220. return;
  4221. j = json_object_get(req, "params");
  4222. if (!j)
  4223. {
  4224. n = json_array();
  4225. if (!n)
  4226. return;
  4227. if (json_object_set_new(req, "params", n))
  4228. goto erradd;
  4229. j = n;
  4230. }
  4231. n = json_array_get(j, 0);
  4232. if (!n)
  4233. {
  4234. n = json_object();
  4235. if (!n)
  4236. return;
  4237. if (json_array_append_new(j, n))
  4238. goto erradd;
  4239. }
  4240. j = n;
  4241. n = json_string(request_target_str);
  4242. if (!n)
  4243. return;
  4244. if (json_object_set_new(j, "target", n))
  4245. goto erradd;
  4246. return;
  4247. erradd:
  4248. json_decref(n);
  4249. }
  4250. static char *prepare_rpc_req2(struct work *work, enum pool_protocol proto, const char *lpid, bool probe)
  4251. {
  4252. char *rpc_req;
  4253. clean_work(work);
  4254. switch (proto) {
  4255. case PLP_GETWORK:
  4256. work->getwork_mode = GETWORK_MODE_POOL;
  4257. return strdup(getwork_req);
  4258. case PLP_GETBLOCKTEMPLATE:
  4259. work->getwork_mode = GETWORK_MODE_GBT;
  4260. work->tmpl_refcount = malloc(sizeof(*work->tmpl_refcount));
  4261. if (!work->tmpl_refcount)
  4262. return NULL;
  4263. work->tmpl = blktmpl_create();
  4264. if (!work->tmpl)
  4265. goto gbtfail2;
  4266. *work->tmpl_refcount = 1;
  4267. gbt_capabilities_t caps = blktmpl_addcaps(work->tmpl);
  4268. if (!caps)
  4269. goto gbtfail;
  4270. caps |= GBT_LONGPOLL;
  4271. #if BLKMAKER_VERSION > 1
  4272. if (opt_coinbase_script.sz)
  4273. caps |= GBT_CBVALUE;
  4274. #endif
  4275. json_t *req = blktmpl_request_jansson(caps, lpid);
  4276. if (!req)
  4277. goto gbtfail;
  4278. if (probe)
  4279. gbt_req_target(req);
  4280. rpc_req = json_dumps(req, 0);
  4281. if (!rpc_req)
  4282. goto gbtfail;
  4283. json_decref(req);
  4284. return rpc_req;
  4285. default:
  4286. return NULL;
  4287. }
  4288. return NULL;
  4289. gbtfail:
  4290. blktmpl_free(work->tmpl);
  4291. work->tmpl = NULL;
  4292. gbtfail2:
  4293. free(work->tmpl_refcount);
  4294. work->tmpl_refcount = NULL;
  4295. return NULL;
  4296. }
  4297. #define prepare_rpc_req(work, proto, lpid) prepare_rpc_req2(work, proto, lpid, false)
  4298. #define prepare_rpc_req_probe(work, proto, lpid) prepare_rpc_req2(work, proto, lpid, true)
  4299. static const char *pool_protocol_name(enum pool_protocol proto)
  4300. {
  4301. switch (proto) {
  4302. case PLP_GETBLOCKTEMPLATE:
  4303. return "getblocktemplate";
  4304. case PLP_GETWORK:
  4305. return "getwork";
  4306. default:
  4307. return "UNKNOWN";
  4308. }
  4309. }
  4310. static enum pool_protocol pool_protocol_fallback(enum pool_protocol proto)
  4311. {
  4312. switch (proto) {
  4313. case PLP_GETBLOCKTEMPLATE:
  4314. if (want_getwork)
  4315. return PLP_GETWORK;
  4316. default:
  4317. return PLP_NONE;
  4318. }
  4319. }
  4320. static bool get_upstream_work(struct work *work, CURL *curl)
  4321. {
  4322. struct pool *pool = work->pool;
  4323. struct cgminer_pool_stats *pool_stats = &(pool->cgminer_pool_stats);
  4324. struct timeval tv_elapsed;
  4325. json_t *val = NULL;
  4326. bool rc = false;
  4327. char *url;
  4328. enum pool_protocol proto;
  4329. char *rpc_req;
  4330. if (pool->proto == PLP_NONE)
  4331. pool->proto = PLP_GETBLOCKTEMPLATE;
  4332. tryagain:
  4333. rpc_req = prepare_rpc_req(work, pool->proto, NULL);
  4334. work->pool = pool;
  4335. if (!rpc_req)
  4336. return false;
  4337. applog(LOG_DEBUG, "DBG: sending %s get RPC call: %s", pool->rpc_url, rpc_req);
  4338. url = pool->rpc_url;
  4339. cgtime(&work->tv_getwork);
  4340. val = json_rpc_call(curl, url, pool->rpc_userpass, rpc_req, false,
  4341. false, &work->rolltime, pool, false);
  4342. pool_stats->getwork_attempts++;
  4343. free(rpc_req);
  4344. if (likely(val)) {
  4345. rc = work_decode(pool, work, val);
  4346. if (unlikely(!rc))
  4347. applog(LOG_DEBUG, "Failed to decode work in get_upstream_work");
  4348. } else if (PLP_NONE != (proto = pool_protocol_fallback(pool->proto))) {
  4349. applog(LOG_WARNING, "Pool %u failed getblocktemplate request; falling back to getwork protocol", pool->pool_no);
  4350. pool->proto = proto;
  4351. goto tryagain;
  4352. } else
  4353. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  4354. cgtime(&work->tv_getwork_reply);
  4355. timersub(&(work->tv_getwork_reply), &(work->tv_getwork), &tv_elapsed);
  4356. pool_stats->getwork_wait_rolling += ((double)tv_elapsed.tv_sec + ((double)tv_elapsed.tv_usec / 1000000)) * 0.63;
  4357. pool_stats->getwork_wait_rolling /= 1.63;
  4358. timeradd(&tv_elapsed, &(pool_stats->getwork_wait), &(pool_stats->getwork_wait));
  4359. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_max), >)) {
  4360. pool_stats->getwork_wait_max.tv_sec = tv_elapsed.tv_sec;
  4361. pool_stats->getwork_wait_max.tv_usec = tv_elapsed.tv_usec;
  4362. }
  4363. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_min), <)) {
  4364. pool_stats->getwork_wait_min.tv_sec = tv_elapsed.tv_sec;
  4365. pool_stats->getwork_wait_min.tv_usec = tv_elapsed.tv_usec;
  4366. }
  4367. pool_stats->getwork_calls++;
  4368. work->pool = pool;
  4369. work->longpoll = false;
  4370. calc_diff(work, 0);
  4371. total_getworks++;
  4372. pool->getwork_requested++;
  4373. if (rc)
  4374. update_last_work(work);
  4375. if (likely(val))
  4376. json_decref(val);
  4377. return rc;
  4378. }
  4379. #ifdef HAVE_CURSES
  4380. static void disable_curses(void)
  4381. {
  4382. if (curses_active_locked()) {
  4383. use_curses = false;
  4384. curses_active = false;
  4385. leaveok(logwin, false);
  4386. leaveok(statuswin, false);
  4387. leaveok(mainwin, false);
  4388. nocbreak();
  4389. echo();
  4390. delwin(logwin);
  4391. delwin(statuswin);
  4392. delwin(mainwin);
  4393. endwin();
  4394. #ifdef WIN32
  4395. // Move the cursor to after curses output.
  4396. HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
  4397. CONSOLE_SCREEN_BUFFER_INFO csbi;
  4398. COORD coord;
  4399. if (GetConsoleScreenBufferInfo(hout, &csbi)) {
  4400. coord.X = 0;
  4401. coord.Y = csbi.dwSize.Y - 1;
  4402. SetConsoleCursorPosition(hout, coord);
  4403. }
  4404. #endif
  4405. unlock_curses();
  4406. }
  4407. }
  4408. #endif
  4409. static void __kill_work(void)
  4410. {
  4411. struct cgpu_info *cgpu;
  4412. struct thr_info *thr;
  4413. int i;
  4414. if (!successful_connect)
  4415. return;
  4416. applog(LOG_INFO, "Received kill message");
  4417. shutting_down = true;
  4418. applog(LOG_DEBUG, "Prompting submit_work thread to finish");
  4419. notifier_wake(submit_waiting_notifier);
  4420. #ifdef USE_LIBMICROHTTPD
  4421. httpsrv_stop();
  4422. #endif
  4423. applog(LOG_DEBUG, "Killing off watchpool thread");
  4424. /* Kill the watchpool thread */
  4425. thr = &control_thr[watchpool_thr_id];
  4426. thr_info_cancel(thr);
  4427. applog(LOG_DEBUG, "Killing off watchdog thread");
  4428. /* Kill the watchdog thread */
  4429. thr = &control_thr[watchdog_thr_id];
  4430. thr_info_cancel(thr);
  4431. applog(LOG_DEBUG, "Shutting down mining threads");
  4432. for (i = 0; i < mining_threads; i++) {
  4433. thr = get_thread(i);
  4434. if (!thr)
  4435. continue;
  4436. cgpu = thr->cgpu;
  4437. if (!cgpu)
  4438. continue;
  4439. if (!cgpu->threads)
  4440. continue;
  4441. cgpu->shutdown = true;
  4442. thr->work_restart = true;
  4443. notifier_wake(thr->notifier);
  4444. notifier_wake(thr->work_restart_notifier);
  4445. }
  4446. sleep(1);
  4447. applog(LOG_DEBUG, "Killing off mining threads");
  4448. /* Kill the mining threads*/
  4449. for (i = 0; i < mining_threads; i++) {
  4450. thr = get_thread(i);
  4451. if (!thr)
  4452. continue;
  4453. cgpu = thr->cgpu;
  4454. if (cgpu->threads)
  4455. {
  4456. applog(LOG_WARNING, "Killing %"PRIpreprv, thr->cgpu->proc_repr);
  4457. thr_info_cancel(thr);
  4458. }
  4459. cgpu->status = LIFE_DEAD2;
  4460. }
  4461. /* Stop the others */
  4462. applog(LOG_DEBUG, "Killing off API thread");
  4463. thr = &control_thr[api_thr_id];
  4464. thr_info_cancel(thr);
  4465. }
  4466. /* This should be the common exit path */
  4467. void kill_work(void)
  4468. {
  4469. __kill_work();
  4470. quit(0, "Shutdown signal received.");
  4471. }
  4472. static
  4473. #ifdef WIN32
  4474. #ifndef _WIN64
  4475. const
  4476. #endif
  4477. #endif
  4478. char **initial_args;
  4479. void _bfg_clean_up(bool);
  4480. void app_restart(void)
  4481. {
  4482. applog(LOG_WARNING, "Attempting to restart %s", packagename);
  4483. __kill_work();
  4484. _bfg_clean_up(true);
  4485. #if defined(unix) || defined(__APPLE__)
  4486. if (forkpid > 0) {
  4487. kill(forkpid, SIGTERM);
  4488. forkpid = 0;
  4489. }
  4490. #endif
  4491. execv(initial_args[0], initial_args);
  4492. applog(LOG_WARNING, "Failed to restart application");
  4493. }
  4494. static void sighandler(int __maybe_unused sig)
  4495. {
  4496. /* Restore signal handlers so we can still quit if kill_work fails */
  4497. sigaction(SIGTERM, &termhandler, NULL);
  4498. sigaction(SIGINT, &inthandler, NULL);
  4499. kill_work();
  4500. }
  4501. static void start_longpoll(void);
  4502. static void stop_longpoll(void);
  4503. /* Called with pool_lock held. Recruit an extra curl if none are available for
  4504. * this pool. */
  4505. static void recruit_curl(struct pool *pool)
  4506. {
  4507. struct curl_ent *ce = calloc(sizeof(struct curl_ent), 1);
  4508. if (unlikely(!ce))
  4509. quit(1, "Failed to calloc in recruit_curl");
  4510. ce->curl = curl_easy_init();
  4511. if (unlikely(!ce->curl))
  4512. quit(1, "Failed to init in recruit_curl");
  4513. LL_PREPEND(pool->curllist, ce);
  4514. pool->curls++;
  4515. }
  4516. /* Grab an available curl if there is one. If not, then recruit extra curls
  4517. * unless we are in a submit_fail situation, or we have opt_delaynet enabled
  4518. * and there are already 5 curls in circulation. Limit total number to the
  4519. * number of mining threads per pool as well to prevent blasting a pool during
  4520. * network delays/outages. */
  4521. static struct curl_ent *pop_curl_entry3(struct pool *pool, int blocking)
  4522. {
  4523. int curl_limit = opt_delaynet ? 5 : (mining_threads + opt_queue) * 2;
  4524. bool recruited = false;
  4525. struct curl_ent *ce;
  4526. mutex_lock(&pool->pool_lock);
  4527. retry:
  4528. if (!pool->curls) {
  4529. recruit_curl(pool);
  4530. recruited = true;
  4531. } else if (!pool->curllist) {
  4532. if (blocking < 2 && pool->curls >= curl_limit && (blocking || pool->curls >= opt_submit_threads)) {
  4533. if (!blocking) {
  4534. mutex_unlock(&pool->pool_lock);
  4535. return NULL;
  4536. }
  4537. pthread_cond_wait(&pool->cr_cond, &pool->pool_lock);
  4538. goto retry;
  4539. } else {
  4540. recruit_curl(pool);
  4541. recruited = true;
  4542. }
  4543. }
  4544. ce = pool->curllist;
  4545. LL_DELETE(pool->curllist, ce);
  4546. mutex_unlock(&pool->pool_lock);
  4547. if (recruited)
  4548. applog(LOG_DEBUG, "Recruited curl for pool %d", pool->pool_no);
  4549. return ce;
  4550. }
  4551. static struct curl_ent *pop_curl_entry2(struct pool *pool, bool blocking)
  4552. {
  4553. return pop_curl_entry3(pool, blocking ? 1 : 0);
  4554. }
  4555. __maybe_unused
  4556. static struct curl_ent *pop_curl_entry(struct pool *pool)
  4557. {
  4558. return pop_curl_entry3(pool, 1);
  4559. }
  4560. static void push_curl_entry(struct curl_ent *ce, struct pool *pool)
  4561. {
  4562. mutex_lock(&pool->pool_lock);
  4563. if (!ce || !ce->curl)
  4564. quithere(1, "Attempted to add NULL");
  4565. LL_PREPEND(pool->curllist, ce);
  4566. cgtime(&ce->tv);
  4567. pthread_cond_broadcast(&pool->cr_cond);
  4568. mutex_unlock(&pool->pool_lock);
  4569. }
  4570. bool stale_work(struct work *work, bool share);
  4571. static inline bool should_roll(struct work *work)
  4572. {
  4573. struct timeval now;
  4574. time_t expiry;
  4575. if (!pool_actively_in_use(work->pool, NULL))
  4576. return false;
  4577. if (stale_work(work, false))
  4578. return false;
  4579. if (work->rolltime > opt_scantime)
  4580. expiry = work->rolltime;
  4581. else
  4582. expiry = opt_scantime;
  4583. expiry = expiry * 2 / 3;
  4584. /* We shouldn't roll if we're unlikely to get one shares' duration
  4585. * work out of doing so */
  4586. cgtime(&now);
  4587. if (now.tv_sec - work->tv_staged.tv_sec > expiry)
  4588. return false;
  4589. return true;
  4590. }
  4591. /* Limit rolls to 7000 to not beyond 2 hours in the future where bitcoind will
  4592. * reject blocks as invalid. */
  4593. static inline bool can_roll(struct work *work)
  4594. {
  4595. if (work->stratum)
  4596. return false;
  4597. if (!(work->pool && !work->clone))
  4598. return false;
  4599. if (work->tmpl) {
  4600. if (stale_work(work, false))
  4601. return false;
  4602. return blkmk_work_left(work->tmpl);
  4603. }
  4604. return (work->rolltime &&
  4605. work->rolls < 7000 && !stale_work(work, false));
  4606. }
  4607. static void roll_work(struct work *work)
  4608. {
  4609. if (work->tmpl) {
  4610. struct timeval tv_now;
  4611. cgtime(&tv_now);
  4612. if (blkmk_get_data(work->tmpl, work->data, 80, tv_now.tv_sec, NULL, &work->dataid) < 76)
  4613. applog(LOG_ERR, "Failed to get next data from template; spinning wheels!");
  4614. swap32yes(work->data, work->data, 80 / 4);
  4615. calc_midstate(work);
  4616. applog(LOG_DEBUG, "Successfully rolled extranonce to dataid %u", work->dataid);
  4617. } else {
  4618. uint32_t *work_ntime;
  4619. uint32_t ntime;
  4620. work_ntime = (uint32_t *)(work->data + 68);
  4621. ntime = be32toh(*work_ntime);
  4622. ntime++;
  4623. *work_ntime = htobe32(ntime);
  4624. applog(LOG_DEBUG, "Successfully rolled time header in work");
  4625. }
  4626. local_work++;
  4627. work->rolls++;
  4628. work->blk.nonce = 0;
  4629. /* This is now a different work item so it needs a different ID for the
  4630. * hashtable */
  4631. work->id = total_work++;
  4632. }
  4633. /* Duplicates any dynamically allocated arrays within the work struct to
  4634. * prevent a copied work struct from freeing ram belonging to another struct */
  4635. static void _copy_work(struct work *work, const struct work *base_work, int noffset)
  4636. {
  4637. int id = work->id;
  4638. clean_work(work);
  4639. memcpy(work, base_work, sizeof(struct work));
  4640. /* Keep the unique new id assigned during make_work to prevent copied
  4641. * work from having the same id. */
  4642. work->id = id;
  4643. if (base_work->job_id)
  4644. work->job_id = strdup(base_work->job_id);
  4645. if (base_work->nonce1)
  4646. work->nonce1 = strdup(base_work->nonce1);
  4647. bytes_cpy(&work->nonce2, &base_work->nonce2);
  4648. if (base_work->tmpl) {
  4649. struct pool *pool = work->pool;
  4650. mutex_lock(&pool->pool_lock);
  4651. ++*work->tmpl_refcount;
  4652. mutex_unlock(&pool->pool_lock);
  4653. }
  4654. if (noffset)
  4655. {
  4656. uint32_t *work_ntime = (uint32_t *)(work->data + 68);
  4657. uint32_t ntime = be32toh(*work_ntime);
  4658. ntime += noffset;
  4659. *work_ntime = htobe32(ntime);
  4660. }
  4661. if (work->device_data_dup_func)
  4662. work->device_data = work->device_data_dup_func(work);
  4663. }
  4664. /* Generates a copy of an existing work struct, creating fresh heap allocations
  4665. * for all dynamically allocated arrays within the struct */
  4666. struct work *copy_work(const struct work *base_work)
  4667. {
  4668. struct work *work = make_work();
  4669. _copy_work(work, base_work, 0);
  4670. return work;
  4671. }
  4672. void __copy_work(struct work *work, const struct work *base_work)
  4673. {
  4674. _copy_work(work, base_work, 0);
  4675. }
  4676. static struct work *make_clone(struct work *work)
  4677. {
  4678. struct work *work_clone = copy_work(work);
  4679. work_clone->clone = true;
  4680. cgtime((struct timeval *)&(work_clone->tv_cloned));
  4681. work_clone->longpoll = false;
  4682. work_clone->mandatory = false;
  4683. /* Make cloned work appear slightly older to bias towards keeping the
  4684. * master work item which can be further rolled */
  4685. work_clone->tv_staged.tv_sec -= 1;
  4686. return work_clone;
  4687. }
  4688. static void stage_work(struct work *work);
  4689. static bool clone_available(void)
  4690. {
  4691. struct work *work_clone = NULL, *work, *tmp;
  4692. bool cloned = false;
  4693. mutex_lock(stgd_lock);
  4694. if (!staged_rollable)
  4695. goto out_unlock;
  4696. HASH_ITER(hh, staged_work, work, tmp) {
  4697. if (can_roll(work) && should_roll(work)) {
  4698. roll_work(work);
  4699. work_clone = make_clone(work);
  4700. applog(LOG_DEBUG, "%s: Rolling work %d to %d", __func__, work->id, work_clone->id);
  4701. roll_work(work);
  4702. cloned = true;
  4703. break;
  4704. }
  4705. }
  4706. out_unlock:
  4707. mutex_unlock(stgd_lock);
  4708. if (cloned) {
  4709. applog(LOG_DEBUG, "Pushing cloned available work to stage thread");
  4710. stage_work(work_clone);
  4711. }
  4712. return cloned;
  4713. }
  4714. static void pool_died(struct pool *pool)
  4715. {
  4716. if (!pool_tset(pool, &pool->idle)) {
  4717. cgtime(&pool->tv_idle);
  4718. if (pool == current_pool()) {
  4719. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  4720. switch_pools(NULL);
  4721. } else
  4722. applog(LOG_INFO, "Pool %d %s failed to return work", pool->pool_no, pool->rpc_url);
  4723. }
  4724. }
  4725. bool stale_work(struct work *work, bool share)
  4726. {
  4727. unsigned work_expiry;
  4728. struct pool *pool;
  4729. uint32_t block_id;
  4730. unsigned getwork_delay;
  4731. if (opt_benchmark)
  4732. return false;
  4733. block_id = ((uint32_t*)work->data)[1];
  4734. pool = work->pool;
  4735. /* Technically the rolltime should be correct but some pools
  4736. * advertise a broken expire= that is lower than a meaningful
  4737. * scantime */
  4738. if (work->rolltime >= opt_scantime || work->tmpl)
  4739. work_expiry = work->rolltime;
  4740. else
  4741. work_expiry = opt_expiry;
  4742. unsigned max_expiry = (have_longpoll ? opt_expiry_lp : opt_expiry);
  4743. if (work_expiry > max_expiry)
  4744. work_expiry = max_expiry;
  4745. if (share) {
  4746. /* If the share isn't on this pool's latest block, it's stale */
  4747. if (pool->block_id && pool->block_id != block_id)
  4748. {
  4749. applog(LOG_DEBUG, "Share stale due to block mismatch (%08lx != %08lx)", (long)block_id, (long)pool->block_id);
  4750. return true;
  4751. }
  4752. /* If the pool doesn't want old shares, then any found in work before
  4753. * the most recent longpoll is stale */
  4754. if ((!pool->submit_old) && work->work_restart_id != pool->work_restart_id)
  4755. {
  4756. applog(LOG_DEBUG, "Share stale due to mandatory work update (%02x != %02x)", work->work_restart_id, pool->work_restart_id);
  4757. return true;
  4758. }
  4759. } else {
  4760. /* If this work isn't for the latest Bitcoin block, it's stale */
  4761. /* But only care about the current pool if failover-only */
  4762. if (enabled_pools <= 1 || opt_fail_only) {
  4763. if (pool->block_id && block_id != pool->block_id)
  4764. {
  4765. applog(LOG_DEBUG, "Work stale due to block mismatch (%08lx != 1 ? %08lx : %08lx)", (long)block_id, (long)pool->block_id, (long)current_block_id);
  4766. return true;
  4767. }
  4768. } else {
  4769. if (block_id != current_block_id)
  4770. {
  4771. applog(LOG_DEBUG, "Work stale due to block mismatch (%08lx != 0 ? %08lx : %08lx)", (long)block_id, (long)pool->block_id, (long)current_block_id);
  4772. return true;
  4773. }
  4774. }
  4775. /* If the pool has asked us to restart since this work, it's stale */
  4776. if (work->work_restart_id != pool->work_restart_id)
  4777. {
  4778. applog(LOG_DEBUG, "Work stale due to work update (%02x != %02x)", work->work_restart_id, pool->work_restart_id);
  4779. return true;
  4780. }
  4781. if (pool->has_stratum && work->job_id) {
  4782. bool same_job;
  4783. if (!pool->stratum_active || !pool->stratum_notify) {
  4784. applog(LOG_DEBUG, "Work stale due to stratum inactive");
  4785. return true;
  4786. }
  4787. same_job = true;
  4788. cg_rlock(&pool->data_lock);
  4789. if (strcmp(work->job_id, pool->swork.job_id))
  4790. same_job = false;
  4791. cg_runlock(&pool->data_lock);
  4792. if (!same_job) {
  4793. applog(LOG_DEBUG, "Work stale due to stratum job_id mismatch");
  4794. return true;
  4795. }
  4796. }
  4797. /* Factor in the average getwork delay of this pool, rounding it up to
  4798. * the nearest second */
  4799. getwork_delay = pool->cgminer_pool_stats.getwork_wait_rolling * 5 + 1;
  4800. if (unlikely(work_expiry <= getwork_delay + 5))
  4801. work_expiry = 5;
  4802. else
  4803. work_expiry -= getwork_delay;
  4804. }
  4805. int elapsed_since_staged = timer_elapsed(&work->tv_staged, NULL);
  4806. if (elapsed_since_staged > work_expiry) {
  4807. applog(LOG_DEBUG, "%s stale due to expiry (%d >= %u)", share?"Share":"Work", elapsed_since_staged, work_expiry);
  4808. return true;
  4809. }
  4810. /* If the user only wants strict failover, any work from a pool other than
  4811. * the current one is always considered stale */
  4812. if (opt_fail_only && !share && !work->mandatory && !pool_actively_in_use(pool, NULL))
  4813. {
  4814. applog(LOG_DEBUG, "Work stale due to fail only pool mismatch (pool %u vs %u)", pool->pool_no, current_pool()->pool_no);
  4815. return true;
  4816. }
  4817. return false;
  4818. }
  4819. static double share_diff(const struct work *work)
  4820. {
  4821. double ret;
  4822. bool new_best = false;
  4823. ret = target_diff(work->hash);
  4824. cg_wlock(&control_lock);
  4825. if (unlikely(ret > best_diff)) {
  4826. new_best = true;
  4827. best_diff = ret;
  4828. suffix_string(best_diff, best_share, sizeof(best_share), 0);
  4829. }
  4830. if (unlikely(ret > work->pool->best_diff))
  4831. work->pool->best_diff = ret;
  4832. cg_wunlock(&control_lock);
  4833. if (unlikely(new_best))
  4834. applog(LOG_INFO, "New best share: %s", best_share);
  4835. return ret;
  4836. }
  4837. static void regen_hash(struct work *work)
  4838. {
  4839. hash_data(work->hash, work->data);
  4840. }
  4841. static void rebuild_hash(struct work *work)
  4842. {
  4843. if (opt_scrypt)
  4844. scrypt_regenhash(work);
  4845. else
  4846. regen_hash(work);
  4847. work->share_diff = share_diff(work);
  4848. if (unlikely(work->share_diff >= current_diff)) {
  4849. work->block = true;
  4850. work->pool->solved++;
  4851. found_blocks++;
  4852. work->mandatory = true;
  4853. applog(LOG_NOTICE, "Found block for pool %d!", work->pool->pool_no);
  4854. }
  4855. }
  4856. static void submit_discard_share2(const char *reason, struct work *work)
  4857. {
  4858. struct cgpu_info *cgpu = get_thr_cgpu(work->thr_id);
  4859. sharelog(reason, work);
  4860. mutex_lock(&stats_lock);
  4861. ++total_stale;
  4862. ++cgpu->stale;
  4863. ++(work->pool->stale_shares);
  4864. total_diff_stale += work->work_difficulty;
  4865. cgpu->diff_stale += work->work_difficulty;
  4866. work->pool->diff_stale += work->work_difficulty;
  4867. mutex_unlock(&stats_lock);
  4868. }
  4869. static void submit_discard_share(struct work *work)
  4870. {
  4871. submit_discard_share2("discard", work);
  4872. }
  4873. struct submit_work_state {
  4874. struct work *work;
  4875. bool resubmit;
  4876. struct curl_ent *ce;
  4877. int failures;
  4878. struct timeval tv_staleexpire;
  4879. char *s;
  4880. struct timeval tv_submit;
  4881. struct submit_work_state *next;
  4882. };
  4883. static int my_curl_timer_set(__maybe_unused CURLM *curlm, long timeout_ms, void *userp)
  4884. {
  4885. long *p_timeout_us = userp;
  4886. const long max_ms = LONG_MAX / 1000;
  4887. if (max_ms < timeout_ms)
  4888. timeout_ms = max_ms;
  4889. *p_timeout_us = timeout_ms * 1000;
  4890. return 0;
  4891. }
  4892. static void sws_has_ce(struct submit_work_state *sws)
  4893. {
  4894. struct pool *pool = sws->work->pool;
  4895. sws->s = submit_upstream_work_request(sws->work);
  4896. cgtime(&sws->tv_submit);
  4897. json_rpc_call_async(sws->ce->curl, pool->rpc_url, pool->rpc_userpass, sws->s, false, pool, true, sws);
  4898. }
  4899. static struct submit_work_state *begin_submission(struct work *work)
  4900. {
  4901. struct pool *pool;
  4902. struct submit_work_state *sws = NULL;
  4903. pool = work->pool;
  4904. sws = malloc(sizeof(*sws));
  4905. *sws = (struct submit_work_state){
  4906. .work = work,
  4907. };
  4908. rebuild_hash(work);
  4909. if (stale_work(work, true)) {
  4910. work->stale = true;
  4911. if (opt_submit_stale)
  4912. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as user requested", pool->pool_no);
  4913. else if (pool->submit_old)
  4914. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as pool requested", pool->pool_no);
  4915. else {
  4916. applog(LOG_NOTICE, "Pool %d stale share detected, discarding", pool->pool_no);
  4917. submit_discard_share(work);
  4918. goto out;
  4919. }
  4920. timer_set_delay_from_now(&sws->tv_staleexpire, 300000000);
  4921. }
  4922. if (work->stratum) {
  4923. char *s;
  4924. s = malloc(1024);
  4925. sws->s = s;
  4926. } else {
  4927. /* submit solution to bitcoin via JSON-RPC */
  4928. sws->ce = pop_curl_entry2(pool, false);
  4929. if (sws->ce) {
  4930. sws_has_ce(sws);
  4931. } else {
  4932. sws->next = pool->sws_waiting_on_curl;
  4933. pool->sws_waiting_on_curl = sws;
  4934. if (sws->next)
  4935. applog(LOG_DEBUG, "submit_thread queuing submission");
  4936. else
  4937. applog(LOG_WARNING, "submit_thread queuing submissions (see --submit-threads)");
  4938. }
  4939. }
  4940. return sws;
  4941. out:
  4942. free(sws);
  4943. return NULL;
  4944. }
  4945. static bool retry_submission(struct submit_work_state *sws)
  4946. {
  4947. struct work *work = sws->work;
  4948. struct pool *pool = work->pool;
  4949. sws->resubmit = true;
  4950. if ((!work->stale) && stale_work(work, true)) {
  4951. work->stale = true;
  4952. if (opt_submit_stale)
  4953. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, will retry as user requested", pool->pool_no);
  4954. else if (pool->submit_old)
  4955. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, will retry as pool requested", pool->pool_no);
  4956. else {
  4957. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, discarding", pool->pool_no);
  4958. submit_discard_share(work);
  4959. return false;
  4960. }
  4961. timer_set_delay_from_now(&sws->tv_staleexpire, 300000000);
  4962. }
  4963. if (unlikely((opt_retries >= 0) && (++sws->failures > opt_retries))) {
  4964. applog(LOG_ERR, "Pool %d failed %d submission retries, discarding", pool->pool_no, opt_retries);
  4965. submit_discard_share(work);
  4966. return false;
  4967. }
  4968. else if (work->stale) {
  4969. if (unlikely(opt_retries < 0 && timer_passed(&sws->tv_staleexpire, NULL)))
  4970. {
  4971. applog(LOG_NOTICE, "Pool %d stale share failed to submit for 5 minutes, discarding", pool->pool_no);
  4972. submit_discard_share(work);
  4973. return false;
  4974. }
  4975. }
  4976. /* pause, then restart work-request loop */
  4977. applog(LOG_INFO, "json_rpc_call failed on submit_work, retrying");
  4978. cgtime(&sws->tv_submit);
  4979. json_rpc_call_async(sws->ce->curl, pool->rpc_url, pool->rpc_userpass, sws->s, false, pool, true, sws);
  4980. return true;
  4981. }
  4982. static void free_sws(struct submit_work_state *sws)
  4983. {
  4984. free(sws->s);
  4985. free_work(sws->work);
  4986. free(sws);
  4987. }
  4988. static void *submit_work_thread(__maybe_unused void *userdata)
  4989. {
  4990. int wip = 0;
  4991. CURLM *curlm;
  4992. long curlm_timeout_us = -1;
  4993. struct timeval curlm_timer;
  4994. struct submit_work_state *sws, **swsp;
  4995. struct submit_work_state *write_sws = NULL;
  4996. unsigned tsreduce = 0;
  4997. pthread_detach(pthread_self());
  4998. RenameThread("submit_work");
  4999. applog(LOG_DEBUG, "Creating extra submit work thread");
  5000. curlm = curl_multi_init();
  5001. curlm_timeout_us = -1;
  5002. curl_multi_setopt(curlm, CURLMOPT_TIMERDATA, &curlm_timeout_us);
  5003. curl_multi_setopt(curlm, CURLMOPT_TIMERFUNCTION, my_curl_timer_set);
  5004. fd_set rfds, wfds, efds;
  5005. int maxfd;
  5006. struct timeval tv_timeout, tv_now;
  5007. int n;
  5008. CURLMsg *cm;
  5009. FD_ZERO(&rfds);
  5010. while (1) {
  5011. mutex_lock(&submitting_lock);
  5012. total_submitting -= tsreduce;
  5013. tsreduce = 0;
  5014. if (FD_ISSET(submit_waiting_notifier[0], &rfds)) {
  5015. notifier_read(submit_waiting_notifier);
  5016. }
  5017. // Receive any new submissions
  5018. while (submit_waiting) {
  5019. struct work *work = submit_waiting;
  5020. DL_DELETE(submit_waiting, work);
  5021. if ( (sws = begin_submission(work)) ) {
  5022. if (sws->ce)
  5023. curl_multi_add_handle(curlm, sws->ce->curl);
  5024. else if (sws->s) {
  5025. sws->next = write_sws;
  5026. write_sws = sws;
  5027. }
  5028. ++wip;
  5029. }
  5030. else {
  5031. --total_submitting;
  5032. free_work(work);
  5033. }
  5034. }
  5035. if (unlikely(shutting_down && !wip))
  5036. break;
  5037. mutex_unlock(&submitting_lock);
  5038. FD_ZERO(&rfds);
  5039. FD_ZERO(&wfds);
  5040. FD_ZERO(&efds);
  5041. tv_timeout.tv_sec = -1;
  5042. // Setup cURL with select
  5043. // Need to call perform to ensure the timeout gets updated
  5044. curl_multi_perform(curlm, &n);
  5045. curl_multi_fdset(curlm, &rfds, &wfds, &efds, &maxfd);
  5046. if (curlm_timeout_us >= 0)
  5047. {
  5048. timer_set_delay_from_now(&curlm_timer, curlm_timeout_us);
  5049. reduce_timeout_to(&tv_timeout, &curlm_timer);
  5050. }
  5051. // Setup waiting stratum submissions with select
  5052. for (sws = write_sws; sws; sws = sws->next)
  5053. {
  5054. struct pool *pool = sws->work->pool;
  5055. int fd = pool->sock;
  5056. if (fd == INVSOCK || (!pool->stratum_init) || !pool->stratum_notify)
  5057. continue;
  5058. FD_SET(fd, &wfds);
  5059. set_maxfd(&maxfd, fd);
  5060. }
  5061. // Setup "submit waiting" notifier with select
  5062. FD_SET(submit_waiting_notifier[0], &rfds);
  5063. set_maxfd(&maxfd, submit_waiting_notifier[0]);
  5064. // Wait for something interesting to happen :)
  5065. cgtime(&tv_now);
  5066. if (select(maxfd+1, &rfds, &wfds, &efds, select_timeout(&tv_timeout, &tv_now)) < 0) {
  5067. FD_ZERO(&rfds);
  5068. continue;
  5069. }
  5070. // Handle any stratum ready-to-write results
  5071. for (swsp = &write_sws; (sws = *swsp); ) {
  5072. struct work *work = sws->work;
  5073. struct pool *pool = work->pool;
  5074. int fd = pool->sock;
  5075. bool sessionid_match;
  5076. if (fd == INVSOCK || (!pool->stratum_init) || (!pool->stratum_notify) || !FD_ISSET(fd, &wfds)) {
  5077. next_write_sws:
  5078. // TODO: Check if stale, possibly discard etc
  5079. swsp = &sws->next;
  5080. continue;
  5081. }
  5082. cg_rlock(&pool->data_lock);
  5083. // 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
  5084. // NOTE: Worst case scenario for a false positive: the pool rejects it as H-not-zero
  5085. sessionid_match = (!pool->nonce1) || !strcmp(work->nonce1, pool->nonce1);
  5086. cg_runlock(&pool->data_lock);
  5087. if (!sessionid_match)
  5088. {
  5089. applog(LOG_DEBUG, "No matching session id for resubmitting stratum share");
  5090. submit_discard_share2("disconnect", work);
  5091. ++tsreduce;
  5092. next_write_sws_del:
  5093. // Clear the fd from wfds, to avoid potentially blocking on other submissions to the same socket
  5094. FD_CLR(fd, &wfds);
  5095. // Delete sws for this submission, since we're done with it
  5096. *swsp = sws->next;
  5097. free_sws(sws);
  5098. --wip;
  5099. continue;
  5100. }
  5101. char *s = sws->s;
  5102. struct stratum_share *sshare = calloc(sizeof(struct stratum_share), 1);
  5103. int sshare_id;
  5104. uint32_t nonce;
  5105. char nonce2hex[(bytes_len(&work->nonce2) * 2) + 1];
  5106. char noncehex[9];
  5107. char ntimehex[9];
  5108. sshare->work = copy_work(work);
  5109. bin2hex(nonce2hex, bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  5110. nonce = *((uint32_t *)(work->data + 76));
  5111. bin2hex(noncehex, (const unsigned char *)&nonce, 4);
  5112. bin2hex(ntimehex, (void *)&work->data[68], 4);
  5113. mutex_lock(&sshare_lock);
  5114. /* Give the stratum share a unique id */
  5115. sshare_id =
  5116. sshare->id = swork_id++;
  5117. HASH_ADD_INT(stratum_shares, id, sshare);
  5118. snprintf(s, 1024, "{\"params\": [\"%s\", \"%s\", \"%s\", \"%s\", \"%s\"], \"id\": %d, \"method\": \"mining.submit\"}",
  5119. pool->rpc_user, work->job_id, nonce2hex, ntimehex, noncehex, sshare->id);
  5120. mutex_unlock(&sshare_lock);
  5121. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->stratum_url, s);
  5122. if (likely(stratum_send(pool, s, strlen(s)))) {
  5123. if (pool_tclear(pool, &pool->submit_fail))
  5124. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  5125. applog(LOG_DEBUG, "Successfully submitted, adding to stratum_shares db");
  5126. goto next_write_sws_del;
  5127. } else if (!pool_tset(pool, &pool->submit_fail)) {
  5128. // Undo stuff
  5129. mutex_lock(&sshare_lock);
  5130. // NOTE: Need to find it again in case something else has consumed it already (like the stratum-disconnect resubmitter...)
  5131. HASH_FIND_INT(stratum_shares, &sshare_id, sshare);
  5132. if (sshare)
  5133. HASH_DEL(stratum_shares, sshare);
  5134. mutex_unlock(&sshare_lock);
  5135. if (sshare)
  5136. {
  5137. free_work(sshare->work);
  5138. free(sshare);
  5139. }
  5140. applog(LOG_WARNING, "Pool %d stratum share submission failure", pool->pool_no);
  5141. total_ro++;
  5142. pool->remotefail_occasions++;
  5143. if (!sshare)
  5144. goto next_write_sws_del;
  5145. goto next_write_sws;
  5146. }
  5147. }
  5148. // Handle any cURL activities
  5149. curl_multi_perform(curlm, &n);
  5150. while( (cm = curl_multi_info_read(curlm, &n)) ) {
  5151. if (cm->msg == CURLMSG_DONE)
  5152. {
  5153. bool finished;
  5154. json_t *val = json_rpc_call_completed(cm->easy_handle, cm->data.result, false, NULL, &sws);
  5155. curl_multi_remove_handle(curlm, cm->easy_handle);
  5156. finished = submit_upstream_work_completed(sws->work, sws->resubmit, &sws->tv_submit, val);
  5157. if (!finished) {
  5158. if (retry_submission(sws))
  5159. curl_multi_add_handle(curlm, sws->ce->curl);
  5160. else
  5161. finished = true;
  5162. }
  5163. if (finished) {
  5164. --wip;
  5165. ++tsreduce;
  5166. struct pool *pool = sws->work->pool;
  5167. if (pool->sws_waiting_on_curl) {
  5168. pool->sws_waiting_on_curl->ce = sws->ce;
  5169. sws_has_ce(pool->sws_waiting_on_curl);
  5170. pool->sws_waiting_on_curl = pool->sws_waiting_on_curl->next;
  5171. curl_multi_add_handle(curlm, sws->ce->curl);
  5172. } else {
  5173. push_curl_entry(sws->ce, sws->work->pool);
  5174. }
  5175. free_sws(sws);
  5176. }
  5177. }
  5178. }
  5179. }
  5180. assert(!write_sws);
  5181. mutex_unlock(&submitting_lock);
  5182. curl_multi_cleanup(curlm);
  5183. applog(LOG_DEBUG, "submit_work thread exiting");
  5184. return NULL;
  5185. }
  5186. /* Find the pool that currently has the highest priority */
  5187. static struct pool *priority_pool(int choice)
  5188. {
  5189. struct pool *ret = NULL;
  5190. int i;
  5191. for (i = 0; i < total_pools; i++) {
  5192. struct pool *pool = pools[i];
  5193. if (pool->prio == choice) {
  5194. ret = pool;
  5195. break;
  5196. }
  5197. }
  5198. if (unlikely(!ret)) {
  5199. applog(LOG_ERR, "WTF No pool %d found!", choice);
  5200. return pools[choice];
  5201. }
  5202. return ret;
  5203. }
  5204. int prioritize_pools(char *param, int *pid)
  5205. {
  5206. char *ptr, *next;
  5207. int i, pr, prio = 0;
  5208. if (total_pools == 0) {
  5209. return MSG_NOPOOL;
  5210. }
  5211. if (param == NULL || *param == '\0') {
  5212. return MSG_MISPID;
  5213. }
  5214. bool pools_changed[total_pools];
  5215. int new_prio[total_pools];
  5216. for (i = 0; i < total_pools; ++i)
  5217. pools_changed[i] = false;
  5218. next = param;
  5219. while (next && *next) {
  5220. ptr = next;
  5221. next = strchr(ptr, ',');
  5222. if (next)
  5223. *(next++) = '\0';
  5224. i = atoi(ptr);
  5225. if (i < 0 || i >= total_pools) {
  5226. *pid = i;
  5227. return MSG_INVPID;
  5228. }
  5229. if (pools_changed[i]) {
  5230. *pid = i;
  5231. return MSG_DUPPID;
  5232. }
  5233. pools_changed[i] = true;
  5234. new_prio[i] = prio++;
  5235. }
  5236. // Only change them if no errors
  5237. for (i = 0; i < total_pools; i++) {
  5238. if (pools_changed[i])
  5239. pools[i]->prio = new_prio[i];
  5240. }
  5241. // In priority order, cycle through the unchanged pools and append them
  5242. for (pr = 0; pr < total_pools; pr++)
  5243. for (i = 0; i < total_pools; i++) {
  5244. if (!pools_changed[i] && pools[i]->prio == pr) {
  5245. pools[i]->prio = prio++;
  5246. pools_changed[i] = true;
  5247. break;
  5248. }
  5249. }
  5250. if (current_pool()->prio)
  5251. switch_pools(NULL);
  5252. return MSG_POOLPRIO;
  5253. }
  5254. void validate_pool_priorities(void)
  5255. {
  5256. // TODO: this should probably do some sort of logging
  5257. int i, j;
  5258. bool used[total_pools];
  5259. bool valid[total_pools];
  5260. for (i = 0; i < total_pools; i++)
  5261. used[i] = valid[i] = false;
  5262. for (i = 0; i < total_pools; i++) {
  5263. if (pools[i]->prio >=0 && pools[i]->prio < total_pools) {
  5264. if (!used[pools[i]->prio]) {
  5265. valid[i] = true;
  5266. used[pools[i]->prio] = true;
  5267. }
  5268. }
  5269. }
  5270. for (i = 0; i < total_pools; i++) {
  5271. if (!valid[i]) {
  5272. for (j = 0; j < total_pools; j++) {
  5273. if (!used[j]) {
  5274. applog(LOG_WARNING, "Pool %d priority changed from %d to %d", i, pools[i]->prio, j);
  5275. pools[i]->prio = j;
  5276. used[j] = true;
  5277. break;
  5278. }
  5279. }
  5280. }
  5281. }
  5282. }
  5283. static void clear_pool_work(struct pool *pool);
  5284. /* Specifies whether we can switch to this pool or not. */
  5285. static bool pool_unusable(struct pool *pool)
  5286. {
  5287. if (pool->idle)
  5288. return true;
  5289. if (pool->enabled != POOL_ENABLED)
  5290. return true;
  5291. return false;
  5292. }
  5293. void switch_pools(struct pool *selected)
  5294. {
  5295. struct pool *pool, *last_pool;
  5296. int i, pool_no, next_pool;
  5297. cg_wlock(&control_lock);
  5298. last_pool = currentpool;
  5299. pool_no = currentpool->pool_no;
  5300. /* Switch selected to pool number 0 and move the rest down */
  5301. if (selected) {
  5302. if (selected->prio != 0) {
  5303. for (i = 0; i < total_pools; i++) {
  5304. pool = pools[i];
  5305. if (pool->prio < selected->prio)
  5306. pool->prio++;
  5307. }
  5308. selected->prio = 0;
  5309. }
  5310. }
  5311. switch (pool_strategy) {
  5312. /* All of these set to the master pool */
  5313. case POOL_BALANCE:
  5314. case POOL_FAILOVER:
  5315. case POOL_LOADBALANCE:
  5316. for (i = 0; i < total_pools; i++) {
  5317. pool = priority_pool(i);
  5318. if (pool_unusable(pool))
  5319. continue;
  5320. pool_no = pool->pool_no;
  5321. break;
  5322. }
  5323. break;
  5324. /* Both of these simply increment and cycle */
  5325. case POOL_ROUNDROBIN:
  5326. case POOL_ROTATE:
  5327. if (selected && !selected->idle) {
  5328. pool_no = selected->pool_no;
  5329. break;
  5330. }
  5331. next_pool = pool_no;
  5332. /* Select the next alive pool */
  5333. for (i = 1; i < total_pools; i++) {
  5334. next_pool++;
  5335. if (next_pool >= total_pools)
  5336. next_pool = 0;
  5337. pool = pools[next_pool];
  5338. if (pool_unusable(pool))
  5339. continue;
  5340. pool_no = next_pool;
  5341. break;
  5342. }
  5343. break;
  5344. default:
  5345. break;
  5346. }
  5347. currentpool = pools[pool_no];
  5348. pool = currentpool;
  5349. cg_wunlock(&control_lock);
  5350. /* Set the lagging flag to avoid pool not providing work fast enough
  5351. * messages in failover only mode since we have to get all fresh work
  5352. * as in restart_threads */
  5353. if (opt_fail_only)
  5354. pool_tset(pool, &pool->lagging);
  5355. if (pool != last_pool)
  5356. {
  5357. pool->block_id = 0;
  5358. if (pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  5359. applog(LOG_WARNING, "Switching to pool %d %s", pool->pool_no, pool->rpc_url);
  5360. if (pool_localgen(pool) || opt_fail_only)
  5361. clear_pool_work(last_pool);
  5362. }
  5363. }
  5364. mutex_lock(&lp_lock);
  5365. pthread_cond_broadcast(&lp_cond);
  5366. mutex_unlock(&lp_lock);
  5367. }
  5368. static void discard_work(struct work *work)
  5369. {
  5370. if (!work->clone && !work->rolls && !work->mined) {
  5371. if (work->pool) {
  5372. work->pool->discarded_work++;
  5373. work->pool->quota_used--;
  5374. work->pool->works--;
  5375. }
  5376. total_discarded++;
  5377. applog(LOG_DEBUG, "Discarded work");
  5378. } else
  5379. applog(LOG_DEBUG, "Discarded cloned or rolled work");
  5380. free_work(work);
  5381. }
  5382. static void wake_gws(void)
  5383. {
  5384. mutex_lock(stgd_lock);
  5385. pthread_cond_signal(&gws_cond);
  5386. mutex_unlock(stgd_lock);
  5387. }
  5388. static void discard_stale(void)
  5389. {
  5390. struct work *work, *tmp;
  5391. int stale = 0;
  5392. mutex_lock(stgd_lock);
  5393. HASH_ITER(hh, staged_work, work, tmp) {
  5394. if (stale_work(work, false)) {
  5395. HASH_DEL(staged_work, work);
  5396. discard_work(work);
  5397. stale++;
  5398. staged_full = false;
  5399. }
  5400. }
  5401. pthread_cond_signal(&gws_cond);
  5402. mutex_unlock(stgd_lock);
  5403. if (stale)
  5404. applog(LOG_DEBUG, "Discarded %d stales that didn't match current hash", stale);
  5405. }
  5406. bool stale_work_future(struct work *work, bool share, unsigned long ustime)
  5407. {
  5408. bool rv;
  5409. struct timeval tv, orig;
  5410. ldiv_t d;
  5411. d = ldiv(ustime, 1000000);
  5412. tv = (struct timeval){
  5413. .tv_sec = d.quot,
  5414. .tv_usec = d.rem,
  5415. };
  5416. orig = work->tv_staged;
  5417. timersub(&orig, &tv, &work->tv_staged);
  5418. rv = stale_work(work, share);
  5419. work->tv_staged = orig;
  5420. return rv;
  5421. }
  5422. static
  5423. void pool_update_work_restart_time(struct pool * const pool)
  5424. {
  5425. pool->work_restart_time = time(NULL);
  5426. get_timestamp(pool->work_restart_timestamp, sizeof(pool->work_restart_timestamp), pool->work_restart_time);
  5427. }
  5428. static void restart_threads(void)
  5429. {
  5430. struct pool *cp = current_pool();
  5431. int i;
  5432. struct thr_info *thr;
  5433. /* Artificially set the lagging flag to avoid pool not providing work
  5434. * fast enough messages after every long poll */
  5435. pool_tset(cp, &cp->lagging);
  5436. /* Discard staged work that is now stale */
  5437. discard_stale();
  5438. rd_lock(&mining_thr_lock);
  5439. for (i = 0; i < mining_threads; i++)
  5440. {
  5441. thr = mining_thr[i];
  5442. thr->work_restart = true;
  5443. }
  5444. for (i = 0; i < mining_threads; i++)
  5445. {
  5446. thr = mining_thr[i];
  5447. notifier_wake(thr->work_restart_notifier);
  5448. }
  5449. rd_unlock(&mining_thr_lock);
  5450. }
  5451. static
  5452. void blkhashstr(char *rv, const unsigned char *hash)
  5453. {
  5454. unsigned char hash_swap[32];
  5455. swap256(hash_swap, hash);
  5456. swap32tole(hash_swap, hash_swap, 32 / 4);
  5457. bin2hex(rv, hash_swap, 32);
  5458. }
  5459. static void set_curblock(char *hexstr, unsigned char *hash)
  5460. {
  5461. unsigned char hash_swap[32];
  5462. current_block_id = ((uint32_t*)hash)[0];
  5463. strcpy(current_block, hexstr);
  5464. swap256(hash_swap, hash);
  5465. swap32tole(hash_swap, hash_swap, 32 / 4);
  5466. cg_wlock(&ch_lock);
  5467. block_time = time(NULL);
  5468. __update_block_title(hash_swap);
  5469. free(current_fullhash);
  5470. current_fullhash = malloc(65);
  5471. bin2hex(current_fullhash, hash_swap, 32);
  5472. get_timestamp(blocktime, sizeof(blocktime), block_time);
  5473. cg_wunlock(&ch_lock);
  5474. applog(LOG_INFO, "New block: %s diff %s (%s)", current_hash, block_diff, net_hashrate);
  5475. }
  5476. /* Search to see if this string is from a block that has been seen before */
  5477. static bool block_exists(char *hexstr)
  5478. {
  5479. struct block *s;
  5480. rd_lock(&blk_lock);
  5481. HASH_FIND_STR(blocks, hexstr, s);
  5482. rd_unlock(&blk_lock);
  5483. if (s)
  5484. return true;
  5485. return false;
  5486. }
  5487. /* Tests if this work is from a block that has been seen before */
  5488. static inline bool from_existing_block(struct work *work)
  5489. {
  5490. char hexstr[37];
  5491. bool ret;
  5492. bin2hex(hexstr, work->data + 8, 18);
  5493. ret = block_exists(hexstr);
  5494. return ret;
  5495. }
  5496. static int block_sort(struct block *blocka, struct block *blockb)
  5497. {
  5498. return blocka->block_no - blockb->block_no;
  5499. }
  5500. static void set_blockdiff(const struct work *work)
  5501. {
  5502. unsigned char target[32];
  5503. double diff;
  5504. uint64_t diff64;
  5505. real_block_target(target, work->data);
  5506. diff = target_diff(target);
  5507. diff64 = diff;
  5508. suffix_string(diff64, block_diff, sizeof(block_diff), 0);
  5509. format_unit2(net_hashrate, sizeof(net_hashrate),
  5510. true, "h/s", H2B_SHORT, diff * 7158278, -1);
  5511. if (unlikely(current_diff != diff))
  5512. applog(LOG_NOTICE, "Network difficulty changed to %s (%s)", block_diff, net_hashrate);
  5513. current_diff = diff;
  5514. }
  5515. static bool test_work_current(struct work *work)
  5516. {
  5517. bool ret = true;
  5518. char hexstr[65];
  5519. if (work->mandatory)
  5520. return ret;
  5521. uint32_t block_id = ((uint32_t*)(work->data))[1];
  5522. /* Hack to work around dud work sneaking into test */
  5523. bin2hex(hexstr, work->data + 8, 18);
  5524. if (!strncmp(hexstr, "000000000000000000000000000000000000", 36))
  5525. goto out_free;
  5526. struct pool * const pool = work->pool;
  5527. /* Search to see if this block exists yet and if not, consider it a
  5528. * new block and set the current block details to this one */
  5529. if (!block_exists(hexstr))
  5530. {
  5531. struct block *s = calloc(sizeof(struct block), 1);
  5532. int deleted_block = 0;
  5533. ret = false;
  5534. if (unlikely(!s))
  5535. quit (1, "test_work_current OOM");
  5536. strcpy(s->hash, hexstr);
  5537. s->block_no = new_blocks++;
  5538. wr_lock(&blk_lock);
  5539. /* Only keep the last hour's worth of blocks in memory since
  5540. * work from blocks before this is virtually impossible and we
  5541. * want to prevent memory usage from continually rising */
  5542. if (HASH_COUNT(blocks) > 6)
  5543. {
  5544. struct block *oldblock;
  5545. HASH_SORT(blocks, block_sort);
  5546. oldblock = blocks;
  5547. deleted_block = oldblock->block_no;
  5548. HASH_DEL(blocks, oldblock);
  5549. free(oldblock);
  5550. }
  5551. HASH_ADD_STR(blocks, hash, s);
  5552. set_blockdiff(work);
  5553. wr_unlock(&blk_lock);
  5554. pool->block_id = block_id;
  5555. pool_update_work_restart_time(pool);
  5556. if (deleted_block)
  5557. applog(LOG_DEBUG, "Deleted block %d from database", deleted_block);
  5558. #if BLKMAKER_VERSION > 1
  5559. template_nonce = 0;
  5560. #endif
  5561. set_curblock(hexstr, &work->data[4]);
  5562. if (unlikely(new_blocks == 1))
  5563. goto out_free;
  5564. if (!work->stratum)
  5565. {
  5566. if (work->longpoll)
  5567. {
  5568. applog(LOG_NOTICE, "Longpoll from pool %d detected new block",
  5569. pool->pool_no);
  5570. }
  5571. else
  5572. if (have_longpoll)
  5573. applog(LOG_NOTICE, "New block detected on network before longpoll");
  5574. else
  5575. applog(LOG_NOTICE, "New block detected on network");
  5576. }
  5577. restart_threads();
  5578. }
  5579. else
  5580. {
  5581. bool restart = false;
  5582. if (unlikely(pool->block_id != block_id))
  5583. {
  5584. bool was_active = pool->block_id != 0;
  5585. pool->block_id = block_id;
  5586. pool_update_work_restart_time(pool);
  5587. if (!work->longpoll)
  5588. update_last_work(work);
  5589. if (was_active)
  5590. {
  5591. // Pool actively changed block
  5592. if (pool == current_pool())
  5593. restart = true;
  5594. if (block_id == current_block_id)
  5595. {
  5596. // Caught up, only announce if this pool is the one in use
  5597. if (restart)
  5598. applog(LOG_NOTICE, "%s %d caught up to new block",
  5599. work->longpoll ? "Longpoll from pool" : "Pool",
  5600. pool->pool_no);
  5601. }
  5602. else
  5603. {
  5604. // Switched to a block we know, but not the latest... why?
  5605. // This might detect pools trying to double-spend or 51%,
  5606. // but let's not make any accusations until it's had time
  5607. // in the real world.
  5608. blkhashstr(hexstr, &work->data[4]);
  5609. applog(LOG_WARNING, "%s %d is issuing work for an old block: %s",
  5610. work->longpoll ? "Longpoll from pool" : "Pool",
  5611. pool->pool_no,
  5612. hexstr);
  5613. }
  5614. }
  5615. }
  5616. if (work->longpoll)
  5617. {
  5618. struct pool * const cp = current_pool();
  5619. ++pool->work_restart_id;
  5620. update_last_work(work);
  5621. pool_update_work_restart_time(pool);
  5622. applog(
  5623. ((!opt_quiet_work_updates) && pool_actively_in_use(pool, cp) ? LOG_NOTICE : LOG_DEBUG),
  5624. "Longpoll from pool %d requested work update",
  5625. pool->pool_no);
  5626. if ((!restart) && pool == cp)
  5627. restart = true;
  5628. }
  5629. if (restart)
  5630. restart_threads();
  5631. }
  5632. work->longpoll = false;
  5633. out_free:
  5634. return ret;
  5635. }
  5636. static int tv_sort(struct work *worka, struct work *workb)
  5637. {
  5638. return worka->tv_staged.tv_sec - workb->tv_staged.tv_sec;
  5639. }
  5640. static bool work_rollable(struct work *work)
  5641. {
  5642. return (!work->clone && work->rolltime);
  5643. }
  5644. static bool hash_push(struct work *work)
  5645. {
  5646. bool rc = true;
  5647. mutex_lock(stgd_lock);
  5648. if (work_rollable(work))
  5649. staged_rollable++;
  5650. if (likely(!getq->frozen)) {
  5651. HASH_ADD_INT(staged_work, id, work);
  5652. HASH_SORT(staged_work, tv_sort);
  5653. } else
  5654. rc = false;
  5655. pthread_cond_broadcast(&getq->cond);
  5656. mutex_unlock(stgd_lock);
  5657. return rc;
  5658. }
  5659. static void stage_work(struct work *work)
  5660. {
  5661. applog(LOG_DEBUG, "Pushing work %d from pool %d to hash queue",
  5662. work->id, work->pool->pool_no);
  5663. work->work_restart_id = work->pool->work_restart_id;
  5664. work->pool->last_work_time = time(NULL);
  5665. cgtime(&work->pool->tv_last_work_time);
  5666. test_work_current(work);
  5667. work->pool->works++;
  5668. hash_push(work);
  5669. }
  5670. #ifdef HAVE_CURSES
  5671. int curses_int(const char *query)
  5672. {
  5673. int ret;
  5674. char *cvar;
  5675. cvar = curses_input(query);
  5676. if (unlikely(!cvar))
  5677. return -1;
  5678. ret = atoi(cvar);
  5679. free(cvar);
  5680. return ret;
  5681. }
  5682. #endif
  5683. #ifdef HAVE_CURSES
  5684. static bool input_pool(bool live);
  5685. #endif
  5686. #ifdef HAVE_CURSES
  5687. static void display_pool_summary(struct pool *pool)
  5688. {
  5689. double efficiency = 0.0;
  5690. char xfer[ALLOC_H2B_NOUNIT+ALLOC_H2B_SPACED+4+1], bw[ALLOC_H2B_NOUNIT+ALLOC_H2B_SPACED+6+1];
  5691. int pool_secs;
  5692. if (curses_active_locked()) {
  5693. wlog("Pool: %s\n", pool->rpc_url);
  5694. if (pool->solved)
  5695. wlog("SOLVED %d BLOCK%s!\n", pool->solved, pool->solved > 1 ? "S" : "");
  5696. if (!pool->has_stratum)
  5697. wlog("%s own long-poll support\n", pool->lp_url ? "Has" : "Does not have");
  5698. wlog(" Queued work requests: %d\n", pool->getwork_requested);
  5699. wlog(" Share submissions: %d\n", pool->accepted + pool->rejected);
  5700. wlog(" Accepted shares: %d\n", pool->accepted);
  5701. wlog(" Rejected shares: %d + %d stale (%.2f%%)\n",
  5702. pool->rejected, pool->stale_shares,
  5703. (float)(pool->rejected + pool->stale_shares) / (float)(pool->rejected + pool->stale_shares + pool->accepted)
  5704. );
  5705. wlog(" Accepted difficulty shares: %1.f\n", pool->diff_accepted);
  5706. wlog(" Rejected difficulty shares: %1.f\n", pool->diff_rejected);
  5707. pool_secs = timer_elapsed(&pool->cgminer_stats.start_tv, NULL);
  5708. wlog(" Network transfer: %s (%s)\n",
  5709. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  5710. (float)pool->cgminer_pool_stats.net_bytes_received,
  5711. (float)pool->cgminer_pool_stats.net_bytes_sent),
  5712. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  5713. (float)(pool->cgminer_pool_stats.net_bytes_received / pool_secs),
  5714. (float)(pool->cgminer_pool_stats.net_bytes_sent / pool_secs)));
  5715. uint64_t pool_bytes_xfer = pool->cgminer_pool_stats.net_bytes_received + pool->cgminer_pool_stats.net_bytes_sent;
  5716. efficiency = pool_bytes_xfer ? pool->diff_accepted * 2048. / pool_bytes_xfer : 0.0;
  5717. wlog(" Efficiency (accepted * difficulty / 2 KB): %.2f\n", efficiency);
  5718. wlog(" Items worked on: %d\n", pool->works);
  5719. wlog(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  5720. wlog(" Unable to get work from server occasions: %d\n", pool->getfail_occasions);
  5721. wlog(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  5722. unlock_curses();
  5723. }
  5724. }
  5725. #endif
  5726. /* We can't remove the memory used for this struct pool because there may
  5727. * still be work referencing it. We just remove it from the pools list */
  5728. void remove_pool(struct pool *pool)
  5729. {
  5730. int i, last_pool = total_pools - 1;
  5731. struct pool *other;
  5732. /* Boost priority of any lower prio than this one */
  5733. for (i = 0; i < total_pools; i++) {
  5734. other = pools[i];
  5735. if (other->prio > pool->prio)
  5736. other->prio--;
  5737. }
  5738. if (pool->pool_no < last_pool) {
  5739. /* Swap the last pool for this one */
  5740. (pools[last_pool])->pool_no = pool->pool_no;
  5741. pools[pool->pool_no] = pools[last_pool];
  5742. }
  5743. /* Give it an invalid number */
  5744. pool->pool_no = total_pools;
  5745. pool->removed = true;
  5746. pool->has_stratum = false;
  5747. total_pools--;
  5748. }
  5749. /* add a mutex if this needs to be thread safe in the future */
  5750. static struct JE {
  5751. char *buf;
  5752. struct JE *next;
  5753. } *jedata = NULL;
  5754. static void json_escape_free()
  5755. {
  5756. struct JE *jeptr = jedata;
  5757. struct JE *jenext;
  5758. jedata = NULL;
  5759. while (jeptr) {
  5760. jenext = jeptr->next;
  5761. free(jeptr->buf);
  5762. free(jeptr);
  5763. jeptr = jenext;
  5764. }
  5765. }
  5766. static
  5767. char *json_escape(const char *str)
  5768. {
  5769. struct JE *jeptr;
  5770. char *buf, *ptr;
  5771. /* 2x is the max, may as well just allocate that */
  5772. ptr = buf = malloc(strlen(str) * 2 + 1);
  5773. jeptr = malloc(sizeof(*jeptr));
  5774. jeptr->buf = buf;
  5775. jeptr->next = jedata;
  5776. jedata = jeptr;
  5777. while (*str) {
  5778. if (*str == '\\' || *str == '"')
  5779. *(ptr++) = '\\';
  5780. *(ptr++) = *(str++);
  5781. }
  5782. *ptr = '\0';
  5783. return buf;
  5784. }
  5785. static
  5786. void _write_config_string_elist(FILE *fcfg, const char *configname, struct string_elist * const elist)
  5787. {
  5788. if (!elist)
  5789. return;
  5790. static struct string_elist *entry;
  5791. fprintf(fcfg, ",\n\"%s\" : [", configname);
  5792. bool first = true;
  5793. DL_FOREACH(elist, entry)
  5794. {
  5795. const char * const s = entry->string;
  5796. fprintf(fcfg, "%s\n\t\"%s\"", first ? "" : ",", json_escape(s));
  5797. first = false;
  5798. }
  5799. fprintf(fcfg, "\n]");
  5800. }
  5801. void write_config(FILE *fcfg)
  5802. {
  5803. int i;
  5804. /* Write pool values */
  5805. fputs("{\n\"pools\" : [", fcfg);
  5806. for(i = 0; i < total_pools; i++) {
  5807. struct pool *pool = pools[i];
  5808. if (pool->quota != 1) {
  5809. fprintf(fcfg, "%s\n\t{\n\t\t\"quota\" : \"%d;%s\",", i > 0 ? "," : "",
  5810. pool->quota,
  5811. json_escape(pool->rpc_url));
  5812. } else {
  5813. fprintf(fcfg, "%s\n\t{\n\t\t\"url\" : \"%s\",", i > 0 ? "," : "",
  5814. json_escape(pool->rpc_url));
  5815. }
  5816. if (pool->rpc_proxy)
  5817. fprintf(fcfg, "\n\t\t\"pool-proxy\" : \"%s\",", json_escape(pool->rpc_proxy));
  5818. fprintf(fcfg, "\n\t\t\"user\" : \"%s\",", json_escape(pool->rpc_user));
  5819. fprintf(fcfg, "\n\t\t\"pass\" : \"%s\",", json_escape(pool->rpc_pass));
  5820. fprintf(fcfg, "\n\t\t\"pool-priority\" : \"%d\"", pool->prio);
  5821. if (pool->force_rollntime)
  5822. fprintf(fcfg, ",\n\t\t\"force-rollntime\" : %d", pool->force_rollntime);
  5823. fprintf(fcfg, "\n\t}");
  5824. }
  5825. fputs("\n]\n", fcfg);
  5826. #ifdef HAVE_OPENCL
  5827. write_config_opencl(fcfg);
  5828. #endif
  5829. #ifdef WANT_CPUMINE
  5830. fprintf(fcfg, ",\n\"algo\" : \"%s\"", algo_names[opt_algo]);
  5831. #endif
  5832. /* Simple bool and int options */
  5833. struct opt_table *opt;
  5834. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  5835. char *p, *name = strdup(opt->names);
  5836. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  5837. if (p[1] != '-')
  5838. continue;
  5839. if (opt->type & OPT_NOARG &&
  5840. ((void *)opt->cb == (void *)opt_set_bool || (void *)opt->cb == (void *)opt_set_invbool) &&
  5841. (*(bool *)opt->u.arg == ((void *)opt->cb == (void *)opt_set_bool)))
  5842. fprintf(fcfg, ",\n\"%s\" : true", p+2);
  5843. if (opt->type & OPT_HASARG &&
  5844. ((void *)opt->cb_arg == (void *)set_int_0_to_9999 ||
  5845. (void *)opt->cb_arg == (void *)set_int_1_to_65535 ||
  5846. (void *)opt->cb_arg == (void *)set_int_0_to_10 ||
  5847. (void *)opt->cb_arg == (void *)set_int_1_to_10) &&
  5848. opt->desc != opt_hidden &&
  5849. 0 <= *(int *)opt->u.arg)
  5850. fprintf(fcfg, ",\n\"%s\" : \"%d\"", p+2, *(int *)opt->u.arg);
  5851. }
  5852. }
  5853. /* Special case options */
  5854. if (request_target_str)
  5855. {
  5856. if (request_pdiff == (long)request_pdiff)
  5857. fprintf(fcfg, ",\n\"request-diff\" : %ld", (long)request_pdiff);
  5858. else
  5859. fprintf(fcfg, ",\n\"request-diff\" : %f", request_pdiff);
  5860. }
  5861. fprintf(fcfg, ",\n\"shares\" : %g", opt_shares);
  5862. if (pool_strategy == POOL_BALANCE)
  5863. fputs(",\n\"balance\" : true", fcfg);
  5864. if (pool_strategy == POOL_LOADBALANCE)
  5865. fputs(",\n\"load-balance\" : true", fcfg);
  5866. if (pool_strategy == POOL_ROUNDROBIN)
  5867. fputs(",\n\"round-robin\" : true", fcfg);
  5868. if (pool_strategy == POOL_ROTATE)
  5869. fprintf(fcfg, ",\n\"rotate\" : \"%d\"", opt_rotate_period);
  5870. #if defined(unix) || defined(__APPLE__)
  5871. if (opt_stderr_cmd && *opt_stderr_cmd)
  5872. fprintf(fcfg, ",\n\"monitor\" : \"%s\"", json_escape(opt_stderr_cmd));
  5873. #endif // defined(unix)
  5874. if (opt_kernel_path && *opt_kernel_path) {
  5875. char *kpath = strdup(opt_kernel_path);
  5876. if (kpath[strlen(kpath)-1] == '/')
  5877. kpath[strlen(kpath)-1] = 0;
  5878. fprintf(fcfg, ",\n\"kernel-path\" : \"%s\"", json_escape(kpath));
  5879. free(kpath);
  5880. }
  5881. if (schedstart.enable)
  5882. fprintf(fcfg, ",\n\"sched-time\" : \"%d:%d\"", schedstart.tm.tm_hour, schedstart.tm.tm_min);
  5883. if (schedstop.enable)
  5884. fprintf(fcfg, ",\n\"stop-time\" : \"%d:%d\"", schedstop.tm.tm_hour, schedstop.tm.tm_min);
  5885. if (opt_socks_proxy && *opt_socks_proxy)
  5886. fprintf(fcfg, ",\n\"socks-proxy\" : \"%s\"", json_escape(opt_socks_proxy));
  5887. _write_config_string_elist(fcfg, "scan", scan_devices);
  5888. #ifdef USE_LIBMICROHTTPD
  5889. if (httpsrv_port != -1)
  5890. fprintf(fcfg, ",\n\"http-port\" : %d", httpsrv_port);
  5891. #endif
  5892. #ifdef USE_LIBEVENT
  5893. if (stratumsrv_port != -1)
  5894. fprintf(fcfg, ",\n\"stratum-port\" : %d", stratumsrv_port);
  5895. #endif
  5896. _write_config_string_elist(fcfg, "device", opt_devices_enabled_list);
  5897. _write_config_string_elist(fcfg, "set-device", opt_set_device_list);
  5898. if (opt_api_allow)
  5899. fprintf(fcfg, ",\n\"api-allow\" : \"%s\"", json_escape(opt_api_allow));
  5900. if (strcmp(opt_api_mcast_addr, API_MCAST_ADDR) != 0)
  5901. fprintf(fcfg, ",\n\"api-mcast-addr\" : \"%s\"", json_escape(opt_api_mcast_addr));
  5902. if (strcmp(opt_api_mcast_code, API_MCAST_CODE) != 0)
  5903. fprintf(fcfg, ",\n\"api-mcast-code\" : \"%s\"", json_escape(opt_api_mcast_code));
  5904. if (*opt_api_mcast_des)
  5905. fprintf(fcfg, ",\n\"api-mcast-des\" : \"%s\"", json_escape(opt_api_mcast_des));
  5906. if (strcmp(opt_api_description, PACKAGE_STRING) != 0)
  5907. fprintf(fcfg, ",\n\"api-description\" : \"%s\"", json_escape(opt_api_description));
  5908. if (opt_api_groups)
  5909. fprintf(fcfg, ",\n\"api-groups\" : \"%s\"", json_escape(opt_api_groups));
  5910. fputs("\n}\n", fcfg);
  5911. json_escape_free();
  5912. }
  5913. void zero_bestshare(void)
  5914. {
  5915. int i;
  5916. best_diff = 0;
  5917. suffix_string(best_diff, best_share, sizeof(best_share), 0);
  5918. for (i = 0; i < total_pools; i++) {
  5919. struct pool *pool = pools[i];
  5920. pool->best_diff = 0;
  5921. }
  5922. }
  5923. void zero_stats(void)
  5924. {
  5925. int i;
  5926. applog(LOG_DEBUG, "Zeroing stats");
  5927. cgtime(&total_tv_start);
  5928. miner_started = total_tv_start;
  5929. total_rolling = 0;
  5930. total_mhashes_done = 0;
  5931. total_getworks = 0;
  5932. total_accepted = 0;
  5933. total_rejected = 0;
  5934. hw_errors = 0;
  5935. total_stale = 0;
  5936. total_discarded = 0;
  5937. total_bytes_rcvd = total_bytes_sent = 0;
  5938. new_blocks = 0;
  5939. local_work = 0;
  5940. total_go = 0;
  5941. total_ro = 0;
  5942. total_secs = 1.0;
  5943. total_diff1 = 0;
  5944. total_bad_diff1 = 0;
  5945. found_blocks = 0;
  5946. total_diff_accepted = 0;
  5947. total_diff_rejected = 0;
  5948. total_diff_stale = 0;
  5949. #ifdef HAVE_CURSES
  5950. awidth = rwidth = swidth = hwwidth = 1;
  5951. #endif
  5952. for (i = 0; i < total_pools; i++) {
  5953. struct pool *pool = pools[i];
  5954. pool->getwork_requested = 0;
  5955. pool->accepted = 0;
  5956. pool->rejected = 0;
  5957. pool->solved = 0;
  5958. pool->getwork_requested = 0;
  5959. pool->stale_shares = 0;
  5960. pool->discarded_work = 0;
  5961. pool->getfail_occasions = 0;
  5962. pool->remotefail_occasions = 0;
  5963. pool->last_share_time = 0;
  5964. pool->diff1 = 0;
  5965. pool->diff_accepted = 0;
  5966. pool->diff_rejected = 0;
  5967. pool->diff_stale = 0;
  5968. pool->last_share_diff = 0;
  5969. pool->cgminer_stats.start_tv = total_tv_start;
  5970. pool->cgminer_stats.getwork_calls = 0;
  5971. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  5972. pool->cgminer_stats.getwork_wait_max.tv_sec = 0;
  5973. pool->cgminer_stats.getwork_wait_max.tv_usec = 0;
  5974. pool->cgminer_pool_stats.getwork_calls = 0;
  5975. pool->cgminer_pool_stats.getwork_attempts = 0;
  5976. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  5977. pool->cgminer_pool_stats.getwork_wait_max.tv_sec = 0;
  5978. pool->cgminer_pool_stats.getwork_wait_max.tv_usec = 0;
  5979. pool->cgminer_pool_stats.min_diff = 0;
  5980. pool->cgminer_pool_stats.max_diff = 0;
  5981. pool->cgminer_pool_stats.min_diff_count = 0;
  5982. pool->cgminer_pool_stats.max_diff_count = 0;
  5983. pool->cgminer_pool_stats.times_sent = 0;
  5984. pool->cgminer_pool_stats.bytes_sent = 0;
  5985. pool->cgminer_pool_stats.net_bytes_sent = 0;
  5986. pool->cgminer_pool_stats.times_received = 0;
  5987. pool->cgminer_pool_stats.bytes_received = 0;
  5988. pool->cgminer_pool_stats.net_bytes_received = 0;
  5989. }
  5990. zero_bestshare();
  5991. for (i = 0; i < total_devices; ++i) {
  5992. struct cgpu_info *cgpu = get_devices(i);
  5993. mutex_lock(&hash_lock);
  5994. cgpu->total_mhashes = 0;
  5995. cgpu->accepted = 0;
  5996. cgpu->rejected = 0;
  5997. cgpu->stale = 0;
  5998. cgpu->hw_errors = 0;
  5999. cgpu->utility = 0.0;
  6000. cgpu->utility_diff1 = 0;
  6001. cgpu->last_share_pool_time = 0;
  6002. cgpu->bad_diff1 = 0;
  6003. cgpu->diff1 = 0;
  6004. cgpu->diff_accepted = 0;
  6005. cgpu->diff_rejected = 0;
  6006. cgpu->diff_stale = 0;
  6007. cgpu->last_share_diff = 0;
  6008. cgpu->thread_fail_init_count = 0;
  6009. cgpu->thread_zero_hash_count = 0;
  6010. cgpu->thread_fail_queue_count = 0;
  6011. cgpu->dev_sick_idle_60_count = 0;
  6012. cgpu->dev_dead_idle_600_count = 0;
  6013. cgpu->dev_nostart_count = 0;
  6014. cgpu->dev_over_heat_count = 0;
  6015. cgpu->dev_thermal_cutoff_count = 0;
  6016. cgpu->dev_comms_error_count = 0;
  6017. cgpu->dev_throttle_count = 0;
  6018. cgpu->cgminer_stats.start_tv = total_tv_start;
  6019. cgpu->cgminer_stats.getwork_calls = 0;
  6020. cgpu->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6021. cgpu->cgminer_stats.getwork_wait_max.tv_sec = 0;
  6022. cgpu->cgminer_stats.getwork_wait_max.tv_usec = 0;
  6023. mutex_unlock(&hash_lock);
  6024. }
  6025. }
  6026. #ifdef HAVE_CURSES
  6027. static
  6028. void loginput_mode(const int size)
  6029. {
  6030. clear_logwin();
  6031. loginput_size = size;
  6032. check_winsizes();
  6033. }
  6034. static void display_pools(void)
  6035. {
  6036. struct pool *pool;
  6037. int selected, i, j;
  6038. char input;
  6039. loginput_mode(7 + total_pools);
  6040. immedok(logwin, true);
  6041. updated:
  6042. for (j = 0; j < total_pools; j++) {
  6043. for (i = 0; i < total_pools; i++) {
  6044. pool = pools[i];
  6045. if (pool->prio != j)
  6046. continue;
  6047. if (pool == current_pool())
  6048. wattron(logwin, A_BOLD);
  6049. if (pool->enabled != POOL_ENABLED)
  6050. wattron(logwin, A_DIM);
  6051. wlogprint("%d: ", pool->prio);
  6052. switch (pool->enabled) {
  6053. case POOL_ENABLED:
  6054. wlogprint("Enabled ");
  6055. break;
  6056. case POOL_DISABLED:
  6057. wlogprint("Disabled ");
  6058. break;
  6059. case POOL_REJECTING:
  6060. wlogprint("Rejectin ");
  6061. break;
  6062. }
  6063. _wlogprint(pool_proto_str(pool));
  6064. wlogprint(" Quota %d Pool %d: %s User:%s\n",
  6065. pool->quota,
  6066. pool->pool_no,
  6067. pool->rpc_url, pool->rpc_user);
  6068. wattroff(logwin, A_BOLD | A_DIM);
  6069. break; //for (i = 0; i < total_pools; i++)
  6070. }
  6071. }
  6072. retry:
  6073. wlogprint("\nCurrent pool management strategy: %s\n",
  6074. strategies[pool_strategy].s);
  6075. if (pool_strategy == POOL_ROTATE)
  6076. wlogprint("Set to rotate every %d minutes\n", opt_rotate_period);
  6077. wlogprint("[F]ailover only %s\n", opt_fail_only ? "enabled" : "disabled");
  6078. wlogprint("Pool [A]dd [R]emove [D]isable [E]nable [P]rioritize [Q]uota change\n");
  6079. wlogprint("[C]hange management strategy [S]witch pool [I]nformation\n");
  6080. wlogprint("Or press any other key to continue\n");
  6081. logwin_update();
  6082. input = getch();
  6083. if (!strncasecmp(&input, "a", 1)) {
  6084. if (opt_benchmark)
  6085. {
  6086. wlogprint("Cannot add pools in benchmark mode");
  6087. goto retry;
  6088. }
  6089. input_pool(true);
  6090. goto updated;
  6091. } else if (!strncasecmp(&input, "r", 1)) {
  6092. if (total_pools <= 1) {
  6093. wlogprint("Cannot remove last pool");
  6094. goto retry;
  6095. }
  6096. selected = curses_int("Select pool number");
  6097. if (selected < 0 || selected >= total_pools) {
  6098. wlogprint("Invalid selection\n");
  6099. goto retry;
  6100. }
  6101. pool = pools[selected];
  6102. if (pool == current_pool())
  6103. switch_pools(NULL);
  6104. if (pool == current_pool()) {
  6105. wlogprint("Unable to remove pool due to activity\n");
  6106. goto retry;
  6107. }
  6108. disable_pool(pool);
  6109. remove_pool(pool);
  6110. goto updated;
  6111. } else if (!strncasecmp(&input, "s", 1)) {
  6112. selected = curses_int("Select pool number");
  6113. if (selected < 0 || selected >= total_pools) {
  6114. wlogprint("Invalid selection\n");
  6115. goto retry;
  6116. }
  6117. pool = pools[selected];
  6118. enable_pool(pool);
  6119. switch_pools(pool);
  6120. goto updated;
  6121. } else if (!strncasecmp(&input, "d", 1)) {
  6122. if (enabled_pools <= 1) {
  6123. wlogprint("Cannot disable last pool");
  6124. goto retry;
  6125. }
  6126. selected = curses_int("Select pool number");
  6127. if (selected < 0 || selected >= total_pools) {
  6128. wlogprint("Invalid selection\n");
  6129. goto retry;
  6130. }
  6131. pool = pools[selected];
  6132. disable_pool(pool);
  6133. if (pool == current_pool())
  6134. switch_pools(NULL);
  6135. goto updated;
  6136. } else if (!strncasecmp(&input, "e", 1)) {
  6137. selected = curses_int("Select pool number");
  6138. if (selected < 0 || selected >= total_pools) {
  6139. wlogprint("Invalid selection\n");
  6140. goto retry;
  6141. }
  6142. pool = pools[selected];
  6143. enable_pool(pool);
  6144. if (pool->prio < current_pool()->prio)
  6145. switch_pools(pool);
  6146. goto updated;
  6147. } else if (!strncasecmp(&input, "c", 1)) {
  6148. for (i = 0; i <= TOP_STRATEGY; i++)
  6149. wlogprint("%d: %s\n", i, strategies[i].s);
  6150. selected = curses_int("Select strategy number type");
  6151. if (selected < 0 || selected > TOP_STRATEGY) {
  6152. wlogprint("Invalid selection\n");
  6153. goto retry;
  6154. }
  6155. if (selected == POOL_ROTATE) {
  6156. opt_rotate_period = curses_int("Select interval in minutes");
  6157. if (opt_rotate_period < 0 || opt_rotate_period > 9999) {
  6158. opt_rotate_period = 0;
  6159. wlogprint("Invalid selection\n");
  6160. goto retry;
  6161. }
  6162. }
  6163. pool_strategy = selected;
  6164. switch_pools(NULL);
  6165. goto updated;
  6166. } else if (!strncasecmp(&input, "i", 1)) {
  6167. selected = curses_int("Select pool number");
  6168. if (selected < 0 || selected >= total_pools) {
  6169. wlogprint("Invalid selection\n");
  6170. goto retry;
  6171. }
  6172. pool = pools[selected];
  6173. display_pool_summary(pool);
  6174. goto retry;
  6175. } else if (!strncasecmp(&input, "q", 1)) {
  6176. selected = curses_int("Select pool number");
  6177. if (selected < 0 || selected >= total_pools) {
  6178. wlogprint("Invalid selection\n");
  6179. goto retry;
  6180. }
  6181. pool = pools[selected];
  6182. selected = curses_int("Set quota");
  6183. if (selected < 0) {
  6184. wlogprint("Invalid negative quota\n");
  6185. goto retry;
  6186. }
  6187. pool->quota = selected;
  6188. adjust_quota_gcd();
  6189. goto updated;
  6190. } else if (!strncasecmp(&input, "f", 1)) {
  6191. opt_fail_only ^= true;
  6192. goto updated;
  6193. } else if (!strncasecmp(&input, "p", 1)) {
  6194. char *prilist = curses_input("Enter new pool priority (comma separated list)");
  6195. if (!prilist)
  6196. {
  6197. wlogprint("Not changing priorities\n");
  6198. goto retry;
  6199. }
  6200. int res = prioritize_pools(prilist, &i);
  6201. free(prilist);
  6202. switch (res) {
  6203. case MSG_NOPOOL:
  6204. wlogprint("No pools\n");
  6205. goto retry;
  6206. case MSG_MISPID:
  6207. wlogprint("Missing pool id parameter\n");
  6208. goto retry;
  6209. case MSG_INVPID:
  6210. wlogprint("Invalid pool id %d - range is 0 - %d\n", i, total_pools - 1);
  6211. goto retry;
  6212. case MSG_DUPPID:
  6213. wlogprint("Duplicate pool specified %d\n", i);
  6214. goto retry;
  6215. case MSG_POOLPRIO:
  6216. default:
  6217. goto updated;
  6218. }
  6219. }
  6220. immedok(logwin, false);
  6221. loginput_mode(0);
  6222. }
  6223. static const char *summary_detail_level_str(void)
  6224. {
  6225. if (opt_compact)
  6226. return "compact";
  6227. if (opt_show_procs)
  6228. return "processors";
  6229. return "devices";
  6230. }
  6231. static void display_options(void)
  6232. {
  6233. int selected;
  6234. char input;
  6235. immedok(logwin, true);
  6236. loginput_mode(12);
  6237. retry:
  6238. clear_logwin();
  6239. wlogprint("[N]ormal [C]lear [S]ilent mode (disable all output)\n");
  6240. wlogprint("[D]ebug:%s\n[P]er-device:%s\n[Q]uiet:%s\n[V]erbose:%s\n"
  6241. "[R]PC debug:%s\n[W]orkTime details:%s\nsu[M]mary detail level:%s\n"
  6242. "[L]og interval:%d\nS[T]atistical counts: %s\n[Z]ero statistics\n",
  6243. opt_debug_console ? "on" : "off",
  6244. want_per_device_stats? "on" : "off",
  6245. opt_quiet ? "on" : "off",
  6246. opt_log_output ? "on" : "off",
  6247. opt_protocol ? "on" : "off",
  6248. opt_worktime ? "on" : "off",
  6249. summary_detail_level_str(),
  6250. opt_log_interval,
  6251. opt_weighed_stats ? "weighed" : "absolute");
  6252. wlogprint("Select an option or any other key to return\n");
  6253. logwin_update();
  6254. input = getch();
  6255. if (!strncasecmp(&input, "q", 1)) {
  6256. opt_quiet ^= true;
  6257. wlogprint("Quiet mode %s\n", opt_quiet ? "enabled" : "disabled");
  6258. goto retry;
  6259. } else if (!strncasecmp(&input, "v", 1)) {
  6260. opt_log_output ^= true;
  6261. if (opt_log_output)
  6262. opt_quiet = false;
  6263. wlogprint("Verbose mode %s\n", opt_log_output ? "enabled" : "disabled");
  6264. goto retry;
  6265. } else if (!strncasecmp(&input, "n", 1)) {
  6266. opt_log_output = false;
  6267. opt_debug_console = false;
  6268. opt_quiet = false;
  6269. opt_protocol = false;
  6270. opt_compact = false;
  6271. opt_show_procs = false;
  6272. devsummaryYOffset = 0;
  6273. want_per_device_stats = false;
  6274. wlogprint("Output mode reset to normal\n");
  6275. switch_logsize();
  6276. goto retry;
  6277. } else if (!strncasecmp(&input, "d", 1)) {
  6278. opt_debug = true;
  6279. opt_debug_console ^= true;
  6280. opt_log_output = opt_debug_console;
  6281. if (opt_debug_console)
  6282. opt_quiet = false;
  6283. wlogprint("Debug mode %s\n", opt_debug_console ? "enabled" : "disabled");
  6284. goto retry;
  6285. } else if (!strncasecmp(&input, "m", 1)) {
  6286. if (opt_compact)
  6287. opt_compact = false;
  6288. else
  6289. if (!opt_show_procs)
  6290. opt_show_procs = true;
  6291. else
  6292. {
  6293. opt_compact = true;
  6294. opt_show_procs = false;
  6295. devsummaryYOffset = 0;
  6296. }
  6297. wlogprint("su[M]mary detail level changed to: %s\n", summary_detail_level_str());
  6298. switch_logsize();
  6299. goto retry;
  6300. } else if (!strncasecmp(&input, "p", 1)) {
  6301. want_per_device_stats ^= true;
  6302. opt_log_output = want_per_device_stats;
  6303. wlogprint("Per-device stats %s\n", want_per_device_stats ? "enabled" : "disabled");
  6304. goto retry;
  6305. } else if (!strncasecmp(&input, "r", 1)) {
  6306. opt_protocol ^= true;
  6307. if (opt_protocol)
  6308. opt_quiet = false;
  6309. wlogprint("RPC protocol debugging %s\n", opt_protocol ? "enabled" : "disabled");
  6310. goto retry;
  6311. } else if (!strncasecmp(&input, "c", 1))
  6312. clear_logwin();
  6313. else if (!strncasecmp(&input, "l", 1)) {
  6314. selected = curses_int("Interval in seconds");
  6315. if (selected < 0 || selected > 9999) {
  6316. wlogprint("Invalid selection\n");
  6317. goto retry;
  6318. }
  6319. opt_log_interval = selected;
  6320. wlogprint("Log interval set to %d seconds\n", opt_log_interval);
  6321. goto retry;
  6322. } else if (!strncasecmp(&input, "s", 1)) {
  6323. opt_realquiet = true;
  6324. } else if (!strncasecmp(&input, "w", 1)) {
  6325. opt_worktime ^= true;
  6326. wlogprint("WorkTime details %s\n", opt_worktime ? "enabled" : "disabled");
  6327. goto retry;
  6328. } else if (!strncasecmp(&input, "t", 1)) {
  6329. opt_weighed_stats ^= true;
  6330. wlogprint("Now displaying %s statistics\n", opt_weighed_stats ? "weighed" : "absolute");
  6331. goto retry;
  6332. } else if (!strncasecmp(&input, "z", 1)) {
  6333. zero_stats();
  6334. goto retry;
  6335. }
  6336. immedok(logwin, false);
  6337. loginput_mode(0);
  6338. }
  6339. #endif
  6340. void default_save_file(char *filename)
  6341. {
  6342. #if defined(unix) || defined(__APPLE__)
  6343. if (getenv("HOME") && *getenv("HOME")) {
  6344. strcpy(filename, getenv("HOME"));
  6345. strcat(filename, "/");
  6346. }
  6347. else
  6348. strcpy(filename, "");
  6349. strcat(filename, ".bfgminer/");
  6350. mkdir(filename, 0777);
  6351. #else
  6352. strcpy(filename, "");
  6353. #endif
  6354. strcat(filename, def_conf);
  6355. }
  6356. #ifdef HAVE_CURSES
  6357. static void set_options(void)
  6358. {
  6359. int selected;
  6360. char input;
  6361. immedok(logwin, true);
  6362. loginput_mode(8);
  6363. retry:
  6364. wlogprint("\n[L]ongpoll: %s\n", want_longpoll ? "On" : "Off");
  6365. wlogprint("[Q]ueue: %d\n[S]cantime: %d\n[E]xpiry: %d\n[R]etries: %d\n"
  6366. "[W]rite config file\n[B]FGMiner restart\n",
  6367. opt_queue, opt_scantime, opt_expiry, opt_retries);
  6368. wlogprint("Select an option or any other key to return\n");
  6369. logwin_update();
  6370. input = getch();
  6371. if (!strncasecmp(&input, "q", 1)) {
  6372. selected = curses_int("Extra work items to queue");
  6373. if (selected < 0 || selected > 9999) {
  6374. wlogprint("Invalid selection\n");
  6375. goto retry;
  6376. }
  6377. opt_queue = selected;
  6378. goto retry;
  6379. } else if (!strncasecmp(&input, "l", 1)) {
  6380. if (want_longpoll)
  6381. stop_longpoll();
  6382. else
  6383. start_longpoll();
  6384. applog(LOG_WARNING, "Longpoll %s", want_longpoll ? "enabled" : "disabled");
  6385. goto retry;
  6386. } else if (!strncasecmp(&input, "s", 1)) {
  6387. selected = curses_int("Set scantime in seconds");
  6388. if (selected < 0 || selected > 9999) {
  6389. wlogprint("Invalid selection\n");
  6390. goto retry;
  6391. }
  6392. opt_scantime = selected;
  6393. goto retry;
  6394. } else if (!strncasecmp(&input, "e", 1)) {
  6395. selected = curses_int("Set expiry time in seconds");
  6396. if (selected < 0 || selected > 9999) {
  6397. wlogprint("Invalid selection\n");
  6398. goto retry;
  6399. }
  6400. opt_expiry = selected;
  6401. goto retry;
  6402. } else if (!strncasecmp(&input, "r", 1)) {
  6403. selected = curses_int("Retries before failing (-1 infinite)");
  6404. if (selected < -1 || selected > 9999) {
  6405. wlogprint("Invalid selection\n");
  6406. goto retry;
  6407. }
  6408. opt_retries = selected;
  6409. goto retry;
  6410. } else if (!strncasecmp(&input, "w", 1)) {
  6411. FILE *fcfg;
  6412. char *str, filename[PATH_MAX], prompt[PATH_MAX + 50];
  6413. default_save_file(filename);
  6414. snprintf(prompt, sizeof(prompt), "Config filename to write (Enter for default) [%s]", filename);
  6415. str = curses_input(prompt);
  6416. if (str) {
  6417. struct stat statbuf;
  6418. strcpy(filename, str);
  6419. free(str);
  6420. if (!stat(filename, &statbuf)) {
  6421. wlogprint("File exists, overwrite?\n");
  6422. input = getch();
  6423. if (strncasecmp(&input, "y", 1))
  6424. goto retry;
  6425. }
  6426. }
  6427. fcfg = fopen(filename, "w");
  6428. if (!fcfg) {
  6429. wlogprint("Cannot open or create file\n");
  6430. goto retry;
  6431. }
  6432. write_config(fcfg);
  6433. fclose(fcfg);
  6434. goto retry;
  6435. } else if (!strncasecmp(&input, "b", 1)) {
  6436. wlogprint("Are you sure?\n");
  6437. input = getch();
  6438. if (!strncasecmp(&input, "y", 1))
  6439. app_restart();
  6440. else
  6441. clear_logwin();
  6442. } else
  6443. clear_logwin();
  6444. loginput_mode(0);
  6445. immedok(logwin, false);
  6446. }
  6447. int scan_serial(const char *);
  6448. static
  6449. void _managetui_msg(const char *repr, const char **msg)
  6450. {
  6451. if (*msg)
  6452. {
  6453. applog(LOG_DEBUG, "ManageTUI: %"PRIpreprv": %s", repr, *msg);
  6454. wattron(logwin, A_BOLD);
  6455. wlogprint("%s", *msg);
  6456. wattroff(logwin, A_BOLD);
  6457. *msg = NULL;
  6458. }
  6459. logwin_update();
  6460. }
  6461. void manage_device(void)
  6462. {
  6463. char logline[256];
  6464. const char *msg = NULL;
  6465. struct cgpu_info *cgpu;
  6466. const struct device_drv *drv;
  6467. selecting_device = true;
  6468. immedok(logwin, true);
  6469. loginput_mode(12);
  6470. devchange:
  6471. if (unlikely(!total_devices))
  6472. {
  6473. clear_logwin();
  6474. wlogprint("(no devices)\n");
  6475. wlogprint("[Plus] Add device(s) [Enter] Close device manager\n");
  6476. _managetui_msg("(none)", &msg);
  6477. int input = getch();
  6478. switch (input)
  6479. {
  6480. case '+': case '=': // add new device
  6481. goto addnew;
  6482. default:
  6483. goto out;
  6484. }
  6485. }
  6486. cgpu = devices[selected_device];
  6487. drv = cgpu->drv;
  6488. refresh_devstatus();
  6489. refresh:
  6490. clear_logwin();
  6491. wlogprint("Select processor to manage using up/down arrow keys\n");
  6492. get_statline3(logline, sizeof(logline), cgpu, true, true);
  6493. wattron(logwin, A_BOLD);
  6494. wlogprint("%s", logline);
  6495. wattroff(logwin, A_BOLD);
  6496. wlogprint("\n");
  6497. if (cgpu->dev_manufacturer)
  6498. wlogprint(" %s from %s\n", (cgpu->dev_product ?: "Device"), cgpu->dev_manufacturer);
  6499. else
  6500. if (cgpu->dev_product)
  6501. wlogprint(" %s\n", cgpu->dev_product);
  6502. if (cgpu->dev_serial)
  6503. wlogprint("Serial: %s\n", cgpu->dev_serial);
  6504. if (cgpu->kname)
  6505. wlogprint("Kernel: %s\n", cgpu->kname);
  6506. if (drv->proc_wlogprint_status && likely(cgpu->status != LIFE_INIT))
  6507. drv->proc_wlogprint_status(cgpu);
  6508. wlogprint("\n");
  6509. // TODO: Last share at TIMESTAMP on pool N
  6510. // TODO: Custom device info/commands
  6511. if (cgpu->deven != DEV_ENABLED)
  6512. wlogprint("[E]nable ");
  6513. if (cgpu->deven != DEV_DISABLED)
  6514. wlogprint("[D]isable ");
  6515. if (drv->identify_device)
  6516. wlogprint("[I]dentify ");
  6517. if (drv->proc_tui_wlogprint_choices && likely(cgpu->status != LIFE_INIT))
  6518. drv->proc_tui_wlogprint_choices(cgpu);
  6519. wlogprint("\n");
  6520. wlogprint("[Slash] Find processor [Plus] Add device(s) [Enter] Close device manager\n");
  6521. _managetui_msg(cgpu->proc_repr, &msg);
  6522. while (true)
  6523. {
  6524. int input = getch();
  6525. applog(LOG_DEBUG, "ManageTUI: %"PRIpreprv": (choice %d)", cgpu->proc_repr, input);
  6526. switch (input) {
  6527. case 'd': case 'D':
  6528. if (cgpu->deven == DEV_DISABLED)
  6529. msg = "Processor already disabled\n";
  6530. else
  6531. {
  6532. cgpu->deven = DEV_DISABLED;
  6533. msg = "Processor being disabled\n";
  6534. }
  6535. goto refresh;
  6536. case 'e': case 'E':
  6537. if (cgpu->deven == DEV_ENABLED)
  6538. msg = "Processor already enabled\n";
  6539. else
  6540. {
  6541. proc_enable(cgpu);
  6542. msg = "Processor being enabled\n";
  6543. }
  6544. goto refresh;
  6545. case 'i': case 'I':
  6546. if (drv->identify_device && drv->identify_device(cgpu))
  6547. msg = "Identify command sent\n";
  6548. else
  6549. goto key_default;
  6550. goto refresh;
  6551. case KEY_DOWN:
  6552. if (selected_device >= total_devices - 1)
  6553. break;
  6554. ++selected_device;
  6555. goto devchange;
  6556. case KEY_UP:
  6557. if (selected_device <= 0)
  6558. break;
  6559. --selected_device;
  6560. goto devchange;
  6561. case KEY_NPAGE:
  6562. {
  6563. if (selected_device >= total_devices - 1)
  6564. break;
  6565. struct cgpu_info *mdev = devices[selected_device]->device;
  6566. do {
  6567. ++selected_device;
  6568. } while (devices[selected_device]->device == mdev && selected_device < total_devices - 1);
  6569. goto devchange;
  6570. }
  6571. case KEY_PPAGE:
  6572. {
  6573. if (selected_device <= 0)
  6574. break;
  6575. struct cgpu_info *mdev = devices[selected_device]->device;
  6576. do {
  6577. --selected_device;
  6578. } while (devices[selected_device]->device == mdev && selected_device > 0);
  6579. goto devchange;
  6580. }
  6581. case '/': case '?': // find device
  6582. {
  6583. static char *pattern = NULL;
  6584. char *newpattern = curses_input("Enter pattern");
  6585. if (newpattern)
  6586. {
  6587. free(pattern);
  6588. pattern = newpattern;
  6589. }
  6590. else
  6591. if (!pattern)
  6592. pattern = calloc(1, 1);
  6593. int match = cgpu_search(pattern, selected_device + 1);
  6594. if (match == -1)
  6595. {
  6596. msg = "Couldn't find device\n";
  6597. goto refresh;
  6598. }
  6599. selected_device = match;
  6600. goto devchange;
  6601. }
  6602. case '+': case '=': // add new device
  6603. {
  6604. addnew:
  6605. clear_logwin();
  6606. _wlogprint(
  6607. "Enter \"auto\", \"all\", or a serial port to probe for mining devices.\n"
  6608. "Prefix by a driver name and colon to only probe a specific driver.\n"
  6609. "For example: erupter:"
  6610. #ifdef WIN32
  6611. "\\\\.\\COM40"
  6612. #elif defined(__APPLE__)
  6613. "/dev/cu.SLAB_USBtoUART"
  6614. #else
  6615. "/dev/ttyUSB39"
  6616. #endif
  6617. "\n"
  6618. );
  6619. char *scanser = curses_input("Enter target");
  6620. if (scan_serial(scanser))
  6621. {
  6622. selected_device = total_devices - 1;
  6623. msg = "Device scan succeeded\n";
  6624. }
  6625. else
  6626. msg = "No new devices found\n";
  6627. goto devchange;
  6628. }
  6629. case 'Q': case 'q':
  6630. case KEY_BREAK: case KEY_BACKSPACE: case KEY_CANCEL: case KEY_CLOSE: case KEY_EXIT:
  6631. case '\x1b': // ESC
  6632. case KEY_ENTER:
  6633. case '\r': // Ctrl-M on Windows, with nonl
  6634. #ifdef PADENTER
  6635. case PADENTER: // pdcurses, used by Enter key on Windows with nonl
  6636. #endif
  6637. case '\n':
  6638. goto out;
  6639. default:
  6640. ;
  6641. key_default:
  6642. if (drv->proc_tui_handle_choice && likely(drv_ready(cgpu)))
  6643. {
  6644. msg = drv->proc_tui_handle_choice(cgpu, input);
  6645. if (msg)
  6646. goto refresh;
  6647. }
  6648. }
  6649. }
  6650. out:
  6651. selecting_device = false;
  6652. loginput_mode(0);
  6653. immedok(logwin, false);
  6654. }
  6655. void show_help(void)
  6656. {
  6657. loginput_mode(11);
  6658. // NOTE: wlogprint is a macro with a buffer limit
  6659. _wlogprint(
  6660. "LU: oldest explicit work update currently being used for new work\n"
  6661. "ST: work in queue | F: network fails | NB: new blocks detected\n"
  6662. "AS: shares being submitted | BW: bandwidth (up/down)\n"
  6663. "E: # shares * diff per 2kB bw | I: expected income | BS: best share ever found\n"
  6664. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6665. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6666. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6667. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_BTEE
  6668. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6669. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6670. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_BTEE U8_HLINE U8_HLINE U8_HLINE
  6671. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6672. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6673. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6674. "\n"
  6675. "devices/processors hashing (only for totals line), hottest temperature\n"
  6676. );
  6677. wlogprint(
  6678. "hashrates: %ds decaying / all-time average / all-time average (effective)\n"
  6679. , opt_log_interval);
  6680. _wlogprint(
  6681. "A: accepted shares | R: rejected+discarded(% of total)\n"
  6682. "HW: hardware errors / % nonces invalid\n"
  6683. "\n"
  6684. "Press any key to clear"
  6685. );
  6686. logwin_update();
  6687. getch();
  6688. loginput_mode(0);
  6689. }
  6690. static void *input_thread(void __maybe_unused *userdata)
  6691. {
  6692. RenameThread("input");
  6693. if (!curses_active)
  6694. return NULL;
  6695. while (1) {
  6696. int input;
  6697. input = getch();
  6698. switch (input) {
  6699. case 'h': case 'H': case '?':
  6700. case KEY_F(1):
  6701. show_help();
  6702. break;
  6703. case 'q': case 'Q':
  6704. kill_work();
  6705. return NULL;
  6706. case 'd': case 'D':
  6707. display_options();
  6708. break;
  6709. case 'm': case 'M':
  6710. manage_device();
  6711. break;
  6712. case 'p': case 'P':
  6713. display_pools();
  6714. break;
  6715. case 's': case 'S':
  6716. set_options();
  6717. break;
  6718. #ifdef HAVE_CURSES
  6719. case KEY_DOWN:
  6720. {
  6721. const int visible_lines = logcursor - devcursor;
  6722. const int invisible_lines = total_lines - visible_lines;
  6723. if (devsummaryYOffset <= -invisible_lines)
  6724. break;
  6725. devsummaryYOffset -= 2;
  6726. }
  6727. case KEY_UP:
  6728. if (devsummaryYOffset == 0)
  6729. break;
  6730. ++devsummaryYOffset;
  6731. refresh_devstatus();
  6732. break;
  6733. case KEY_NPAGE:
  6734. {
  6735. const int visible_lines = logcursor - devcursor;
  6736. const int invisible_lines = total_lines - visible_lines;
  6737. if (devsummaryYOffset - visible_lines <= -invisible_lines)
  6738. devsummaryYOffset = -invisible_lines;
  6739. else
  6740. devsummaryYOffset -= visible_lines;
  6741. refresh_devstatus();
  6742. break;
  6743. }
  6744. case KEY_PPAGE:
  6745. {
  6746. const int visible_lines = logcursor - devcursor;
  6747. if (devsummaryYOffset + visible_lines >= 0)
  6748. devsummaryYOffset = 0;
  6749. else
  6750. devsummaryYOffset += visible_lines;
  6751. refresh_devstatus();
  6752. break;
  6753. }
  6754. #endif
  6755. }
  6756. if (opt_realquiet) {
  6757. disable_curses();
  6758. break;
  6759. }
  6760. }
  6761. return NULL;
  6762. }
  6763. #endif
  6764. static void *api_thread(void *userdata)
  6765. {
  6766. struct thr_info *mythr = userdata;
  6767. pthread_detach(pthread_self());
  6768. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  6769. RenameThread("rpc");
  6770. api(api_thr_id);
  6771. mythr->has_pth = false;
  6772. return NULL;
  6773. }
  6774. void thread_reportin(struct thr_info *thr)
  6775. {
  6776. cgtime(&thr->last);
  6777. thr->cgpu->status = LIFE_WELL;
  6778. thr->getwork = 0;
  6779. thr->cgpu->device_last_well = time(NULL);
  6780. }
  6781. void thread_reportout(struct thr_info *thr)
  6782. {
  6783. thr->getwork = time(NULL);
  6784. }
  6785. static void hashmeter(int thr_id, struct timeval *diff,
  6786. uint64_t hashes_done)
  6787. {
  6788. char logstatusline[256];
  6789. struct timeval temp_tv_end, total_diff;
  6790. double secs;
  6791. double local_secs;
  6792. static double local_mhashes_done = 0;
  6793. double local_mhashes = (double)hashes_done / 1000000.0;
  6794. bool showlog = false;
  6795. char cHr[ALLOC_H2B_NOUNIT+1], aHr[ALLOC_H2B_NOUNIT+1], uHr[ALLOC_H2B_SPACED+3+1];
  6796. char rejpcbuf[6];
  6797. char bnbuf[6];
  6798. struct thr_info *thr;
  6799. /* Update the last time this thread reported in */
  6800. if (thr_id >= 0) {
  6801. thr = get_thread(thr_id);
  6802. cgtime(&(thr->last));
  6803. thr->cgpu->device_last_well = time(NULL);
  6804. }
  6805. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  6806. /* So we can call hashmeter from a non worker thread */
  6807. if (thr_id >= 0) {
  6808. struct cgpu_info *cgpu = thr->cgpu;
  6809. int threadobj = cgpu->threads ?: 1;
  6810. double thread_rolling = 0.0;
  6811. int i;
  6812. applog(LOG_DEBUG, "[thread %d: %"PRIu64" hashes, %.1f khash/sec]",
  6813. thr_id, hashes_done, hashes_done / 1000 / secs);
  6814. /* Rolling average for each thread and each device */
  6815. decay_time(&thr->rolling, local_mhashes / secs, secs);
  6816. for (i = 0; i < threadobj; i++)
  6817. thread_rolling += cgpu->thr[i]->rolling;
  6818. mutex_lock(&hash_lock);
  6819. decay_time(&cgpu->rolling, thread_rolling, secs);
  6820. cgpu->total_mhashes += local_mhashes;
  6821. mutex_unlock(&hash_lock);
  6822. // If needed, output detailed, per-device stats
  6823. if (want_per_device_stats) {
  6824. struct timeval now;
  6825. struct timeval elapsed;
  6826. struct timeval *last_msg_tv = opt_show_procs ? &thr->cgpu->last_message_tv : &thr->cgpu->device->last_message_tv;
  6827. cgtime(&now);
  6828. timersub(&now, last_msg_tv, &elapsed);
  6829. if (opt_log_interval <= elapsed.tv_sec) {
  6830. struct cgpu_info *cgpu = thr->cgpu;
  6831. char logline[255];
  6832. *last_msg_tv = now;
  6833. get_statline(logline, sizeof(logline), cgpu);
  6834. if (!curses_active) {
  6835. printf("%s \r", logline);
  6836. fflush(stdout);
  6837. } else
  6838. applog(LOG_INFO, "%s", logline);
  6839. }
  6840. }
  6841. }
  6842. /* Totals are updated by all threads so can race without locking */
  6843. mutex_lock(&hash_lock);
  6844. cgtime(&temp_tv_end);
  6845. timersub(&temp_tv_end, &total_tv_end, &total_diff);
  6846. total_mhashes_done += local_mhashes;
  6847. local_mhashes_done += local_mhashes;
  6848. /* Only update with opt_log_interval */
  6849. if (total_diff.tv_sec < opt_log_interval)
  6850. goto out_unlock;
  6851. showlog = true;
  6852. cgtime(&total_tv_end);
  6853. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  6854. decay_time(&total_rolling, local_mhashes_done / local_secs, local_secs);
  6855. global_hashrate = ((unsigned long long)lround(total_rolling)) * 1000000;
  6856. timersub(&total_tv_end, &total_tv_start, &total_diff);
  6857. total_secs = (double)total_diff.tv_sec +
  6858. ((double)total_diff.tv_usec / 1000000.0);
  6859. double wtotal = (total_diff_accepted + total_diff_rejected + total_diff_stale);
  6860. multi_format_unit_array2(
  6861. ((char*[]){cHr, aHr, uHr}),
  6862. ((size_t[]){sizeof(cHr), sizeof(aHr), sizeof(uHr)}),
  6863. true, "h/s", H2B_SHORT,
  6864. 3,
  6865. 1e6*total_rolling,
  6866. 1e6*total_mhashes_done / total_secs,
  6867. utility_to_hashrate(total_diff1 * (wtotal ? (total_diff_accepted / wtotal) : 1) * 60 / total_secs));
  6868. int ui_accepted, ui_rejected, ui_stale;
  6869. if (opt_weighed_stats)
  6870. {
  6871. ui_accepted = total_diff_accepted;
  6872. ui_rejected = total_diff_rejected;
  6873. ui_stale = total_diff_stale;
  6874. }
  6875. else
  6876. {
  6877. ui_accepted = total_accepted;
  6878. ui_rejected = total_rejected;
  6879. ui_stale = total_stale;
  6880. }
  6881. #ifdef HAVE_CURSES
  6882. if (curses_active_locked()) {
  6883. float temp = 0;
  6884. struct cgpu_info *proc, *last_working_dev = NULL;
  6885. int i, working_devs = 0, working_procs = 0;
  6886. int divx;
  6887. bool bad = false;
  6888. // Find the highest temperature of all processors
  6889. for (i = 0; i < total_devices; ++i)
  6890. {
  6891. proc = get_devices(i);
  6892. if (proc->temp > temp)
  6893. temp = proc->temp;
  6894. if (unlikely(proc->deven == DEV_DISABLED))
  6895. ; // Just need to block it off from both conditions
  6896. else
  6897. if (likely(proc->status == LIFE_WELL && proc->deven == DEV_ENABLED))
  6898. {
  6899. if (proc->rolling > .1)
  6900. {
  6901. ++working_procs;
  6902. if (proc->device != last_working_dev)
  6903. {
  6904. ++working_devs;
  6905. last_working_dev = proc->device;
  6906. }
  6907. }
  6908. }
  6909. else
  6910. bad = true;
  6911. }
  6912. if (working_devs == working_procs)
  6913. snprintf(statusline, sizeof(statusline), "%s%d ", bad ? U8_BAD_START : "", working_devs);
  6914. else
  6915. snprintf(statusline, sizeof(statusline), "%s%d/%d ", bad ? U8_BAD_START : "", working_devs, working_procs);
  6916. divx = 7;
  6917. if (opt_show_procs && !opt_compact)
  6918. ++divx;
  6919. if (bad)
  6920. {
  6921. divx += sizeof(U8_BAD_START)-1;
  6922. strcpy(&statusline[divx], U8_BAD_END);
  6923. divx += sizeof(U8_BAD_END)-1;
  6924. }
  6925. temperature_column(&statusline[divx], sizeof(statusline)-divx, true, &temp);
  6926. format_statline(statusline, sizeof(statusline),
  6927. cHr, aHr,
  6928. uHr,
  6929. ui_accepted,
  6930. ui_rejected,
  6931. ui_stale,
  6932. total_diff_rejected + total_diff_stale, total_diff_accepted,
  6933. hw_errors,
  6934. total_bad_diff1, total_bad_diff1 + total_diff1);
  6935. unlock_curses();
  6936. }
  6937. #endif
  6938. // Add a space
  6939. memmove(&uHr[6], &uHr[5], strlen(&uHr[5]) + 1);
  6940. uHr[5] = ' ';
  6941. percentf4(rejpcbuf, sizeof(rejpcbuf), total_diff_rejected + total_diff_stale, total_diff_accepted);
  6942. percentf4(bnbuf, sizeof(bnbuf), total_bad_diff1, total_diff1);
  6943. snprintf(logstatusline, sizeof(logstatusline),
  6944. "%s%ds:%s avg:%s u:%s | A:%d R:%d+%d(%s) HW:%d/%s",
  6945. want_per_device_stats ? "ALL " : "",
  6946. opt_log_interval,
  6947. cHr, aHr,
  6948. uHr,
  6949. ui_accepted,
  6950. ui_rejected,
  6951. ui_stale,
  6952. rejpcbuf,
  6953. hw_errors,
  6954. bnbuf
  6955. );
  6956. local_mhashes_done = 0;
  6957. out_unlock:
  6958. mutex_unlock(&hash_lock);
  6959. if (showlog) {
  6960. if (!curses_active) {
  6961. printf("%s \r", logstatusline);
  6962. fflush(stdout);
  6963. } else
  6964. applog(LOG_INFO, "%s", logstatusline);
  6965. }
  6966. }
  6967. void hashmeter2(struct thr_info *thr)
  6968. {
  6969. struct timeval tv_now, tv_elapsed;
  6970. timerclear(&thr->tv_hashes_done);
  6971. cgtime(&tv_now);
  6972. timersub(&tv_now, &thr->tv_lastupdate, &tv_elapsed);
  6973. /* Update the hashmeter at most 5 times per second */
  6974. if ((thr->hashes_done && (tv_elapsed.tv_sec > 0 || tv_elapsed.tv_usec > 200000)) ||
  6975. tv_elapsed.tv_sec >= opt_log_interval) {
  6976. hashmeter(thr->id, &tv_elapsed, thr->hashes_done);
  6977. thr->hashes_done = 0;
  6978. thr->tv_lastupdate = tv_now;
  6979. }
  6980. }
  6981. static void stratum_share_result(json_t *val, json_t *res_val, json_t *err_val,
  6982. struct stratum_share *sshare)
  6983. {
  6984. struct work *work = sshare->work;
  6985. share_result(val, res_val, err_val, work, false, "");
  6986. }
  6987. /* Parses stratum json responses and tries to find the id that the request
  6988. * matched to and treat it accordingly. */
  6989. bool parse_stratum_response(struct pool *pool, char *s)
  6990. {
  6991. json_t *val = NULL, *err_val, *res_val, *id_val;
  6992. struct stratum_share *sshare;
  6993. json_error_t err;
  6994. bool ret = false;
  6995. int id;
  6996. val = JSON_LOADS(s, &err);
  6997. if (!val) {
  6998. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  6999. goto out;
  7000. }
  7001. res_val = json_object_get(val, "result");
  7002. err_val = json_object_get(val, "error");
  7003. id_val = json_object_get(val, "id");
  7004. if (json_is_null(id_val) || !id_val) {
  7005. char *ss;
  7006. if (err_val)
  7007. ss = json_dumps(err_val, JSON_INDENT(3));
  7008. else
  7009. ss = strdup("(unknown reason)");
  7010. applog(LOG_INFO, "JSON-RPC non method decode failed: %s", ss);
  7011. free(ss);
  7012. goto out;
  7013. }
  7014. if (!json_is_integer(id_val)) {
  7015. if (json_is_string(id_val)
  7016. && !strncmp(json_string_value(id_val), "txlist", 6))
  7017. {
  7018. const bool is_array = json_is_array(res_val);
  7019. applog(LOG_DEBUG, "Received %s for pool %u job %s",
  7020. is_array ? "transaction list" : "no-transaction-list response",
  7021. pool->pool_no, &json_string_value(id_val)[6]);
  7022. if (!is_array)
  7023. {
  7024. // No need to wait for a timeout
  7025. timer_unset(&pool->swork.tv_transparency);
  7026. pool_set_opaque(pool, true);
  7027. goto fishy;
  7028. }
  7029. if (strcmp(json_string_value(id_val) + 6, pool->swork.job_id))
  7030. // We only care about a transaction list for the current job id
  7031. goto fishy;
  7032. // Check that the transactions actually hash to the merkle links
  7033. {
  7034. unsigned maxtx = 1 << pool->swork.merkles;
  7035. unsigned mintx = maxtx >> 1;
  7036. --maxtx;
  7037. unsigned acttx = (unsigned)json_array_size(res_val);
  7038. if (acttx < mintx || acttx > maxtx) {
  7039. applog(LOG_WARNING, "Pool %u is sending mismatched block contents to us (%u is not %u-%u)",
  7040. pool->pool_no, acttx, mintx, maxtx);
  7041. goto fishy;
  7042. }
  7043. // TODO: Check hashes match actual merkle links
  7044. }
  7045. pool_set_opaque(pool, false);
  7046. timer_unset(&pool->swork.tv_transparency);
  7047. fishy:
  7048. ret = true;
  7049. }
  7050. goto out;
  7051. }
  7052. id = json_integer_value(id_val);
  7053. mutex_lock(&sshare_lock);
  7054. HASH_FIND_INT(stratum_shares, &id, sshare);
  7055. if (sshare)
  7056. HASH_DEL(stratum_shares, sshare);
  7057. mutex_unlock(&sshare_lock);
  7058. if (!sshare) {
  7059. double pool_diff;
  7060. /* Since the share is untracked, we can only guess at what the
  7061. * work difficulty is based on the current pool diff. */
  7062. cg_rlock(&pool->data_lock);
  7063. pool_diff = pool->swork.diff;
  7064. cg_runlock(&pool->data_lock);
  7065. if (json_is_true(res_val)) {
  7066. applog(LOG_NOTICE, "Accepted untracked stratum share from pool %d", pool->pool_no);
  7067. /* We don't know what device this came from so we can't
  7068. * attribute the work to the relevant cgpu */
  7069. mutex_lock(&stats_lock);
  7070. total_accepted++;
  7071. pool->accepted++;
  7072. total_diff_accepted += pool_diff;
  7073. pool->diff_accepted += pool_diff;
  7074. mutex_unlock(&stats_lock);
  7075. } else {
  7076. applog(LOG_NOTICE, "Rejected untracked stratum share from pool %d", pool->pool_no);
  7077. mutex_lock(&stats_lock);
  7078. total_rejected++;
  7079. pool->rejected++;
  7080. total_diff_rejected += pool_diff;
  7081. pool->diff_rejected += pool_diff;
  7082. mutex_unlock(&stats_lock);
  7083. }
  7084. goto out;
  7085. }
  7086. else {
  7087. mutex_lock(&submitting_lock);
  7088. --total_submitting;
  7089. mutex_unlock(&submitting_lock);
  7090. }
  7091. stratum_share_result(val, res_val, err_val, sshare);
  7092. free_work(sshare->work);
  7093. free(sshare);
  7094. ret = true;
  7095. out:
  7096. if (val)
  7097. json_decref(val);
  7098. return ret;
  7099. }
  7100. static void shutdown_stratum(struct pool *pool)
  7101. {
  7102. // Shut down Stratum as if we never had it
  7103. pool->stratum_active = false;
  7104. pool->stratum_init = false;
  7105. pool->has_stratum = false;
  7106. shutdown(pool->sock, SHUT_RDWR);
  7107. free(pool->stratum_url);
  7108. if (pool->sockaddr_url == pool->stratum_url)
  7109. pool->sockaddr_url = NULL;
  7110. pool->stratum_url = NULL;
  7111. }
  7112. void clear_stratum_shares(struct pool *pool)
  7113. {
  7114. int my_mining_threads = mining_threads; // Cached outside of locking
  7115. struct stratum_share *sshare, *tmpshare;
  7116. struct work *work;
  7117. struct cgpu_info *cgpu;
  7118. double diff_cleared = 0;
  7119. double thr_diff_cleared[my_mining_threads];
  7120. int cleared = 0;
  7121. int thr_cleared[my_mining_threads];
  7122. // NOTE: This is per-thread rather than per-device to avoid getting devices lock in stratum_shares loop
  7123. for (int i = 0; i < my_mining_threads; ++i)
  7124. {
  7125. thr_diff_cleared[i] = 0;
  7126. thr_cleared[i] = 0;
  7127. }
  7128. mutex_lock(&sshare_lock);
  7129. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  7130. work = sshare->work;
  7131. if (sshare->work->pool == pool && work->thr_id < my_mining_threads) {
  7132. HASH_DEL(stratum_shares, sshare);
  7133. sharelog("disconnect", work);
  7134. diff_cleared += sshare->work->work_difficulty;
  7135. thr_diff_cleared[work->thr_id] += work->work_difficulty;
  7136. ++thr_cleared[work->thr_id];
  7137. free_work(sshare->work);
  7138. free(sshare);
  7139. cleared++;
  7140. }
  7141. }
  7142. mutex_unlock(&sshare_lock);
  7143. if (cleared) {
  7144. applog(LOG_WARNING, "Lost %d shares due to stratum disconnect on pool %d", cleared, pool->pool_no);
  7145. mutex_lock(&stats_lock);
  7146. pool->stale_shares += cleared;
  7147. total_stale += cleared;
  7148. pool->diff_stale += diff_cleared;
  7149. total_diff_stale += diff_cleared;
  7150. for (int i = 0; i < my_mining_threads; ++i)
  7151. if (thr_cleared[i])
  7152. {
  7153. cgpu = get_thr_cgpu(i);
  7154. cgpu->diff_stale += thr_diff_cleared[i];
  7155. cgpu->stale += thr_cleared[i];
  7156. }
  7157. mutex_unlock(&stats_lock);
  7158. mutex_lock(&submitting_lock);
  7159. total_submitting -= cleared;
  7160. mutex_unlock(&submitting_lock);
  7161. }
  7162. }
  7163. static void resubmit_stratum_shares(struct pool *pool)
  7164. {
  7165. struct stratum_share *sshare, *tmpshare;
  7166. struct work *work;
  7167. unsigned resubmitted = 0;
  7168. mutex_lock(&sshare_lock);
  7169. mutex_lock(&submitting_lock);
  7170. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  7171. if (sshare->work->pool != pool)
  7172. continue;
  7173. HASH_DEL(stratum_shares, sshare);
  7174. work = sshare->work;
  7175. DL_APPEND(submit_waiting, work);
  7176. free(sshare);
  7177. ++resubmitted;
  7178. }
  7179. mutex_unlock(&submitting_lock);
  7180. mutex_unlock(&sshare_lock);
  7181. if (resubmitted) {
  7182. notifier_wake(submit_waiting_notifier);
  7183. applog(LOG_DEBUG, "Resubmitting %u shares due to stratum disconnect on pool %u", resubmitted, pool->pool_no);
  7184. }
  7185. }
  7186. static void clear_pool_work(struct pool *pool)
  7187. {
  7188. struct work *work, *tmp;
  7189. int cleared = 0;
  7190. mutex_lock(stgd_lock);
  7191. HASH_ITER(hh, staged_work, work, tmp) {
  7192. if (work->pool == pool) {
  7193. HASH_DEL(staged_work, work);
  7194. free_work(work);
  7195. cleared++;
  7196. staged_full = false;
  7197. }
  7198. }
  7199. mutex_unlock(stgd_lock);
  7200. }
  7201. static int cp_prio(void)
  7202. {
  7203. int prio;
  7204. cg_rlock(&control_lock);
  7205. prio = currentpool->prio;
  7206. cg_runlock(&control_lock);
  7207. return prio;
  7208. }
  7209. /* We only need to maintain a secondary pool connection when we need the
  7210. * capacity to get work from the backup pools while still on the primary */
  7211. static bool cnx_needed(struct pool *pool)
  7212. {
  7213. struct pool *cp;
  7214. if (pool->enabled != POOL_ENABLED)
  7215. return false;
  7216. /* Idle stratum pool needs something to kick it alive again */
  7217. if (pool->has_stratum && pool->idle)
  7218. return true;
  7219. /* Getwork pools without opt_fail_only need backup pools up to be able
  7220. * to leak shares */
  7221. cp = current_pool();
  7222. if (pool_actively_desired(pool, cp))
  7223. return true;
  7224. if (!pool_localgen(cp) && (!opt_fail_only || !cp->hdr_path))
  7225. return true;
  7226. /* Keep the connection open to allow any stray shares to be submitted
  7227. * on switching pools for 2 minutes. */
  7228. if (!timer_passed(&pool->tv_last_work_time, NULL))
  7229. return true;
  7230. /* If the pool has only just come to life and is higher priority than
  7231. * the current pool keep the connection open so we can fail back to
  7232. * it. */
  7233. if (pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  7234. return true;
  7235. if (pool_unworkable(cp))
  7236. return true;
  7237. /* We've run out of work, bring anything back to life. */
  7238. if (no_work)
  7239. return true;
  7240. return false;
  7241. }
  7242. static void wait_lpcurrent(struct pool *pool);
  7243. static void pool_resus(struct pool *pool);
  7244. static void gen_stratum_work(struct pool *pool, struct work *work);
  7245. static void stratum_resumed(struct pool *pool)
  7246. {
  7247. if (!pool->stratum_notify)
  7248. return;
  7249. if (pool_tclear(pool, &pool->idle)) {
  7250. applog(LOG_INFO, "Stratum connection to pool %d resumed", pool->pool_no);
  7251. pool_resus(pool);
  7252. }
  7253. }
  7254. static bool supports_resume(struct pool *pool)
  7255. {
  7256. bool ret;
  7257. cg_rlock(&pool->data_lock);
  7258. ret = (pool->sessionid != NULL);
  7259. cg_runlock(&pool->data_lock);
  7260. return ret;
  7261. }
  7262. /* One stratum thread per pool that has stratum waits on the socket checking
  7263. * for new messages and for the integrity of the socket connection. We reset
  7264. * the connection based on the integrity of the receive side only as the send
  7265. * side will eventually expire data it fails to send. */
  7266. static void *stratum_thread(void *userdata)
  7267. {
  7268. struct pool *pool = (struct pool *)userdata;
  7269. pthread_detach(pthread_self());
  7270. char threadname[20];
  7271. snprintf(threadname, 20, "stratum%u", pool->pool_no);
  7272. RenameThread(threadname);
  7273. srand(time(NULL) + (intptr_t)userdata);
  7274. while (42) {
  7275. struct timeval timeout;
  7276. int sel_ret;
  7277. fd_set rd;
  7278. char *s;
  7279. int sock;
  7280. if (unlikely(!pool->has_stratum))
  7281. break;
  7282. /* Check to see whether we need to maintain this connection
  7283. * indefinitely or just bring it up when we switch to this
  7284. * pool */
  7285. while (true)
  7286. {
  7287. sock = pool->sock;
  7288. if (sock == INVSOCK)
  7289. applog(LOG_DEBUG, "Pool %u: Invalid socket, suspending",
  7290. pool->pool_no);
  7291. else
  7292. if (!sock_full(pool) && !cnx_needed(pool))
  7293. applog(LOG_DEBUG, "Pool %u: Connection not needed, suspending",
  7294. pool->pool_no);
  7295. else
  7296. break;
  7297. suspend_stratum(pool);
  7298. clear_stratum_shares(pool);
  7299. clear_pool_work(pool);
  7300. wait_lpcurrent(pool);
  7301. if (!restart_stratum(pool)) {
  7302. pool_died(pool);
  7303. while (!restart_stratum(pool)) {
  7304. if (pool->removed)
  7305. goto out;
  7306. cgsleep_ms(30000);
  7307. }
  7308. }
  7309. }
  7310. FD_ZERO(&rd);
  7311. FD_SET(sock, &rd);
  7312. timeout.tv_sec = 120;
  7313. timeout.tv_usec = 0;
  7314. /* If we fail to receive any notify messages for 2 minutes we
  7315. * assume the connection has been dropped and treat this pool
  7316. * as dead */
  7317. if (!sock_full(pool) && (sel_ret = select(sock + 1, &rd, NULL, NULL, &timeout)) < 1) {
  7318. applog(LOG_DEBUG, "Stratum select failed on pool %d with value %d", pool->pool_no, sel_ret);
  7319. s = NULL;
  7320. } else
  7321. s = recv_line(pool);
  7322. if (!s) {
  7323. if (!pool->has_stratum)
  7324. break;
  7325. applog(LOG_NOTICE, "Stratum connection to pool %d interrupted", pool->pool_no);
  7326. pool->getfail_occasions++;
  7327. total_go++;
  7328. mutex_lock(&pool->stratum_lock);
  7329. pool->stratum_active = pool->stratum_notify = false;
  7330. pool->sock = INVSOCK;
  7331. mutex_unlock(&pool->stratum_lock);
  7332. /* If the socket to our stratum pool disconnects, all
  7333. * submissions need to be discarded or resent. */
  7334. if (!supports_resume(pool))
  7335. clear_stratum_shares(pool);
  7336. else
  7337. resubmit_stratum_shares(pool);
  7338. clear_pool_work(pool);
  7339. if (pool == current_pool())
  7340. restart_threads();
  7341. if (restart_stratum(pool))
  7342. continue;
  7343. shutdown_stratum(pool);
  7344. pool_died(pool);
  7345. break;
  7346. }
  7347. /* Check this pool hasn't died while being a backup pool and
  7348. * has not had its idle flag cleared */
  7349. stratum_resumed(pool);
  7350. if (!parse_method(pool, s) && !parse_stratum_response(pool, s))
  7351. applog(LOG_INFO, "Unknown stratum msg: %s", s);
  7352. free(s);
  7353. if (pool->swork.clean) {
  7354. struct work *work = make_work();
  7355. /* Generate a single work item to update the current
  7356. * block database */
  7357. pool->swork.clean = false;
  7358. gen_stratum_work(pool, work);
  7359. /* Try to extract block height from coinbase scriptSig */
  7360. uint8_t *bin_height = &bytes_buf(&pool->swork.coinbase)[4 /*version*/ + 1 /*txin count*/ + 36 /*prevout*/ + 1 /*scriptSig len*/ + 1 /*push opcode*/];
  7361. unsigned char cb_height_sz;
  7362. cb_height_sz = bin_height[-1];
  7363. if (cb_height_sz == 3) {
  7364. // FIXME: The block number will overflow this by AD 2173
  7365. uint32_t block_id = ((uint32_t*)work->data)[1];
  7366. uint32_t height = 0;
  7367. memcpy(&height, bin_height, 3);
  7368. height = le32toh(height);
  7369. have_block_height(block_id, height);
  7370. }
  7371. ++pool->work_restart_id;
  7372. pool_update_work_restart_time(pool);
  7373. if (test_work_current(work)) {
  7374. /* Only accept a work update if this stratum
  7375. * connection is from the current pool */
  7376. struct pool * const cp = current_pool();
  7377. if (pool == cp)
  7378. restart_threads();
  7379. applog(
  7380. ((!opt_quiet_work_updates) && pool_actively_in_use(pool, cp) ? LOG_NOTICE : LOG_DEBUG),
  7381. "Stratum from pool %d requested work update", pool->pool_no);
  7382. } else
  7383. applog(LOG_NOTICE, "Stratum from pool %d detected new block", pool->pool_no);
  7384. free_work(work);
  7385. }
  7386. if (timer_passed(&pool->swork.tv_transparency, NULL)) {
  7387. // More than 4 timmills past since requested transactions
  7388. timer_unset(&pool->swork.tv_transparency);
  7389. pool_set_opaque(pool, true);
  7390. }
  7391. }
  7392. out:
  7393. return NULL;
  7394. }
  7395. static void init_stratum_thread(struct pool *pool)
  7396. {
  7397. have_longpoll = true;
  7398. if (unlikely(pthread_create(&pool->stratum_thread, NULL, stratum_thread, (void *)pool)))
  7399. quit(1, "Failed to create stratum thread");
  7400. }
  7401. static void *longpoll_thread(void *userdata);
  7402. static bool stratum_works(struct pool *pool)
  7403. {
  7404. applog(LOG_INFO, "Testing pool %d stratum %s", pool->pool_no, pool->stratum_url);
  7405. if (!extract_sockaddr(pool->stratum_url, &pool->sockaddr_url, &pool->stratum_port))
  7406. return false;
  7407. if (pool->stratum_active)
  7408. return true;
  7409. if (!initiate_stratum(pool))
  7410. return false;
  7411. return true;
  7412. }
  7413. static bool pool_active(struct pool *pool, bool pinging)
  7414. {
  7415. struct timeval tv_getwork, tv_getwork_reply;
  7416. bool ret = false;
  7417. json_t *val;
  7418. CURL *curl;
  7419. int rolltime;
  7420. char *rpc_req;
  7421. struct work *work;
  7422. enum pool_protocol proto;
  7423. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  7424. /* This is the central point we activate stratum when we can */
  7425. curl = curl_easy_init();
  7426. if (unlikely(!curl)) {
  7427. applog(LOG_ERR, "CURL initialisation failed");
  7428. return false;
  7429. }
  7430. if (!(want_gbt || want_getwork))
  7431. goto nohttp;
  7432. work = make_work();
  7433. /* Probe for GBT support on first pass */
  7434. proto = want_gbt ? PLP_GETBLOCKTEMPLATE : PLP_GETWORK;
  7435. tryagain:
  7436. rpc_req = prepare_rpc_req_probe(work, proto, NULL);
  7437. work->pool = pool;
  7438. if (!rpc_req)
  7439. goto out;
  7440. pool->probed = false;
  7441. cgtime(&tv_getwork);
  7442. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  7443. true, false, &rolltime, pool, false);
  7444. cgtime(&tv_getwork_reply);
  7445. free(rpc_req);
  7446. /* Detect if a http getwork pool has an X-Stratum header at startup,
  7447. * and if so, switch to that in preference to getwork if it works */
  7448. if (pool->stratum_url && want_stratum && (pool->has_stratum || stratum_works(pool))) {
  7449. if (!pool->has_stratum) {
  7450. applog(LOG_NOTICE, "Switching pool %d %s to %s", pool->pool_no, pool->rpc_url, pool->stratum_url);
  7451. if (!pool->rpc_url)
  7452. pool->rpc_url = strdup(pool->stratum_url);
  7453. pool->has_stratum = true;
  7454. }
  7455. free_work(work);
  7456. if (val)
  7457. json_decref(val);
  7458. retry_stratum:
  7459. curl_easy_cleanup(curl);
  7460. /* We create the stratum thread for each pool just after
  7461. * successful authorisation. Once the init flag has been set
  7462. * we never unset it and the stratum thread is responsible for
  7463. * setting/unsetting the active flag */
  7464. bool init = pool_tset(pool, &pool->stratum_init);
  7465. if (!init) {
  7466. bool ret = initiate_stratum(pool) && auth_stratum(pool);
  7467. if (ret)
  7468. {
  7469. detect_algo = 2;
  7470. init_stratum_thread(pool);
  7471. }
  7472. else
  7473. pool_tclear(pool, &pool->stratum_init);
  7474. return ret;
  7475. }
  7476. return pool->stratum_active;
  7477. }
  7478. else if (pool->has_stratum)
  7479. shutdown_stratum(pool);
  7480. if (val) {
  7481. bool rc;
  7482. json_t *res;
  7483. res = json_object_get(val, "result");
  7484. if ((!json_is_object(res)) || (proto == PLP_GETBLOCKTEMPLATE && !json_object_get(res, "bits")))
  7485. goto badwork;
  7486. work->rolltime = rolltime;
  7487. rc = work_decode(pool, work, val);
  7488. if (rc) {
  7489. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  7490. pool->pool_no, pool->rpc_url);
  7491. work->pool = pool;
  7492. copy_time(&work->tv_getwork, &tv_getwork);
  7493. copy_time(&work->tv_getwork_reply, &tv_getwork_reply);
  7494. work->getwork_mode = GETWORK_MODE_TESTPOOL;
  7495. calc_diff(work, 0);
  7496. update_last_work(work);
  7497. applog(LOG_DEBUG, "Pushing pooltest work to base pool");
  7498. stage_work(work);
  7499. total_getworks++;
  7500. pool->getwork_requested++;
  7501. ret = true;
  7502. cgtime(&pool->tv_idle);
  7503. } else {
  7504. badwork:
  7505. json_decref(val);
  7506. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher work from pool %u %s",
  7507. pool->pool_no, pool->rpc_url);
  7508. pool->proto = proto = pool_protocol_fallback(proto);
  7509. if (PLP_NONE != proto)
  7510. goto tryagain;
  7511. free_work(work);
  7512. goto out;
  7513. }
  7514. json_decref(val);
  7515. if (proto != pool->proto) {
  7516. pool->proto = proto;
  7517. applog(LOG_INFO, "Selected %s protocol for pool %u", pool_protocol_name(proto), pool->pool_no);
  7518. }
  7519. if (pool->lp_url)
  7520. goto out;
  7521. /* Decipher the longpoll URL, if any, and store it in ->lp_url */
  7522. const struct blktmpl_longpoll_req *lp;
  7523. if (work->tmpl && (lp = blktmpl_get_longpoll(work->tmpl))) {
  7524. // NOTE: work_decode takes care of lp id
  7525. pool->lp_url = lp->uri ? absolute_uri(lp->uri, pool->rpc_url) : pool->rpc_url;
  7526. if (!pool->lp_url)
  7527. {
  7528. ret = false;
  7529. goto out;
  7530. }
  7531. pool->lp_proto = PLP_GETBLOCKTEMPLATE;
  7532. }
  7533. else
  7534. if (pool->hdr_path && want_getwork) {
  7535. pool->lp_url = absolute_uri(pool->hdr_path, pool->rpc_url);
  7536. if (!pool->lp_url)
  7537. {
  7538. ret = false;
  7539. goto out;
  7540. }
  7541. pool->lp_proto = PLP_GETWORK;
  7542. } else
  7543. pool->lp_url = NULL;
  7544. if (want_longpoll && !pool->lp_started) {
  7545. pool->lp_started = true;
  7546. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  7547. quit(1, "Failed to create pool longpoll thread");
  7548. }
  7549. } else if (PLP_NONE != (proto = pool_protocol_fallback(proto))) {
  7550. pool->proto = proto;
  7551. goto tryagain;
  7552. } else {
  7553. free_work(work);
  7554. nohttp:
  7555. /* If we failed to parse a getwork, this could be a stratum
  7556. * url without the prefix stratum+tcp:// so let's check it */
  7557. if (extract_sockaddr(pool->rpc_url, &pool->sockaddr_url, &pool->stratum_port) && initiate_stratum(pool)) {
  7558. pool->has_stratum = true;
  7559. goto retry_stratum;
  7560. }
  7561. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  7562. pool->pool_no, pool->rpc_url);
  7563. if (!pinging)
  7564. applog(LOG_WARNING, "Pool %u slow/down or URL or credentials invalid", pool->pool_no);
  7565. }
  7566. out:
  7567. curl_easy_cleanup(curl);
  7568. return ret;
  7569. }
  7570. static void pool_resus(struct pool *pool)
  7571. {
  7572. if (pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  7573. applog(LOG_WARNING, "Pool %d %s alive, testing stability", pool->pool_no, pool->rpc_url);
  7574. else
  7575. applog(LOG_INFO, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  7576. }
  7577. static struct work *hash_pop(void)
  7578. {
  7579. struct work *work = NULL, *tmp;
  7580. int hc;
  7581. struct timespec ts;
  7582. retry:
  7583. mutex_lock(stgd_lock);
  7584. while (!HASH_COUNT(staged_work))
  7585. {
  7586. if (unlikely(staged_full))
  7587. {
  7588. if (likely(opt_queue < 10 + mining_threads))
  7589. {
  7590. ++opt_queue;
  7591. applog(LOG_WARNING, "Staged work underrun; increasing queue minimum to %d", opt_queue);
  7592. }
  7593. else
  7594. applog(LOG_WARNING, "Staged work underrun; not automatically increasing above %d", opt_queue);
  7595. staged_full = false; // Let it fill up before triggering an underrun again
  7596. no_work = true;
  7597. }
  7598. ts = (struct timespec){ .tv_sec = opt_log_interval, };
  7599. pthread_cond_signal(&gws_cond);
  7600. if (ETIMEDOUT == pthread_cond_timedwait(&getq->cond, stgd_lock, &ts))
  7601. {
  7602. run_cmd(cmd_idle);
  7603. pthread_cond_signal(&gws_cond);
  7604. pthread_cond_wait(&getq->cond, stgd_lock);
  7605. }
  7606. }
  7607. no_work = false;
  7608. hc = HASH_COUNT(staged_work);
  7609. /* Find clone work if possible, to allow masters to be reused */
  7610. if (hc > staged_rollable) {
  7611. HASH_ITER(hh, staged_work, work, tmp) {
  7612. if (!work_rollable(work))
  7613. break;
  7614. }
  7615. } else
  7616. work = staged_work;
  7617. if (can_roll(work) && should_roll(work))
  7618. {
  7619. // Instead of consuming it, force it to be cloned and grab the clone
  7620. mutex_unlock(stgd_lock);
  7621. clone_available();
  7622. goto retry;
  7623. }
  7624. HASH_DEL(staged_work, work);
  7625. if (work_rollable(work))
  7626. staged_rollable--;
  7627. /* Signal the getwork scheduler to look for more work */
  7628. pthread_cond_signal(&gws_cond);
  7629. /* Signal hash_pop again in case there are mutliple hash_pop waiters */
  7630. pthread_cond_signal(&getq->cond);
  7631. mutex_unlock(stgd_lock);
  7632. work->pool->last_work_time = time(NULL);
  7633. cgtime(&work->pool->tv_last_work_time);
  7634. return work;
  7635. }
  7636. /* Clones work by rolling it if possible, and returning a clone instead of the
  7637. * original work item which gets staged again to possibly be rolled again in
  7638. * the future */
  7639. static struct work *clone_work(struct work *work)
  7640. {
  7641. int mrs = mining_threads + opt_queue - total_staged();
  7642. struct work *work_clone;
  7643. bool cloned;
  7644. if (mrs < 1)
  7645. return work;
  7646. cloned = false;
  7647. work_clone = make_clone(work);
  7648. while (mrs-- > 0 && can_roll(work) && should_roll(work)) {
  7649. applog(LOG_DEBUG, "Pushing rolled converted work to stage thread");
  7650. stage_work(work_clone);
  7651. roll_work(work);
  7652. work_clone = make_clone(work);
  7653. /* Roll it again to prevent duplicates should this be used
  7654. * directly later on */
  7655. roll_work(work);
  7656. cloned = true;
  7657. }
  7658. if (cloned) {
  7659. stage_work(work);
  7660. return work_clone;
  7661. }
  7662. free_work(work_clone);
  7663. return work;
  7664. }
  7665. void gen_hash(unsigned char *data, unsigned char *hash, int len)
  7666. {
  7667. unsigned char hash1[32];
  7668. sha256(data, len, hash1);
  7669. sha256(hash1, 32, hash);
  7670. }
  7671. /* Diff 1 is a 256 bit unsigned integer of
  7672. * 0x00000000ffff0000000000000000000000000000000000000000000000000000
  7673. * so we use a big endian 64 bit unsigned integer centred on the 5th byte to
  7674. * cover a huge range of difficulty targets, though not all 256 bits' worth */
  7675. static void bdiff_target_leadzero(unsigned char *target, double diff)
  7676. {
  7677. uint64_t *data64, h64;
  7678. double d64;
  7679. d64 = diffone;
  7680. d64 /= diff;
  7681. d64 = ceil(d64);
  7682. h64 = d64;
  7683. memset(target, 0, 32);
  7684. if (d64 < 18446744073709551616.0) {
  7685. unsigned char *rtarget = target;
  7686. memset(rtarget, 0, 32);
  7687. if (opt_scrypt)
  7688. data64 = (uint64_t *)(rtarget + 2);
  7689. else
  7690. data64 = (uint64_t *)(rtarget + 4);
  7691. *data64 = htobe64(h64);
  7692. } else {
  7693. /* Support for the classic all FFs just-below-1 diff */
  7694. if (opt_scrypt)
  7695. memset(&target[2], 0xff, 30);
  7696. else
  7697. memset(&target[4], 0xff, 28);
  7698. }
  7699. }
  7700. void set_target(unsigned char *dest_target, double diff)
  7701. {
  7702. unsigned char rtarget[32];
  7703. bdiff_target_leadzero(rtarget, diff);
  7704. swab256(dest_target, rtarget);
  7705. if (opt_debug) {
  7706. char htarget[65];
  7707. bin2hex(htarget, rtarget, 32);
  7708. applog(LOG_DEBUG, "Generated target %s", htarget);
  7709. }
  7710. }
  7711. void stratum_work_cpy(struct stratum_work * const dst, const struct stratum_work * const src)
  7712. {
  7713. *dst = *src;
  7714. dst->job_id = strdup(src->job_id);
  7715. bytes_cpy(&dst->coinbase, &src->coinbase);
  7716. bytes_cpy(&dst->merkle_bin, &src->merkle_bin);
  7717. }
  7718. void stratum_work_clean(struct stratum_work * const swork)
  7719. {
  7720. free(swork->job_id);
  7721. bytes_free(&swork->coinbase);
  7722. bytes_free(&swork->merkle_bin);
  7723. }
  7724. /* Generates stratum based work based on the most recent notify information
  7725. * from the pool. This will keep generating work while a pool is down so we use
  7726. * other means to detect when the pool has died in stratum_thread */
  7727. static void gen_stratum_work(struct pool *pool, struct work *work)
  7728. {
  7729. clean_work(work);
  7730. cg_wlock(&pool->data_lock);
  7731. pool->swork.data_lock_p = &pool->data_lock;
  7732. bytes_resize(&work->nonce2, pool->n2size);
  7733. if (pool->nonce2sz < pool->n2size)
  7734. memset(&bytes_buf(&work->nonce2)[pool->nonce2sz], 0, pool->n2size - pool->nonce2sz);
  7735. memcpy(bytes_buf(&work->nonce2),
  7736. #ifdef WORDS_BIGENDIAN
  7737. // NOTE: On big endian, the most significant bits are stored at the end, so skip the LSBs
  7738. &((char*)&pool->nonce2)[pool->nonce2off],
  7739. #else
  7740. &pool->nonce2,
  7741. #endif
  7742. pool->nonce2sz);
  7743. pool->nonce2++;
  7744. work->pool = pool;
  7745. work->work_restart_id = work->pool->work_restart_id;
  7746. gen_stratum_work2(work, &pool->swork, pool->nonce1);
  7747. cgtime(&work->tv_staged);
  7748. }
  7749. void gen_stratum_work2(struct work *work, struct stratum_work *swork, const char *nonce1)
  7750. {
  7751. unsigned char *coinbase, merkle_root[32], merkle_sha[64];
  7752. uint8_t *merkle_bin;
  7753. uint32_t *data32, *swap32;
  7754. int i;
  7755. /* Generate coinbase */
  7756. coinbase = bytes_buf(&swork->coinbase);
  7757. memcpy(&coinbase[swork->nonce2_offset], bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  7758. /* Downgrade to a read lock to read off the variables */
  7759. if (swork->data_lock_p)
  7760. cg_dwlock(swork->data_lock_p);
  7761. /* Generate merkle root */
  7762. gen_hash(coinbase, merkle_root, bytes_len(&swork->coinbase));
  7763. memcpy(merkle_sha, merkle_root, 32);
  7764. merkle_bin = bytes_buf(&swork->merkle_bin);
  7765. for (i = 0; i < swork->merkles; ++i, merkle_bin += 32) {
  7766. memcpy(merkle_sha + 32, merkle_bin, 32);
  7767. gen_hash(merkle_sha, merkle_root, 64);
  7768. memcpy(merkle_sha, merkle_root, 32);
  7769. }
  7770. data32 = (uint32_t *)merkle_sha;
  7771. swap32 = (uint32_t *)merkle_root;
  7772. flip32(swap32, data32);
  7773. memcpy(&work->data[0], swork->header1, 36);
  7774. memcpy(&work->data[36], merkle_root, 32);
  7775. *((uint32_t*)&work->data[68]) = htobe32(swork->ntime + timer_elapsed(&swork->tv_received, NULL));
  7776. memcpy(&work->data[72], swork->diffbits, 4);
  7777. memset(&work->data[76], 0, 4); // nonce
  7778. memcpy(&work->data[80], workpadding_bin, 48);
  7779. /* Store the stratum work diff to check it still matches the pool's
  7780. * stratum diff when submitting shares */
  7781. work->sdiff = swork->diff;
  7782. /* Copy parameters required for share submission */
  7783. work->job_id = strdup(swork->job_id);
  7784. work->nonce1 = strdup(nonce1);
  7785. if (swork->data_lock_p)
  7786. cg_runlock(swork->data_lock_p);
  7787. if (opt_debug)
  7788. {
  7789. char header[161];
  7790. char nonce2hex[(bytes_len(&work->nonce2) * 2) + 1];
  7791. bin2hex(header, work->data, 80);
  7792. bin2hex(nonce2hex, bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  7793. applog(LOG_DEBUG, "Generated stratum header %s", header);
  7794. applog(LOG_DEBUG, "Work job_id %s nonce2 %s", work->job_id, nonce2hex);
  7795. }
  7796. calc_midstate(work);
  7797. set_target(work->target, work->sdiff);
  7798. local_work++;
  7799. work->stratum = true;
  7800. work->blk.nonce = 0;
  7801. work->id = total_work++;
  7802. work->longpoll = false;
  7803. work->getwork_mode = GETWORK_MODE_STRATUM;
  7804. /* Nominally allow a driver to ntime roll 60 seconds */
  7805. work->drv_rolllimit = 60;
  7806. calc_diff(work, 0);
  7807. }
  7808. void request_work(struct thr_info *thr)
  7809. {
  7810. struct cgpu_info *cgpu = thr->cgpu;
  7811. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  7812. /* Tell the watchdog thread this thread is waiting on getwork and
  7813. * should not be restarted */
  7814. thread_reportout(thr);
  7815. // HACK: Since get_work still blocks, reportout all processors dependent on this thread
  7816. for (struct cgpu_info *proc = thr->cgpu->next_proc; proc; proc = proc->next_proc)
  7817. {
  7818. if (proc->threads)
  7819. break;
  7820. thread_reportout(proc->thr[0]);
  7821. }
  7822. cgtime(&dev_stats->_get_start);
  7823. }
  7824. // FIXME: Make this non-blocking (and remove HACK above)
  7825. struct work *get_work(struct thr_info *thr)
  7826. {
  7827. const int thr_id = thr->id;
  7828. struct cgpu_info *cgpu = thr->cgpu;
  7829. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  7830. struct cgminer_stats *pool_stats;
  7831. struct timeval tv_get;
  7832. struct work *work = NULL;
  7833. applog(LOG_DEBUG, "%"PRIpreprv": Popping work from get queue to get work", cgpu->proc_repr);
  7834. while (!work) {
  7835. work = hash_pop();
  7836. if (stale_work(work, false)) {
  7837. staged_full = false; // It wasn't really full, since it was stale :(
  7838. discard_work(work);
  7839. work = NULL;
  7840. wake_gws();
  7841. }
  7842. }
  7843. last_getwork = time(NULL);
  7844. applog(LOG_DEBUG, "%"PRIpreprv": Got work %d from get queue to get work for thread %d",
  7845. cgpu->proc_repr, work->id, thr_id);
  7846. work->thr_id = thr_id;
  7847. thread_reportin(thr);
  7848. // HACK: Since get_work still blocks, reportin all processors dependent on this thread
  7849. for (struct cgpu_info *proc = thr->cgpu->next_proc; proc; proc = proc->next_proc)
  7850. {
  7851. if (proc->threads)
  7852. break;
  7853. thread_reportin(proc->thr[0]);
  7854. }
  7855. work->mined = true;
  7856. work->blk.nonce = 0;
  7857. cgtime(&tv_get);
  7858. timersub(&tv_get, &dev_stats->_get_start, &tv_get);
  7859. timeradd(&tv_get, &dev_stats->getwork_wait, &dev_stats->getwork_wait);
  7860. if (timercmp(&tv_get, &dev_stats->getwork_wait_max, >))
  7861. dev_stats->getwork_wait_max = tv_get;
  7862. if (timercmp(&tv_get, &dev_stats->getwork_wait_min, <))
  7863. dev_stats->getwork_wait_min = tv_get;
  7864. ++dev_stats->getwork_calls;
  7865. pool_stats = &(work->pool->cgminer_stats);
  7866. timeradd(&tv_get, &pool_stats->getwork_wait, &pool_stats->getwork_wait);
  7867. if (timercmp(&tv_get, &pool_stats->getwork_wait_max, >))
  7868. pool_stats->getwork_wait_max = tv_get;
  7869. if (timercmp(&tv_get, &pool_stats->getwork_wait_min, <))
  7870. pool_stats->getwork_wait_min = tv_get;
  7871. ++pool_stats->getwork_calls;
  7872. if (work->work_difficulty < 1)
  7873. {
  7874. if (unlikely(work->work_difficulty < cgpu->min_nonce_diff))
  7875. {
  7876. applog(LOG_WARNING, "%"PRIpreprv": Using work with lower difficulty than device supports",
  7877. cgpu->proc_repr);
  7878. work->nonce_diff = cgpu->min_nonce_diff;
  7879. }
  7880. else
  7881. work->nonce_diff = work->work_difficulty;
  7882. }
  7883. else
  7884. work->nonce_diff = 1;
  7885. return work;
  7886. }
  7887. static
  7888. void _submit_work_async(struct work *work)
  7889. {
  7890. applog(LOG_DEBUG, "Pushing submit work to work thread");
  7891. if (opt_benchmark)
  7892. {
  7893. json_t * const jn = json_null();
  7894. rebuild_hash(work);
  7895. share_result(jn, jn, jn, work, false, "");
  7896. free_work(work);
  7897. return;
  7898. }
  7899. mutex_lock(&submitting_lock);
  7900. ++total_submitting;
  7901. DL_APPEND(submit_waiting, work);
  7902. mutex_unlock(&submitting_lock);
  7903. notifier_wake(submit_waiting_notifier);
  7904. }
  7905. /* Submit a copy of the tested, statistic recorded work item asynchronously */
  7906. static void submit_work_async2(struct work *work, struct timeval *tv_work_found)
  7907. {
  7908. if (tv_work_found)
  7909. copy_time(&work->tv_work_found, tv_work_found);
  7910. _submit_work_async(work);
  7911. }
  7912. void inc_hw_errors3(struct thr_info *thr, const struct work *work, const uint32_t *bad_nonce_p, float nonce_diff)
  7913. {
  7914. struct cgpu_info * const cgpu = thr->cgpu;
  7915. if (bad_nonce_p)
  7916. {
  7917. if (bad_nonce_p == UNKNOWN_NONCE)
  7918. applog(LOG_DEBUG, "%"PRIpreprv": invalid nonce - HW error",
  7919. cgpu->proc_repr);
  7920. else
  7921. applog(LOG_DEBUG, "%"PRIpreprv": invalid nonce (%08lx) - HW error",
  7922. cgpu->proc_repr, (unsigned long)be32toh(*bad_nonce_p));
  7923. }
  7924. mutex_lock(&stats_lock);
  7925. hw_errors++;
  7926. ++cgpu->hw_errors;
  7927. if (bad_nonce_p)
  7928. {
  7929. total_bad_diff1 += nonce_diff;
  7930. cgpu->bad_diff1 += nonce_diff;
  7931. }
  7932. mutex_unlock(&stats_lock);
  7933. if (thr->cgpu->drv->hw_error)
  7934. thr->cgpu->drv->hw_error(thr);
  7935. }
  7936. enum test_nonce2_result hashtest2(struct work *work, bool checktarget)
  7937. {
  7938. uint32_t *hash2_32 = (uint32_t *)&work->hash[0];
  7939. hash_data(work->hash, work->data);
  7940. if (hash2_32[7] != 0)
  7941. return TNR_BAD;
  7942. if (!checktarget)
  7943. return TNR_GOOD;
  7944. if (!hash_target_check_v(work->hash, work->target))
  7945. return TNR_HIGH;
  7946. return TNR_GOOD;
  7947. }
  7948. enum test_nonce2_result _test_nonce2(struct work *work, uint32_t nonce, bool checktarget)
  7949. {
  7950. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  7951. *work_nonce = htole32(nonce);
  7952. #ifdef USE_SCRYPT
  7953. if (opt_scrypt)
  7954. // NOTE: Depends on scrypt_test return matching enum values
  7955. return scrypt_test(work->data, work->target, nonce);
  7956. #endif
  7957. return hashtest2(work, checktarget);
  7958. }
  7959. /* Returns true if nonce for work was a valid share */
  7960. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  7961. {
  7962. return submit_noffset_nonce(thr, work, nonce, 0);
  7963. }
  7964. /* Allows drivers to submit work items where the driver has changed the ntime
  7965. * value by noffset. Must be only used with a work protocol that does not ntime
  7966. * roll itself intrinsically to generate work (eg stratum). We do not touch
  7967. * the original work struct, but the copy of it only. */
  7968. bool submit_noffset_nonce(struct thr_info *thr, struct work *work_in, uint32_t nonce,
  7969. int noffset)
  7970. {
  7971. struct work *work = make_work();
  7972. _copy_work(work, work_in, noffset);
  7973. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  7974. struct timeval tv_work_found;
  7975. enum test_nonce2_result res;
  7976. bool ret = true;
  7977. thread_reportout(thr);
  7978. cgtime(&tv_work_found);
  7979. *work_nonce = htole32(nonce);
  7980. work->thr_id = thr->id;
  7981. /* Do one last check before attempting to submit the work */
  7982. /* Side effect: sets work->data for us */
  7983. res = test_nonce2(work, nonce);
  7984. if (unlikely(res == TNR_BAD))
  7985. {
  7986. inc_hw_errors(thr, work, nonce);
  7987. ret = false;
  7988. goto out;
  7989. }
  7990. mutex_lock(&stats_lock);
  7991. total_diff1 += work->nonce_diff;
  7992. thr ->cgpu->diff1 += work->nonce_diff;
  7993. work->pool->diff1 += work->nonce_diff;
  7994. thr->cgpu->last_device_valid_work = time(NULL);
  7995. mutex_unlock(&stats_lock);
  7996. if (noncelog_file)
  7997. noncelog(work);
  7998. if (res == TNR_HIGH)
  7999. {
  8000. // Share above target, normal
  8001. /* Check the diff of the share, even if it didn't reach the
  8002. * target, just to set the best share value if it's higher. */
  8003. share_diff(work);
  8004. goto out;
  8005. }
  8006. submit_work_async2(work, &tv_work_found);
  8007. work = NULL; // Taken by submit_work_async2
  8008. out:
  8009. if (work)
  8010. free_work(work);
  8011. thread_reportin(thr);
  8012. return ret;
  8013. }
  8014. bool abandon_work(struct work *work, struct timeval *wdiff, uint64_t hashes)
  8015. {
  8016. if (wdiff->tv_sec > opt_scantime ||
  8017. work->blk.nonce >= 0xfffffffe - hashes ||
  8018. hashes >= 0xfffffffe ||
  8019. stale_work(work, false))
  8020. return true;
  8021. return false;
  8022. }
  8023. void __thr_being_msg(int prio, struct thr_info *thr, const char *being)
  8024. {
  8025. struct cgpu_info *proc = thr->cgpu;
  8026. if (proc->threads > 1)
  8027. applog(prio, "%"PRIpreprv" (thread %d) %s", proc->proc_repr, thr->id, being);
  8028. else
  8029. applog(prio, "%"PRIpreprv" %s", proc->proc_repr, being);
  8030. }
  8031. // Called by asynchronous minerloops, when they find their processor should be disabled
  8032. void mt_disable_start(struct thr_info *mythr)
  8033. {
  8034. struct cgpu_info *cgpu = mythr->cgpu;
  8035. struct device_drv *drv = cgpu->drv;
  8036. if (drv->thread_disable)
  8037. drv->thread_disable(mythr);
  8038. hashmeter2(mythr);
  8039. __thr_being_msg(LOG_WARNING, mythr, "being disabled");
  8040. mythr->rolling = mythr->cgpu->rolling = 0;
  8041. thread_reportout(mythr);
  8042. mythr->_mt_disable_called = true;
  8043. }
  8044. /* Put a new unqueued work item in cgpu->unqueued_work under cgpu->qlock till
  8045. * the driver tells us it's full so that it may extract the work item using
  8046. * the get_queued() function which adds it to the hashtable on
  8047. * cgpu->queued_work. */
  8048. static void fill_queue(struct thr_info *mythr, struct cgpu_info *cgpu, struct device_drv *drv, const int thr_id)
  8049. {
  8050. thread_reportout(mythr);
  8051. do {
  8052. bool need_work;
  8053. /* Do this lockless just to know if we need more unqueued work. */
  8054. need_work = (!cgpu->unqueued_work);
  8055. /* get_work is a blocking function so do it outside of lock
  8056. * to prevent deadlocks with other locks. */
  8057. if (need_work) {
  8058. struct work *work = get_work(mythr);
  8059. wr_lock(&cgpu->qlock);
  8060. /* Check we haven't grabbed work somehow between
  8061. * checking and picking up the lock. */
  8062. if (likely(!cgpu->unqueued_work))
  8063. cgpu->unqueued_work = work;
  8064. else
  8065. need_work = false;
  8066. wr_unlock(&cgpu->qlock);
  8067. if (unlikely(!need_work))
  8068. discard_work(work);
  8069. }
  8070. /* The queue_full function should be used by the driver to
  8071. * actually place work items on the physical device if it
  8072. * does have a queue. */
  8073. } while (drv->queue_full && !drv->queue_full(cgpu));
  8074. }
  8075. /* Add a work item to a cgpu's queued hashlist */
  8076. void __add_queued(struct cgpu_info *cgpu, struct work *work)
  8077. {
  8078. cgpu->queued_count++;
  8079. HASH_ADD_INT(cgpu->queued_work, id, work);
  8080. }
  8081. /* This function is for retrieving one work item from the unqueued pointer and
  8082. * adding it to the hashtable of queued work. Code using this function must be
  8083. * able to handle NULL as a return which implies there is no work available. */
  8084. struct work *get_queued(struct cgpu_info *cgpu)
  8085. {
  8086. struct work *work = NULL;
  8087. wr_lock(&cgpu->qlock);
  8088. if (cgpu->unqueued_work) {
  8089. work = cgpu->unqueued_work;
  8090. if (unlikely(stale_work(work, false))) {
  8091. discard_work(work);
  8092. work = NULL;
  8093. wake_gws();
  8094. } else
  8095. __add_queued(cgpu, work);
  8096. cgpu->unqueued_work = NULL;
  8097. }
  8098. wr_unlock(&cgpu->qlock);
  8099. return work;
  8100. }
  8101. void add_queued(struct cgpu_info *cgpu, struct work *work)
  8102. {
  8103. wr_lock(&cgpu->qlock);
  8104. __add_queued(cgpu, work);
  8105. wr_unlock(&cgpu->qlock);
  8106. }
  8107. /* Get fresh work and add it to cgpu's queued hashlist */
  8108. struct work *get_queue_work(struct thr_info *thr, struct cgpu_info *cgpu, int thr_id)
  8109. {
  8110. struct work *work = get_work(thr);
  8111. add_queued(cgpu, work);
  8112. return work;
  8113. }
  8114. /* This function is for finding an already queued work item in the
  8115. * given que hashtable. Code using this function must be able
  8116. * to handle NULL as a return which implies there is no matching work.
  8117. * The calling function must lock access to the que if it is required.
  8118. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  8119. struct work *__find_work_bymidstate(struct work *que, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  8120. {
  8121. struct work *work, *tmp, *ret = NULL;
  8122. HASH_ITER(hh, que, work, tmp) {
  8123. if (memcmp(work->midstate, midstate, midstatelen) == 0 &&
  8124. memcmp(work->data + offset, data, datalen) == 0) {
  8125. ret = work;
  8126. break;
  8127. }
  8128. }
  8129. return ret;
  8130. }
  8131. /* This function is for finding an already queued work item in the
  8132. * device's queued_work hashtable. Code using this function must be able
  8133. * to handle NULL as a return which implies there is no matching work.
  8134. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  8135. struct work *find_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  8136. {
  8137. struct work *ret;
  8138. rd_lock(&cgpu->qlock);
  8139. ret = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  8140. rd_unlock(&cgpu->qlock);
  8141. return ret;
  8142. }
  8143. struct work *clone_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  8144. {
  8145. struct work *work, *ret = NULL;
  8146. rd_lock(&cgpu->qlock);
  8147. work = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  8148. if (work)
  8149. ret = copy_work(work);
  8150. rd_unlock(&cgpu->qlock);
  8151. return ret;
  8152. }
  8153. void __work_completed(struct cgpu_info *cgpu, struct work *work)
  8154. {
  8155. cgpu->queued_count--;
  8156. HASH_DEL(cgpu->queued_work, work);
  8157. }
  8158. /* This function should be used by queued device drivers when they're sure
  8159. * the work struct is no longer in use. */
  8160. void work_completed(struct cgpu_info *cgpu, struct work *work)
  8161. {
  8162. wr_lock(&cgpu->qlock);
  8163. __work_completed(cgpu, work);
  8164. wr_unlock(&cgpu->qlock);
  8165. free_work(work);
  8166. }
  8167. /* Combines find_queued_work_bymidstate and work_completed in one function
  8168. * withOUT destroying the work so the driver must free it. */
  8169. struct work *take_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  8170. {
  8171. struct work *work;
  8172. wr_lock(&cgpu->qlock);
  8173. work = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  8174. if (work)
  8175. __work_completed(cgpu, work);
  8176. wr_unlock(&cgpu->qlock);
  8177. return work;
  8178. }
  8179. static void flush_queue(struct cgpu_info *cgpu)
  8180. {
  8181. struct work *work = NULL;
  8182. wr_lock(&cgpu->qlock);
  8183. work = cgpu->unqueued_work;
  8184. cgpu->unqueued_work = NULL;
  8185. wr_unlock(&cgpu->qlock);
  8186. if (work) {
  8187. free_work(work);
  8188. applog(LOG_DEBUG, "Discarded queued work item");
  8189. }
  8190. }
  8191. /* This version of hash work is for devices that are fast enough to always
  8192. * perform a full nonce range and need a queue to maintain the device busy.
  8193. * Work creation and destruction is not done from within this function
  8194. * directly. */
  8195. void hash_queued_work(struct thr_info *mythr)
  8196. {
  8197. const long cycle = opt_log_interval / 5 ? : 1;
  8198. struct timeval tv_start = {0, 0}, tv_end;
  8199. struct cgpu_info *cgpu = mythr->cgpu;
  8200. struct device_drv *drv = cgpu->drv;
  8201. const int thr_id = mythr->id;
  8202. int64_t hashes_done = 0;
  8203. if (unlikely(cgpu->deven != DEV_ENABLED))
  8204. mt_disable(mythr);
  8205. while (likely(!cgpu->shutdown)) {
  8206. struct timeval diff;
  8207. int64_t hashes;
  8208. fill_queue(mythr, cgpu, drv, thr_id);
  8209. thread_reportin(mythr);
  8210. hashes = drv->scanwork(mythr);
  8211. /* Reset the bool here in case the driver looks for it
  8212. * synchronously in the scanwork loop. */
  8213. mythr->work_restart = false;
  8214. if (unlikely(hashes == -1 )) {
  8215. applog(LOG_ERR, "%s %d failure, disabling!", drv->name, cgpu->device_id);
  8216. cgpu->deven = DEV_DISABLED;
  8217. dev_error(cgpu, REASON_THREAD_ZERO_HASH);
  8218. mt_disable(mythr);
  8219. }
  8220. hashes_done += hashes;
  8221. cgtime(&tv_end);
  8222. timersub(&tv_end, &tv_start, &diff);
  8223. if (diff.tv_sec >= cycle) {
  8224. hashmeter(thr_id, &diff, hashes_done);
  8225. hashes_done = 0;
  8226. copy_time(&tv_start, &tv_end);
  8227. }
  8228. if (unlikely(mythr->pause || cgpu->deven != DEV_ENABLED))
  8229. mt_disable(mythr);
  8230. if (unlikely(mythr->work_restart)) {
  8231. flush_queue(cgpu);
  8232. if (drv->flush_work)
  8233. drv->flush_work(cgpu);
  8234. }
  8235. }
  8236. // cgpu->deven = DEV_DISABLED; set in miner_thread
  8237. }
  8238. // Called by minerloop, when it is re-enabling a processor
  8239. void mt_disable_finish(struct thr_info *mythr)
  8240. {
  8241. struct device_drv *drv = mythr->cgpu->drv;
  8242. thread_reportin(mythr);
  8243. __thr_being_msg(LOG_WARNING, mythr, "being re-enabled");
  8244. if (drv->thread_enable)
  8245. drv->thread_enable(mythr);
  8246. mythr->_mt_disable_called = false;
  8247. }
  8248. // Called by synchronous minerloops, when they find their processor should be disabled
  8249. // Calls mt_disable_start, waits until it's re-enabled, then calls mt_disable_finish
  8250. void mt_disable(struct thr_info *mythr)
  8251. {
  8252. const struct cgpu_info * const cgpu = mythr->cgpu;
  8253. mt_disable_start(mythr);
  8254. applog(LOG_DEBUG, "Waiting for wakeup notification in miner thread");
  8255. do {
  8256. notifier_read(mythr->notifier);
  8257. } while (mythr->pause || cgpu->deven != DEV_ENABLED);
  8258. mt_disable_finish(mythr);
  8259. }
  8260. enum {
  8261. STAT_SLEEP_INTERVAL = 1,
  8262. STAT_CTR_INTERVAL = 10000000,
  8263. FAILURE_INTERVAL = 30,
  8264. };
  8265. /* Stage another work item from the work returned in a longpoll */
  8266. 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)
  8267. {
  8268. bool rc;
  8269. work->rolltime = rolltime;
  8270. rc = work_decode(pool, work, val);
  8271. if (unlikely(!rc)) {
  8272. applog(LOG_ERR, "Could not convert longpoll data to work");
  8273. free_work(work);
  8274. return;
  8275. }
  8276. total_getworks++;
  8277. pool->getwork_requested++;
  8278. work->pool = pool;
  8279. copy_time(&work->tv_getwork, tv_lp);
  8280. copy_time(&work->tv_getwork_reply, tv_lp_reply);
  8281. calc_diff(work, 0);
  8282. if (pool->enabled == POOL_REJECTING)
  8283. work->mandatory = true;
  8284. work->longpoll = true;
  8285. work->getwork_mode = GETWORK_MODE_LP;
  8286. update_last_work(work);
  8287. /* We'll be checking this work item twice, but we already know it's
  8288. * from a new block so explicitly force the new block detection now
  8289. * rather than waiting for it to hit the stage thread. This also
  8290. * allows testwork to know whether LP discovered the block or not. */
  8291. test_work_current(work);
  8292. /* Don't use backup LPs as work if we have failover-only enabled. Use
  8293. * the longpoll work from a pool that has been rejecting shares as a
  8294. * way to detect when the pool has recovered.
  8295. */
  8296. if (pool != current_pool() && opt_fail_only && pool->enabled != POOL_REJECTING) {
  8297. free_work(work);
  8298. return;
  8299. }
  8300. work = clone_work(work);
  8301. applog(LOG_DEBUG, "Pushing converted work to stage thread");
  8302. stage_work(work);
  8303. applog(LOG_DEBUG, "Converted longpoll data to work");
  8304. }
  8305. /* If we want longpoll, enable it for the chosen default pool, or, if
  8306. * the pool does not support longpoll, find the first one that does
  8307. * and use its longpoll support */
  8308. static struct pool *select_longpoll_pool(struct pool *cp)
  8309. {
  8310. int i;
  8311. if (cp->lp_url)
  8312. return cp;
  8313. for (i = 0; i < total_pools; i++) {
  8314. struct pool *pool = pools[i];
  8315. if (pool->has_stratum || pool->lp_url)
  8316. return pool;
  8317. }
  8318. return NULL;
  8319. }
  8320. /* This will make the longpoll thread wait till it's the current pool, or it
  8321. * has been flagged as rejecting, before attempting to open any connections.
  8322. */
  8323. static void wait_lpcurrent(struct pool *pool)
  8324. {
  8325. while (!cnx_needed(pool))
  8326. {
  8327. mutex_lock(&lp_lock);
  8328. pthread_cond_wait(&lp_cond, &lp_lock);
  8329. mutex_unlock(&lp_lock);
  8330. }
  8331. }
  8332. static curl_socket_t save_curl_socket(void *vpool, __maybe_unused curlsocktype purpose, struct curl_sockaddr *addr) {
  8333. struct pool *pool = vpool;
  8334. curl_socket_t sock = socket(addr->family, addr->socktype, addr->protocol);
  8335. pool->lp_socket = sock;
  8336. return sock;
  8337. }
  8338. static void *longpoll_thread(void *userdata)
  8339. {
  8340. struct pool *cp = (struct pool *)userdata;
  8341. /* This *pool is the source of the actual longpoll, not the pool we've
  8342. * tied it to */
  8343. struct timeval start, reply, end;
  8344. struct pool *pool = NULL;
  8345. char threadname[20];
  8346. CURL *curl = NULL;
  8347. int failures = 0;
  8348. char *lp_url;
  8349. int rolltime;
  8350. #ifndef HAVE_PTHREAD_CANCEL
  8351. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  8352. #endif
  8353. snprintf(threadname, 20, "longpoll%u", cp->pool_no);
  8354. RenameThread(threadname);
  8355. curl = curl_easy_init();
  8356. if (unlikely(!curl)) {
  8357. applog(LOG_ERR, "CURL initialisation failed");
  8358. return NULL;
  8359. }
  8360. retry_pool:
  8361. pool = select_longpoll_pool(cp);
  8362. if (!pool) {
  8363. applog(LOG_WARNING, "No suitable long-poll found for %s", cp->rpc_url);
  8364. while (!pool) {
  8365. cgsleep_ms(60000);
  8366. pool = select_longpoll_pool(cp);
  8367. }
  8368. }
  8369. if (pool->has_stratum) {
  8370. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  8371. cp->rpc_url, pool->rpc_url);
  8372. goto out;
  8373. }
  8374. /* Any longpoll from any pool is enough for this to be true */
  8375. have_longpoll = true;
  8376. wait_lpcurrent(cp);
  8377. {
  8378. lp_url = pool->lp_url;
  8379. if (cp == pool)
  8380. applog(LOG_WARNING, "Long-polling activated for %s (%s)", lp_url, pool_protocol_name(pool->lp_proto));
  8381. else
  8382. applog(LOG_WARNING, "Long-polling activated for %s via %s (%s)", cp->rpc_url, lp_url, pool_protocol_name(pool->lp_proto));
  8383. }
  8384. while (42) {
  8385. json_t *val, *soval;
  8386. struct work *work = make_work();
  8387. char *lpreq;
  8388. lpreq = prepare_rpc_req(work, pool->lp_proto, pool->lp_id);
  8389. work->pool = pool;
  8390. if (!lpreq)
  8391. {
  8392. free_work(work);
  8393. goto lpfail;
  8394. }
  8395. wait_lpcurrent(cp);
  8396. cgtime(&start);
  8397. /* Longpoll connections can be persistent for a very long time
  8398. * and any number of issues could have come up in the meantime
  8399. * so always establish a fresh connection instead of relying on
  8400. * a persistent one. */
  8401. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  8402. curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, save_curl_socket);
  8403. curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, pool);
  8404. val = json_rpc_call(curl, lp_url, pool->rpc_userpass,
  8405. lpreq, false, true, &rolltime, pool, false);
  8406. pool->lp_socket = CURL_SOCKET_BAD;
  8407. cgtime(&reply);
  8408. free(lpreq);
  8409. if (likely(val)) {
  8410. soval = json_object_get(json_object_get(val, "result"), "submitold");
  8411. if (soval)
  8412. pool->submit_old = json_is_true(soval);
  8413. else
  8414. pool->submit_old = false;
  8415. convert_to_work(val, rolltime, pool, work, &start, &reply);
  8416. failures = 0;
  8417. json_decref(val);
  8418. } else {
  8419. /* Some pools regularly drop the longpoll request so
  8420. * only see this as longpoll failure if it happens
  8421. * immediately and just restart it the rest of the
  8422. * time. */
  8423. cgtime(&end);
  8424. free_work(work);
  8425. if (end.tv_sec - start.tv_sec > 30)
  8426. continue;
  8427. if (failures == 1)
  8428. applog(LOG_WARNING, "longpoll failed for %s, retrying every 30s", lp_url);
  8429. lpfail:
  8430. cgsleep_ms(30000);
  8431. }
  8432. if (pool != cp) {
  8433. pool = select_longpoll_pool(cp);
  8434. if (pool->has_stratum) {
  8435. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  8436. cp->rpc_url, pool->rpc_url);
  8437. break;
  8438. }
  8439. if (unlikely(!pool))
  8440. goto retry_pool;
  8441. }
  8442. if (unlikely(pool->removed))
  8443. break;
  8444. }
  8445. out:
  8446. curl_easy_cleanup(curl);
  8447. return NULL;
  8448. }
  8449. static void stop_longpoll(void)
  8450. {
  8451. int i;
  8452. want_longpoll = false;
  8453. for (i = 0; i < total_pools; ++i)
  8454. {
  8455. struct pool *pool = pools[i];
  8456. if (unlikely(!pool->lp_started))
  8457. continue;
  8458. pool->lp_started = false;
  8459. pthread_cancel(pool->longpoll_thread);
  8460. }
  8461. have_longpoll = false;
  8462. }
  8463. static void start_longpoll(void)
  8464. {
  8465. int i;
  8466. want_longpoll = true;
  8467. for (i = 0; i < total_pools; ++i)
  8468. {
  8469. struct pool *pool = pools[i];
  8470. if (unlikely(pool->removed || pool->lp_started || !pool->lp_url))
  8471. continue;
  8472. pool->lp_started = true;
  8473. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  8474. quit(1, "Failed to create pool longpoll thread");
  8475. }
  8476. }
  8477. void reinit_device(struct cgpu_info *cgpu)
  8478. {
  8479. if (cgpu->drv->reinit_device)
  8480. cgpu->drv->reinit_device(cgpu);
  8481. }
  8482. static struct timeval rotate_tv;
  8483. /* We reap curls if they are unused for over a minute */
  8484. static void reap_curl(struct pool *pool)
  8485. {
  8486. struct curl_ent *ent, *iter;
  8487. struct timeval now;
  8488. int reaped = 0;
  8489. cgtime(&now);
  8490. mutex_lock(&pool->pool_lock);
  8491. LL_FOREACH_SAFE(pool->curllist, ent, iter) {
  8492. if (pool->curls < 2)
  8493. break;
  8494. if (now.tv_sec - ent->tv.tv_sec > 300) {
  8495. reaped++;
  8496. pool->curls--;
  8497. LL_DELETE(pool->curllist, ent);
  8498. curl_easy_cleanup(ent->curl);
  8499. free(ent);
  8500. }
  8501. }
  8502. mutex_unlock(&pool->pool_lock);
  8503. if (reaped)
  8504. applog(LOG_DEBUG, "Reaped %d curl%s from pool %d", reaped, reaped > 1 ? "s" : "", pool->pool_no);
  8505. }
  8506. static void *watchpool_thread(void __maybe_unused *userdata)
  8507. {
  8508. int intervals = 0;
  8509. #ifndef HAVE_PTHREAD_CANCEL
  8510. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  8511. #endif
  8512. RenameThread("watchpool");
  8513. while (42) {
  8514. struct timeval now;
  8515. int i;
  8516. if (++intervals > 20)
  8517. intervals = 0;
  8518. cgtime(&now);
  8519. for (i = 0; i < total_pools; i++) {
  8520. struct pool *pool = pools[i];
  8521. if (!opt_benchmark)
  8522. reap_curl(pool);
  8523. /* Get a rolling utility per pool over 10 mins */
  8524. if (intervals > 19) {
  8525. int shares = pool->diff1 - pool->last_shares;
  8526. pool->last_shares = pool->diff1;
  8527. pool->utility = (pool->utility + (double)shares * 0.63) / 1.63;
  8528. pool->shares = pool->utility;
  8529. }
  8530. if (pool->enabled == POOL_DISABLED)
  8531. continue;
  8532. /* Don't start testing any pools if the test threads
  8533. * from startup are still doing their first attempt. */
  8534. if (unlikely(pool->testing)) {
  8535. pthread_join(pool->test_thread, NULL);
  8536. }
  8537. /* Test pool is idle once every minute */
  8538. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 30) {
  8539. cgtime(&pool->tv_idle);
  8540. if (pool_active(pool, true) && pool_tclear(pool, &pool->idle))
  8541. pool_resus(pool);
  8542. }
  8543. /* Only switch pools if the failback pool has been
  8544. * alive for more than 5 minutes to prevent
  8545. * intermittently failing pools from being used. */
  8546. if (!pool->idle && pool_strategy == POOL_FAILOVER && pool->prio < cp_prio() &&
  8547. now.tv_sec - pool->tv_idle.tv_sec > 300) {
  8548. applog(LOG_WARNING, "Pool %d %s stable for 5 mins",
  8549. pool->pool_no, pool->rpc_url);
  8550. switch_pools(NULL);
  8551. }
  8552. }
  8553. if (current_pool()->idle)
  8554. switch_pools(NULL);
  8555. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  8556. cgtime(&rotate_tv);
  8557. switch_pools(NULL);
  8558. }
  8559. cgsleep_ms(30000);
  8560. }
  8561. return NULL;
  8562. }
  8563. void mt_enable(struct thr_info *thr)
  8564. {
  8565. applog(LOG_DEBUG, "Waking up thread %d", thr->id);
  8566. notifier_wake(thr->notifier);
  8567. }
  8568. void proc_enable(struct cgpu_info *cgpu)
  8569. {
  8570. int j;
  8571. cgpu->deven = DEV_ENABLED;
  8572. for (j = cgpu->threads ?: 1; j--; )
  8573. mt_enable(cgpu->thr[j]);
  8574. }
  8575. #define device_recovered(cgpu) proc_enable(cgpu)
  8576. void cgpu_set_defaults(struct cgpu_info * const cgpu)
  8577. {
  8578. struct string_elist *setstr_elist;
  8579. const char *p, *p2;
  8580. char replybuf[0x2000];
  8581. size_t L;
  8582. DL_FOREACH(opt_set_device_list, setstr_elist)
  8583. {
  8584. const char * const setstr = setstr_elist->string;
  8585. p = strchr(setstr, ':');
  8586. if (!p)
  8587. p = setstr;
  8588. {
  8589. L = p - setstr;
  8590. char pattern[L + 1];
  8591. if (L)
  8592. memcpy(pattern, setstr, L);
  8593. pattern[L] = '\0';
  8594. if (!cgpu_match(pattern, cgpu))
  8595. continue;
  8596. }
  8597. applog(LOG_DEBUG, "%"PRIpreprv": %s: Matched with set default: %s",
  8598. cgpu->proc_repr, __func__, setstr);
  8599. if (p[0] == ':')
  8600. ++p;
  8601. p2 = strchr(p, '=');
  8602. if (!p2)
  8603. {
  8604. L = strlen(p);
  8605. p2 = "";
  8606. }
  8607. else
  8608. {
  8609. L = p2 - p;
  8610. ++p2;
  8611. }
  8612. char opt[L + 1];
  8613. if (L)
  8614. memcpy(opt, p, L);
  8615. opt[L] = '\0';
  8616. L = strlen(p2);
  8617. char setval[L + 1];
  8618. if (L)
  8619. memcpy(setval, p2, L);
  8620. setval[L] = '\0';
  8621. enum bfg_set_device_replytype success;
  8622. p = proc_set_device(cgpu, opt, setval, replybuf, &success);
  8623. switch (success)
  8624. {
  8625. case SDR_OK:
  8626. applog(LOG_DEBUG, "%"PRIpreprv": Applied rule %s%s%s",
  8627. cgpu->proc_repr, setstr,
  8628. p ? ": " : "", p ?: "");
  8629. break;
  8630. case SDR_ERR:
  8631. case SDR_HELP:
  8632. case SDR_UNKNOWN:
  8633. applog(LOG_DEBUG, "%"PRIpreprv": Applying rule %s: %s",
  8634. cgpu->proc_repr, setstr, p);
  8635. break;
  8636. case SDR_AUTO:
  8637. case SDR_NOSUPP:
  8638. applog(LOG_WARNING, "%"PRIpreprv": set_device is not implemented (trying to apply rule: %s)",
  8639. cgpu->proc_repr, setstr);
  8640. }
  8641. }
  8642. cgpu->already_set_defaults = true;
  8643. }
  8644. 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)
  8645. {
  8646. struct device_drv dummy_drv = *drv;
  8647. struct cgpu_info dummy_cgpu = {
  8648. .drv = &dummy_drv,
  8649. .device = &dummy_cgpu,
  8650. .device_id = -1,
  8651. .proc_id = -1,
  8652. .device_data = userp,
  8653. .device_path = devpath,
  8654. .dev_serial = serial,
  8655. };
  8656. strcpy(dummy_cgpu.proc_repr, drv->name);
  8657. switch (mode)
  8658. {
  8659. case 0:
  8660. dummy_drv.set_device = datap;
  8661. break;
  8662. case 1:
  8663. dummy_drv.set_device = NULL;
  8664. dummy_cgpu.set_device_funcs = datap;
  8665. break;
  8666. }
  8667. cgpu_set_defaults(&dummy_cgpu);
  8668. }
  8669. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  8670. * the screen at regular intervals, and restarts threads if they appear to have
  8671. * died. */
  8672. #define WATCHDOG_SICK_TIME 60
  8673. #define WATCHDOG_DEAD_TIME 600
  8674. #define WATCHDOG_SICK_COUNT (WATCHDOG_SICK_TIME/WATCHDOG_INTERVAL)
  8675. #define WATCHDOG_DEAD_COUNT (WATCHDOG_DEAD_TIME/WATCHDOG_INTERVAL)
  8676. static void *watchdog_thread(void __maybe_unused *userdata)
  8677. {
  8678. const unsigned int interval = WATCHDOG_INTERVAL;
  8679. struct timeval zero_tv;
  8680. #ifndef HAVE_PTHREAD_CANCEL
  8681. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  8682. #endif
  8683. RenameThread("watchdog");
  8684. memset(&zero_tv, 0, sizeof(struct timeval));
  8685. cgtime(&rotate_tv);
  8686. while (1) {
  8687. int i;
  8688. struct timeval now;
  8689. sleep(interval);
  8690. discard_stale();
  8691. hashmeter(-1, &zero_tv, 0);
  8692. #ifdef HAVE_CURSES
  8693. const int ts = total_staged();
  8694. if (curses_active_locked()) {
  8695. change_logwinsize();
  8696. curses_print_status(ts);
  8697. _refresh_devstatus(true);
  8698. touchwin(logwin);
  8699. wrefresh(logwin);
  8700. unlock_curses();
  8701. }
  8702. #endif
  8703. cgtime(&now);
  8704. if (!sched_paused && !should_run()) {
  8705. applog(LOG_WARNING, "Pausing execution as per stop time %02d:%02d scheduled",
  8706. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  8707. if (!schedstart.enable) {
  8708. quit(0, "Terminating execution as planned");
  8709. break;
  8710. }
  8711. applog(LOG_WARNING, "Will restart execution as scheduled at %02d:%02d",
  8712. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  8713. sched_paused = true;
  8714. rd_lock(&mining_thr_lock);
  8715. for (i = 0; i < mining_threads; i++)
  8716. mining_thr[i]->pause = true;
  8717. rd_unlock(&mining_thr_lock);
  8718. } else if (sched_paused && should_run()) {
  8719. applog(LOG_WARNING, "Restarting execution as per start time %02d:%02d scheduled",
  8720. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  8721. if (schedstop.enable)
  8722. applog(LOG_WARNING, "Will pause execution as scheduled at %02d:%02d",
  8723. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  8724. sched_paused = false;
  8725. for (i = 0; i < mining_threads; i++) {
  8726. struct thr_info *thr;
  8727. thr = get_thread(i);
  8728. thr->pause = false;
  8729. }
  8730. for (i = 0; i < total_devices; ++i)
  8731. {
  8732. struct cgpu_info *cgpu = get_devices(i);
  8733. /* Don't touch disabled devices */
  8734. if (cgpu->deven == DEV_DISABLED)
  8735. continue;
  8736. proc_enable(cgpu);
  8737. }
  8738. }
  8739. for (i = 0; i < total_devices; ++i) {
  8740. struct cgpu_info *cgpu = get_devices(i);
  8741. if (!cgpu->disable_watchdog)
  8742. bfg_watchdog(cgpu, &now);
  8743. }
  8744. }
  8745. return NULL;
  8746. }
  8747. void bfg_watchdog(struct cgpu_info * const cgpu, struct timeval * const tvp_now)
  8748. {
  8749. struct thr_info *thr = cgpu->thr[0];
  8750. enum dev_enable *denable;
  8751. char *dev_str = cgpu->proc_repr;
  8752. if (likely(drv_ready(cgpu)))
  8753. {
  8754. if (unlikely(!cgpu->already_set_defaults))
  8755. cgpu_set_defaults(cgpu);
  8756. if (cgpu->drv->get_stats)
  8757. cgpu->drv->get_stats(cgpu);
  8758. }
  8759. denable = &cgpu->deven;
  8760. if (cgpu->drv->watchdog)
  8761. cgpu->drv->watchdog(cgpu, tvp_now);
  8762. /* Thread is disabled */
  8763. if (*denable == DEV_DISABLED)
  8764. return;
  8765. else
  8766. if (*denable == DEV_RECOVER_ERR) {
  8767. if (opt_restart && timer_elapsed(&cgpu->tv_device_last_not_well, NULL) > cgpu->reinit_backoff) {
  8768. applog(LOG_NOTICE, "Attempting to reinitialize %s",
  8769. dev_str);
  8770. if (cgpu->reinit_backoff < 300)
  8771. cgpu->reinit_backoff *= 2;
  8772. device_recovered(cgpu);
  8773. }
  8774. return;
  8775. }
  8776. else
  8777. if (*denable == DEV_RECOVER) {
  8778. if (opt_restart && cgpu->temp < cgpu->targettemp) {
  8779. applog(LOG_NOTICE, "%s recovered to temperature below target, re-enabling",
  8780. dev_str);
  8781. device_recovered(cgpu);
  8782. }
  8783. dev_error_update(cgpu, REASON_DEV_THERMAL_CUTOFF);
  8784. return;
  8785. }
  8786. else
  8787. if (cgpu->temp > cgpu->cutofftemp)
  8788. {
  8789. applog(LOG_WARNING, "%s hit thermal cutoff limit at %dC, disabling!",
  8790. dev_str, (int)cgpu->temp);
  8791. *denable = DEV_RECOVER;
  8792. dev_error(cgpu, REASON_DEV_THERMAL_CUTOFF);
  8793. run_cmd(cmd_idle);
  8794. }
  8795. if (thr->getwork) {
  8796. if (cgpu->status == LIFE_WELL && thr->getwork < tvp_now->tv_sec - opt_log_interval) {
  8797. int thrid;
  8798. bool cgpu_idle = true;
  8799. thr->rolling = 0;
  8800. for (thrid = 0; thrid < cgpu->threads; ++thrid)
  8801. if (!cgpu->thr[thrid]->getwork)
  8802. cgpu_idle = false;
  8803. if (cgpu_idle) {
  8804. cgpu->rolling = 0;
  8805. cgpu->status = LIFE_WAIT;
  8806. }
  8807. }
  8808. return;
  8809. }
  8810. else if (cgpu->status == LIFE_WAIT)
  8811. cgpu->status = LIFE_WELL;
  8812. #ifdef WANT_CPUMINE
  8813. if (!strcmp(cgpu->drv->dname, "cpu"))
  8814. return;
  8815. #endif
  8816. if (cgpu->status != LIFE_WELL && (tvp_now->tv_sec - thr->last.tv_sec < WATCHDOG_SICK_TIME)) {
  8817. if (likely(cgpu->status != LIFE_INIT && cgpu->status != LIFE_INIT2))
  8818. applog(LOG_ERR, "%s: Recovered, declaring WELL!", dev_str);
  8819. cgpu->status = LIFE_WELL;
  8820. cgpu->device_last_well = time(NULL);
  8821. } else if (cgpu->status == LIFE_WELL && (tvp_now->tv_sec - thr->last.tv_sec > WATCHDOG_SICK_TIME)) {
  8822. thr->rolling = cgpu->rolling = 0;
  8823. cgpu->status = LIFE_SICK;
  8824. applog(LOG_ERR, "%s: Idle for more than 60 seconds, declaring SICK!", dev_str);
  8825. cgtime(&thr->sick);
  8826. dev_error(cgpu, REASON_DEV_SICK_IDLE_60);
  8827. run_cmd(cmd_sick);
  8828. if (opt_restart && cgpu->drv->reinit_device) {
  8829. applog(LOG_ERR, "%s: Attempting to restart", dev_str);
  8830. reinit_device(cgpu);
  8831. }
  8832. } else if (cgpu->status == LIFE_SICK && (tvp_now->tv_sec - thr->last.tv_sec > WATCHDOG_DEAD_TIME)) {
  8833. cgpu->status = LIFE_DEAD;
  8834. applog(LOG_ERR, "%s: Not responded for more than 10 minutes, declaring DEAD!", dev_str);
  8835. cgtime(&thr->sick);
  8836. dev_error(cgpu, REASON_DEV_DEAD_IDLE_600);
  8837. run_cmd(cmd_dead);
  8838. } else if (tvp_now->tv_sec - thr->sick.tv_sec > 60 &&
  8839. (cgpu->status == LIFE_SICK || cgpu->status == LIFE_DEAD)) {
  8840. /* Attempt to restart a GPU that's sick or dead once every minute */
  8841. cgtime(&thr->sick);
  8842. if (opt_restart)
  8843. reinit_device(cgpu);
  8844. }
  8845. }
  8846. static void log_print_status(struct cgpu_info *cgpu)
  8847. {
  8848. char logline[255];
  8849. get_statline(logline, sizeof(logline), cgpu);
  8850. applog(LOG_WARNING, "%s", logline);
  8851. }
  8852. void print_summary(void)
  8853. {
  8854. struct timeval diff;
  8855. int hours, mins, secs, i;
  8856. double utility, efficiency = 0.0;
  8857. char xfer[(ALLOC_H2B_SPACED*2)+4+1], bw[(ALLOC_H2B_SPACED*2)+6+1];
  8858. int pool_secs;
  8859. timersub(&total_tv_end, &total_tv_start, &diff);
  8860. hours = diff.tv_sec / 3600;
  8861. mins = (diff.tv_sec % 3600) / 60;
  8862. secs = diff.tv_sec % 60;
  8863. utility = total_accepted / total_secs * 60;
  8864. efficiency = total_bytes_xfer ? total_diff_accepted * 2048. / total_bytes_xfer : 0.0;
  8865. applog(LOG_WARNING, "\nSummary of runtime statistics:\n");
  8866. applog(LOG_WARNING, "Started at %s", datestamp);
  8867. if (total_pools == 1)
  8868. applog(LOG_WARNING, "Pool: %s", pools[0]->rpc_url);
  8869. #ifdef WANT_CPUMINE
  8870. if (opt_n_threads)
  8871. applog(LOG_WARNING, "CPU hasher algorithm used: %s", algo_names[opt_algo]);
  8872. #endif
  8873. applog(LOG_WARNING, "Runtime: %d hrs : %d mins : %d secs", hours, mins, secs);
  8874. applog(LOG_WARNING, "Average hashrate: %.1f Megahash/s", total_mhashes_done / total_secs);
  8875. applog(LOG_WARNING, "Solved blocks: %d", found_blocks);
  8876. applog(LOG_WARNING, "Best share difficulty: %s", best_share);
  8877. applog(LOG_WARNING, "Share submissions: %d", total_accepted + total_rejected);
  8878. applog(LOG_WARNING, "Accepted shares: %d", total_accepted);
  8879. applog(LOG_WARNING, "Rejected shares: %d + %d stale (%.2f%%)",
  8880. total_rejected, total_stale,
  8881. (float)(total_rejected + total_stale) / (float)(total_rejected + total_stale + total_accepted)
  8882. );
  8883. applog(LOG_WARNING, "Accepted difficulty shares: %1.f", total_diff_accepted);
  8884. applog(LOG_WARNING, "Rejected difficulty shares: %1.f", total_diff_rejected);
  8885. applog(LOG_WARNING, "Hardware errors: %d", hw_errors);
  8886. applog(LOG_WARNING, "Network transfer: %s (%s)",
  8887. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  8888. (float)total_bytes_rcvd,
  8889. (float)total_bytes_sent),
  8890. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  8891. (float)(total_bytes_rcvd / total_secs),
  8892. (float)(total_bytes_sent / total_secs)));
  8893. applog(LOG_WARNING, "Efficiency (accepted shares * difficulty / 2 KB): %.2f", efficiency);
  8894. applog(LOG_WARNING, "Utility (accepted shares / min): %.2f/min\n", utility);
  8895. applog(LOG_WARNING, "Unable to get work from server occasions: %d", total_go);
  8896. applog(LOG_WARNING, "Work items generated locally: %d", local_work);
  8897. applog(LOG_WARNING, "Submitting work remotely delay occasions: %d", total_ro);
  8898. applog(LOG_WARNING, "New blocks detected on network: %d\n", new_blocks);
  8899. if (total_pools > 1) {
  8900. for (i = 0; i < total_pools; i++) {
  8901. struct pool *pool = pools[i];
  8902. applog(LOG_WARNING, "Pool: %s", pool->rpc_url);
  8903. if (pool->solved)
  8904. applog(LOG_WARNING, "SOLVED %d BLOCK%s!", pool->solved, pool->solved > 1 ? "S" : "");
  8905. applog(LOG_WARNING, " Share submissions: %d", pool->accepted + pool->rejected);
  8906. applog(LOG_WARNING, " Accepted shares: %d", pool->accepted);
  8907. applog(LOG_WARNING, " Rejected shares: %d + %d stale (%.2f%%)",
  8908. pool->rejected, pool->stale_shares,
  8909. (float)(pool->rejected + pool->stale_shares) / (float)(pool->rejected + pool->stale_shares + pool->accepted)
  8910. );
  8911. applog(LOG_WARNING, " Accepted difficulty shares: %1.f", pool->diff_accepted);
  8912. applog(LOG_WARNING, " Rejected difficulty shares: %1.f", pool->diff_rejected);
  8913. pool_secs = timer_elapsed(&pool->cgminer_stats.start_tv, NULL);
  8914. applog(LOG_WARNING, " Network transfer: %s (%s)",
  8915. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  8916. (float)pool->cgminer_pool_stats.net_bytes_received,
  8917. (float)pool->cgminer_pool_stats.net_bytes_sent),
  8918. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  8919. (float)(pool->cgminer_pool_stats.net_bytes_received / pool_secs),
  8920. (float)(pool->cgminer_pool_stats.net_bytes_sent / pool_secs)));
  8921. uint64_t pool_bytes_xfer = pool->cgminer_pool_stats.net_bytes_received + pool->cgminer_pool_stats.net_bytes_sent;
  8922. efficiency = pool_bytes_xfer ? pool->diff_accepted * 2048. / pool_bytes_xfer : 0.0;
  8923. applog(LOG_WARNING, " Efficiency (accepted * difficulty / 2 KB): %.2f", efficiency);
  8924. applog(LOG_WARNING, " Items worked on: %d", pool->works);
  8925. applog(LOG_WARNING, " Unable to get work from server occasions: %d", pool->getfail_occasions);
  8926. applog(LOG_WARNING, " Submitting work remotely delay occasions: %d\n", pool->remotefail_occasions);
  8927. }
  8928. }
  8929. if (opt_quit_summary != BQS_NONE)
  8930. {
  8931. if (opt_quit_summary == BQS_DETAILED)
  8932. include_serial_in_statline = true;
  8933. applog(LOG_WARNING, "Summary of per device statistics:\n");
  8934. for (i = 0; i < total_devices; ++i) {
  8935. struct cgpu_info *cgpu = get_devices(i);
  8936. if (!cgpu->proc_id)
  8937. {
  8938. // Device summary line
  8939. opt_show_procs = false;
  8940. log_print_status(cgpu);
  8941. opt_show_procs = true;
  8942. }
  8943. if ((opt_quit_summary == BQS_PROCS || opt_quit_summary == BQS_DETAILED) && cgpu->procs > 1)
  8944. log_print_status(cgpu);
  8945. }
  8946. }
  8947. if (opt_shares) {
  8948. applog(LOG_WARNING, "Mined %g accepted shares of %g requested\n", total_diff_accepted, opt_shares);
  8949. if (opt_shares > total_diff_accepted)
  8950. applog(LOG_WARNING, "WARNING - Mined only %g shares of %g requested.", total_diff_accepted, opt_shares);
  8951. }
  8952. applog(LOG_WARNING, " ");
  8953. fflush(stderr);
  8954. fflush(stdout);
  8955. }
  8956. void _bfg_clean_up(bool restarting)
  8957. {
  8958. #ifdef HAVE_OPENCL
  8959. clear_adl(nDevs);
  8960. #endif
  8961. #ifdef HAVE_LIBUSB
  8962. if (likely(have_libusb))
  8963. libusb_exit(NULL);
  8964. #endif
  8965. cgtime(&total_tv_end);
  8966. #ifdef WIN32
  8967. timeEndPeriod(1);
  8968. #endif
  8969. if (!restarting) {
  8970. /* Attempting to disable curses or print a summary during a
  8971. * restart can lead to a deadlock. */
  8972. #ifdef HAVE_CURSES
  8973. disable_curses();
  8974. #endif
  8975. if (!opt_realquiet && successful_connect)
  8976. print_summary();
  8977. }
  8978. if (opt_n_threads)
  8979. free(cpus);
  8980. curl_global_cleanup();
  8981. #ifdef WIN32
  8982. WSACleanup();
  8983. #endif
  8984. }
  8985. void _quit(int status)
  8986. {
  8987. if (status) {
  8988. const char *ev = getenv("__BFGMINER_SEGFAULT_ERRQUIT");
  8989. if (unlikely(ev && ev[0] && ev[0] != '0')) {
  8990. int *p = NULL;
  8991. // NOTE debugger can bypass with: p = &p
  8992. *p = status; // Segfault, hopefully dumping core
  8993. }
  8994. }
  8995. #if defined(unix) || defined(__APPLE__)
  8996. if (forkpid > 0) {
  8997. kill(forkpid, SIGTERM);
  8998. forkpid = 0;
  8999. }
  9000. #endif
  9001. exit(status);
  9002. }
  9003. #ifdef HAVE_CURSES
  9004. char *curses_input(const char *query)
  9005. {
  9006. char *input;
  9007. echo();
  9008. input = malloc(255);
  9009. if (!input)
  9010. quit(1, "Failed to malloc input");
  9011. leaveok(logwin, false);
  9012. wlogprint("%s:\n", query);
  9013. wgetnstr(logwin, input, 255);
  9014. if (!strlen(input))
  9015. {
  9016. free(input);
  9017. input = NULL;
  9018. }
  9019. leaveok(logwin, true);
  9020. noecho();
  9021. return input;
  9022. }
  9023. #endif
  9024. static bool pools_active = false;
  9025. static void *test_pool_thread(void *arg)
  9026. {
  9027. struct pool *pool = (struct pool *)arg;
  9028. if (pool_active(pool, false)) {
  9029. pool_tset(pool, &pool->lagging);
  9030. pool_tclear(pool, &pool->idle);
  9031. bool first_pool = false;
  9032. cg_wlock(&control_lock);
  9033. if (!pools_active) {
  9034. currentpool = pool;
  9035. if (pool->pool_no != 0)
  9036. first_pool = true;
  9037. pools_active = true;
  9038. }
  9039. cg_wunlock(&control_lock);
  9040. if (unlikely(first_pool))
  9041. applog(LOG_NOTICE, "Switching to pool %d %s - first alive pool", pool->pool_no, pool->rpc_url);
  9042. else
  9043. applog(LOG_NOTICE, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  9044. switch_pools(NULL);
  9045. } else
  9046. pool_died(pool);
  9047. pool->testing = false;
  9048. return NULL;
  9049. }
  9050. /* Always returns true that the pool details were added unless we are not
  9051. * live, implying this is the only pool being added, so if no pools are
  9052. * active it returns false. */
  9053. bool add_pool_details(struct pool *pool, bool live, char *url, char *user, char *pass)
  9054. {
  9055. size_t siz;
  9056. pool->rpc_url = url;
  9057. pool->rpc_user = user;
  9058. pool->rpc_pass = pass;
  9059. siz = strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2;
  9060. pool->rpc_userpass = malloc(siz);
  9061. if (!pool->rpc_userpass)
  9062. quit(1, "Failed to malloc userpass");
  9063. snprintf(pool->rpc_userpass, siz, "%s:%s", pool->rpc_user, pool->rpc_pass);
  9064. pool->testing = true;
  9065. pool->idle = true;
  9066. enable_pool(pool);
  9067. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  9068. if (!live) {
  9069. pthread_join(pool->test_thread, NULL);
  9070. return pools_active;
  9071. }
  9072. return true;
  9073. }
  9074. #ifdef HAVE_CURSES
  9075. static bool input_pool(bool live)
  9076. {
  9077. char *url = NULL, *user = NULL, *pass = NULL;
  9078. struct pool *pool;
  9079. bool ret = false;
  9080. immedok(logwin, true);
  9081. wlogprint("Input server details.\n");
  9082. url = curses_input("URL");
  9083. if (!url)
  9084. goto out;
  9085. user = curses_input("Username");
  9086. if (!user)
  9087. goto out;
  9088. pass = curses_input("Password");
  9089. if (!pass)
  9090. pass = calloc(1, 1);
  9091. pool = add_pool();
  9092. if (!detect_stratum(pool, url) && strncmp(url, "http://", 7) &&
  9093. strncmp(url, "https://", 8)) {
  9094. char *httpinput;
  9095. httpinput = malloc(256);
  9096. if (!httpinput)
  9097. quit(1, "Failed to malloc httpinput");
  9098. strcpy(httpinput, "http://");
  9099. strncat(httpinput, url, 248);
  9100. free(url);
  9101. url = httpinput;
  9102. }
  9103. ret = add_pool_details(pool, live, url, user, pass);
  9104. out:
  9105. immedok(logwin, false);
  9106. if (!ret) {
  9107. if (url)
  9108. free(url);
  9109. if (user)
  9110. free(user);
  9111. if (pass)
  9112. free(pass);
  9113. }
  9114. return ret;
  9115. }
  9116. #endif
  9117. #if defined(unix) || defined(__APPLE__)
  9118. static void fork_monitor()
  9119. {
  9120. // Make a pipe: [readFD, writeFD]
  9121. int pfd[2];
  9122. int r = pipe(pfd);
  9123. if (r < 0) {
  9124. perror("pipe - failed to create pipe for --monitor");
  9125. exit(1);
  9126. }
  9127. // Make stderr write end of pipe
  9128. fflush(stderr);
  9129. r = dup2(pfd[1], 2);
  9130. if (r < 0) {
  9131. perror("dup2 - failed to alias stderr to write end of pipe for --monitor");
  9132. exit(1);
  9133. }
  9134. r = close(pfd[1]);
  9135. if (r < 0) {
  9136. perror("close - failed to close write end of pipe for --monitor");
  9137. exit(1);
  9138. }
  9139. // Don't allow a dying monitor to kill the main process
  9140. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  9141. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  9142. if (SIG_ERR == sr0 || SIG_ERR == sr1) {
  9143. perror("signal - failed to edit signal mask for --monitor");
  9144. exit(1);
  9145. }
  9146. // Fork a child process
  9147. forkpid = fork();
  9148. if (forkpid < 0) {
  9149. perror("fork - failed to fork child process for --monitor");
  9150. exit(1);
  9151. }
  9152. // Child: launch monitor command
  9153. if (0 == forkpid) {
  9154. // Make stdin read end of pipe
  9155. r = dup2(pfd[0], 0);
  9156. if (r < 0) {
  9157. perror("dup2 - in child, failed to alias read end of pipe to stdin for --monitor");
  9158. exit(1);
  9159. }
  9160. close(pfd[0]);
  9161. if (r < 0) {
  9162. perror("close - in child, failed to close read end of pipe for --monitor");
  9163. exit(1);
  9164. }
  9165. // Launch user specified command
  9166. execl("/bin/bash", "/bin/bash", "-c", opt_stderr_cmd, (char*)NULL);
  9167. perror("execl - in child failed to exec user specified command for --monitor");
  9168. exit(1);
  9169. }
  9170. // Parent: clean up unused fds and bail
  9171. r = close(pfd[0]);
  9172. if (r < 0) {
  9173. perror("close - failed to close read end of pipe for --monitor");
  9174. exit(1);
  9175. }
  9176. }
  9177. #endif // defined(unix)
  9178. #ifdef HAVE_CURSES
  9179. #ifdef USE_UNICODE
  9180. static
  9181. wchar_t select_unicode_char(const wchar_t *opt)
  9182. {
  9183. for ( ; *opt; ++opt)
  9184. if (iswprint(*opt))
  9185. return *opt;
  9186. return '?';
  9187. }
  9188. #endif
  9189. void enable_curses(void) {
  9190. int x;
  9191. __maybe_unused int y;
  9192. lock_curses();
  9193. if (curses_active) {
  9194. unlock_curses();
  9195. return;
  9196. }
  9197. #ifdef USE_UNICODE
  9198. if (use_unicode)
  9199. {
  9200. setlocale(LC_CTYPE, "");
  9201. if (iswprint(0xb0))
  9202. have_unicode_degrees = true;
  9203. unicode_micro = select_unicode_char(L"\xb5\u03bcu");
  9204. }
  9205. #endif
  9206. mainwin = initscr();
  9207. start_color();
  9208. #if defined(PDCURSES) || defined(NCURSES_VERSION)
  9209. if (ERR != use_default_colors())
  9210. default_bgcolor = -1;
  9211. #endif
  9212. if (has_colors() && ERR != init_pair(1, COLOR_WHITE, COLOR_BLUE))
  9213. {
  9214. menu_attr = COLOR_PAIR(1);
  9215. if (ERR != init_pair(2, COLOR_RED, default_bgcolor))
  9216. attr_bad |= COLOR_PAIR(2);
  9217. }
  9218. keypad(mainwin, true);
  9219. getmaxyx(mainwin, y, x);
  9220. statuswin = newwin(logstart, x, 0, 0);
  9221. leaveok(statuswin, true);
  9222. // For whatever reason, PDCurses crashes if the logwin is initialized to height y-logcursor
  9223. // We resize the window later anyway, so just start it off at 1 :)
  9224. logwin = newwin(1, 0, logcursor, 0);
  9225. idlok(logwin, true);
  9226. scrollok(logwin, true);
  9227. leaveok(logwin, true);
  9228. cbreak();
  9229. noecho();
  9230. nonl();
  9231. curses_active = true;
  9232. statusy = logstart;
  9233. unlock_curses();
  9234. }
  9235. #endif
  9236. /* TODO: fix need a dummy CPU device_drv even if no support for CPU mining */
  9237. #ifndef WANT_CPUMINE
  9238. struct device_drv cpu_drv;
  9239. struct device_drv cpu_drv = {
  9240. .name = "CPU",
  9241. };
  9242. #endif
  9243. static int cgminer_id_count = 0;
  9244. static int device_line_id_count;
  9245. void register_device(struct cgpu_info *cgpu)
  9246. {
  9247. cgpu->deven = DEV_ENABLED;
  9248. wr_lock(&devices_lock);
  9249. devices[cgpu->cgminer_id = cgminer_id_count++] = cgpu;
  9250. wr_unlock(&devices_lock);
  9251. if (!cgpu->proc_id)
  9252. cgpu->device_line_id = device_line_id_count++;
  9253. mining_threads += cgpu->threads ?: 1;
  9254. #ifdef HAVE_CURSES
  9255. adj_width(mining_threads, &dev_width);
  9256. #endif
  9257. rwlock_init(&cgpu->qlock);
  9258. cgpu->queued_work = NULL;
  9259. }
  9260. struct _cgpu_devid_counter {
  9261. char name[4];
  9262. int lastid;
  9263. UT_hash_handle hh;
  9264. };
  9265. void renumber_cgpu(struct cgpu_info *cgpu)
  9266. {
  9267. static struct _cgpu_devid_counter *devids = NULL;
  9268. struct _cgpu_devid_counter *d;
  9269. HASH_FIND_STR(devids, cgpu->drv->name, d);
  9270. if (d)
  9271. cgpu->device_id = ++d->lastid;
  9272. else {
  9273. d = malloc(sizeof(*d));
  9274. memcpy(d->name, cgpu->drv->name, sizeof(d->name));
  9275. cgpu->device_id = d->lastid = 0;
  9276. HASH_ADD_STR(devids, name, d);
  9277. }
  9278. // Build repr strings
  9279. sprintf(cgpu->dev_repr, "%s%2u", cgpu->drv->name, cgpu->device_id % 100);
  9280. sprintf(cgpu->dev_repr_ns, "%s%u", cgpu->drv->name, cgpu->device_id % 100);
  9281. strcpy(cgpu->proc_repr, cgpu->dev_repr);
  9282. sprintf(cgpu->proc_repr_ns, "%s%u", cgpu->drv->name, cgpu->device_id);
  9283. const int lpcount = cgpu->procs;
  9284. if (lpcount > 1)
  9285. {
  9286. int ns;
  9287. struct cgpu_info *slave;
  9288. int lpdigits = 1;
  9289. for (int i = lpcount; i > 26 && lpdigits < 3; i /= 26)
  9290. ++lpdigits;
  9291. memset(&cgpu->proc_repr[5], 'a', lpdigits);
  9292. cgpu->proc_repr[5 + lpdigits] = '\0';
  9293. ns = strlen(cgpu->proc_repr_ns);
  9294. strcpy(&cgpu->proc_repr_ns[ns], &cgpu->proc_repr[5]);
  9295. slave = cgpu;
  9296. for (int i = 1; i < lpcount; ++i)
  9297. {
  9298. slave = slave->next_proc;
  9299. strcpy(slave->proc_repr, cgpu->proc_repr);
  9300. strcpy(slave->proc_repr_ns, cgpu->proc_repr_ns);
  9301. for (int x = i, y = lpdigits; --y, x; x /= 26)
  9302. {
  9303. slave->proc_repr_ns[ns + y] =
  9304. slave->proc_repr[5 + y] += (x % 26);
  9305. }
  9306. }
  9307. }
  9308. }
  9309. static bool my_blkmaker_sha256_callback(void *digest, const void *buffer, size_t length)
  9310. {
  9311. sha256(buffer, length, digest);
  9312. return true;
  9313. }
  9314. static
  9315. int drv_algo_check(const struct device_drv * const drv)
  9316. {
  9317. const int algomatch = opt_scrypt ? POW_SCRYPT : POW_SHA256D;
  9318. const supported_algos_t algos = drv->supported_algos ?: POW_SHA256D;
  9319. return (algos & algomatch);
  9320. }
  9321. #ifndef HAVE_PTHREAD_CANCEL
  9322. extern void setup_pthread_cancel_workaround();
  9323. extern struct sigaction pcwm_orig_term_handler;
  9324. #endif
  9325. bool bfg_need_detect_rescan;
  9326. extern void probe_device(struct lowlevel_device_info *);
  9327. static void schedule_rescan(const struct timeval *);
  9328. static
  9329. void drv_detect_all()
  9330. {
  9331. bool rescanning = false;
  9332. rescan:
  9333. bfg_need_detect_rescan = false;
  9334. #ifdef HAVE_BFG_LOWLEVEL
  9335. struct lowlevel_device_info * const infolist = lowlevel_scan(), *info, *infotmp;
  9336. LL_FOREACH_SAFE(infolist, info, infotmp)
  9337. probe_device(info);
  9338. LL_FOREACH_SAFE(infolist, info, infotmp)
  9339. pthread_join(info->probe_pth, NULL);
  9340. #endif
  9341. struct driver_registration *reg, *tmp;
  9342. BFG_FOREACH_DRIVER_BY_PRIORITY(reg, tmp)
  9343. {
  9344. const struct device_drv * const drv = reg->drv;
  9345. if (!(drv_algo_check(drv) && drv->drv_detect))
  9346. continue;
  9347. drv->drv_detect();
  9348. }
  9349. #ifdef HAVE_BFG_LOWLEVEL
  9350. lowlevel_scan_free();
  9351. #endif
  9352. if (bfg_need_detect_rescan)
  9353. {
  9354. if (rescanning)
  9355. {
  9356. applog(LOG_DEBUG, "Device rescan requested a second time, delaying");
  9357. struct timeval tv_when;
  9358. timer_set_delay_from_now(&tv_when, rescan_delay_ms * 1000);
  9359. schedule_rescan(&tv_when);
  9360. }
  9361. else
  9362. {
  9363. rescanning = true;
  9364. applog(LOG_DEBUG, "Device rescan requested");
  9365. goto rescan;
  9366. }
  9367. }
  9368. }
  9369. static
  9370. void allocate_cgpu(struct cgpu_info *cgpu, unsigned int *kp)
  9371. {
  9372. struct thr_info *thr;
  9373. int j;
  9374. struct device_drv *api = cgpu->drv;
  9375. cgpu->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  9376. int threadobj = cgpu->threads;
  9377. if (!threadobj)
  9378. // Create a fake thread object to handle hashmeter etc
  9379. threadobj = 1;
  9380. cgpu->thr = calloc(threadobj + 1, sizeof(*cgpu->thr));
  9381. cgpu->thr[threadobj] = NULL;
  9382. cgpu->status = LIFE_INIT;
  9383. if (opt_devices_enabled_list)
  9384. {
  9385. struct string_elist *enablestr_elist;
  9386. cgpu->deven = DEV_DISABLED;
  9387. DL_FOREACH(opt_devices_enabled_list, enablestr_elist)
  9388. {
  9389. const char * const enablestr = enablestr_elist->string;
  9390. if (cgpu_match(enablestr, cgpu))
  9391. {
  9392. cgpu->deven = DEV_ENABLED;
  9393. break;
  9394. }
  9395. }
  9396. }
  9397. cgpu->max_hashes = 0;
  9398. BFGINIT(cgpu->min_nonce_diff, 1);
  9399. BFGINIT(cgpu->cutofftemp, opt_cutofftemp);
  9400. BFGINIT(cgpu->targettemp, cgpu->cutofftemp - 6);
  9401. // Setup thread structs before starting any of the threads, in case they try to interact
  9402. for (j = 0; j < threadobj; ++j, ++*kp) {
  9403. thr = get_thread(*kp);
  9404. thr->id = *kp;
  9405. thr->cgpu = cgpu;
  9406. thr->device_thread = j;
  9407. thr->work_restart_notifier[1] = INVSOCK;
  9408. thr->mutex_request[1] = INVSOCK;
  9409. thr->_job_transition_in_progress = true;
  9410. timerclear(&thr->tv_morework);
  9411. thr->scanhash_working = true;
  9412. thr->hashes_done = 0;
  9413. timerclear(&thr->tv_hashes_done);
  9414. cgtime(&thr->tv_lastupdate);
  9415. thr->tv_poll.tv_sec = -1;
  9416. thr->_max_nonce = api->can_limit_work ? api->can_limit_work(thr) : 0xffffffff;
  9417. cgpu->thr[j] = thr;
  9418. }
  9419. if (!cgpu->device->threads)
  9420. notifier_init_invalid(cgpu->thr[0]->notifier);
  9421. else
  9422. if (!cgpu->threads)
  9423. memcpy(&cgpu->thr[0]->notifier, &cgpu->device->thr[0]->notifier, sizeof(cgpu->thr[0]->notifier));
  9424. else
  9425. for (j = 0; j < cgpu->threads; ++j)
  9426. {
  9427. thr = cgpu->thr[j];
  9428. notifier_init(thr->notifier);
  9429. }
  9430. }
  9431. static
  9432. void start_cgpu(struct cgpu_info *cgpu)
  9433. {
  9434. struct thr_info *thr;
  9435. int j;
  9436. for (j = 0; j < cgpu->threads; ++j) {
  9437. thr = cgpu->thr[j];
  9438. /* Enable threads for devices set not to mine but disable
  9439. * their queue in case we wish to enable them later */
  9440. if (cgpu->drv->thread_prepare && !cgpu->drv->thread_prepare(thr))
  9441. continue;
  9442. thread_reportout(thr);
  9443. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  9444. quit(1, "thread %d create failed", thr->id);
  9445. notifier_wake(thr->notifier);
  9446. }
  9447. if (cgpu->deven == DEV_ENABLED)
  9448. proc_enable(cgpu);
  9449. }
  9450. static
  9451. void _scan_serial(void *p)
  9452. {
  9453. const char *s = p;
  9454. struct string_elist *iter, *tmp;
  9455. struct string_elist *orig_scan_devices = scan_devices;
  9456. if (s)
  9457. {
  9458. // Make temporary scan_devices list
  9459. scan_devices = NULL;
  9460. string_elist_add("noauto", &scan_devices);
  9461. add_serial(s);
  9462. }
  9463. drv_detect_all();
  9464. if (s)
  9465. {
  9466. DL_FOREACH_SAFE(scan_devices, iter, tmp)
  9467. {
  9468. string_elist_del(&scan_devices, iter);
  9469. }
  9470. scan_devices = orig_scan_devices;
  9471. }
  9472. }
  9473. #ifdef HAVE_BFG_LOWLEVEL
  9474. static
  9475. bool _probe_device_match(const struct lowlevel_device_info * const info, const char * const ser)
  9476. {
  9477. if (!(false
  9478. || (info->serial && !strcasecmp(ser, info->serial))
  9479. || (info->path && !strcasecmp(ser, info->path ))
  9480. || (info->devid && !strcasecmp(ser, info->devid ))
  9481. ))
  9482. {
  9483. char *devid = devpath_to_devid(ser);
  9484. if (!devid)
  9485. return false;
  9486. const bool different = strcmp(info->devid, devid);
  9487. free(devid);
  9488. if (different)
  9489. return false;
  9490. }
  9491. return true;
  9492. }
  9493. static
  9494. const struct device_drv *_probe_device_find_drv(const char * const _dname, const size_t dnamelen)
  9495. {
  9496. struct driver_registration *dreg;
  9497. char dname[dnamelen];
  9498. int i;
  9499. for (i = 0; i < dnamelen; ++i)
  9500. dname[i] = tolower(_dname[i]);
  9501. BFG_FIND_DRV_BY_DNAME(dreg, dname, dnamelen);
  9502. if (!dreg)
  9503. {
  9504. for (i = 0; i < dnamelen; ++i)
  9505. dname[i] = toupper(_dname[i]);
  9506. BFG_FIND_DRV_BY_NAME(dreg, dname, dnamelen);
  9507. if (!dreg)
  9508. return NULL;
  9509. }
  9510. if (!drv_algo_check(dreg->drv))
  9511. return NULL;
  9512. return dreg->drv;
  9513. }
  9514. static
  9515. void *probe_device_thread(void *p)
  9516. {
  9517. struct lowlevel_device_info * const infolist = p;
  9518. struct lowlevel_device_info *info = infolist;
  9519. bool request_rescan = false;
  9520. {
  9521. char threadname[5 + strlen(info->devid) + 1];
  9522. sprintf(threadname, "probe_%s", info->devid);
  9523. RenameThread(threadname);
  9524. }
  9525. // If already in use, ignore
  9526. if (bfg_claim_any(NULL, NULL, info->devid))
  9527. applogr(NULL, LOG_DEBUG, "%s: \"%s\" already in use",
  9528. __func__, info->product);
  9529. // if lowlevel device matches specific user assignment, probe requested driver(s)
  9530. struct string_elist *sd_iter, *sd_tmp;
  9531. struct driver_registration *dreg, *dreg_tmp;
  9532. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  9533. {
  9534. const char * const dname = sd_iter->string;
  9535. const char * const colon = strpbrk(dname, ":@");
  9536. if (!(colon && colon != dname))
  9537. continue;
  9538. const char * const ser = &colon[1];
  9539. LL_FOREACH2(infolist, info, same_devid_next)
  9540. {
  9541. if (!_probe_device_match(info, ser))
  9542. continue;
  9543. const size_t dnamelen = (colon - dname);
  9544. const struct device_drv * const drv = _probe_device_find_drv(dname, dnamelen);
  9545. if (!(drv && drv->lowl_probe && drv_algo_check(drv)))
  9546. continue;
  9547. if (drv->lowl_probe(info))
  9548. return NULL;
  9549. else
  9550. if (opt_hotplug)
  9551. request_rescan = true;
  9552. }
  9553. }
  9554. // probe driver(s) with auto enabled and matching VID/PID/Product/etc of device
  9555. BFG_FOREACH_DRIVER_BY_PRIORITY(dreg, dreg_tmp)
  9556. {
  9557. const struct device_drv * const drv = dreg->drv;
  9558. if (!drv_algo_check(drv))
  9559. continue;
  9560. // Check for "noauto" flag
  9561. // NOTE: driver-specific configuration overrides general
  9562. bool doauto = true;
  9563. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  9564. {
  9565. const char * const dname = sd_iter->string;
  9566. // NOTE: Only checking flags here, NOT path/serial, so @ is unacceptable
  9567. const char *colon = strchr(dname, ':');
  9568. if (!colon)
  9569. colon = &dname[-1];
  9570. if (strcasecmp("noauto", &colon[1]) && strcasecmp("auto", &colon[1]))
  9571. continue;
  9572. const ssize_t dnamelen = (colon - dname);
  9573. if (dnamelen >= 0 && _probe_device_find_drv(dname, dnamelen) != drv)
  9574. continue;
  9575. doauto = (tolower(colon[1]) == 'a');
  9576. if (dnamelen != -1)
  9577. break;
  9578. }
  9579. if (doauto && drv->lowl_match)
  9580. {
  9581. LL_FOREACH2(infolist, info, same_devid_next)
  9582. {
  9583. if (!drv->lowl_match(info))
  9584. continue;
  9585. if (drv->lowl_probe(info))
  9586. return NULL;
  9587. else
  9588. if (opt_hotplug)
  9589. bfg_need_detect_rescan = true;
  9590. }
  9591. }
  9592. }
  9593. // probe driver(s) with 'all' enabled
  9594. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  9595. {
  9596. const char * const dname = sd_iter->string;
  9597. // NOTE: Only checking flags here, NOT path/serial, so @ is unacceptable
  9598. const char * const colon = strchr(dname, ':');
  9599. if (!colon)
  9600. {
  9601. LL_FOREACH2(infolist, info, same_devid_next)
  9602. {
  9603. if (
  9604. #ifdef NEED_BFG_LOWL_VCOM
  9605. (info->lowl == &lowl_vcom && !strcasecmp(dname, "all")) ||
  9606. #endif
  9607. _probe_device_match(info, (dname[0] == '@') ? &dname[1] : dname))
  9608. {
  9609. BFG_FOREACH_DRIVER_BY_PRIORITY(dreg, dreg_tmp)
  9610. {
  9611. const struct device_drv * const drv = dreg->drv;
  9612. if (!drv_algo_check(drv))
  9613. continue;
  9614. if (drv->lowl_probe_by_name_only)
  9615. continue;
  9616. if (!drv->lowl_probe)
  9617. continue;
  9618. if (drv->lowl_probe(info))
  9619. return NULL;
  9620. }
  9621. if (opt_hotplug)
  9622. request_rescan = true;
  9623. break;
  9624. }
  9625. }
  9626. continue;
  9627. }
  9628. if (strcasecmp(&colon[1], "all"))
  9629. continue;
  9630. const size_t dnamelen = (colon - dname);
  9631. LL_FOREACH2(infolist, info, same_devid_next)
  9632. {
  9633. const struct device_drv * const drv = _probe_device_find_drv(dname, dnamelen);
  9634. if (!(drv && drv->lowl_probe && drv_algo_check(drv)))
  9635. continue;
  9636. if (drv->lowl_probe(info))
  9637. return NULL;
  9638. }
  9639. }
  9640. // Only actually request a rescan if we never found any cgpu
  9641. if (request_rescan)
  9642. bfg_need_detect_rescan = true;
  9643. return NULL;
  9644. }
  9645. void probe_device(struct lowlevel_device_info * const info)
  9646. {
  9647. pthread_create(&info->probe_pth, NULL, probe_device_thread, info);
  9648. }
  9649. #endif
  9650. int create_new_cgpus(void (*addfunc)(void*), void *arg)
  9651. {
  9652. static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  9653. int devcount, i, mining_threads_new = 0;
  9654. unsigned int k;
  9655. struct cgpu_info *cgpu;
  9656. struct thr_info *thr;
  9657. void *p;
  9658. mutex_lock(&mutex);
  9659. devcount = total_devices;
  9660. addfunc(arg);
  9661. if (!total_devices_new)
  9662. goto out;
  9663. wr_lock(&devices_lock);
  9664. p = realloc(devices, sizeof(struct cgpu_info *) * (total_devices + total_devices_new + 1));
  9665. if (unlikely(!p))
  9666. {
  9667. wr_unlock(&devices_lock);
  9668. applog(LOG_ERR, "scan_serial: realloc failed trying to grow devices array");
  9669. goto out;
  9670. }
  9671. devices = p;
  9672. wr_unlock(&devices_lock);
  9673. for (i = 0; i < total_devices_new; ++i)
  9674. {
  9675. cgpu = devices_new[i];
  9676. mining_threads_new += cgpu->threads ?: 1;
  9677. }
  9678. wr_lock(&mining_thr_lock);
  9679. mining_threads_new += mining_threads;
  9680. p = realloc(mining_thr, sizeof(struct thr_info *) * mining_threads_new);
  9681. if (unlikely(!p))
  9682. {
  9683. wr_unlock(&mining_thr_lock);
  9684. applog(LOG_ERR, "scan_serial: realloc failed trying to grow mining_thr");
  9685. goto out;
  9686. }
  9687. mining_thr = p;
  9688. wr_unlock(&mining_thr_lock);
  9689. for (i = mining_threads; i < mining_threads_new; ++i) {
  9690. mining_thr[i] = calloc(1, sizeof(*thr));
  9691. if (!mining_thr[i])
  9692. {
  9693. applog(LOG_ERR, "scan_serial: Failed to calloc mining_thr[%d]", i);
  9694. for ( ; --i >= mining_threads; )
  9695. free(mining_thr[i]);
  9696. goto out;
  9697. }
  9698. }
  9699. k = mining_threads;
  9700. for (i = 0; i < total_devices_new; ++i)
  9701. {
  9702. cgpu = devices_new[i];
  9703. allocate_cgpu(cgpu, &k);
  9704. }
  9705. for (i = 0; i < total_devices_new; ++i)
  9706. {
  9707. cgpu = devices_new[i];
  9708. start_cgpu(cgpu);
  9709. register_device(cgpu);
  9710. ++total_devices;
  9711. }
  9712. #ifdef HAVE_CURSES
  9713. switch_logsize();
  9714. #endif
  9715. out:
  9716. total_devices_new = 0;
  9717. devcount = total_devices - devcount;
  9718. mutex_unlock(&mutex);
  9719. return devcount;
  9720. }
  9721. int scan_serial(const char *s)
  9722. {
  9723. return create_new_cgpus(_scan_serial, (void*)s);
  9724. }
  9725. static pthread_mutex_t rescan_mutex = PTHREAD_MUTEX_INITIALIZER;
  9726. static bool rescan_active;
  9727. static struct timeval tv_rescan;
  9728. static notifier_t rescan_notifier;
  9729. static
  9730. void *rescan_thread(__maybe_unused void *p)
  9731. {
  9732. pthread_detach(pthread_self());
  9733. RenameThread("rescan");
  9734. struct timeval tv_timeout, tv_now;
  9735. fd_set rfds;
  9736. while (true)
  9737. {
  9738. mutex_lock(&rescan_mutex);
  9739. tv_timeout = tv_rescan;
  9740. if (!timer_isset(&tv_timeout))
  9741. {
  9742. rescan_active = false;
  9743. mutex_unlock(&rescan_mutex);
  9744. break;
  9745. }
  9746. mutex_unlock(&rescan_mutex);
  9747. FD_ZERO(&rfds);
  9748. FD_SET(rescan_notifier[0], &rfds);
  9749. const int maxfd = rescan_notifier[0];
  9750. timer_set_now(&tv_now);
  9751. if (select(maxfd+1, &rfds, NULL, NULL, select_timeout(&tv_timeout, &tv_now)) > 0)
  9752. notifier_read(rescan_notifier);
  9753. mutex_lock(&rescan_mutex);
  9754. if (timer_passed(&tv_rescan, NULL))
  9755. {
  9756. timer_unset(&tv_rescan);
  9757. mutex_unlock(&rescan_mutex);
  9758. applog(LOG_DEBUG, "Rescan timer expired, triggering");
  9759. scan_serial(NULL);
  9760. }
  9761. else
  9762. mutex_unlock(&rescan_mutex);
  9763. }
  9764. return NULL;
  9765. }
  9766. static
  9767. void _schedule_rescan(const struct timeval * const tvp_when)
  9768. {
  9769. if (rescan_active)
  9770. {
  9771. if (timercmp(tvp_when, &tv_rescan, <))
  9772. applog(LOG_DEBUG, "schedule_rescan: New schedule is before current, waiting it out");
  9773. else
  9774. {
  9775. applog(LOG_DEBUG, "schedule_rescan: New schedule is after current, delaying rescan");
  9776. tv_rescan = *tvp_when;
  9777. }
  9778. return;
  9779. }
  9780. applog(LOG_DEBUG, "schedule_rescan: Scheduling rescan (no rescans currently pending)");
  9781. tv_rescan = *tvp_when;
  9782. rescan_active = true;
  9783. static pthread_t pth;
  9784. if (unlikely(pthread_create(&pth, NULL, rescan_thread, NULL)))
  9785. applog(LOG_ERR, "Failed to start rescan thread");
  9786. }
  9787. static
  9788. void schedule_rescan(const struct timeval * const tvp_when)
  9789. {
  9790. mutex_lock(&rescan_mutex);
  9791. _schedule_rescan(tvp_when);
  9792. mutex_unlock(&rescan_mutex);
  9793. }
  9794. #ifdef HAVE_BFG_HOTPLUG
  9795. static
  9796. void hotplug_trigger()
  9797. {
  9798. applog(LOG_DEBUG, "%s: Scheduling rescan immediately", __func__);
  9799. struct timeval tv_now;
  9800. timer_set_now(&tv_now);
  9801. schedule_rescan(&tv_now);
  9802. }
  9803. #endif
  9804. #if defined(HAVE_LIBUDEV) && defined(HAVE_SYS_EPOLL_H)
  9805. static
  9806. void *hotplug_thread(__maybe_unused void *p)
  9807. {
  9808. pthread_detach(pthread_self());
  9809. RenameThread("hotplug");
  9810. struct udev * const udev = udev_new();
  9811. if (unlikely(!udev))
  9812. applogfailr(NULL, LOG_ERR, "udev_new");
  9813. struct udev_monitor * const mon = udev_monitor_new_from_netlink(udev, "udev");
  9814. if (unlikely(!mon))
  9815. applogfailr(NULL, LOG_ERR, "udev_monitor_new_from_netlink");
  9816. if (unlikely(udev_monitor_enable_receiving(mon)))
  9817. applogfailr(NULL, LOG_ERR, "udev_monitor_enable_receiving");
  9818. const int epfd = epoll_create(1);
  9819. if (unlikely(epfd == -1))
  9820. applogfailr(NULL, LOG_ERR, "epoll_create");
  9821. {
  9822. const int fd = udev_monitor_get_fd(mon);
  9823. struct epoll_event ev = {
  9824. .events = EPOLLIN | EPOLLPRI,
  9825. .data.fd = fd,
  9826. };
  9827. if (epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev))
  9828. applogfailr(NULL, LOG_ERR, "epoll_ctl");
  9829. }
  9830. struct epoll_event ev;
  9831. int rv;
  9832. bool pending = false;
  9833. while (true)
  9834. {
  9835. rv = epoll_wait(epfd, &ev, 1, pending ? hotplug_delay_ms : -1);
  9836. if (rv == -1)
  9837. {
  9838. if (errno == EAGAIN || errno == EINTR)
  9839. continue;
  9840. break;
  9841. }
  9842. if (!rv)
  9843. {
  9844. hotplug_trigger();
  9845. pending = false;
  9846. continue;
  9847. }
  9848. struct udev_device * const device = udev_monitor_receive_device(mon);
  9849. if (!device)
  9850. continue;
  9851. const char * const action = udev_device_get_action(device);
  9852. applog(LOG_DEBUG, "%s: Received %s event", __func__, action);
  9853. if (strcmp(action, "add"))
  9854. continue;
  9855. pending = true;
  9856. }
  9857. applogfailr(NULL, LOG_ERR, "epoll_wait");
  9858. }
  9859. #elif defined(WIN32)
  9860. static UINT_PTR _hotplug_wintimer_id;
  9861. VOID CALLBACK hotplug_win_timer(HWND hwnd, UINT msg, UINT_PTR idEvent, DWORD dwTime)
  9862. {
  9863. KillTimer(NULL, _hotplug_wintimer_id);
  9864. _hotplug_wintimer_id = 0;
  9865. hotplug_trigger();
  9866. }
  9867. LRESULT CALLBACK hotplug_win_callback(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
  9868. {
  9869. if (msg == WM_DEVICECHANGE && wParam == DBT_DEVNODES_CHANGED)
  9870. {
  9871. applog(LOG_DEBUG, "%s: Received DBT_DEVNODES_CHANGED event", __func__);
  9872. _hotplug_wintimer_id = SetTimer(NULL, _hotplug_wintimer_id, hotplug_delay_ms, hotplug_win_timer);
  9873. }
  9874. return DefWindowProc(hwnd, msg, wParam, lParam);
  9875. }
  9876. static
  9877. void *hotplug_thread(__maybe_unused void *p)
  9878. {
  9879. pthread_detach(pthread_self());
  9880. WNDCLASS DummyWinCls = {
  9881. .lpszClassName = "BFGDummyWinCls",
  9882. .lpfnWndProc = hotplug_win_callback,
  9883. };
  9884. ATOM a = RegisterClass(&DummyWinCls);
  9885. if (unlikely(!a))
  9886. applogfailinfor(NULL, LOG_ERR, "RegisterClass", "%d", (int)GetLastError());
  9887. HWND hwnd = CreateWindow((void*)(intptr_t)a, NULL, WS_OVERLAPPED, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, NULL, NULL);
  9888. if (unlikely(!hwnd))
  9889. applogfailinfor(NULL, LOG_ERR, "CreateWindow", "%d", (int)GetLastError());
  9890. MSG msg;
  9891. while (GetMessage(&msg, NULL, 0, 0))
  9892. {
  9893. TranslateMessage(&msg);
  9894. DispatchMessage(&msg);
  9895. }
  9896. quit(0, "WM_QUIT received");
  9897. return NULL;
  9898. }
  9899. #endif
  9900. #ifdef HAVE_BFG_HOTPLUG
  9901. static
  9902. void hotplug_start()
  9903. {
  9904. pthread_t pth;
  9905. if (unlikely(pthread_create(&pth, NULL, hotplug_thread, NULL)))
  9906. applog(LOG_ERR, "Failed to start hotplug thread");
  9907. }
  9908. #endif
  9909. static void probe_pools(void)
  9910. {
  9911. int i;
  9912. for (i = 0; i < total_pools; i++) {
  9913. struct pool *pool = pools[i];
  9914. pool->testing = true;
  9915. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  9916. }
  9917. }
  9918. static void raise_fd_limits(void)
  9919. {
  9920. #ifdef HAVE_SETRLIMIT
  9921. struct rlimit fdlimit;
  9922. unsigned long old_soft_limit;
  9923. char frombuf[0x10] = "unlimited";
  9924. char hardbuf[0x10] = "unlimited";
  9925. if (getrlimit(RLIMIT_NOFILE, &fdlimit))
  9926. applogr(, LOG_DEBUG, "setrlimit: Failed to getrlimit(RLIMIT_NOFILE)");
  9927. old_soft_limit = fdlimit.rlim_cur;
  9928. if (fdlimit.rlim_max > FD_SETSIZE || fdlimit.rlim_max == RLIM_INFINITY)
  9929. fdlimit.rlim_cur = FD_SETSIZE;
  9930. else
  9931. fdlimit.rlim_cur = fdlimit.rlim_max;
  9932. if (fdlimit.rlim_max != RLIM_INFINITY)
  9933. snprintf(hardbuf, sizeof(hardbuf), "%lu", (unsigned long)fdlimit.rlim_max);
  9934. if (old_soft_limit != RLIM_INFINITY)
  9935. snprintf(frombuf, sizeof(frombuf), "%lu", old_soft_limit);
  9936. if (fdlimit.rlim_cur == old_soft_limit)
  9937. applogr(, LOG_DEBUG, "setrlimit: Soft fd limit not being changed from %lu (FD_SETSIZE=%lu; hard limit=%s)",
  9938. old_soft_limit, (unsigned long)FD_SETSIZE, hardbuf);
  9939. if (setrlimit(RLIMIT_NOFILE, &fdlimit))
  9940. applogr(, LOG_DEBUG, "setrlimit: Failed to change soft fd limit from %s to %lu (FD_SETSIZE=%lu; hard limit=%s)",
  9941. frombuf, (unsigned long)fdlimit.rlim_cur, (unsigned long)FD_SETSIZE, hardbuf);
  9942. applog(LOG_DEBUG, "setrlimit: Changed soft fd limit from %s to %lu (FD_SETSIZE=%lu; hard limit=%s)",
  9943. frombuf, (unsigned long)fdlimit.rlim_cur, (unsigned long)FD_SETSIZE, hardbuf);
  9944. #else
  9945. applog(LOG_DEBUG, "setrlimit: Not supported by platform");
  9946. #endif
  9947. }
  9948. extern void bfg_init_threadlocal();
  9949. extern void stratumsrv_start();
  9950. int main(int argc, char *argv[])
  9951. {
  9952. struct sigaction handler;
  9953. struct thr_info *thr;
  9954. struct block *block;
  9955. unsigned int k;
  9956. int i;
  9957. int rearrange_pools = 0;
  9958. char *s;
  9959. #ifdef WIN32
  9960. LoadLibrary("backtrace.dll");
  9961. #endif
  9962. blkmk_sha256_impl = my_blkmaker_sha256_callback;
  9963. bfg_init_threadlocal();
  9964. #ifndef HAVE_PTHREAD_CANCEL
  9965. setup_pthread_cancel_workaround();
  9966. #endif
  9967. bfg_init_checksums();
  9968. #ifdef WIN32
  9969. {
  9970. WSADATA wsa;
  9971. i = WSAStartup(MAKEWORD(2, 2), &wsa);
  9972. if (i)
  9973. quit(1, "Failed to initialise Winsock: %s", bfg_strerror(i, BST_SOCKET));
  9974. }
  9975. #endif
  9976. /* This dangerous functions tramples random dynamically allocated
  9977. * variables so do it before anything at all */
  9978. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  9979. quit(1, "Failed to curl_global_init");
  9980. initial_args = malloc(sizeof(char *) * (argc + 1));
  9981. for (i = 0; i < argc; i++)
  9982. initial_args[i] = strdup(argv[i]);
  9983. initial_args[argc] = NULL;
  9984. mutex_init(&hash_lock);
  9985. mutex_init(&console_lock);
  9986. cglock_init(&control_lock);
  9987. mutex_init(&stats_lock);
  9988. mutex_init(&sharelog_lock);
  9989. cglock_init(&ch_lock);
  9990. mutex_init(&sshare_lock);
  9991. rwlock_init(&blk_lock);
  9992. rwlock_init(&netacc_lock);
  9993. rwlock_init(&mining_thr_lock);
  9994. rwlock_init(&devices_lock);
  9995. mutex_init(&lp_lock);
  9996. if (unlikely(pthread_cond_init(&lp_cond, NULL)))
  9997. quit(1, "Failed to pthread_cond_init lp_cond");
  9998. if (unlikely(pthread_cond_init(&gws_cond, NULL)))
  9999. quit(1, "Failed to pthread_cond_init gws_cond");
  10000. notifier_init(submit_waiting_notifier);
  10001. timer_unset(&tv_rescan);
  10002. notifier_init(rescan_notifier);
  10003. snprintf(packagename, sizeof(packagename), "%s %s", PACKAGE, VERSION);
  10004. #ifdef WANT_CPUMINE
  10005. init_max_name_len();
  10006. #endif
  10007. handler.sa_handler = &sighandler;
  10008. handler.sa_flags = 0;
  10009. sigemptyset(&handler.sa_mask);
  10010. #ifdef HAVE_PTHREAD_CANCEL
  10011. sigaction(SIGTERM, &handler, &termhandler);
  10012. #else
  10013. // Need to let pthread_cancel emulation handle SIGTERM first
  10014. termhandler = pcwm_orig_term_handler;
  10015. pcwm_orig_term_handler = handler;
  10016. #endif
  10017. sigaction(SIGINT, &handler, &inthandler);
  10018. #ifndef WIN32
  10019. signal(SIGPIPE, SIG_IGN);
  10020. #else
  10021. timeBeginPeriod(1);
  10022. #endif
  10023. opt_kernel_path = CGMINER_PREFIX;
  10024. cgminer_path = alloca(PATH_MAX);
  10025. s = strdup(argv[0]);
  10026. strcpy(cgminer_path, dirname(s));
  10027. free(s);
  10028. strcat(cgminer_path, "/");
  10029. #if defined(WANT_CPUMINE) && defined(WIN32)
  10030. {
  10031. char buf[32];
  10032. int gev = GetEnvironmentVariable("BFGMINER_BENCH_ALGO", buf, sizeof(buf));
  10033. if (gev > 0 && gev < sizeof(buf))
  10034. {
  10035. setup_benchmark_pool();
  10036. double rate = bench_algo_stage3(atoi(buf));
  10037. // Write result to shared memory for parent
  10038. char unique_name[64];
  10039. if (GetEnvironmentVariable("BFGMINER_SHARED_MEM", unique_name, 32))
  10040. {
  10041. HANDLE map_handle = CreateFileMapping(
  10042. INVALID_HANDLE_VALUE, // use paging file
  10043. NULL, // default security attributes
  10044. PAGE_READWRITE, // read/write access
  10045. 0, // size: high 32-bits
  10046. 4096, // size: low 32-bits
  10047. unique_name // name of map object
  10048. );
  10049. if (NULL != map_handle) {
  10050. void *shared_mem = MapViewOfFile(
  10051. map_handle, // object to map view of
  10052. FILE_MAP_WRITE, // read/write access
  10053. 0, // high offset: map from
  10054. 0, // low offset: beginning
  10055. 0 // default: map entire file
  10056. );
  10057. if (NULL != shared_mem)
  10058. CopyMemory(shared_mem, &rate, sizeof(rate));
  10059. (void)UnmapViewOfFile(shared_mem);
  10060. }
  10061. (void)CloseHandle(map_handle);
  10062. }
  10063. exit(0);
  10064. }
  10065. }
  10066. #endif
  10067. devcursor = 8;
  10068. logstart = devcursor;
  10069. logcursor = logstart;
  10070. block = calloc(sizeof(struct block), 1);
  10071. if (unlikely(!block))
  10072. quit (1, "main OOM");
  10073. for (i = 0; i < 36; i++)
  10074. strcat(block->hash, "0");
  10075. HASH_ADD_STR(blocks, hash, block);
  10076. strcpy(current_block, block->hash);
  10077. mutex_init(&submitting_lock);
  10078. #ifdef HAVE_OPENCL
  10079. opencl_early_init();
  10080. #endif
  10081. schedstart.tm.tm_sec = 1;
  10082. schedstop .tm.tm_sec = 1;
  10083. opt_register_table(opt_early_table, NULL);
  10084. opt_register_table(opt_config_table, NULL);
  10085. opt_register_table(opt_cmdline_table, NULL);
  10086. opt_early_parse(argc, argv, applog_and_exit);
  10087. if (!config_loaded)
  10088. {
  10089. load_default_config();
  10090. rearrange_pools = total_pools;
  10091. }
  10092. opt_free_table();
  10093. /* parse command line */
  10094. opt_register_table(opt_config_table,
  10095. "Options for both config file and command line");
  10096. opt_register_table(opt_cmdline_table,
  10097. "Options for command line only");
  10098. opt_parse(&argc, argv, applog_and_exit);
  10099. if (argc != 1)
  10100. quit(1, "Unexpected extra commandline arguments");
  10101. if (rearrange_pools && rearrange_pools < total_pools)
  10102. {
  10103. // Prioritise commandline pools before default-config pools
  10104. for (i = 0; i < rearrange_pools; ++i)
  10105. pools[i]->prio += rearrange_pools;
  10106. for ( ; i < total_pools; ++i)
  10107. pools[i]->prio -= rearrange_pools;
  10108. }
  10109. #ifndef HAVE_PTHREAD_CANCEL
  10110. // Can't do this any earlier, or config isn't loaded
  10111. applog(LOG_DEBUG, "pthread_cancel workaround in use");
  10112. #endif
  10113. #ifdef HAVE_PWD_H
  10114. struct passwd *user_info = NULL;
  10115. if (opt_setuid != NULL) {
  10116. if ((user_info = getpwnam(opt_setuid)) == NULL) {
  10117. quit(1, "Unable to find setuid user information");
  10118. }
  10119. }
  10120. #endif
  10121. #ifdef HAVE_CHROOT
  10122. if (chroot_dir != NULL) {
  10123. #ifdef HAVE_PWD_H
  10124. if (user_info == NULL && getuid() == 0) {
  10125. applog(LOG_WARNING, "Running as root inside chroot");
  10126. }
  10127. #endif
  10128. if (chroot(chroot_dir) != 0) {
  10129. quit(1, "Unable to chroot");
  10130. }
  10131. if (chdir("/"))
  10132. quit(1, "Unable to chdir to chroot");
  10133. }
  10134. #endif
  10135. #ifdef HAVE_PWD_H
  10136. if (user_info != NULL) {
  10137. if (setgid((*user_info).pw_gid) != 0)
  10138. quit(1, "Unable to setgid");
  10139. if (setuid((*user_info).pw_uid) != 0)
  10140. quit(1, "Unable to setuid");
  10141. }
  10142. #endif
  10143. raise_fd_limits();
  10144. if (opt_benchmark) {
  10145. while (total_pools)
  10146. remove_pool(pools[0]);
  10147. setup_benchmark_pool();
  10148. }
  10149. if (opt_unittest) {
  10150. test_cgpu_match();
  10151. test_intrange();
  10152. test_decimal_width();
  10153. utf8_test();
  10154. }
  10155. #ifdef HAVE_CURSES
  10156. if (opt_realquiet || opt_display_devs)
  10157. use_curses = false;
  10158. setlocale(LC_ALL, "C");
  10159. if (use_curses)
  10160. enable_curses();
  10161. #endif
  10162. #ifdef HAVE_LIBUSB
  10163. int err = libusb_init(NULL);
  10164. if (err)
  10165. applog(LOG_WARNING, "libusb_init() failed err %d", err);
  10166. else
  10167. have_libusb = true;
  10168. #endif
  10169. applog(LOG_WARNING, "Started %s", packagename);
  10170. if (cnfbuf) {
  10171. applog(LOG_NOTICE, "Loaded configuration file %s", cnfbuf);
  10172. switch (fileconf_load) {
  10173. case 0:
  10174. applog(LOG_WARNING, "Fatal JSON error in configuration file.");
  10175. applog(LOG_WARNING, "Configuration file could not be used.");
  10176. break;
  10177. case -1:
  10178. applog(LOG_WARNING, "Error in configuration file, partially loaded.");
  10179. if (use_curses)
  10180. applog(LOG_WARNING, "Start BFGMiner with -T to see what failed to load.");
  10181. break;
  10182. default:
  10183. break;
  10184. }
  10185. free(cnfbuf);
  10186. cnfbuf = NULL;
  10187. }
  10188. i = strlen(opt_kernel_path) + 2;
  10189. char __kernel_path[i];
  10190. snprintf(__kernel_path, i, "%s/", opt_kernel_path);
  10191. opt_kernel_path = __kernel_path;
  10192. if (want_per_device_stats)
  10193. opt_log_output = true;
  10194. #ifdef WANT_CPUMINE
  10195. #ifdef USE_SCRYPT
  10196. if (opt_scrypt)
  10197. set_scrypt_algo(&opt_algo);
  10198. #endif
  10199. #endif
  10200. bfg_devapi_init();
  10201. drv_detect_all();
  10202. total_devices = total_devices_new;
  10203. devices = devices_new;
  10204. total_devices_new = 0;
  10205. devices_new = NULL;
  10206. if (opt_display_devs) {
  10207. int devcount = 0;
  10208. applog(LOG_ERR, "Devices detected:");
  10209. for (i = 0; i < total_devices; ++i) {
  10210. struct cgpu_info *cgpu = devices[i];
  10211. char buf[0x100];
  10212. if (cgpu->device != cgpu)
  10213. continue;
  10214. if (cgpu->name)
  10215. snprintf(buf, sizeof(buf), " %s", cgpu->name);
  10216. else
  10217. if (cgpu->dev_manufacturer)
  10218. snprintf(buf, sizeof(buf), " %s by %s", (cgpu->dev_product ?: "Device"), cgpu->dev_manufacturer);
  10219. else
  10220. if (cgpu->dev_product)
  10221. snprintf(buf, sizeof(buf), " %s", cgpu->dev_product);
  10222. else
  10223. strcpy(buf, " Device");
  10224. tailsprintf(buf, sizeof(buf), " (driver=%s; procs=%d", cgpu->drv->dname, cgpu->procs);
  10225. if (cgpu->dev_serial)
  10226. tailsprintf(buf, sizeof(buf), "; serial=%s", cgpu->dev_serial);
  10227. if (cgpu->device_path)
  10228. tailsprintf(buf, sizeof(buf), "; path=%s", cgpu->device_path);
  10229. tailsprintf(buf, sizeof(buf), ")");
  10230. _applog(LOG_NOTICE, buf);
  10231. ++devcount;
  10232. }
  10233. quit(0, "%d devices listed", devcount);
  10234. }
  10235. mining_threads = 0;
  10236. for (i = 0; i < total_devices; ++i)
  10237. register_device(devices[i]);
  10238. if (!total_devices) {
  10239. applog(LOG_WARNING, "No devices detected!");
  10240. if (use_curses)
  10241. applog(LOG_WARNING, "Waiting for devices; press 'M+' to add, or 'Q' to quit");
  10242. else
  10243. applog(LOG_WARNING, "Waiting for devices");
  10244. }
  10245. if (opt_quit_summary == BQS_DEFAULT)
  10246. {
  10247. if (total_devices < 25)
  10248. opt_quit_summary = BQS_PROCS;
  10249. else
  10250. opt_quit_summary = BQS_DEVS;
  10251. }
  10252. #ifdef HAVE_CURSES
  10253. switch_logsize();
  10254. #endif
  10255. if (!total_pools) {
  10256. applog(LOG_WARNING, "Need to specify at least one pool server.");
  10257. #ifdef HAVE_CURSES
  10258. if (!use_curses || !input_pool(false))
  10259. #endif
  10260. quit(1, "Pool setup failed");
  10261. }
  10262. for (i = 0; i < total_pools; i++) {
  10263. struct pool *pool = pools[i];
  10264. size_t siz;
  10265. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  10266. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  10267. if (!pool->rpc_url)
  10268. quit(1, "No URI supplied for pool %u", i);
  10269. if (!pool->rpc_userpass) {
  10270. if (!pool->rpc_user || !pool->rpc_pass)
  10271. quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  10272. siz = strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2;
  10273. pool->rpc_userpass = malloc(siz);
  10274. if (!pool->rpc_userpass)
  10275. quit(1, "Failed to malloc userpass");
  10276. snprintf(pool->rpc_userpass, siz, "%s:%s", pool->rpc_user, pool->rpc_pass);
  10277. }
  10278. }
  10279. /* Set the currentpool to pool with priority 0 */
  10280. validate_pool_priorities();
  10281. for (i = 0; i < total_pools; i++) {
  10282. struct pool *pool = pools[i];
  10283. if (!pool->prio)
  10284. currentpool = pool;
  10285. }
  10286. #ifdef HAVE_SYSLOG_H
  10287. if (use_syslog)
  10288. openlog(PACKAGE, LOG_PID, LOG_USER);
  10289. #endif
  10290. #if defined(unix) || defined(__APPLE__)
  10291. if (opt_stderr_cmd)
  10292. fork_monitor();
  10293. #endif // defined(unix)
  10294. mining_thr = calloc(mining_threads, sizeof(thr));
  10295. if (!mining_thr)
  10296. quit(1, "Failed to calloc mining_thr");
  10297. for (i = 0; i < mining_threads; i++) {
  10298. mining_thr[i] = calloc(1, sizeof(*thr));
  10299. if (!mining_thr[i])
  10300. quit(1, "Failed to calloc mining_thr[%d]", i);
  10301. }
  10302. total_control_threads = 6;
  10303. control_thr = calloc(total_control_threads, sizeof(*thr));
  10304. if (!control_thr)
  10305. quit(1, "Failed to calloc control_thr");
  10306. gwsched_thr_id = 0;
  10307. /* Create a unique get work queue */
  10308. getq = tq_new();
  10309. if (!getq)
  10310. quit(1, "Failed to create getq");
  10311. /* We use the getq mutex as the staged lock */
  10312. stgd_lock = &getq->mutex;
  10313. if (opt_benchmark)
  10314. goto begin_bench;
  10315. for (i = 0; i < total_pools; i++) {
  10316. struct pool *pool = pools[i];
  10317. enable_pool(pool);
  10318. pool->idle = true;
  10319. }
  10320. applog(LOG_NOTICE, "Probing for an alive pool");
  10321. do {
  10322. bool still_testing;
  10323. int i;
  10324. /* Look for at least one active pool before starting */
  10325. probe_pools();
  10326. do {
  10327. sleep(1);
  10328. if (pools_active)
  10329. break;
  10330. still_testing = false;
  10331. for (int i = 0; i < total_pools; ++i)
  10332. if (pools[i]->testing)
  10333. still_testing = true;
  10334. } while (still_testing);
  10335. if (!pools_active) {
  10336. applog(LOG_ERR, "No servers were found that could be used to get work from.");
  10337. applog(LOG_ERR, "Please check the details from the list below of the servers you have input");
  10338. applog(LOG_ERR, "Most likely you have input the wrong URL, forgotten to add a port, or have not set up workers");
  10339. for (i = 0; i < total_pools; i++) {
  10340. struct pool *pool;
  10341. pool = pools[i];
  10342. applog(LOG_WARNING, "Pool: %d URL: %s User: %s Password: %s",
  10343. i, pool->rpc_url, pool->rpc_user, pool->rpc_pass);
  10344. }
  10345. #ifdef HAVE_CURSES
  10346. if (use_curses) {
  10347. halfdelay(150);
  10348. applog(LOG_ERR, "Press any key to exit, or BFGMiner will try again in 15s.");
  10349. if (getch() != ERR)
  10350. quit(0, "No servers could be used! Exiting.");
  10351. cbreak();
  10352. } else
  10353. #endif
  10354. quit(0, "No servers could be used! Exiting.");
  10355. }
  10356. } while (!pools_active);
  10357. #ifdef USE_SCRYPT
  10358. if (detect_algo == 1 && !opt_scrypt) {
  10359. applog(LOG_NOTICE, "Detected scrypt algorithm");
  10360. opt_scrypt = true;
  10361. }
  10362. #endif
  10363. detect_algo = 0;
  10364. begin_bench:
  10365. total_mhashes_done = 0;
  10366. for (i = 0; i < total_devices; i++) {
  10367. struct cgpu_info *cgpu = devices[i];
  10368. cgpu->rolling = cgpu->total_mhashes = 0;
  10369. }
  10370. cgtime(&total_tv_start);
  10371. cgtime(&total_tv_end);
  10372. miner_started = total_tv_start;
  10373. time_t miner_start_ts = time(NULL);
  10374. if (schedstart.tm.tm_sec)
  10375. localtime_r(&miner_start_ts, &schedstart.tm);
  10376. if (schedstop.tm.tm_sec)
  10377. localtime_r(&miner_start_ts, &schedstop .tm);
  10378. get_datestamp(datestamp, sizeof(datestamp), miner_start_ts);
  10379. // Initialise processors and threads
  10380. k = 0;
  10381. for (i = 0; i < total_devices; ++i) {
  10382. struct cgpu_info *cgpu = devices[i];
  10383. allocate_cgpu(cgpu, &k);
  10384. }
  10385. // Start threads
  10386. for (i = 0; i < total_devices; ++i) {
  10387. struct cgpu_info *cgpu = devices[i];
  10388. start_cgpu(cgpu);
  10389. }
  10390. #ifdef HAVE_OPENCL
  10391. for (i = 0; i < nDevs; i++)
  10392. pause_dynamic_threads(i);
  10393. #endif
  10394. #ifdef WANT_CPUMINE
  10395. applog(LOG_INFO, "%d cpu miner threads started, "
  10396. "using SHA256 '%s' algorithm.",
  10397. opt_n_threads,
  10398. algo_names[opt_algo]);
  10399. #endif
  10400. cgtime(&total_tv_start);
  10401. cgtime(&total_tv_end);
  10402. if (!opt_benchmark)
  10403. {
  10404. pthread_t submit_thread;
  10405. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, NULL)))
  10406. quit(1, "submit_work thread create failed");
  10407. }
  10408. watchpool_thr_id = 1;
  10409. thr = &control_thr[watchpool_thr_id];
  10410. /* start watchpool thread */
  10411. if (thr_info_create(thr, NULL, watchpool_thread, NULL))
  10412. quit(1, "watchpool thread create failed");
  10413. pthread_detach(thr->pth);
  10414. watchdog_thr_id = 2;
  10415. thr = &control_thr[watchdog_thr_id];
  10416. /* start watchdog thread */
  10417. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  10418. quit(1, "watchdog thread create failed");
  10419. pthread_detach(thr->pth);
  10420. #ifdef HAVE_OPENCL
  10421. /* Create reinit gpu thread */
  10422. gpur_thr_id = 3;
  10423. thr = &control_thr[gpur_thr_id];
  10424. thr->q = tq_new();
  10425. if (!thr->q)
  10426. quit(1, "tq_new failed for gpur_thr_id");
  10427. if (thr_info_create(thr, NULL, reinit_gpu, thr))
  10428. quit(1, "reinit_gpu thread create failed");
  10429. #endif
  10430. /* Create API socket thread */
  10431. api_thr_id = 4;
  10432. thr = &control_thr[api_thr_id];
  10433. if (thr_info_create(thr, NULL, api_thread, thr))
  10434. quit(1, "API thread create failed");
  10435. #ifdef USE_LIBMICROHTTPD
  10436. if (httpsrv_port != -1)
  10437. httpsrv_start(httpsrv_port);
  10438. #endif
  10439. #ifdef USE_LIBEVENT
  10440. if (stratumsrv_port != -1)
  10441. stratumsrv_start();
  10442. #endif
  10443. #ifdef HAVE_BFG_HOTPLUG
  10444. if (opt_hotplug && !opt_scrypt)
  10445. hotplug_start();
  10446. #endif
  10447. #ifdef HAVE_CURSES
  10448. /* Create curses input thread for keyboard input. Create this last so
  10449. * that we know all threads are created since this can call kill_work
  10450. * to try and shut down ll previous threads. */
  10451. input_thr_id = 5;
  10452. thr = &control_thr[input_thr_id];
  10453. if (thr_info_create(thr, NULL, input_thread, thr))
  10454. quit(1, "input thread create failed");
  10455. pthread_detach(thr->pth);
  10456. #endif
  10457. /* Just to be sure */
  10458. if (total_control_threads != 6)
  10459. quit(1, "incorrect total_control_threads (%d) should be 7", total_control_threads);
  10460. /* Once everything is set up, main() becomes the getwork scheduler */
  10461. while (42) {
  10462. int ts, max_staged = opt_queue;
  10463. struct pool *pool, *cp;
  10464. bool lagging = false;
  10465. struct curl_ent *ce;
  10466. struct work *work;
  10467. cp = current_pool();
  10468. // Generally, each processor needs a new work, and all at once during work restarts
  10469. max_staged += mining_threads;
  10470. mutex_lock(stgd_lock);
  10471. ts = __total_staged();
  10472. if (!pool_localgen(cp) && !ts && !opt_fail_only)
  10473. lagging = true;
  10474. /* Wait until hash_pop tells us we need to create more work */
  10475. if (ts > max_staged) {
  10476. staged_full = true;
  10477. pthread_cond_wait(&gws_cond, stgd_lock);
  10478. ts = __total_staged();
  10479. }
  10480. mutex_unlock(stgd_lock);
  10481. if (ts > max_staged)
  10482. continue;
  10483. work = make_work();
  10484. if (lagging && !pool_tset(cp, &cp->lagging)) {
  10485. applog(LOG_WARNING, "Pool %d not providing work fast enough", cp->pool_no);
  10486. cp->getfail_occasions++;
  10487. total_go++;
  10488. }
  10489. pool = select_pool(lagging);
  10490. retry:
  10491. if (pool->has_stratum) {
  10492. while (!pool->stratum_active || !pool->stratum_notify) {
  10493. struct pool *altpool = select_pool(true);
  10494. if (altpool == pool && pool->has_stratum)
  10495. cgsleep_ms(5000);
  10496. pool = altpool;
  10497. goto retry;
  10498. }
  10499. gen_stratum_work(pool, work);
  10500. applog(LOG_DEBUG, "Generated stratum work");
  10501. stage_work(work);
  10502. continue;
  10503. }
  10504. if (pool->last_work_copy) {
  10505. mutex_lock(&pool->last_work_lock);
  10506. struct work *last_work = pool->last_work_copy;
  10507. if (!last_work)
  10508. {}
  10509. else
  10510. if (can_roll(last_work) && should_roll(last_work)) {
  10511. struct timeval tv_now;
  10512. cgtime(&tv_now);
  10513. free_work(work);
  10514. work = make_clone(pool->last_work_copy);
  10515. mutex_unlock(&pool->last_work_lock);
  10516. roll_work(work);
  10517. applog(LOG_DEBUG, "Generated work from latest GBT job in get_work_thread with %d seconds left", (int)blkmk_time_left(work->tmpl, tv_now.tv_sec));
  10518. stage_work(work);
  10519. continue;
  10520. } else if (last_work->tmpl && pool->proto == PLP_GETBLOCKTEMPLATE && blkmk_work_left(last_work->tmpl) > (unsigned long)mining_threads) {
  10521. // Don't free last_work_copy, since it is used to detect upstream provides plenty of work per template
  10522. } else {
  10523. free_work(last_work);
  10524. pool->last_work_copy = NULL;
  10525. }
  10526. mutex_unlock(&pool->last_work_lock);
  10527. }
  10528. if (clone_available()) {
  10529. applog(LOG_DEBUG, "Cloned getwork work");
  10530. free_work(work);
  10531. continue;
  10532. }
  10533. if (opt_benchmark) {
  10534. get_benchmark_work(work);
  10535. applog(LOG_DEBUG, "Generated benchmark work");
  10536. stage_work(work);
  10537. continue;
  10538. }
  10539. work->pool = pool;
  10540. ce = pop_curl_entry3(pool, 2);
  10541. /* obtain new work from bitcoin via JSON-RPC */
  10542. if (!get_upstream_work(work, ce->curl)) {
  10543. struct pool *next_pool;
  10544. /* Make sure the pool just hasn't stopped serving
  10545. * requests but is up as we'll keep hammering it */
  10546. push_curl_entry(ce, pool);
  10547. ++pool->seq_getfails;
  10548. pool_died(pool);
  10549. next_pool = select_pool(!opt_fail_only);
  10550. if (pool == next_pool) {
  10551. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, retrying in 5s", pool->pool_no);
  10552. cgsleep_ms(5000);
  10553. } else {
  10554. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, failover activated", pool->pool_no);
  10555. pool = next_pool;
  10556. }
  10557. goto retry;
  10558. }
  10559. if (ts >= max_staged)
  10560. pool_tclear(pool, &pool->lagging);
  10561. if (pool_tclear(pool, &pool->idle))
  10562. pool_resus(pool);
  10563. applog(LOG_DEBUG, "Generated getwork work");
  10564. stage_work(work);
  10565. push_curl_entry(ce, pool);
  10566. }
  10567. return 0;
  10568. }