miner.c 300 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710
  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 <limits.h>
  22. #include <locale.h>
  23. #include <stdio.h>
  24. #include <stdlib.h>
  25. #include <string.h>
  26. #include <stdbool.h>
  27. #include <stdint.h>
  28. #include <unistd.h>
  29. #include <sys/time.h>
  30. #include <time.h>
  31. #include <math.h>
  32. #include <stdarg.h>
  33. #include <assert.h>
  34. #include <signal.h>
  35. #include <wctype.h>
  36. #include <sys/stat.h>
  37. #include <sys/types.h>
  38. #include <dirent.h>
  39. #ifdef HAVE_PWD_H
  40. #include <pwd.h>
  41. #endif
  42. #ifndef WIN32
  43. #include <sys/resource.h>
  44. #include <sys/socket.h>
  45. #else
  46. #include <winsock2.h>
  47. #include <windows.h>
  48. #endif
  49. #include <ccan/opt/opt.h>
  50. #include <jansson.h>
  51. #include <curl/curl.h>
  52. #include <libgen.h>
  53. #include <sha2.h>
  54. #include <utlist.h>
  55. #include <blkmaker.h>
  56. #include <blkmaker_jansson.h>
  57. #include <blktemplate.h>
  58. #include "compat.h"
  59. #include "deviceapi.h"
  60. #include "logging.h"
  61. #include "miner.h"
  62. #include "findnonce.h"
  63. #include "adl.h"
  64. #include "driver-cpu.h"
  65. #include "driver-opencl.h"
  66. #include "bench_block.h"
  67. #include "scrypt.h"
  68. #ifdef USE_AVALON
  69. #include "driver-avalon.h"
  70. #endif
  71. #ifdef HAVE_BFG_LOWLEVEL
  72. #include "lowlevel.h"
  73. #endif
  74. #if defined(unix) || defined(__APPLE__)
  75. #include <errno.h>
  76. #include <fcntl.h>
  77. #include <sys/wait.h>
  78. #endif
  79. #ifdef USE_SCRYPT
  80. #include "scrypt.h"
  81. #endif
  82. #if defined(USE_AVALON) || defined(USE_BITFORCE) || defined(USE_ICARUS) || defined(USE_MODMINER) || defined(USE_NANOFURY) || defined(USE_X6500) || defined(USE_ZTEX)
  83. # define USE_FPGA
  84. #endif
  85. struct strategies strategies[] = {
  86. { "Failover" },
  87. { "Round Robin" },
  88. { "Rotate" },
  89. { "Load Balance" },
  90. { "Balance" },
  91. };
  92. static char packagename[256];
  93. bool opt_protocol;
  94. bool opt_dev_protocol;
  95. static bool opt_benchmark;
  96. static bool want_longpoll = true;
  97. static bool want_gbt = true;
  98. static bool want_getwork = true;
  99. #if BLKMAKER_VERSION > 1
  100. struct _cbscript_t {
  101. char *data;
  102. size_t sz;
  103. };
  104. static struct _cbscript_t opt_coinbase_script;
  105. static uint32_t template_nonce;
  106. #endif
  107. #if BLKMAKER_VERSION > 0
  108. char *opt_coinbase_sig;
  109. #endif
  110. char *request_target_str;
  111. float request_pdiff = 1.0;
  112. double request_bdiff;
  113. static bool want_stratum = true;
  114. bool have_longpoll;
  115. int opt_skip_checks;
  116. bool want_per_device_stats;
  117. bool use_syslog;
  118. bool opt_quiet_work_updates;
  119. bool opt_quiet;
  120. bool opt_realquiet;
  121. int loginput_size;
  122. bool opt_compact;
  123. bool opt_show_procs;
  124. const int opt_cutofftemp = 95;
  125. int opt_hysteresis = 3;
  126. static int opt_retries = -1;
  127. int opt_fail_pause = 5;
  128. int opt_log_interval = 5;
  129. int opt_queue = 1;
  130. int opt_scantime = 60;
  131. int opt_expiry = 120;
  132. int opt_expiry_lp = 3600;
  133. int opt_bench_algo = -1;
  134. unsigned long long global_hashrate;
  135. static bool opt_unittest = false;
  136. unsigned long global_quota_gcd = 1;
  137. #ifdef HAVE_OPENCL
  138. int opt_dynamic_interval = 7;
  139. int nDevs;
  140. int opt_g_threads = -1;
  141. #endif
  142. #ifdef USE_SCRYPT
  143. static char detect_algo = 1;
  144. bool opt_scrypt;
  145. #else
  146. static char detect_algo;
  147. #endif
  148. bool opt_restart = true;
  149. #ifdef USE_LIBMICROHTTPD
  150. #include "httpsrv.h"
  151. int httpsrv_port = -1;
  152. #endif
  153. #ifdef USE_LIBEVENT
  154. int stratumsrv_port = -1;
  155. #endif
  156. struct string_elist *scan_devices;
  157. static struct string_elist *opt_set_device_list;
  158. bool opt_force_dev_init;
  159. static struct string_elist *opt_devices_enabled_list;
  160. static bool opt_display_devs;
  161. int total_devices;
  162. struct cgpu_info **devices;
  163. int total_devices_new;
  164. struct cgpu_info **devices_new;
  165. bool have_opencl;
  166. int opt_n_threads = -1;
  167. int mining_threads;
  168. int num_processors;
  169. #ifdef HAVE_CURSES
  170. bool use_curses = true;
  171. #else
  172. bool use_curses;
  173. #endif
  174. #ifdef HAVE_LIBUSB
  175. bool have_libusb;
  176. #endif
  177. static bool opt_submit_stale = true;
  178. static int opt_shares;
  179. static int opt_submit_threads = 0x40;
  180. bool opt_fail_only;
  181. bool opt_autofan;
  182. bool opt_autoengine;
  183. bool opt_noadl;
  184. char *opt_api_allow = NULL;
  185. char *opt_api_groups;
  186. char *opt_api_description = PACKAGE_STRING;
  187. int opt_api_port = 4028;
  188. bool opt_api_listen;
  189. bool opt_api_mcast;
  190. char *opt_api_mcast_addr = API_MCAST_ADDR;
  191. char *opt_api_mcast_code = API_MCAST_CODE;
  192. char *opt_api_mcast_des = "";
  193. int opt_api_mcast_port = 4028;
  194. bool opt_api_network;
  195. bool opt_delaynet;
  196. bool opt_disable_pool;
  197. static bool no_work;
  198. bool opt_worktime;
  199. bool opt_weighed_stats;
  200. char *opt_kernel_path;
  201. char *cgminer_path;
  202. #if defined(USE_BITFORCE)
  203. bool opt_bfl_noncerange;
  204. #endif
  205. #define QUIET (opt_quiet || opt_realquiet)
  206. struct thr_info *control_thr;
  207. struct thr_info **mining_thr;
  208. static int gwsched_thr_id;
  209. static int watchpool_thr_id;
  210. static int watchdog_thr_id;
  211. #ifdef HAVE_CURSES
  212. static int input_thr_id;
  213. #endif
  214. int gpur_thr_id;
  215. static int api_thr_id;
  216. static int total_control_threads;
  217. pthread_mutex_t hash_lock;
  218. static pthread_mutex_t *stgd_lock;
  219. pthread_mutex_t console_lock;
  220. cglock_t ch_lock;
  221. static pthread_rwlock_t blk_lock;
  222. static pthread_mutex_t sshare_lock;
  223. pthread_rwlock_t netacc_lock;
  224. pthread_rwlock_t mining_thr_lock;
  225. pthread_rwlock_t devices_lock;
  226. static pthread_mutex_t lp_lock;
  227. static pthread_cond_t lp_cond;
  228. pthread_cond_t gws_cond;
  229. bool shutting_down;
  230. double total_rolling;
  231. double total_mhashes_done;
  232. static struct timeval total_tv_start, total_tv_end;
  233. static struct timeval miner_started;
  234. cglock_t control_lock;
  235. pthread_mutex_t stats_lock;
  236. static pthread_mutex_t submitting_lock;
  237. static int total_submitting;
  238. static struct work *submit_waiting;
  239. notifier_t submit_waiting_notifier;
  240. int hw_errors;
  241. int total_accepted, total_rejected;
  242. int total_getworks, total_stale, total_discarded;
  243. uint64_t total_bytes_rcvd, total_bytes_sent;
  244. double total_diff1, total_bad_diff1;
  245. double total_diff_accepted, total_diff_rejected, total_diff_stale;
  246. static int staged_rollable;
  247. unsigned int new_blocks;
  248. unsigned int found_blocks;
  249. unsigned int local_work;
  250. unsigned int total_go, total_ro;
  251. struct pool **pools;
  252. static struct pool *currentpool = NULL;
  253. int total_pools, enabled_pools;
  254. enum pool_strategy pool_strategy = POOL_FAILOVER;
  255. int opt_rotate_period;
  256. static int total_urls, total_users, total_passes;
  257. static
  258. #ifndef HAVE_CURSES
  259. const
  260. #endif
  261. bool curses_active;
  262. #ifdef HAVE_CURSES
  263. #if !(defined(PDCURSES) || defined(NCURSES_VERSION))
  264. const
  265. #endif
  266. short default_bgcolor = COLOR_BLACK;
  267. static int attr_title = A_BOLD;
  268. #endif
  269. static
  270. #if defined(HAVE_CURSES) && defined(USE_UNICODE)
  271. bool use_unicode;
  272. static
  273. bool have_unicode_degrees;
  274. static
  275. wchar_t unicode_micro = 'u';
  276. #else
  277. const bool use_unicode;
  278. static
  279. const bool have_unicode_degrees;
  280. static
  281. const char unicode_micro = 'u';
  282. #endif
  283. #ifdef HAVE_CURSES
  284. #define U8_BAD_START "\xef\x80\x81"
  285. #define U8_BAD_END "\xef\x80\x80"
  286. #define AS_BAD(x) U8_BAD_START x U8_BAD_END
  287. bool selecting_device;
  288. unsigned selected_device;
  289. #endif
  290. static char current_block[40];
  291. /* Protected by ch_lock */
  292. static char *current_hash;
  293. static uint32_t current_block_id;
  294. char *current_fullhash;
  295. static char datestamp[40];
  296. static char blocktime[32];
  297. time_t block_time;
  298. static char best_share[8] = "0";
  299. double current_diff = 0xFFFFFFFFFFFFFFFFULL;
  300. static char block_diff[8];
  301. static char net_hashrate[10];
  302. uint64_t best_diff = 0;
  303. static bool known_blkheight_current;
  304. static uint32_t known_blkheight;
  305. static uint32_t known_blkheight_blkid;
  306. static uint64_t block_subsidy;
  307. struct block {
  308. char hash[40];
  309. UT_hash_handle hh;
  310. int block_no;
  311. };
  312. static struct block *blocks = NULL;
  313. int swork_id;
  314. /* For creating a hash database of stratum shares submitted that have not had
  315. * a response yet */
  316. struct stratum_share {
  317. UT_hash_handle hh;
  318. bool block;
  319. struct work *work;
  320. int id;
  321. };
  322. static struct stratum_share *stratum_shares = NULL;
  323. char *opt_socks_proxy = NULL;
  324. static const char def_conf[] = "bfgminer.conf";
  325. static bool config_loaded;
  326. static int include_count;
  327. #define JSON_INCLUDE_CONF "include"
  328. #define JSON_LOAD_ERROR "JSON decode of file '%s' failed\n %s"
  329. #define JSON_LOAD_ERROR_LEN strlen(JSON_LOAD_ERROR)
  330. #define JSON_MAX_DEPTH 10
  331. #define JSON_MAX_DEPTH_ERR "Too many levels of JSON includes (limit 10) or a loop"
  332. char *cmd_idle, *cmd_sick, *cmd_dead;
  333. #if defined(unix) || defined(__APPLE__)
  334. static char *opt_stderr_cmd = NULL;
  335. static int forkpid;
  336. #endif // defined(unix)
  337. #ifdef HAVE_CHROOT
  338. char *chroot_dir;
  339. #endif
  340. #ifdef HAVE_PWD_H
  341. char *opt_setuid;
  342. #endif
  343. struct sigaction termhandler, inthandler;
  344. struct thread_q *getq;
  345. static int total_work;
  346. static bool staged_full;
  347. struct work *staged_work = NULL;
  348. struct schedtime {
  349. bool enable;
  350. struct tm tm;
  351. };
  352. struct schedtime schedstart;
  353. struct schedtime schedstop;
  354. bool sched_paused;
  355. static bool time_before(struct tm *tm1, struct tm *tm2)
  356. {
  357. if (tm1->tm_hour < tm2->tm_hour)
  358. return true;
  359. if (tm1->tm_hour == tm2->tm_hour && tm1->tm_min < tm2->tm_min)
  360. return true;
  361. return false;
  362. }
  363. static bool should_run(void)
  364. {
  365. struct tm tm;
  366. time_t tt;
  367. bool within_range;
  368. if (!schedstart.enable && !schedstop.enable)
  369. return true;
  370. tt = time(NULL);
  371. localtime_r(&tt, &tm);
  372. // NOTE: This is delicately balanced so that should_run is always false if schedstart==schedstop
  373. if (time_before(&schedstop.tm, &schedstart.tm))
  374. within_range = (time_before(&tm, &schedstop.tm) || !time_before(&tm, &schedstart.tm));
  375. else
  376. within_range = (time_before(&tm, &schedstop.tm) && !time_before(&tm, &schedstart.tm));
  377. if (within_range && !schedstop.enable)
  378. /* This is a once off event with no stop time set */
  379. schedstart.enable = false;
  380. return within_range;
  381. }
  382. void get_datestamp(char *f, size_t fsiz, time_t tt)
  383. {
  384. struct tm _tm;
  385. struct tm *tm = &_tm;
  386. if (tt == INVALID_TIMESTAMP)
  387. tt = time(NULL);
  388. localtime_r(&tt, tm);
  389. snprintf(f, fsiz, "[%d-%02d-%02d %02d:%02d:%02d]",
  390. tm->tm_year + 1900,
  391. tm->tm_mon + 1,
  392. tm->tm_mday,
  393. tm->tm_hour,
  394. tm->tm_min,
  395. tm->tm_sec);
  396. }
  397. static
  398. void get_timestamp(char *f, size_t fsiz, time_t tt)
  399. {
  400. struct tm _tm;
  401. struct tm *tm = &_tm;
  402. localtime_r(&tt, tm);
  403. snprintf(f, fsiz, "[%02d:%02d:%02d]",
  404. tm->tm_hour,
  405. tm->tm_min,
  406. tm->tm_sec);
  407. }
  408. static void applog_and_exit(const char *fmt, ...) FORMAT_SYNTAX_CHECK(printf, 1, 2);
  409. static char exit_buf[512];
  410. static void applog_and_exit(const char *fmt, ...)
  411. {
  412. va_list ap;
  413. va_start(ap, fmt);
  414. vsnprintf(exit_buf, sizeof(exit_buf), fmt, ap);
  415. va_end(ap);
  416. _applog(LOG_ERR, exit_buf);
  417. exit(1);
  418. }
  419. char *devpath_to_devid(const char *devpath)
  420. {
  421. #ifndef WIN32
  422. struct stat my_stat;
  423. if (stat(devpath, &my_stat))
  424. return NULL;
  425. char *devs = malloc(6 + (sizeof(dev_t) * 2) + 1);
  426. memcpy(devs, "dev_t:", 6);
  427. bin2hex(&devs[6], &my_stat.st_rdev, sizeof(dev_t));
  428. #else
  429. if (!strncmp(devpath, "\\\\.\\", 4))
  430. devpath += 4;
  431. if (strncasecmp(devpath, "COM", 3) || !devpath[3])
  432. return NULL;
  433. devpath += 3;
  434. char *p;
  435. strtol(devpath, &p, 10);
  436. if (p[0])
  437. return NULL;
  438. const int sz = (p - devpath);
  439. char *devs = malloc(4 + sz + 1);
  440. sprintf(devs, "com:%s", devpath);
  441. #endif
  442. return devs;
  443. }
  444. static
  445. bool devpaths_match(const char * const ap, const char * const bp)
  446. {
  447. char * const a = devpath_to_devid(ap);
  448. if (!a)
  449. return false;
  450. char * const b = devpath_to_devid(bp);
  451. bool rv = false;
  452. if (b)
  453. {
  454. rv = !strcmp(a, b);
  455. free(b);
  456. }
  457. free(a);
  458. return rv;
  459. }
  460. static
  461. int proc_letter_to_number(const char *s, const char ** const rem)
  462. {
  463. int n = 0, c;
  464. for ( ; s[0]; ++s)
  465. {
  466. if (unlikely(n > INT_MAX / 26))
  467. break;
  468. c = tolower(s[0]) - 'a';
  469. if (unlikely(c < 0 || c > 25))
  470. break;
  471. if (unlikely(INT_MAX - c < n))
  472. break;
  473. n = (n * 26) + c;
  474. }
  475. *rem = s;
  476. return n;
  477. }
  478. static
  479. bool cgpu_match(const char * const pattern, const struct cgpu_info * const cgpu)
  480. {
  481. // all - matches anything
  482. // d0 - matches all processors of device 0
  483. // d0-3 - matches all processors of device 0, 1, 2, or 3
  484. // d0a - matches first processor of device 0
  485. // 0 - matches processor 0
  486. // 0-4 - matches processors 0, 1, 2, 3, or 4
  487. // ___ - matches all processors on all devices using driver/name ___
  488. // ___0 - matches all processors of 0th device using driver/name ___
  489. // ___0a - matches first processor of 0th device using driver/name ___
  490. // @* - matches device with serial or path *
  491. // @*@a - matches first processor of device with serial or path *
  492. // ___@* - matches device with serial or path * using driver/name ___
  493. if (!strcasecmp(pattern, "all"))
  494. return true;
  495. const struct device_drv * const drv = cgpu->drv;
  496. const char *p = pattern, *p2;
  497. size_t L;
  498. int n, i, c = -1;
  499. int n2;
  500. int proc_first = -1, proc_last = -1;
  501. struct cgpu_info *device;
  502. if (!(strncasecmp(drv->dname, p, (L = strlen(drv->dname)))
  503. && strncasecmp(drv-> name, p, (L = strlen(drv-> name)))))
  504. // dname or name
  505. p = &pattern[L];
  506. else
  507. if (p[0] == 'd' && (isdigit(p[1]) || p[1] == '-'))
  508. // d#
  509. ++p;
  510. else
  511. if (isdigit(p[0]) || p[0] == '@' || p[0] == '-')
  512. // # or @
  513. {}
  514. else
  515. return false;
  516. L = p - pattern;
  517. while (isspace(p[0]))
  518. ++p;
  519. if (p[0] == '@')
  520. {
  521. // Serial/path
  522. const char * const ser = &p[1];
  523. for (p = ser; p[0] != '@' && p[0] != '\0'; ++p)
  524. {}
  525. p2 = (p[0] == '@') ? &p[1] : p;
  526. const size_t serlen = (p - ser);
  527. p = "";
  528. n = n2 = 0;
  529. const char * const devpath = cgpu->device_path ?: "";
  530. const char * const devser = cgpu->dev_serial ?: "";
  531. if ((!strncmp(devpath, ser, serlen)) && devpath[serlen] == '\0')
  532. {} // Match
  533. else
  534. if ((!strncmp(devser, ser, serlen)) && devser[serlen] == '\0')
  535. {} // Match
  536. else
  537. {
  538. char devpath2[serlen + 1];
  539. memcpy(devpath2, ser, serlen);
  540. devpath2[serlen] = '\0';
  541. if (!devpaths_match(devpath, ser))
  542. return false;
  543. }
  544. }
  545. else
  546. {
  547. if (isdigit(p[0]))
  548. n = strtol(p, (void*)&p2, 0);
  549. else
  550. {
  551. n = 0;
  552. p2 = p;
  553. }
  554. if (p2[0] == '-')
  555. {
  556. ++p2;
  557. if (p2[0] && isdigit(p2[0]))
  558. n2 = strtol(p2, (void*)&p2, 0);
  559. else
  560. n2 = INT_MAX;
  561. }
  562. else
  563. n2 = n;
  564. if (p == pattern)
  565. {
  566. if (!p[0])
  567. return true;
  568. if (p2 && p2[0])
  569. goto invsyntax;
  570. for (i = n; i <= n2; ++i)
  571. {
  572. if (i >= total_devices)
  573. break;
  574. if (cgpu == devices[i])
  575. return true;
  576. }
  577. return false;
  578. }
  579. }
  580. if (p2[0])
  581. {
  582. proc_first = proc_letter_to_number(&p2[0], &p2);
  583. if (p2[0] == '-')
  584. {
  585. ++p2;
  586. if (p2[0])
  587. proc_last = proc_letter_to_number(p2, &p2);
  588. else
  589. proc_last = INT_MAX;
  590. }
  591. else
  592. proc_last = proc_first;
  593. if (p2[0])
  594. goto invsyntax;
  595. }
  596. if (L > 1 || tolower(pattern[0]) != 'd' || !p[0])
  597. {
  598. if ((L == 3 && !strncasecmp(pattern, drv->name, 3)) ||
  599. (!L) ||
  600. (L == strlen(drv->dname) && !strncasecmp(pattern, drv->dname, L)))
  601. {} // Matched name or dname
  602. else
  603. return false;
  604. if (p[0] && (cgpu->device_id < n || cgpu->device_id > n2))
  605. return false;
  606. if (proc_first != -1 && (cgpu->proc_id < proc_first || cgpu->proc_id > proc_last))
  607. return false;
  608. return true;
  609. }
  610. // d#
  611. c = -1;
  612. for (i = 0; ; ++i)
  613. {
  614. if (i == total_devices)
  615. return false;
  616. if (devices[i]->device != devices[i])
  617. continue;
  618. ++c;
  619. if (c < n)
  620. continue;
  621. if (c > n2)
  622. break;
  623. for (device = devices[i]; device; device = device->next_proc)
  624. {
  625. if (proc_first != -1 && (device->proc_id < proc_first || device->proc_id > proc_last))
  626. continue;
  627. if (device == cgpu)
  628. return true;
  629. }
  630. }
  631. return false;
  632. invsyntax:
  633. applog(LOG_WARNING, "%s: Invalid syntax: %s", __func__, pattern);
  634. return false;
  635. }
  636. #define TEST_CGPU_MATCH(pattern) \
  637. if (!cgpu_match(pattern, &cgpu)) \
  638. applog(LOG_ERR, "%s: Pattern \"%s\" should have matched!", __func__, pattern); \
  639. // END TEST_CGPU_MATCH
  640. #define TEST_CGPU_NOMATCH(pattern) \
  641. if (cgpu_match(pattern, &cgpu)) \
  642. applog(LOG_ERR, "%s: Pattern \"%s\" should NOT have matched!", __func__, pattern); \
  643. // END TEST_CGPU_MATCH
  644. static __maybe_unused
  645. void test_cgpu_match()
  646. {
  647. struct device_drv drv = {
  648. .dname = "test",
  649. .name = "TST",
  650. };
  651. struct cgpu_info cgpu = {
  652. .drv = &drv,
  653. .device = &cgpu,
  654. .device_id = 1,
  655. .proc_id = 1,
  656. .proc_repr = "TST 1b",
  657. }, cgpu0a = {
  658. .drv = &drv,
  659. .device = &cgpu0a,
  660. .device_id = 0,
  661. .proc_id = 0,
  662. .proc_repr = "TST 0a",
  663. }, cgpu1a = {
  664. .drv = &drv,
  665. .device = &cgpu0a,
  666. .device_id = 1,
  667. .proc_id = 0,
  668. .proc_repr = "TST 1a",
  669. };
  670. struct cgpu_info *devices_list[3] = {&cgpu0a, &cgpu1a, &cgpu,};
  671. devices = devices_list;
  672. total_devices = 3;
  673. TEST_CGPU_MATCH("all")
  674. TEST_CGPU_MATCH("d1")
  675. TEST_CGPU_NOMATCH("d2")
  676. TEST_CGPU_MATCH("d0-5")
  677. TEST_CGPU_NOMATCH("d0-0")
  678. TEST_CGPU_NOMATCH("d2-5")
  679. TEST_CGPU_MATCH("d-1")
  680. TEST_CGPU_MATCH("d1-")
  681. TEST_CGPU_NOMATCH("d-0")
  682. TEST_CGPU_NOMATCH("d2-")
  683. TEST_CGPU_MATCH("2")
  684. TEST_CGPU_NOMATCH("3")
  685. TEST_CGPU_MATCH("1-2")
  686. TEST_CGPU_MATCH("2-3")
  687. TEST_CGPU_NOMATCH("1-1")
  688. TEST_CGPU_NOMATCH("3-4")
  689. TEST_CGPU_MATCH("TST")
  690. TEST_CGPU_MATCH("test")
  691. TEST_CGPU_MATCH("tst")
  692. TEST_CGPU_MATCH("TEST")
  693. TEST_CGPU_NOMATCH("TSF")
  694. TEST_CGPU_NOMATCH("TS")
  695. TEST_CGPU_NOMATCH("TSTF")
  696. TEST_CGPU_MATCH("TST1")
  697. TEST_CGPU_MATCH("test1")
  698. TEST_CGPU_MATCH("TST0-1")
  699. TEST_CGPU_MATCH("TST 1")
  700. TEST_CGPU_MATCH("TST 1-2")
  701. TEST_CGPU_MATCH("TEST 1-2")
  702. TEST_CGPU_NOMATCH("TST2")
  703. TEST_CGPU_NOMATCH("TST2-3")
  704. TEST_CGPU_NOMATCH("TST0-0")
  705. TEST_CGPU_MATCH("TST1b")
  706. TEST_CGPU_MATCH("tst1b")
  707. TEST_CGPU_NOMATCH("TST1c")
  708. TEST_CGPU_NOMATCH("TST1bb")
  709. TEST_CGPU_MATCH("TST0-1b")
  710. TEST_CGPU_NOMATCH("TST0-1c")
  711. TEST_CGPU_MATCH("TST1a-d")
  712. TEST_CGPU_NOMATCH("TST1a-a")
  713. TEST_CGPU_NOMATCH("TST1-a")
  714. TEST_CGPU_NOMATCH("TST1c-z")
  715. TEST_CGPU_NOMATCH("TST1c-")
  716. TEST_CGPU_MATCH("@")
  717. TEST_CGPU_NOMATCH("@abc")
  718. TEST_CGPU_MATCH("@@b")
  719. TEST_CGPU_NOMATCH("@@c")
  720. TEST_CGPU_MATCH("TST@")
  721. TEST_CGPU_NOMATCH("TST@abc")
  722. TEST_CGPU_MATCH("TST@@b")
  723. TEST_CGPU_NOMATCH("TST@@c")
  724. TEST_CGPU_MATCH("TST@@b-f")
  725. TEST_CGPU_NOMATCH("TST@@c-f")
  726. TEST_CGPU_NOMATCH("TST@@-a")
  727. cgpu.device_path = "/dev/test";
  728. cgpu.dev_serial = "testy";
  729. TEST_CGPU_MATCH("TST@/dev/test")
  730. TEST_CGPU_MATCH("TST@testy")
  731. TEST_CGPU_NOMATCH("TST@")
  732. TEST_CGPU_NOMATCH("TST@/dev/test5@b")
  733. TEST_CGPU_NOMATCH("TST@testy3@b")
  734. TEST_CGPU_MATCH("TST@/dev/test@b")
  735. TEST_CGPU_MATCH("TST@testy@b")
  736. TEST_CGPU_NOMATCH("TST@/dev/test@c")
  737. TEST_CGPU_NOMATCH("TST@testy@c")
  738. cgpu.device_path = "usb:000:999";
  739. TEST_CGPU_MATCH("TST@usb:000:999")
  740. drv.dname = "test7";
  741. TEST_CGPU_MATCH("test7")
  742. TEST_CGPU_MATCH("TEST7")
  743. TEST_CGPU_NOMATCH("test&")
  744. TEST_CGPU_MATCH("test7 1-2")
  745. TEST_CGPU_MATCH("test7@testy@b")
  746. }
  747. static
  748. int cgpu_search(const char * const pattern, const int first)
  749. {
  750. int i;
  751. struct cgpu_info *cgpu;
  752. #define CHECK_CGPU_SEARCH do{ \
  753. cgpu = get_devices(i); \
  754. if (cgpu_match(pattern, cgpu)) \
  755. return i; \
  756. }while(0)
  757. for (i = first; i < total_devices; ++i)
  758. CHECK_CGPU_SEARCH;
  759. for (i = 0; i < first; ++i)
  760. CHECK_CGPU_SEARCH;
  761. #undef CHECK_CGPU_SEARCH
  762. return -1;
  763. }
  764. static pthread_mutex_t sharelog_lock;
  765. static FILE *sharelog_file = NULL;
  766. struct thr_info *get_thread(int thr_id)
  767. {
  768. struct thr_info *thr;
  769. rd_lock(&mining_thr_lock);
  770. thr = mining_thr[thr_id];
  771. rd_unlock(&mining_thr_lock);
  772. return thr;
  773. }
  774. static struct cgpu_info *get_thr_cgpu(int thr_id)
  775. {
  776. struct thr_info *thr = get_thread(thr_id);
  777. return thr->cgpu;
  778. }
  779. struct cgpu_info *get_devices(int id)
  780. {
  781. struct cgpu_info *cgpu;
  782. rd_lock(&devices_lock);
  783. cgpu = devices[id];
  784. rd_unlock(&devices_lock);
  785. return cgpu;
  786. }
  787. static pthread_mutex_t noncelog_lock = PTHREAD_MUTEX_INITIALIZER;
  788. static FILE *noncelog_file = NULL;
  789. static
  790. void noncelog(const struct work * const work)
  791. {
  792. const int thr_id = work->thr_id;
  793. const struct cgpu_info *proc = get_thr_cgpu(thr_id);
  794. char buf[0x200], hash[65], data[161], midstate[65];
  795. int rv;
  796. size_t ret;
  797. bin2hex(hash, work->hash, 32);
  798. bin2hex(data, work->data, 80);
  799. bin2hex(midstate, work->midstate, 32);
  800. // timestamp,proc,hash,data,midstate
  801. rv = snprintf(buf, sizeof(buf), "%lu,%s,%s,%s,%s\n",
  802. (unsigned long)time(NULL), proc->proc_repr_ns,
  803. hash, data, midstate);
  804. if (unlikely(rv < 1))
  805. {
  806. applog(LOG_ERR, "noncelog printf error");
  807. return;
  808. }
  809. mutex_lock(&noncelog_lock);
  810. ret = fwrite(buf, rv, 1, noncelog_file);
  811. fflush(noncelog_file);
  812. mutex_unlock(&noncelog_lock);
  813. if (ret != 1)
  814. applog(LOG_ERR, "noncelog fwrite error");
  815. }
  816. static void sharelog(const char*disposition, const struct work*work)
  817. {
  818. char target[(sizeof(work->target) * 2) + 1];
  819. char hash[(sizeof(work->hash) * 2) + 1];
  820. char data[(sizeof(work->data) * 2) + 1];
  821. struct cgpu_info *cgpu;
  822. unsigned long int t;
  823. struct pool *pool;
  824. int thr_id, rv;
  825. char s[1024];
  826. size_t ret;
  827. if (!sharelog_file)
  828. return;
  829. thr_id = work->thr_id;
  830. cgpu = get_thr_cgpu(thr_id);
  831. pool = work->pool;
  832. t = work->ts_getwork + timer_elapsed(&work->tv_getwork, &work->tv_work_found);
  833. bin2hex(target, work->target, sizeof(work->target));
  834. bin2hex(hash, work->hash, sizeof(work->hash));
  835. bin2hex(data, work->data, sizeof(work->data));
  836. // timestamp,disposition,target,pool,dev,thr,sharehash,sharedata
  837. 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);
  838. if (rv >= (int)(sizeof(s)))
  839. s[sizeof(s) - 1] = '\0';
  840. else if (rv < 0) {
  841. applog(LOG_ERR, "sharelog printf error");
  842. return;
  843. }
  844. mutex_lock(&sharelog_lock);
  845. ret = fwrite(s, rv, 1, sharelog_file);
  846. fflush(sharelog_file);
  847. mutex_unlock(&sharelog_lock);
  848. if (ret != 1)
  849. applog(LOG_ERR, "sharelog fwrite error");
  850. }
  851. static char *getwork_req = "{\"method\": \"getwork\", \"params\": [], \"id\":0}\n";
  852. /* Adjust all the pools' quota to the greatest common denominator after a pool
  853. * has been added or the quotas changed. */
  854. void adjust_quota_gcd(void)
  855. {
  856. unsigned long gcd, lowest_quota = ~0UL, quota;
  857. struct pool *pool;
  858. int i;
  859. for (i = 0; i < total_pools; i++) {
  860. pool = pools[i];
  861. quota = pool->quota;
  862. if (!quota)
  863. continue;
  864. if (quota < lowest_quota)
  865. lowest_quota = quota;
  866. }
  867. if (likely(lowest_quota < ~0UL)) {
  868. gcd = lowest_quota;
  869. for (i = 0; i < total_pools; i++) {
  870. pool = pools[i];
  871. quota = pool->quota;
  872. if (!quota)
  873. continue;
  874. while (quota % gcd)
  875. gcd--;
  876. }
  877. } else
  878. gcd = 1;
  879. for (i = 0; i < total_pools; i++) {
  880. pool = pools[i];
  881. pool->quota_used *= global_quota_gcd;
  882. pool->quota_used /= gcd;
  883. pool->quota_gcd = pool->quota / gcd;
  884. }
  885. global_quota_gcd = gcd;
  886. applog(LOG_DEBUG, "Global quota greatest common denominator set to %lu", gcd);
  887. }
  888. /* Return value is ignored if not called from add_pool_details */
  889. struct pool *add_pool(void)
  890. {
  891. struct pool *pool;
  892. pool = calloc(sizeof(struct pool), 1);
  893. if (!pool)
  894. quit(1, "Failed to malloc pool in add_pool");
  895. pool->pool_no = pool->prio = total_pools;
  896. mutex_init(&pool->last_work_lock);
  897. mutex_init(&pool->pool_lock);
  898. if (unlikely(pthread_cond_init(&pool->cr_cond, NULL)))
  899. quit(1, "Failed to pthread_cond_init in add_pool");
  900. cglock_init(&pool->data_lock);
  901. mutex_init(&pool->stratum_lock);
  902. timer_unset(&pool->swork.tv_transparency);
  903. /* Make sure the pool doesn't think we've been idle since time 0 */
  904. pool->tv_idle.tv_sec = ~0UL;
  905. cgtime(&pool->cgminer_stats.start_tv);
  906. pool->rpc_proxy = NULL;
  907. pool->quota = 1;
  908. adjust_quota_gcd();
  909. pool->sock = INVSOCK;
  910. pool->lp_socket = CURL_SOCKET_BAD;
  911. pools = realloc(pools, sizeof(struct pool *) * (total_pools + 2));
  912. pools[total_pools++] = pool;
  913. return pool;
  914. }
  915. /* Pool variant of test and set */
  916. static bool pool_tset(struct pool *pool, bool *var)
  917. {
  918. bool ret;
  919. mutex_lock(&pool->pool_lock);
  920. ret = *var;
  921. *var = true;
  922. mutex_unlock(&pool->pool_lock);
  923. return ret;
  924. }
  925. bool pool_tclear(struct pool *pool, bool *var)
  926. {
  927. bool ret;
  928. mutex_lock(&pool->pool_lock);
  929. ret = *var;
  930. *var = false;
  931. mutex_unlock(&pool->pool_lock);
  932. return ret;
  933. }
  934. struct pool *current_pool(void)
  935. {
  936. struct pool *pool;
  937. cg_rlock(&control_lock);
  938. pool = currentpool;
  939. cg_runlock(&control_lock);
  940. return pool;
  941. }
  942. char *set_int_range(const char *arg, int *i, int min, int max)
  943. {
  944. char *err = opt_set_intval(arg, i);
  945. if (err)
  946. return err;
  947. if (*i < min || *i > max)
  948. return "Value out of range";
  949. return NULL;
  950. }
  951. static char *set_int_0_to_9999(const char *arg, int *i)
  952. {
  953. return set_int_range(arg, i, 0, 9999);
  954. }
  955. static char *set_int_1_to_65535(const char *arg, int *i)
  956. {
  957. return set_int_range(arg, i, 1, 65535);
  958. }
  959. static char *set_int_0_to_10(const char *arg, int *i)
  960. {
  961. return set_int_range(arg, i, 0, 10);
  962. }
  963. static char *set_int_1_to_10(const char *arg, int *i)
  964. {
  965. return set_int_range(arg, i, 1, 10);
  966. }
  967. char *set_strdup(const char *arg, char **p)
  968. {
  969. *p = strdup((char *)arg);
  970. return NULL;
  971. }
  972. #if BLKMAKER_VERSION > 1
  973. static char *set_b58addr(const char *arg, struct _cbscript_t *p)
  974. {
  975. size_t scriptsz = blkmk_address_to_script(NULL, 0, arg);
  976. if (!scriptsz)
  977. return "Invalid address";
  978. char *script = malloc(scriptsz);
  979. if (blkmk_address_to_script(script, scriptsz, arg) != scriptsz) {
  980. free(script);
  981. return "Failed to convert address to script";
  982. }
  983. p->data = script;
  984. p->sz = scriptsz;
  985. return NULL;
  986. }
  987. #endif
  988. static void bdiff_target_leadzero(unsigned char *target, double diff);
  989. char *set_request_diff(const char *arg, float *p)
  990. {
  991. unsigned char target[32];
  992. char *e = opt_set_floatval(arg, p);
  993. if (e)
  994. return e;
  995. request_bdiff = (double)*p * 0.9999847412109375;
  996. bdiff_target_leadzero(target, request_bdiff);
  997. request_target_str = malloc(65);
  998. bin2hex(request_target_str, target, 32);
  999. return NULL;
  1000. }
  1001. #ifdef NEED_BFG_LOWL_VCOM
  1002. extern struct lowlevel_device_info *_vcom_devinfo_findorcreate(struct lowlevel_device_info **, const char *);
  1003. #ifdef WIN32
  1004. void _vcom_devinfo_scan_querydosdevice(struct lowlevel_device_info ** const devinfo_list)
  1005. {
  1006. char dev[PATH_MAX];
  1007. char *devp = dev;
  1008. size_t bufLen = 0x100;
  1009. tryagain: ;
  1010. char buf[bufLen];
  1011. if (!QueryDosDevice(NULL, buf, bufLen)) {
  1012. if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
  1013. bufLen *= 2;
  1014. applog(LOG_DEBUG, "QueryDosDevice returned insufficent buffer error; enlarging to %lx", (unsigned long)bufLen);
  1015. goto tryagain;
  1016. }
  1017. applogr(, LOG_WARNING, "Error occurred trying to enumerate COM ports with QueryDosDevice");
  1018. }
  1019. size_t tLen;
  1020. memcpy(devp, "\\\\.\\", 4);
  1021. devp = &devp[4];
  1022. for (char *t = buf; *t; t += tLen) {
  1023. tLen = strlen(t) + 1;
  1024. if (strncmp("COM", t, 3))
  1025. continue;
  1026. memcpy(devp, t, tLen);
  1027. // NOTE: We depend on _vcom_devinfo_findorcreate to further check that there's a number (and only a number) on the end
  1028. _vcom_devinfo_findorcreate(devinfo_list, dev);
  1029. }
  1030. }
  1031. #else
  1032. void _vcom_devinfo_scan_lsdev(struct lowlevel_device_info ** const devinfo_list)
  1033. {
  1034. char dev[PATH_MAX];
  1035. char *devp = dev;
  1036. DIR *D;
  1037. struct dirent *de;
  1038. const char devdir[] = "/dev";
  1039. const size_t devdirlen = sizeof(devdir) - 1;
  1040. char *devpath = devp;
  1041. char *devfile = devpath + devdirlen + 1;
  1042. D = opendir(devdir);
  1043. if (!D)
  1044. applogr(, LOG_DEBUG, "No /dev directory to look for VCOM devices in");
  1045. memcpy(devpath, devdir, devdirlen);
  1046. devpath[devdirlen] = '/';
  1047. while ( (de = readdir(D)) ) {
  1048. if (!strncmp(de->d_name, "cu.", 3)
  1049. //don't probe Bluetooth devices - causes bus errors and segfaults
  1050. && strncmp(de->d_name, "cu.Bluetooth", 12))
  1051. goto trydev;
  1052. if (strncmp(de->d_name, "tty", 3))
  1053. continue;
  1054. if (strncmp(&de->d_name[3], "USB", 3) && strncmp(&de->d_name[3], "ACM", 3))
  1055. continue;
  1056. trydev:
  1057. strcpy(devfile, de->d_name);
  1058. _vcom_devinfo_findorcreate(devinfo_list, dev);
  1059. }
  1060. closedir(D);
  1061. }
  1062. #endif
  1063. #endif
  1064. static char *add_serial(const char *arg)
  1065. {
  1066. string_elist_add(arg, &scan_devices);
  1067. return NULL;
  1068. }
  1069. static
  1070. char *opt_string_elist_add(const char *arg, struct string_elist **elist)
  1071. {
  1072. string_elist_add(arg, elist);
  1073. return NULL;
  1074. }
  1075. bool get_intrange(const char *arg, int *val1, int *val2)
  1076. {
  1077. // NOTE: This could be done with sscanf, but its %n is broken in strange ways on Windows
  1078. char *p, *p2;
  1079. *val1 = strtol(arg, &p, 0);
  1080. if (arg == p)
  1081. // Zero-length ending number, invalid
  1082. return false;
  1083. while (true)
  1084. {
  1085. if (!p[0])
  1086. {
  1087. *val2 = *val1;
  1088. return true;
  1089. }
  1090. if (p[0] == '-')
  1091. break;
  1092. if (!isspace(p[0]))
  1093. // Garbage, invalid
  1094. return false;
  1095. ++p;
  1096. }
  1097. p2 = &p[1];
  1098. *val2 = strtol(p2, &p, 0);
  1099. if (p2 == p)
  1100. // Zero-length ending number, invalid
  1101. return false;
  1102. while (true)
  1103. {
  1104. if (!p[0])
  1105. return true;
  1106. if (!isspace(p[0]))
  1107. // Garbage, invalid
  1108. return false;
  1109. ++p;
  1110. }
  1111. }
  1112. static
  1113. void _test_intrange(const char *s, const int v[2])
  1114. {
  1115. int a[2];
  1116. if (!get_intrange(s, &a[0], &a[1]))
  1117. applog(LOG_ERR, "Test \"%s\" failed: returned false", s);
  1118. for (int i = 0; i < 2; ++i)
  1119. if (unlikely(a[i] != v[i]))
  1120. applog(LOG_ERR, "Test \"%s\" failed: value %d should be %d but got %d", s, i, v[i], a[i]);
  1121. }
  1122. #define _test_intrange(s, ...) _test_intrange(s, (int[]){ __VA_ARGS__ })
  1123. static
  1124. void _test_intrange_fail(const char *s)
  1125. {
  1126. int a[2];
  1127. if (get_intrange(s, &a[0], &a[1]))
  1128. applog(LOG_ERR, "Test !\"%s\" failed: returned true with %d and %d", s, a[0], a[1]);
  1129. }
  1130. static
  1131. void test_intrange()
  1132. {
  1133. _test_intrange("-1--2", -1, -2);
  1134. _test_intrange("-1-2", -1, 2);
  1135. _test_intrange("1--2", 1, -2);
  1136. _test_intrange("1-2", 1, 2);
  1137. _test_intrange("111-222", 111, 222);
  1138. _test_intrange(" 11 - 22 ", 11, 22);
  1139. _test_intrange("+11-+22", 11, 22);
  1140. _test_intrange("-1", -1, -1);
  1141. _test_intrange_fail("all");
  1142. _test_intrange_fail("1-");
  1143. _test_intrange_fail("");
  1144. _test_intrange_fail("1-54x");
  1145. }
  1146. static char *set_devices(char *arg)
  1147. {
  1148. if (*arg) {
  1149. if (*arg == '?') {
  1150. opt_display_devs = true;
  1151. return NULL;
  1152. }
  1153. } else
  1154. return "Invalid device parameters";
  1155. string_elist_add(arg, &opt_devices_enabled_list);
  1156. return NULL;
  1157. }
  1158. static char *set_balance(enum pool_strategy *strategy)
  1159. {
  1160. *strategy = POOL_BALANCE;
  1161. return NULL;
  1162. }
  1163. static char *set_loadbalance(enum pool_strategy *strategy)
  1164. {
  1165. *strategy = POOL_LOADBALANCE;
  1166. return NULL;
  1167. }
  1168. static char *set_rotate(const char *arg, int *i)
  1169. {
  1170. pool_strategy = POOL_ROTATE;
  1171. return set_int_range(arg, i, 0, 9999);
  1172. }
  1173. static char *set_rr(enum pool_strategy *strategy)
  1174. {
  1175. *strategy = POOL_ROUNDROBIN;
  1176. return NULL;
  1177. }
  1178. /* Detect that url is for a stratum protocol either via the presence of
  1179. * stratum+tcp or by detecting a stratum server response */
  1180. bool detect_stratum(struct pool *pool, char *url)
  1181. {
  1182. if (!extract_sockaddr(url, &pool->sockaddr_url, &pool->stratum_port))
  1183. return false;
  1184. if (!strncasecmp(url, "stratum+tcp://", 14)) {
  1185. pool->rpc_url = strdup(url);
  1186. pool->has_stratum = true;
  1187. pool->stratum_url = pool->sockaddr_url;
  1188. return true;
  1189. }
  1190. return false;
  1191. }
  1192. static struct pool *add_url(void)
  1193. {
  1194. total_urls++;
  1195. if (total_urls > total_pools)
  1196. add_pool();
  1197. return pools[total_urls - 1];
  1198. }
  1199. static void setup_url(struct pool *pool, char *arg)
  1200. {
  1201. if (detect_stratum(pool, arg))
  1202. return;
  1203. opt_set_charp(arg, &pool->rpc_url);
  1204. if (strncmp(arg, "http://", 7) &&
  1205. strncmp(arg, "https://", 8)) {
  1206. const size_t L = strlen(arg);
  1207. char *httpinput;
  1208. httpinput = malloc(8 + L);
  1209. if (!httpinput)
  1210. quit(1, "Failed to malloc httpinput");
  1211. sprintf(httpinput, "http://%s", arg);
  1212. pool->rpc_url = httpinput;
  1213. }
  1214. }
  1215. static char *set_url(char *arg)
  1216. {
  1217. struct pool *pool = add_url();
  1218. setup_url(pool, arg);
  1219. return NULL;
  1220. }
  1221. static char *set_quota(char *arg)
  1222. {
  1223. char *semicolon = strchr(arg, ';'), *url;
  1224. int len, qlen, quota;
  1225. struct pool *pool;
  1226. if (!semicolon)
  1227. return "No semicolon separated quota;URL pair found";
  1228. len = strlen(arg);
  1229. *semicolon = '\0';
  1230. qlen = strlen(arg);
  1231. if (!qlen)
  1232. return "No parameter for quota found";
  1233. len -= qlen + 1;
  1234. if (len < 1)
  1235. return "No parameter for URL found";
  1236. quota = atoi(arg);
  1237. if (quota < 0)
  1238. return "Invalid negative parameter for quota set";
  1239. url = arg + qlen + 1;
  1240. pool = add_url();
  1241. setup_url(pool, url);
  1242. pool->quota = quota;
  1243. applog(LOG_INFO, "Setting pool %d to quota %d", pool->pool_no, pool->quota);
  1244. adjust_quota_gcd();
  1245. return NULL;
  1246. }
  1247. static char *set_user(const char *arg)
  1248. {
  1249. struct pool *pool;
  1250. total_users++;
  1251. if (total_users > total_pools)
  1252. add_pool();
  1253. pool = pools[total_users - 1];
  1254. opt_set_charp(arg, &pool->rpc_user);
  1255. return NULL;
  1256. }
  1257. static char *set_pass(const char *arg)
  1258. {
  1259. struct pool *pool;
  1260. total_passes++;
  1261. if (total_passes > total_pools)
  1262. add_pool();
  1263. pool = pools[total_passes - 1];
  1264. opt_set_charp(arg, &pool->rpc_pass);
  1265. return NULL;
  1266. }
  1267. static char *set_userpass(const char *arg)
  1268. {
  1269. struct pool *pool;
  1270. char *updup;
  1271. if (total_users != total_passes)
  1272. return "User + pass options must be balanced before userpass";
  1273. ++total_users;
  1274. ++total_passes;
  1275. if (total_users > total_pools)
  1276. add_pool();
  1277. pool = pools[total_users - 1];
  1278. updup = strdup(arg);
  1279. opt_set_charp(arg, &pool->rpc_userpass);
  1280. pool->rpc_user = strtok(updup, ":");
  1281. if (!pool->rpc_user)
  1282. return "Failed to find : delimited user info";
  1283. pool->rpc_pass = strtok(NULL, ":");
  1284. if (!pool->rpc_pass)
  1285. pool->rpc_pass = "";
  1286. return NULL;
  1287. }
  1288. static char *set_pool_priority(const char *arg)
  1289. {
  1290. struct pool *pool;
  1291. if (!total_pools)
  1292. return "Usage of --pool-priority before pools are defined does not make sense";
  1293. pool = pools[total_pools - 1];
  1294. opt_set_intval(arg, &pool->prio);
  1295. return NULL;
  1296. }
  1297. static char *set_pool_proxy(const char *arg)
  1298. {
  1299. struct pool *pool;
  1300. if (!total_pools)
  1301. return "Usage of --pool-proxy before pools are defined does not make sense";
  1302. if (!our_curl_supports_proxy_uris())
  1303. return "Your installed cURL library does not support proxy URIs. At least version 7.21.7 is required.";
  1304. pool = pools[total_pools - 1];
  1305. opt_set_charp(arg, &pool->rpc_proxy);
  1306. return NULL;
  1307. }
  1308. static char *set_pool_force_rollntime(const char *arg)
  1309. {
  1310. struct pool *pool;
  1311. if (!total_pools)
  1312. return "Usage of --force-rollntime before pools are defined does not make sense";
  1313. pool = pools[total_pools - 1];
  1314. opt_set_intval(arg, &pool->force_rollntime);
  1315. return NULL;
  1316. }
  1317. static char *enable_debug(bool *flag)
  1318. {
  1319. *flag = true;
  1320. opt_debug_console = true;
  1321. /* Turn on verbose output, too. */
  1322. opt_log_output = true;
  1323. return NULL;
  1324. }
  1325. static char *set_schedtime(const char *arg, struct schedtime *st)
  1326. {
  1327. if (sscanf(arg, "%d:%d", &st->tm.tm_hour, &st->tm.tm_min) != 2)
  1328. {
  1329. if (strcasecmp(arg, "now"))
  1330. return "Invalid time set, should be HH:MM";
  1331. } else
  1332. schedstop.tm.tm_sec = 0;
  1333. if (st->tm.tm_hour > 23 || st->tm.tm_min > 59 || st->tm.tm_hour < 0 || st->tm.tm_min < 0)
  1334. return "Invalid time set.";
  1335. st->enable = true;
  1336. return NULL;
  1337. }
  1338. static
  1339. char *set_log_file(char *arg)
  1340. {
  1341. char *r = "";
  1342. long int i = strtol(arg, &r, 10);
  1343. int fd, stderr_fd = fileno(stderr);
  1344. if ((!*r) && i >= 0 && i <= INT_MAX)
  1345. fd = i;
  1346. else
  1347. if (!strcmp(arg, "-"))
  1348. {
  1349. fd = fileno(stdout);
  1350. if (unlikely(fd == -1))
  1351. return "Standard output missing for log-file";
  1352. }
  1353. else
  1354. {
  1355. fd = open(arg, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR);
  1356. if (unlikely(fd == -1))
  1357. return "Failed to open log-file";
  1358. }
  1359. close(stderr_fd);
  1360. if (unlikely(-1 == dup2(fd, stderr_fd)))
  1361. return "Failed to dup2 for log-file";
  1362. close(fd);
  1363. return NULL;
  1364. }
  1365. static
  1366. char *_bfgopt_set_file(const char *arg, FILE **F, const char *mode, const char *purpose)
  1367. {
  1368. char *r = "";
  1369. long int i = strtol(arg, &r, 10);
  1370. static char *err = NULL;
  1371. const size_t errbufsz = 0x100;
  1372. free(err);
  1373. err = NULL;
  1374. if ((!*r) && i >= 0 && i <= INT_MAX) {
  1375. *F = fdopen((int)i, mode);
  1376. if (!*F)
  1377. {
  1378. err = malloc(errbufsz);
  1379. snprintf(err, errbufsz, "Failed to open fd %d for %s",
  1380. (int)i, purpose);
  1381. return err;
  1382. }
  1383. } else if (!strcmp(arg, "-")) {
  1384. *F = (mode[0] == 'a') ? stdout : stdin;
  1385. if (!*F)
  1386. {
  1387. err = malloc(errbufsz);
  1388. snprintf(err, errbufsz, "Standard %sput missing for %s",
  1389. (mode[0] == 'a') ? "out" : "in", purpose);
  1390. return err;
  1391. }
  1392. } else {
  1393. *F = fopen(arg, mode);
  1394. if (!*F)
  1395. {
  1396. err = malloc(errbufsz);
  1397. snprintf(err, errbufsz, "Failed to open %s for %s",
  1398. arg, purpose);
  1399. return err;
  1400. }
  1401. }
  1402. return NULL;
  1403. }
  1404. static char *set_noncelog(char *arg)
  1405. {
  1406. return _bfgopt_set_file(arg, &noncelog_file, "a", "nonce log");
  1407. }
  1408. static char *set_sharelog(char *arg)
  1409. {
  1410. return _bfgopt_set_file(arg, &sharelog_file, "a", "share log");
  1411. }
  1412. char *set_temp_cutoff(char *arg)
  1413. {
  1414. if (strchr(arg, ','))
  1415. return "temp-cutoff no longer supports comma-delimited syntax, use --set-device for better control";
  1416. applog(LOG_WARNING, "temp-cutoff is deprecated! Use --set-device for better control");
  1417. char buf[0x100];
  1418. snprintf(buf, sizeof(buf), "all:temp-cutoff=%s", arg);
  1419. applog(LOG_DEBUG, "%s: Using --set-device %s", __func__, buf);
  1420. string_elist_add(buf, &opt_set_device_list);
  1421. return NULL;
  1422. }
  1423. char *set_temp_target(char *arg)
  1424. {
  1425. if (strchr(arg, ','))
  1426. return "temp-target no longer supports comma-delimited syntax, use --set-device for better control";
  1427. applog(LOG_WARNING, "temp-target is deprecated! Use --set-device for better control");
  1428. char buf[0x100];
  1429. snprintf(buf, sizeof(buf), "all:temp-target=%s", arg);
  1430. applog(LOG_DEBUG, "%s: Using --set-device %s", __func__, buf);
  1431. string_elist_add(buf, &opt_set_device_list);
  1432. return NULL;
  1433. }
  1434. static char *set_api_allow(const char *arg)
  1435. {
  1436. opt_set_charp(arg, &opt_api_allow);
  1437. return NULL;
  1438. }
  1439. static char *set_api_groups(const char *arg)
  1440. {
  1441. opt_set_charp(arg, &opt_api_groups);
  1442. return NULL;
  1443. }
  1444. static char *set_api_description(const char *arg)
  1445. {
  1446. opt_set_charp(arg, &opt_api_description);
  1447. return NULL;
  1448. }
  1449. static char *set_api_mcast_des(const char *arg)
  1450. {
  1451. opt_set_charp(arg, &opt_api_mcast_des);
  1452. return NULL;
  1453. }
  1454. #ifdef USE_ICARUS
  1455. extern const struct bfg_set_device_definition icarus_set_device_funcs[];
  1456. static char *set_icarus_options(const char *arg)
  1457. {
  1458. if (strchr(arg, ','))
  1459. return "icarus-options no longer supports comma-delimited syntax, see README.FPGA for better control";
  1460. applog(LOG_WARNING, "icarus-options is deprecated! See README.FPGA for better control");
  1461. char *opts = strdup(arg), *argdup;
  1462. argdup = opts;
  1463. const struct bfg_set_device_definition *sdf = icarus_set_device_funcs;
  1464. const char *drivers[] = {"antminer", "cairnsmore", "erupter", "icarus"};
  1465. char buf[0x100], *saveptr, *opt;
  1466. for (int i = 0; i < 4; ++i, ++sdf)
  1467. {
  1468. opt = strtok_r(opts, ":", &saveptr);
  1469. opts = NULL;
  1470. if (!opt)
  1471. break;
  1472. if (!opt[0])
  1473. continue;
  1474. for (int j = 0; j < 4; ++j)
  1475. {
  1476. snprintf(buf, sizeof(buf), "%s:%s=%s", drivers[j], sdf->optname, opt);
  1477. applog(LOG_DEBUG, "%s: Using --set-device %s", __func__, buf);
  1478. string_elist_add(buf, &opt_set_device_list);
  1479. }
  1480. }
  1481. free(argdup);
  1482. return NULL;
  1483. }
  1484. static char *set_icarus_timing(const char *arg)
  1485. {
  1486. if (strchr(arg, ','))
  1487. return "icarus-timing no longer supports comma-delimited syntax, see README.FPGA for better control";
  1488. applog(LOG_WARNING, "icarus-timing is deprecated! See README.FPGA for better control");
  1489. const char *drivers[] = {"antminer", "cairnsmore", "erupter", "icarus"};
  1490. char buf[0x100];
  1491. for (int j = 0; j < 4; ++j)
  1492. {
  1493. snprintf(buf, sizeof(buf), "%s:timing=%s", drivers[j], arg);
  1494. applog(LOG_DEBUG, "%s: Using --set-device %s", __func__, buf);
  1495. string_elist_add(buf, &opt_set_device_list);
  1496. }
  1497. return NULL;
  1498. }
  1499. #endif
  1500. #ifdef USE_AVALON
  1501. extern const struct bfg_set_device_definition avalon_set_device_funcs[];
  1502. static char *set_avalon_options(const char *arg)
  1503. {
  1504. if (strchr(arg, ','))
  1505. return "avalon-options no longer supports comma-delimited syntax, see README.FPGA for better control";
  1506. applog(LOG_WARNING, "avalon-options is deprecated! See README.FPGA for better control");
  1507. char *opts = strdup(arg), *argdup;
  1508. argdup = opts;
  1509. const struct bfg_set_device_definition *sdf = avalon_set_device_funcs;
  1510. char buf[0x100], *saveptr, *opt;
  1511. for (int i = 0; i < 5; ++i, ++sdf)
  1512. {
  1513. opt = strtok_r(opts, ":", &saveptr);
  1514. opts = NULL;
  1515. if (!opt)
  1516. break;
  1517. if (!opt[0])
  1518. continue;
  1519. snprintf(buf, sizeof(buf), "avalon:%s=%s", sdf->optname, opt);
  1520. applog(LOG_DEBUG, "%s: Using --set-device %s", __func__, buf);
  1521. string_elist_add(buf, &opt_set_device_list);
  1522. }
  1523. free(argdup);
  1524. return NULL;
  1525. }
  1526. #endif
  1527. #ifdef USE_KLONDIKE
  1528. static char *set_klondike_options(const char *arg)
  1529. {
  1530. char buf[0x100];
  1531. int hashclock;
  1532. double temptarget;
  1533. switch (sscanf(arg, "%d:%lf", &hashclock, &temptarget))
  1534. {
  1535. default:
  1536. return "Unrecognised --klondike-options";
  1537. case 2:
  1538. snprintf(buf, sizeof(buf), "klondike:temp-target=%lf", temptarget);
  1539. applog(LOG_DEBUG, "%s: Using --set-device %s", __func__, buf);
  1540. string_elist_add(buf, &opt_set_device_list);
  1541. // fallthru
  1542. case 1:
  1543. snprintf(buf, sizeof(buf), "klondike:clock=%d", hashclock);
  1544. applog(LOG_DEBUG, "%s: Using --set-device %s", __func__, buf);
  1545. string_elist_add(buf, &opt_set_device_list);
  1546. }
  1547. applog(LOG_WARNING, "klondike-options is deprecated! Use --set-device for better control");
  1548. return NULL;
  1549. }
  1550. #endif
  1551. __maybe_unused
  1552. static char *set_null(const char __maybe_unused *arg)
  1553. {
  1554. return NULL;
  1555. }
  1556. /* These options are available from config file or commandline */
  1557. static struct opt_table opt_config_table[] = {
  1558. #ifdef WANT_CPUMINE
  1559. OPT_WITH_ARG("--algo|-a",
  1560. set_algo, show_algo, &opt_algo,
  1561. "Specify sha256 implementation for CPU mining:\n"
  1562. "\tfastauto*\tQuick benchmark at startup to pick a working algorithm\n"
  1563. "\tauto\t\tBenchmark at startup and pick fastest algorithm"
  1564. "\n\tc\t\tLinux kernel sha256, implemented in C"
  1565. #ifdef WANT_SSE2_4WAY
  1566. "\n\t4way\t\ttcatm's 4-way SSE2 implementation"
  1567. #endif
  1568. #ifdef WANT_VIA_PADLOCK
  1569. "\n\tvia\t\tVIA padlock implementation"
  1570. #endif
  1571. "\n\tcryptopp\tCrypto++ C/C++ implementation"
  1572. #ifdef WANT_CRYPTOPP_ASM32
  1573. "\n\tcryptopp_asm32\tCrypto++ 32-bit assembler implementation"
  1574. #endif
  1575. #ifdef WANT_X8632_SSE2
  1576. "\n\tsse2_32\t\tSSE2 32 bit implementation for i386 machines"
  1577. #endif
  1578. #ifdef WANT_X8664_SSE2
  1579. "\n\tsse2_64\t\tSSE2 64 bit implementation for x86_64 machines"
  1580. #endif
  1581. #ifdef WANT_X8664_SSE4
  1582. "\n\tsse4_64\t\tSSE4.1 64 bit implementation for x86_64 machines"
  1583. #endif
  1584. #ifdef WANT_ALTIVEC_4WAY
  1585. "\n\taltivec_4way\tAltivec implementation for PowerPC G4 and G5 machines"
  1586. #endif
  1587. ),
  1588. #endif
  1589. OPT_WITH_ARG("--api-allow",
  1590. set_api_allow, NULL, NULL,
  1591. "Allow API access only to the given list of [G:]IP[/Prefix] addresses[/subnets]"),
  1592. OPT_WITH_ARG("--api-description",
  1593. set_api_description, NULL, NULL,
  1594. "Description placed in the API status header, default: BFGMiner version"),
  1595. OPT_WITH_ARG("--api-groups",
  1596. set_api_groups, NULL, NULL,
  1597. "API one letter groups G:cmd:cmd[,P:cmd:*...] defining the cmds a groups can use"),
  1598. OPT_WITHOUT_ARG("--api-listen",
  1599. opt_set_bool, &opt_api_listen,
  1600. "Enable API, default: disabled"),
  1601. OPT_WITHOUT_ARG("--api-mcast",
  1602. opt_set_bool, &opt_api_mcast,
  1603. "Enable API Multicast listener, default: disabled"),
  1604. OPT_WITH_ARG("--api-mcast-addr",
  1605. opt_set_charp, opt_show_charp, &opt_api_mcast_addr,
  1606. "API Multicast listen address"),
  1607. OPT_WITH_ARG("--api-mcast-code",
  1608. opt_set_charp, opt_show_charp, &opt_api_mcast_code,
  1609. "Code expected in the API Multicast message, don't use '-'"),
  1610. OPT_WITH_ARG("--api-mcast-des",
  1611. set_api_mcast_des, NULL, NULL,
  1612. "Description appended to the API Multicast reply, default: ''"),
  1613. OPT_WITH_ARG("--api-mcast-port",
  1614. set_int_1_to_65535, opt_show_intval, &opt_api_mcast_port,
  1615. "API Multicast listen port"),
  1616. OPT_WITHOUT_ARG("--api-network",
  1617. opt_set_bool, &opt_api_network,
  1618. "Allow API (if enabled) to listen on/for any address, default: only 127.0.0.1"),
  1619. OPT_WITH_ARG("--api-port",
  1620. set_int_1_to_65535, opt_show_intval, &opt_api_port,
  1621. "Port number of miner API"),
  1622. #ifdef HAVE_ADL
  1623. OPT_WITHOUT_ARG("--auto-fan",
  1624. opt_set_bool, &opt_autofan,
  1625. "Automatically adjust all GPU fan speeds to maintain a target temperature"),
  1626. OPT_WITHOUT_ARG("--auto-gpu",
  1627. opt_set_bool, &opt_autoengine,
  1628. "Automatically adjust all GPU engine clock speeds to maintain a target temperature"),
  1629. #endif
  1630. OPT_WITHOUT_ARG("--balance",
  1631. set_balance, &pool_strategy,
  1632. "Change multipool strategy from failover to even share balance"),
  1633. OPT_WITHOUT_ARG("--benchmark",
  1634. opt_set_bool, &opt_benchmark,
  1635. "Run BFGMiner in benchmark mode - produces no shares"),
  1636. #if defined(USE_BITFORCE)
  1637. OPT_WITHOUT_ARG("--bfl-range",
  1638. opt_set_bool, &opt_bfl_noncerange,
  1639. "Use nonce range on bitforce devices if supported"),
  1640. #endif
  1641. #ifdef WANT_CPUMINE
  1642. OPT_WITH_ARG("--bench-algo|-b",
  1643. set_int_0_to_9999, opt_show_intval, &opt_bench_algo,
  1644. opt_hidden),
  1645. #endif
  1646. #ifdef HAVE_CHROOT
  1647. OPT_WITH_ARG("--chroot-dir",
  1648. opt_set_charp, NULL, &chroot_dir,
  1649. "Chroot to a directory right after startup"),
  1650. #endif
  1651. OPT_WITH_ARG("--cmd-idle",
  1652. opt_set_charp, NULL, &cmd_idle,
  1653. "Execute a command when a device is allowed to be idle (rest or wait)"),
  1654. OPT_WITH_ARG("--cmd-sick",
  1655. opt_set_charp, NULL, &cmd_sick,
  1656. "Execute a command when a device is declared sick"),
  1657. OPT_WITH_ARG("--cmd-dead",
  1658. opt_set_charp, NULL, &cmd_dead,
  1659. "Execute a command when a device is declared dead"),
  1660. #if BLKMAKER_VERSION > 1
  1661. OPT_WITH_ARG("--coinbase-addr",
  1662. set_b58addr, NULL, &opt_coinbase_script,
  1663. "Set coinbase payout address for solo mining"),
  1664. OPT_WITH_ARG("--coinbase-address|--coinbase-payout|--cbaddress|--cbaddr|--cb-address|--cb-addr|--payout",
  1665. set_b58addr, NULL, &opt_coinbase_script,
  1666. opt_hidden),
  1667. #endif
  1668. #if BLKMAKER_VERSION > 0
  1669. OPT_WITH_ARG("--coinbase-sig",
  1670. set_strdup, NULL, &opt_coinbase_sig,
  1671. "Set coinbase signature when possible"),
  1672. OPT_WITH_ARG("--coinbase|--cbsig|--cb-sig|--cb|--prayer",
  1673. set_strdup, NULL, &opt_coinbase_sig,
  1674. opt_hidden),
  1675. #endif
  1676. #ifdef HAVE_CURSES
  1677. OPT_WITHOUT_ARG("--compact",
  1678. opt_set_bool, &opt_compact,
  1679. "Use compact display without per device statistics"),
  1680. #endif
  1681. #ifdef WANT_CPUMINE
  1682. OPT_WITH_ARG("--cpu-threads|-t",
  1683. force_nthreads_int, opt_show_intval, &opt_n_threads,
  1684. "Number of miner CPU threads"),
  1685. #endif
  1686. OPT_WITHOUT_ARG("--debug|-D",
  1687. enable_debug, &opt_debug,
  1688. "Enable debug output"),
  1689. OPT_WITHOUT_ARG("--debuglog",
  1690. opt_set_bool, &opt_debug,
  1691. "Enable debug logging"),
  1692. OPT_WITHOUT_ARG("--device-protocol-dump",
  1693. opt_set_bool, &opt_dev_protocol,
  1694. "Verbose dump of device protocol-level activities"),
  1695. OPT_WITH_ARG("--device|-d",
  1696. set_devices, NULL, NULL,
  1697. "Enable only devices matching pattern (default: all)"),
  1698. OPT_WITHOUT_ARG("--disable-rejecting",
  1699. opt_set_bool, &opt_disable_pool,
  1700. "Automatically disable pools that continually reject shares"),
  1701. #ifdef USE_LIBMICROHTTPD
  1702. OPT_WITH_ARG("--http-port",
  1703. opt_set_intval, opt_show_intval, &httpsrv_port,
  1704. "Port number to listen on for HTTP getwork miners (-1 means disabled)"),
  1705. #endif
  1706. #if defined(WANT_CPUMINE) && (defined(HAVE_OPENCL) || defined(USE_FPGA))
  1707. OPT_WITHOUT_ARG("--enable-cpu|-C",
  1708. opt_set_bool, &opt_usecpu,
  1709. opt_hidden),
  1710. #endif
  1711. OPT_WITH_ARG("--expiry|-E",
  1712. set_int_0_to_9999, opt_show_intval, &opt_expiry,
  1713. "Upper bound on how many seconds after getting work we consider a share from it stale (w/o longpoll active)"),
  1714. OPT_WITH_ARG("--expiry-lp",
  1715. set_int_0_to_9999, opt_show_intval, &opt_expiry_lp,
  1716. "Upper bound on how many seconds after getting work we consider a share from it stale (with longpoll active)"),
  1717. OPT_WITHOUT_ARG("--failover-only",
  1718. opt_set_bool, &opt_fail_only,
  1719. "Don't leak work to backup pools when primary pool is lagging"),
  1720. #ifdef USE_FPGA
  1721. OPT_WITHOUT_ARG("--force-dev-init",
  1722. opt_set_bool, &opt_force_dev_init,
  1723. "Always initialize devices when possible (such as bitstream uploads to some FPGAs)"),
  1724. #endif
  1725. #ifdef HAVE_OPENCL
  1726. OPT_WITH_ARG("--gpu-dyninterval",
  1727. set_int_1_to_65535, opt_show_intval, &opt_dynamic_interval,
  1728. "Set the refresh interval in ms for GPUs using dynamic intensity"),
  1729. OPT_WITH_ARG("--gpu-platform",
  1730. set_int_0_to_9999, opt_show_intval, &opt_platform_id,
  1731. "Select OpenCL platform ID to use for GPU mining"),
  1732. OPT_WITH_ARG("--gpu-threads|-g",
  1733. set_int_1_to_10, opt_show_intval, &opt_g_threads,
  1734. "Number of threads per GPU (1 - 10)"),
  1735. #ifdef HAVE_ADL
  1736. OPT_WITH_ARG("--gpu-engine",
  1737. set_gpu_engine, NULL, NULL,
  1738. "GPU engine (over)clock range in MHz - one value, range and/or comma separated list (e.g. 850-900,900,750-850)"),
  1739. OPT_WITH_ARG("--gpu-fan",
  1740. set_gpu_fan, NULL, NULL,
  1741. "GPU fan percentage range - one value, range and/or comma separated list (e.g. 0-85,85,65)"),
  1742. OPT_WITH_ARG("--gpu-map",
  1743. set_gpu_map, NULL, NULL,
  1744. "Map OpenCL to ADL device order manually, paired CSV (e.g. 1:0,2:1 maps OpenCL 1 to ADL 0, 2 to 1)"),
  1745. OPT_WITH_ARG("--gpu-memclock",
  1746. set_gpu_memclock, NULL, NULL,
  1747. "Set the GPU memory (over)clock in MHz - one value for all or separate by commas for per card"),
  1748. OPT_WITH_ARG("--gpu-memdiff",
  1749. set_gpu_memdiff, NULL, NULL,
  1750. "Set a fixed difference in clock speed between the GPU and memory in auto-gpu mode"),
  1751. OPT_WITH_ARG("--gpu-powertune",
  1752. set_gpu_powertune, NULL, NULL,
  1753. "Set the GPU powertune percentage - one value for all or separate by commas for per card"),
  1754. OPT_WITHOUT_ARG("--gpu-reorder",
  1755. opt_set_bool, &opt_reorder,
  1756. "Attempt to reorder GPU devices according to PCI Bus ID"),
  1757. OPT_WITH_ARG("--gpu-vddc",
  1758. set_gpu_vddc, NULL, NULL,
  1759. "Set the GPU voltage in Volts - one value for all or separate by commas for per card"),
  1760. #endif
  1761. #ifdef USE_SCRYPT
  1762. OPT_WITH_ARG("--lookup-gap",
  1763. set_lookup_gap, NULL, NULL,
  1764. "Set GPU lookup gap for scrypt mining, comma separated"),
  1765. OPT_WITH_ARG("--intensity|-I",
  1766. set_intensity, NULL, NULL,
  1767. "Intensity of GPU scanning (d or " MIN_SHA_INTENSITY_STR
  1768. " -> " MAX_SCRYPT_INTENSITY_STR
  1769. ",default: d to maintain desktop interactivity)"),
  1770. #else
  1771. OPT_WITH_ARG("--intensity|-I",
  1772. set_intensity, NULL, NULL,
  1773. "Intensity of GPU scanning (d or " MIN_SHA_INTENSITY_STR
  1774. " -> " MAX_SHA_INTENSITY_STR
  1775. ",default: d to maintain desktop interactivity)"),
  1776. #endif
  1777. #endif
  1778. #if defined(HAVE_OPENCL) || defined(USE_MODMINER) || defined(USE_X6500) || defined(USE_ZTEX)
  1779. OPT_WITH_ARG("--kernel-path|-K",
  1780. opt_set_charp, opt_show_charp, &opt_kernel_path,
  1781. "Specify a path to where bitstream and kernel files are"),
  1782. #endif
  1783. #ifdef HAVE_OPENCL
  1784. OPT_WITH_ARG("--kernel|-k",
  1785. set_kernel, NULL, NULL,
  1786. "Override sha256 kernel to use (diablo, poclbm, phatk or diakgcn) - one value or comma separated"),
  1787. #endif
  1788. #ifdef USE_ICARUS
  1789. OPT_WITH_ARG("--icarus-options",
  1790. set_icarus_options, NULL, NULL,
  1791. opt_hidden),
  1792. OPT_WITH_ARG("--icarus-timing",
  1793. set_icarus_timing, NULL, NULL,
  1794. opt_hidden),
  1795. #endif
  1796. #ifdef USE_AVALON
  1797. OPT_WITH_ARG("--avalon-options",
  1798. set_avalon_options, NULL, NULL,
  1799. opt_hidden),
  1800. #endif
  1801. #ifdef USE_KLONDIKE
  1802. OPT_WITH_ARG("--klondike-options",
  1803. set_klondike_options, NULL, NULL,
  1804. "Set klondike options clock:temptarget"),
  1805. #endif
  1806. OPT_WITHOUT_ARG("--load-balance",
  1807. set_loadbalance, &pool_strategy,
  1808. "Change multipool strategy from failover to quota based balance"),
  1809. OPT_WITH_ARG("--log|-l",
  1810. set_int_0_to_9999, opt_show_intval, &opt_log_interval,
  1811. "Interval in seconds between log output"),
  1812. OPT_WITH_ARG("--log-file|-L",
  1813. set_log_file, NULL, NULL,
  1814. "Append log file for output messages"),
  1815. OPT_WITH_ARG("--logfile",
  1816. set_log_file, NULL, NULL,
  1817. opt_hidden),
  1818. OPT_WITHOUT_ARG("--log-microseconds",
  1819. opt_set_bool, &opt_log_microseconds,
  1820. "Include microseconds in log output"),
  1821. #if defined(unix) || defined(__APPLE__)
  1822. OPT_WITH_ARG("--monitor|-m",
  1823. opt_set_charp, NULL, &opt_stderr_cmd,
  1824. "Use custom pipe cmd for output messages"),
  1825. #endif // defined(unix)
  1826. OPT_WITHOUT_ARG("--net-delay",
  1827. opt_set_bool, &opt_delaynet,
  1828. "Impose small delays in networking to avoid overloading slow routers"),
  1829. OPT_WITHOUT_ARG("--no-adl",
  1830. opt_set_bool, &opt_noadl,
  1831. #ifdef HAVE_ADL
  1832. "Disable the ATI display library used for monitoring and setting GPU parameters"
  1833. #else
  1834. opt_hidden
  1835. #endif
  1836. ),
  1837. OPT_WITHOUT_ARG("--no-gbt",
  1838. opt_set_invbool, &want_gbt,
  1839. "Disable getblocktemplate support"),
  1840. OPT_WITHOUT_ARG("--no-getwork",
  1841. opt_set_invbool, &want_getwork,
  1842. "Disable getwork support"),
  1843. OPT_WITHOUT_ARG("--no-longpoll",
  1844. opt_set_invbool, &want_longpoll,
  1845. "Disable X-Long-Polling support"),
  1846. OPT_WITHOUT_ARG("--no-pool-disable",
  1847. opt_set_invbool, &opt_disable_pool,
  1848. opt_hidden),
  1849. OPT_WITHOUT_ARG("--no-restart",
  1850. opt_set_invbool, &opt_restart,
  1851. "Do not attempt to restart devices that hang"
  1852. ),
  1853. OPT_WITHOUT_ARG("--no-show-processors",
  1854. opt_set_invbool, &opt_show_procs,
  1855. opt_hidden),
  1856. OPT_WITHOUT_ARG("--no-show-procs",
  1857. opt_set_invbool, &opt_show_procs,
  1858. opt_hidden),
  1859. OPT_WITHOUT_ARG("--no-stratum",
  1860. opt_set_invbool, &want_stratum,
  1861. "Disable Stratum detection"),
  1862. OPT_WITHOUT_ARG("--no-submit-stale",
  1863. opt_set_invbool, &opt_submit_stale,
  1864. "Don't submit shares if they are detected as stale"),
  1865. #ifdef HAVE_OPENCL
  1866. OPT_WITHOUT_ARG("--no-opencl-binaries",
  1867. opt_set_invbool, &opt_opencl_binaries,
  1868. "Don't attempt to use or save OpenCL kernel binaries"),
  1869. #endif
  1870. OPT_WITHOUT_ARG("--no-unicode",
  1871. #ifdef USE_UNICODE
  1872. opt_set_invbool, &use_unicode,
  1873. "Don't use Unicode characters in TUI"
  1874. #else
  1875. set_null, &use_unicode,
  1876. opt_hidden
  1877. #endif
  1878. ),
  1879. OPT_WITH_ARG("--noncelog",
  1880. set_noncelog, NULL, NULL,
  1881. "Create log of all nonces found"),
  1882. OPT_WITH_ARG("--pass|-p",
  1883. set_pass, NULL, NULL,
  1884. "Password for bitcoin JSON-RPC server"),
  1885. OPT_WITHOUT_ARG("--per-device-stats",
  1886. opt_set_bool, &want_per_device_stats,
  1887. "Force verbose mode and output per-device statistics"),
  1888. OPT_WITH_ARG("--userpass|-O", // duplicate to ensure config loads it before pool-priority
  1889. set_userpass, NULL, NULL,
  1890. opt_hidden),
  1891. OPT_WITH_ARG("--pool-priority",
  1892. set_pool_priority, NULL, NULL,
  1893. "Priority for just the previous-defined pool"),
  1894. OPT_WITH_ARG("--pool-proxy|-x",
  1895. set_pool_proxy, NULL, NULL,
  1896. "Proxy URI to use for connecting to just the previous-defined pool"),
  1897. OPT_WITH_ARG("--force-rollntime", // NOTE: must be after --pass for config file ordering
  1898. set_pool_force_rollntime, NULL, NULL,
  1899. opt_hidden),
  1900. OPT_WITHOUT_ARG("--protocol-dump|-P",
  1901. opt_set_bool, &opt_protocol,
  1902. "Verbose dump of protocol-level activities"),
  1903. OPT_WITH_ARG("--queue|-Q",
  1904. set_int_0_to_9999, opt_show_intval, &opt_queue,
  1905. "Minimum number of work items to have queued (0+)"),
  1906. OPT_WITHOUT_ARG("--quiet|-q",
  1907. opt_set_bool, &opt_quiet,
  1908. "Disable logging output, display status and errors"),
  1909. OPT_WITHOUT_ARG("--quiet-work-updates|--quiet-work-update",
  1910. opt_set_bool, &opt_quiet_work_updates,
  1911. opt_hidden),
  1912. OPT_WITH_ARG("--quota|-U",
  1913. set_quota, NULL, NULL,
  1914. "quota;URL combination for server with load-balance strategy quotas"),
  1915. OPT_WITHOUT_ARG("--real-quiet",
  1916. opt_set_bool, &opt_realquiet,
  1917. "Disable all output"),
  1918. OPT_WITH_ARG("--request-diff",
  1919. set_request_diff, opt_show_floatval, &request_pdiff,
  1920. "Request a specific difficulty from pools"),
  1921. OPT_WITH_ARG("--retries",
  1922. opt_set_intval, opt_show_intval, &opt_retries,
  1923. "Number of times to retry failed submissions before giving up (-1 means never)"),
  1924. OPT_WITH_ARG("--retry-pause",
  1925. set_null, NULL, NULL,
  1926. opt_hidden),
  1927. OPT_WITH_ARG("--rotate",
  1928. set_rotate, opt_show_intval, &opt_rotate_period,
  1929. "Change multipool strategy from failover to regularly rotate at N minutes"),
  1930. OPT_WITHOUT_ARG("--round-robin",
  1931. set_rr, &pool_strategy,
  1932. "Change multipool strategy from failover to round robin on failure"),
  1933. OPT_WITH_ARG("--scan|-S",
  1934. add_serial, NULL, NULL,
  1935. "Configure how to scan for mining devices"),
  1936. OPT_WITH_ARG("--scan-device|--scan-serial|--devscan",
  1937. add_serial, NULL, NULL,
  1938. opt_hidden),
  1939. OPT_WITH_ARG("--scan-time|-s",
  1940. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  1941. "Upper bound on time spent scanning current work, in seconds"),
  1942. OPT_WITH_ARG("--scantime",
  1943. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  1944. opt_hidden),
  1945. OPT_WITH_ARG("--sched-start",
  1946. set_schedtime, NULL, &schedstart,
  1947. "Set a time of day in HH:MM to start mining (a once off without a stop time)"),
  1948. OPT_WITH_ARG("--sched-stop",
  1949. set_schedtime, NULL, &schedstop,
  1950. "Set a time of day in HH:MM to stop mining (will quit without a start time)"),
  1951. #ifdef USE_SCRYPT
  1952. OPT_WITHOUT_ARG("--scrypt",
  1953. opt_set_bool, &opt_scrypt,
  1954. "Use the scrypt algorithm for mining (non-bitcoin)"),
  1955. #endif
  1956. OPT_WITH_ARG("--set-device",
  1957. opt_string_elist_add, NULL, &opt_set_device_list,
  1958. "Set default parameters on devices; eg, NFY:osc6_bits=50"),
  1959. #if defined(USE_SCRYPT) && defined(HAVE_OPENCL)
  1960. OPT_WITH_ARG("--shaders",
  1961. set_shaders, NULL, NULL,
  1962. "GPU shaders per card for tuning scrypt, comma separated"),
  1963. #endif
  1964. #ifdef HAVE_PWD_H
  1965. OPT_WITH_ARG("--setuid",
  1966. opt_set_charp, NULL, &opt_setuid,
  1967. "Username of an unprivileged user to run as"),
  1968. #endif
  1969. OPT_WITH_ARG("--sharelog",
  1970. set_sharelog, NULL, NULL,
  1971. "Append share log to file"),
  1972. OPT_WITH_ARG("--shares",
  1973. opt_set_intval, NULL, &opt_shares,
  1974. "Quit after mining N shares (default: unlimited)"),
  1975. OPT_WITHOUT_ARG("--show-processors",
  1976. opt_set_bool, &opt_show_procs,
  1977. "Show per processor statistics in summary"),
  1978. OPT_WITHOUT_ARG("--show-procs",
  1979. opt_set_bool, &opt_show_procs,
  1980. opt_hidden),
  1981. OPT_WITH_ARG("--skip-security-checks",
  1982. set_int_0_to_9999, NULL, &opt_skip_checks,
  1983. "Skip security checks sometimes to save bandwidth; only check 1/<arg>th of the time (default: never skip)"),
  1984. OPT_WITH_ARG("--socks-proxy",
  1985. opt_set_charp, NULL, &opt_socks_proxy,
  1986. "Set socks proxy (host:port)"),
  1987. #ifdef USE_LIBEVENT
  1988. OPT_WITH_ARG("--stratum-port",
  1989. opt_set_intval, opt_show_intval, &stratumsrv_port,
  1990. "Port number to listen on for stratum miners (-1 means disabled)"),
  1991. #endif
  1992. OPT_WITHOUT_ARG("--submit-stale",
  1993. opt_set_bool, &opt_submit_stale,
  1994. opt_hidden),
  1995. OPT_WITH_ARG("--submit-threads",
  1996. opt_set_intval, opt_show_intval, &opt_submit_threads,
  1997. "Minimum number of concurrent share submissions (default: 64)"),
  1998. #ifdef HAVE_SYSLOG_H
  1999. OPT_WITHOUT_ARG("--syslog",
  2000. opt_set_bool, &use_syslog,
  2001. "Use system log for output messages (default: standard error)"),
  2002. #endif
  2003. OPT_WITH_ARG("--temp-cutoff",
  2004. set_temp_cutoff, NULL, &opt_cutofftemp,
  2005. opt_hidden),
  2006. OPT_WITH_ARG("--temp-hysteresis",
  2007. set_int_1_to_10, opt_show_intval, &opt_hysteresis,
  2008. "Set how much the temperature can fluctuate outside limits when automanaging speeds"),
  2009. #ifdef HAVE_ADL
  2010. OPT_WITH_ARG("--temp-overheat",
  2011. set_temp_overheat, opt_show_intval, &opt_overheattemp,
  2012. "Overheat temperature when automatically managing fan and GPU speeds, one value or comma separated list"),
  2013. #endif
  2014. OPT_WITH_ARG("--temp-target",
  2015. set_temp_target, NULL, NULL,
  2016. opt_hidden),
  2017. OPT_WITHOUT_ARG("--text-only|-T",
  2018. opt_set_invbool, &use_curses,
  2019. #ifdef HAVE_CURSES
  2020. "Disable ncurses formatted screen output"
  2021. #else
  2022. opt_hidden
  2023. #endif
  2024. ),
  2025. #if defined(USE_SCRYPT) && defined(HAVE_OPENCL)
  2026. OPT_WITH_ARG("--thread-concurrency",
  2027. set_thread_concurrency, NULL, NULL,
  2028. "Set GPU thread concurrency for scrypt mining, comma separated"),
  2029. #endif
  2030. #ifdef USE_UNICODE
  2031. OPT_WITHOUT_ARG("--unicode",
  2032. opt_set_bool, &use_unicode,
  2033. "Use Unicode characters in TUI"),
  2034. #endif
  2035. OPT_WITH_ARG("--url|-o",
  2036. set_url, NULL, NULL,
  2037. "URL for bitcoin JSON-RPC server"),
  2038. OPT_WITH_ARG("--user|-u",
  2039. set_user, NULL, NULL,
  2040. "Username for bitcoin JSON-RPC server"),
  2041. #ifdef HAVE_OPENCL
  2042. OPT_WITH_ARG("--vectors|-v",
  2043. set_vector, NULL, NULL,
  2044. "Override detected optimal vector (1, 2 or 4) - one value or comma separated list"),
  2045. #endif
  2046. OPT_WITHOUT_ARG("--verbose",
  2047. opt_set_bool, &opt_log_output,
  2048. "Log verbose output to stderr as well as status output"),
  2049. OPT_WITHOUT_ARG("--weighed-stats",
  2050. opt_set_bool, &opt_weighed_stats,
  2051. "Display statistics weighed to difficulty 1"),
  2052. #ifdef HAVE_OPENCL
  2053. OPT_WITH_ARG("--worksize|-w",
  2054. set_worksize, NULL, NULL,
  2055. "Override detected optimal worksize - one value or comma separated list"),
  2056. #endif
  2057. OPT_WITHOUT_ARG("--unittest",
  2058. opt_set_bool, &opt_unittest, opt_hidden),
  2059. OPT_WITH_ARG("--userpass|-O",
  2060. set_userpass, NULL, NULL,
  2061. "Username:Password pair for bitcoin JSON-RPC server"),
  2062. OPT_WITHOUT_ARG("--worktime",
  2063. opt_set_bool, &opt_worktime,
  2064. "Display extra work time debug information"),
  2065. OPT_WITH_ARG("--pools",
  2066. opt_set_bool, NULL, NULL, opt_hidden),
  2067. OPT_ENDTABLE
  2068. };
  2069. static char *load_config(const char *arg, void __maybe_unused *unused);
  2070. static int fileconf_load;
  2071. static char *parse_config(json_t *config, bool fileconf)
  2072. {
  2073. static char err_buf[200];
  2074. struct opt_table *opt;
  2075. json_t *val;
  2076. if (fileconf && !fileconf_load)
  2077. fileconf_load = 1;
  2078. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  2079. char *p, *name, *sp;
  2080. /* We don't handle subtables. */
  2081. assert(!(opt->type & OPT_SUBTABLE));
  2082. if (!opt->names)
  2083. continue;
  2084. /* Pull apart the option name(s). */
  2085. name = strdup(opt->names);
  2086. for (p = strtok_r(name, "|", &sp); p; p = strtok_r(NULL, "|", &sp)) {
  2087. char *err = "Invalid value";
  2088. /* Ignore short options. */
  2089. if (p[1] != '-')
  2090. continue;
  2091. val = json_object_get(config, p+2);
  2092. if (!val)
  2093. continue;
  2094. if (opt->type & OPT_HASARG) {
  2095. if (json_is_string(val)) {
  2096. err = opt->cb_arg(json_string_value(val),
  2097. opt->u.arg);
  2098. } else if (json_is_number(val)) {
  2099. char buf[256], *p, *q;
  2100. snprintf(buf, 256, "%f", json_number_value(val));
  2101. if ( (p = strchr(buf, '.')) ) {
  2102. // Trim /\.0*$/ to work properly with integer-only arguments
  2103. q = p;
  2104. while (*(++q) == '0') {}
  2105. if (*q == '\0')
  2106. *p = '\0';
  2107. }
  2108. err = opt->cb_arg(buf, opt->u.arg);
  2109. } else if (json_is_array(val)) {
  2110. int n, size = json_array_size(val);
  2111. err = NULL;
  2112. for (n = 0; n < size && !err; n++) {
  2113. if (json_is_string(json_array_get(val, n)))
  2114. err = opt->cb_arg(json_string_value(json_array_get(val, n)), opt->u.arg);
  2115. else if (json_is_object(json_array_get(val, n)))
  2116. err = parse_config(json_array_get(val, n), false);
  2117. }
  2118. }
  2119. } else if (opt->type & OPT_NOARG) {
  2120. if (json_is_true(val))
  2121. err = opt->cb(opt->u.arg);
  2122. else if (json_is_boolean(val)) {
  2123. if (opt->cb == (void*)opt_set_bool)
  2124. err = opt_set_invbool(opt->u.arg);
  2125. else if (opt->cb == (void*)opt_set_invbool)
  2126. err = opt_set_bool(opt->u.arg);
  2127. }
  2128. }
  2129. if (err) {
  2130. /* Allow invalid values to be in configuration
  2131. * file, just skipping over them provided the
  2132. * JSON is still valid after that. */
  2133. if (fileconf) {
  2134. applog(LOG_ERR, "Invalid config option %s: %s", p, err);
  2135. fileconf_load = -1;
  2136. } else {
  2137. snprintf(err_buf, sizeof(err_buf), "Parsing JSON option %s: %s",
  2138. p, err);
  2139. return err_buf;
  2140. }
  2141. }
  2142. }
  2143. free(name);
  2144. }
  2145. val = json_object_get(config, JSON_INCLUDE_CONF);
  2146. if (val && json_is_string(val))
  2147. return load_config(json_string_value(val), NULL);
  2148. return NULL;
  2149. }
  2150. char *cnfbuf = NULL;
  2151. static char *load_config(const char *arg, void __maybe_unused *unused)
  2152. {
  2153. json_error_t err;
  2154. json_t *config;
  2155. char *json_error;
  2156. size_t siz;
  2157. if (!cnfbuf)
  2158. cnfbuf = strdup(arg);
  2159. if (++include_count > JSON_MAX_DEPTH)
  2160. return JSON_MAX_DEPTH_ERR;
  2161. #if JANSSON_MAJOR_VERSION > 1
  2162. config = json_load_file(arg, 0, &err);
  2163. #else
  2164. config = json_load_file(arg, &err);
  2165. #endif
  2166. if (!json_is_object(config)) {
  2167. siz = JSON_LOAD_ERROR_LEN + strlen(arg) + strlen(err.text);
  2168. json_error = malloc(siz);
  2169. if (!json_error)
  2170. quit(1, "Malloc failure in json error");
  2171. snprintf(json_error, siz, JSON_LOAD_ERROR, arg, err.text);
  2172. return json_error;
  2173. }
  2174. config_loaded = true;
  2175. /* Parse the config now, so we can override it. That can keep pointers
  2176. * so don't free config object. */
  2177. return parse_config(config, true);
  2178. }
  2179. static void load_default_config(void)
  2180. {
  2181. cnfbuf = malloc(PATH_MAX);
  2182. #if defined(unix)
  2183. if (getenv("HOME") && *getenv("HOME")) {
  2184. strcpy(cnfbuf, getenv("HOME"));
  2185. strcat(cnfbuf, "/");
  2186. } else
  2187. strcpy(cnfbuf, "");
  2188. char *dirp = cnfbuf + strlen(cnfbuf);
  2189. strcpy(dirp, ".bfgminer/");
  2190. strcat(dirp, def_conf);
  2191. if (access(cnfbuf, R_OK))
  2192. // No BFGMiner config, try Cgminer's...
  2193. strcpy(dirp, ".cgminer/cgminer.conf");
  2194. #else
  2195. strcpy(cnfbuf, "");
  2196. strcat(cnfbuf, def_conf);
  2197. #endif
  2198. if (!access(cnfbuf, R_OK))
  2199. load_config(cnfbuf, NULL);
  2200. else {
  2201. free(cnfbuf);
  2202. cnfbuf = NULL;
  2203. }
  2204. }
  2205. extern const char *opt_argv0;
  2206. static char *opt_verusage_and_exit(const char *extra)
  2207. {
  2208. puts(packagename);
  2209. printf(" Drivers:%s\n", BFG_DRIVERLIST);
  2210. printf(" Algoritms:%s\n", BFG_ALGOLIST);
  2211. printf(" Options:%s\n", BFG_OPTLIST);
  2212. printf("%s", opt_usage(opt_argv0, extra));
  2213. fflush(stdout);
  2214. exit(0);
  2215. }
  2216. /* These options are available from commandline only */
  2217. static struct opt_table opt_cmdline_table[] = {
  2218. OPT_WITH_ARG("--config|-c",
  2219. load_config, NULL, NULL,
  2220. "Load a JSON-format configuration file\n"
  2221. "See example.conf for an example configuration."),
  2222. OPT_WITHOUT_ARG("--help|-h",
  2223. opt_verusage_and_exit, NULL,
  2224. "Print this message"),
  2225. #ifdef HAVE_OPENCL
  2226. OPT_WITHOUT_ARG("--ndevs|-n",
  2227. print_ndevs_and_exit, &nDevs,
  2228. opt_hidden),
  2229. #endif
  2230. OPT_WITHOUT_ARG("--version|-V",
  2231. opt_version_and_exit, packagename,
  2232. "Display version and exit"),
  2233. OPT_ENDTABLE
  2234. };
  2235. static bool jobj_binary(const json_t *obj, const char *key,
  2236. void *buf, size_t buflen, bool required)
  2237. {
  2238. const char *hexstr;
  2239. json_t *tmp;
  2240. tmp = json_object_get(obj, key);
  2241. if (unlikely(!tmp)) {
  2242. if (unlikely(required))
  2243. applog(LOG_ERR, "JSON key '%s' not found", key);
  2244. return false;
  2245. }
  2246. hexstr = json_string_value(tmp);
  2247. if (unlikely(!hexstr)) {
  2248. applog(LOG_ERR, "JSON key '%s' is not a string", key);
  2249. return false;
  2250. }
  2251. if (!hex2bin(buf, hexstr, buflen))
  2252. return false;
  2253. return true;
  2254. }
  2255. static void calc_midstate(struct work *work)
  2256. {
  2257. union {
  2258. unsigned char c[64];
  2259. uint32_t i[16];
  2260. } data;
  2261. swap32yes(&data.i[0], work->data, 16);
  2262. sha256_ctx ctx;
  2263. sha256_init(&ctx);
  2264. sha256_update(&ctx, data.c, 64);
  2265. memcpy(work->midstate, ctx.h, sizeof(work->midstate));
  2266. swap32tole(work->midstate, work->midstate, 8);
  2267. }
  2268. static struct work *make_work(void)
  2269. {
  2270. struct work *work = calloc(1, sizeof(struct work));
  2271. if (unlikely(!work))
  2272. quit(1, "Failed to calloc work in make_work");
  2273. cg_wlock(&control_lock);
  2274. work->id = total_work++;
  2275. cg_wunlock(&control_lock);
  2276. return work;
  2277. }
  2278. /* This is the central place all work that is about to be retired should be
  2279. * cleaned to remove any dynamically allocated arrays within the struct */
  2280. void clean_work(struct work *work)
  2281. {
  2282. free(work->job_id);
  2283. bytes_free(&work->nonce2);
  2284. free(work->nonce1);
  2285. if (work->tmpl) {
  2286. struct pool *pool = work->pool;
  2287. mutex_lock(&pool->pool_lock);
  2288. bool free_tmpl = !--*work->tmpl_refcount;
  2289. mutex_unlock(&pool->pool_lock);
  2290. if (free_tmpl) {
  2291. blktmpl_free(work->tmpl);
  2292. free(work->tmpl_refcount);
  2293. }
  2294. }
  2295. memset(work, 0, sizeof(struct work));
  2296. }
  2297. /* All dynamically allocated work structs should be freed here to not leak any
  2298. * ram from arrays allocated within the work struct */
  2299. void free_work(struct work *work)
  2300. {
  2301. clean_work(work);
  2302. free(work);
  2303. }
  2304. 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";
  2305. // Must only be called with ch_lock held!
  2306. static
  2307. void __update_block_title(const unsigned char *hash_swap)
  2308. {
  2309. if (hash_swap) {
  2310. char tmp[17];
  2311. // Only provided when the block has actually changed
  2312. free(current_hash);
  2313. current_hash = malloc(3 /* ... */ + 16 /* block hash segment */ + 1);
  2314. bin2hex(tmp, &hash_swap[24], 8);
  2315. memset(current_hash, '.', 3);
  2316. memcpy(&current_hash[3], tmp, 17);
  2317. known_blkheight_current = false;
  2318. } else if (likely(known_blkheight_current)) {
  2319. return;
  2320. }
  2321. if (current_block_id == known_blkheight_blkid) {
  2322. // FIXME: The block number will overflow this sometime around AD 2025-2027
  2323. if (known_blkheight < 1000000) {
  2324. memmove(&current_hash[3], &current_hash[11], 8);
  2325. snprintf(&current_hash[11], 20-11, " #%6u", known_blkheight);
  2326. }
  2327. known_blkheight_current = true;
  2328. }
  2329. }
  2330. static
  2331. void have_block_height(uint32_t block_id, uint32_t blkheight)
  2332. {
  2333. if (known_blkheight == blkheight)
  2334. return;
  2335. applog(LOG_DEBUG, "Learned that block id %08" PRIx32 " is height %" PRIu32, (uint32_t)be32toh(block_id), blkheight);
  2336. cg_wlock(&ch_lock);
  2337. known_blkheight = blkheight;
  2338. known_blkheight_blkid = block_id;
  2339. block_subsidy = 5000000000LL >> (blkheight / 210000);
  2340. if (block_id == current_block_id)
  2341. __update_block_title(NULL);
  2342. cg_wunlock(&ch_lock);
  2343. }
  2344. static
  2345. void pool_set_opaque(struct pool *pool, bool opaque)
  2346. {
  2347. if (pool->swork.opaque == opaque)
  2348. return;
  2349. pool->swork.opaque = opaque;
  2350. if (opaque)
  2351. applog(LOG_WARNING, "Pool %u is hiding block contents from us",
  2352. pool->pool_no);
  2353. else
  2354. applog(LOG_NOTICE, "Pool %u now providing block contents to us",
  2355. pool->pool_no);
  2356. }
  2357. static bool work_decode(struct pool *pool, struct work *work, json_t *val)
  2358. {
  2359. json_t *res_val = json_object_get(val, "result");
  2360. json_t *tmp_val;
  2361. bool ret = false;
  2362. if (unlikely(detect_algo == 1)) {
  2363. json_t *tmp = json_object_get(res_val, "algorithm");
  2364. const char *v = tmp ? json_string_value(tmp) : "";
  2365. if (strncasecmp(v, "scrypt", 6))
  2366. detect_algo = 2;
  2367. }
  2368. if (work->tmpl) {
  2369. struct timeval tv_now;
  2370. cgtime(&tv_now);
  2371. const char *err = blktmpl_add_jansson(work->tmpl, res_val, tv_now.tv_sec);
  2372. if (err) {
  2373. applog(LOG_ERR, "blktmpl error: %s", err);
  2374. return false;
  2375. }
  2376. work->rolltime = blkmk_time_left(work->tmpl, tv_now.tv_sec);
  2377. #if BLKMAKER_VERSION > 1
  2378. if (opt_coinbase_script.sz)
  2379. {
  2380. bool newcb;
  2381. #if BLKMAKER_VERSION > 2
  2382. blkmk_init_generation2(work->tmpl, opt_coinbase_script.data, opt_coinbase_script.sz, &newcb);
  2383. #else
  2384. newcb = !work->tmpl->cbtxn;
  2385. blkmk_init_generation(work->tmpl, opt_coinbase_script.data, opt_coinbase_script.sz);
  2386. #endif
  2387. if (newcb)
  2388. {
  2389. ssize_t ae = blkmk_append_coinbase_safe(work->tmpl, &template_nonce, sizeof(template_nonce));
  2390. if (ae < (ssize_t)sizeof(template_nonce))
  2391. 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);
  2392. ++template_nonce;
  2393. }
  2394. }
  2395. #endif
  2396. #if BLKMAKER_VERSION > 0
  2397. {
  2398. ssize_t ae = blkmk_append_coinbase_safe(work->tmpl, opt_coinbase_sig, 101);
  2399. static bool appenderr = false;
  2400. if (ae <= 0) {
  2401. if (opt_coinbase_sig) {
  2402. applog((appenderr ? LOG_DEBUG : LOG_WARNING), "Cannot append coinbase signature at all on pool %u (%"PRId64")", pool->pool_no, (int64_t)ae);
  2403. appenderr = true;
  2404. }
  2405. } else if (ae >= 3 || opt_coinbase_sig) {
  2406. const char *cbappend = opt_coinbase_sig;
  2407. const char full[] = PACKAGE " " VERSION;
  2408. if (!cbappend) {
  2409. if ((size_t)ae >= sizeof(full) - 1)
  2410. cbappend = full;
  2411. else if ((size_t)ae >= sizeof(PACKAGE) - 1)
  2412. cbappend = PACKAGE;
  2413. else
  2414. cbappend = "BFG";
  2415. }
  2416. size_t cbappendsz = strlen(cbappend);
  2417. static bool truncatewarning = false;
  2418. if (cbappendsz <= (size_t)ae) {
  2419. if (cbappendsz < (size_t)ae)
  2420. // If we have space, include the trailing \0
  2421. ++cbappendsz;
  2422. ae = cbappendsz;
  2423. truncatewarning = false;
  2424. } else {
  2425. char *tmp = malloc(ae + 1);
  2426. memcpy(tmp, opt_coinbase_sig, ae);
  2427. tmp[ae] = '\0';
  2428. applog((truncatewarning ? LOG_DEBUG : LOG_WARNING),
  2429. "Pool %u truncating appended coinbase signature at %"PRId64" bytes: %s(%s)",
  2430. pool->pool_no, (int64_t)ae, tmp, &opt_coinbase_sig[ae]);
  2431. free(tmp);
  2432. truncatewarning = true;
  2433. }
  2434. ae = blkmk_append_coinbase_safe(work->tmpl, cbappend, ae);
  2435. if (ae <= 0) {
  2436. applog((appenderr ? LOG_DEBUG : LOG_WARNING), "Error appending coinbase signature (%"PRId64")", (int64_t)ae);
  2437. appenderr = true;
  2438. } else
  2439. appenderr = false;
  2440. }
  2441. }
  2442. #endif
  2443. if (blkmk_get_data(work->tmpl, work->data, 80, tv_now.tv_sec, NULL, &work->dataid) < 76)
  2444. return false;
  2445. swap32yes(work->data, work->data, 80 / 4);
  2446. memcpy(&work->data[80], workpadding_bin, 48);
  2447. const struct blktmpl_longpoll_req *lp;
  2448. if ((lp = blktmpl_get_longpoll(work->tmpl)) && ((!pool->lp_id) || strcmp(lp->id, pool->lp_id))) {
  2449. free(pool->lp_id);
  2450. pool->lp_id = strdup(lp->id);
  2451. #if 0 /* This just doesn't work :( */
  2452. curl_socket_t sock = pool->lp_socket;
  2453. if (sock != CURL_SOCKET_BAD) {
  2454. pool->lp_socket = CURL_SOCKET_BAD;
  2455. applog(LOG_WARNING, "Pool %u long poll request hanging, reconnecting", pool->pool_no);
  2456. shutdown(sock, SHUT_RDWR);
  2457. }
  2458. #endif
  2459. }
  2460. }
  2461. else
  2462. if (unlikely(!jobj_binary(res_val, "data", work->data, sizeof(work->data), true))) {
  2463. applog(LOG_ERR, "JSON inval data");
  2464. return false;
  2465. }
  2466. if (!jobj_binary(res_val, "midstate", work->midstate, sizeof(work->midstate), false)) {
  2467. // Calculate it ourselves
  2468. applog(LOG_DEBUG, "Calculating midstate locally");
  2469. calc_midstate(work);
  2470. }
  2471. if (unlikely(!jobj_binary(res_val, "target", work->target, sizeof(work->target), true))) {
  2472. applog(LOG_ERR, "JSON inval target");
  2473. return false;
  2474. }
  2475. if (work->tmpl) {
  2476. for (size_t i = 0; i < sizeof(work->target) / 2; ++i)
  2477. {
  2478. int p = (sizeof(work->target) - 1) - i;
  2479. unsigned char c = work->target[i];
  2480. work->target[i] = work->target[p];
  2481. work->target[p] = c;
  2482. }
  2483. }
  2484. if ( (tmp_val = json_object_get(res_val, "height")) ) {
  2485. uint32_t blkheight = json_number_value(tmp_val);
  2486. uint32_t block_id = ((uint32_t*)work->data)[1];
  2487. have_block_height(block_id, blkheight);
  2488. }
  2489. memset(work->hash, 0, sizeof(work->hash));
  2490. cgtime(&work->tv_staged);
  2491. pool_set_opaque(pool, !work->tmpl);
  2492. ret = true;
  2493. return ret;
  2494. }
  2495. /* Returns whether the pool supports local work generation or not. */
  2496. static bool pool_localgen(struct pool *pool)
  2497. {
  2498. return (pool->last_work_copy || pool->has_stratum);
  2499. }
  2500. int dev_from_id(int thr_id)
  2501. {
  2502. struct cgpu_info *cgpu = get_thr_cgpu(thr_id);
  2503. return cgpu->device_id;
  2504. }
  2505. /* Create an exponentially decaying average over the opt_log_interval */
  2506. void decay_time(double *f, double fadd, double fsecs)
  2507. {
  2508. double ftotal, fprop;
  2509. fprop = 1.0 - 1 / (exp(fsecs / (double)opt_log_interval));
  2510. ftotal = 1.0 + fprop;
  2511. *f += (fadd * fprop);
  2512. *f /= ftotal;
  2513. }
  2514. static int __total_staged(void)
  2515. {
  2516. return HASH_COUNT(staged_work);
  2517. }
  2518. static int total_staged(void)
  2519. {
  2520. int ret;
  2521. mutex_lock(stgd_lock);
  2522. ret = __total_staged();
  2523. mutex_unlock(stgd_lock);
  2524. return ret;
  2525. }
  2526. #ifdef HAVE_CURSES
  2527. WINDOW *mainwin, *statuswin, *logwin;
  2528. #endif
  2529. double total_secs = 1.0;
  2530. static char statusline[256];
  2531. /* logstart is where the log window should start */
  2532. static int devcursor, logstart, logcursor;
  2533. #ifdef HAVE_CURSES
  2534. /* statusy is where the status window goes up to in cases where it won't fit at startup */
  2535. static int statusy;
  2536. static int devsummaryYOffset;
  2537. static int total_lines;
  2538. #endif
  2539. #ifdef HAVE_OPENCL
  2540. struct cgpu_info gpus[MAX_GPUDEVICES]; /* Maximum number apparently possible */
  2541. #endif
  2542. struct cgpu_info *cpus;
  2543. bool _bfg_console_cancel_disabled;
  2544. int _bfg_console_prev_cancelstate;
  2545. #ifdef HAVE_CURSES
  2546. #define lock_curses() bfg_console_lock()
  2547. #define unlock_curses() bfg_console_unlock()
  2548. static bool curses_active_locked(void)
  2549. {
  2550. bool ret;
  2551. lock_curses();
  2552. ret = curses_active;
  2553. if (!ret)
  2554. unlock_curses();
  2555. return ret;
  2556. }
  2557. // Cancellable getch
  2558. int my_cancellable_getch(void)
  2559. {
  2560. // This only works because the macro only hits direct getch() calls
  2561. typedef int (*real_getch_t)(void);
  2562. const real_getch_t real_getch = __real_getch;
  2563. int type, rv;
  2564. bool sct;
  2565. sct = !pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &type);
  2566. rv = real_getch();
  2567. if (sct)
  2568. pthread_setcanceltype(type, &type);
  2569. return rv;
  2570. }
  2571. #ifdef PDCURSES
  2572. static
  2573. int bfg_wresize(WINDOW *win, int lines, int columns)
  2574. {
  2575. int rv = wresize(win, lines, columns);
  2576. int x, y;
  2577. getyx(win, y, x);
  2578. if (unlikely(y >= lines || x >= columns))
  2579. {
  2580. if (y >= lines)
  2581. y = lines - 1;
  2582. if (x >= columns)
  2583. x = columns - 1;
  2584. wmove(win, y, x);
  2585. }
  2586. return rv;
  2587. }
  2588. #else
  2589. # define bfg_wresize wresize
  2590. #endif
  2591. #endif
  2592. void tailsprintf(char *buf, size_t bufsz, const char *fmt, ...)
  2593. {
  2594. va_list ap;
  2595. size_t presz = strlen(buf);
  2596. va_start(ap, fmt);
  2597. vsnprintf(&buf[presz], bufsz - presz, fmt, ap);
  2598. va_end(ap);
  2599. }
  2600. double stats_elapsed(struct cgminer_stats *stats)
  2601. {
  2602. struct timeval now;
  2603. double elapsed;
  2604. if (stats->start_tv.tv_sec == 0)
  2605. elapsed = total_secs;
  2606. else {
  2607. cgtime(&now);
  2608. elapsed = tdiff(&now, &stats->start_tv);
  2609. }
  2610. if (elapsed < 1.0)
  2611. elapsed = 1.0;
  2612. return elapsed;
  2613. }
  2614. bool drv_ready(struct cgpu_info *cgpu)
  2615. {
  2616. switch (cgpu->status) {
  2617. case LIFE_INIT:
  2618. case LIFE_DEAD2:
  2619. return false;
  2620. default:
  2621. return true;
  2622. }
  2623. }
  2624. double cgpu_utility(struct cgpu_info *cgpu)
  2625. {
  2626. double dev_runtime = cgpu_runtime(cgpu);
  2627. return cgpu->utility = cgpu->accepted / dev_runtime * 60;
  2628. }
  2629. /* Convert a uint64_t value into a truncated string for displaying with its
  2630. * associated suitable for Mega, Giga etc. Buf array needs to be long enough */
  2631. static void suffix_string(uint64_t val, char *buf, size_t bufsiz, int sigdigits)
  2632. {
  2633. const double dkilo = 1000.0;
  2634. const uint64_t kilo = 1000ull;
  2635. const uint64_t mega = 1000000ull;
  2636. const uint64_t giga = 1000000000ull;
  2637. const uint64_t tera = 1000000000000ull;
  2638. const uint64_t peta = 1000000000000000ull;
  2639. const uint64_t exa = 1000000000000000000ull;
  2640. char suffix[2] = "";
  2641. bool decimal = true;
  2642. double dval;
  2643. if (val >= exa) {
  2644. val /= peta;
  2645. dval = (double)val / dkilo;
  2646. strcpy(suffix, "E");
  2647. } else if (val >= peta) {
  2648. val /= tera;
  2649. dval = (double)val / dkilo;
  2650. strcpy(suffix, "P");
  2651. } else if (val >= tera) {
  2652. val /= giga;
  2653. dval = (double)val / dkilo;
  2654. strcpy(suffix, "T");
  2655. } else if (val >= giga) {
  2656. val /= mega;
  2657. dval = (double)val / dkilo;
  2658. strcpy(suffix, "G");
  2659. } else if (val >= mega) {
  2660. val /= kilo;
  2661. dval = (double)val / dkilo;
  2662. strcpy(suffix, "M");
  2663. } else if (val >= kilo) {
  2664. dval = (double)val / dkilo;
  2665. strcpy(suffix, "k");
  2666. } else {
  2667. dval = val;
  2668. decimal = false;
  2669. }
  2670. if (!sigdigits) {
  2671. if (decimal)
  2672. snprintf(buf, bufsiz, "%.3g%s", dval, suffix);
  2673. else
  2674. snprintf(buf, bufsiz, "%d%s", (unsigned int)dval, suffix);
  2675. } else {
  2676. /* Always show sigdigits + 1, padded on right with zeroes
  2677. * followed by suffix */
  2678. int ndigits = sigdigits - 1 - (dval > 0.0 ? floor(log10(dval)) : 0);
  2679. snprintf(buf, bufsiz, "%*.*f%s", sigdigits + 1, ndigits, dval, suffix);
  2680. }
  2681. }
  2682. static float
  2683. utility_to_hashrate(double utility)
  2684. {
  2685. return utility * 0x4444444;
  2686. }
  2687. static const char*_unitchar = "pn\xb5m kMGTPEZY?";
  2688. static const int _unitbase = 4;
  2689. static
  2690. void pick_unit(float hashrate, unsigned char *unit)
  2691. {
  2692. unsigned char i;
  2693. if (hashrate == 0)
  2694. {
  2695. if (*unit < _unitbase)
  2696. *unit = _unitbase;
  2697. return;
  2698. }
  2699. hashrate *= 1e12;
  2700. for (i = 0; i < *unit; ++i)
  2701. hashrate /= 1e3;
  2702. // 1000 but with tolerance for floating-point rounding, avoid showing "1000.0"
  2703. while (hashrate >= 999.95)
  2704. {
  2705. hashrate /= 1e3;
  2706. if (likely(_unitchar[*unit] != '?'))
  2707. ++*unit;
  2708. }
  2709. }
  2710. #define hashrate_pick_unit(hashrate, unit) pick_unit(hashrate, unit)
  2711. enum h2bs_fmt {
  2712. H2B_NOUNIT, // "xxx.x"
  2713. H2B_SHORT, // "xxx.xMH/s"
  2714. H2B_SPACED, // "xxx.x MH/s"
  2715. };
  2716. static const size_t h2bs_fmt_size[] = {6, 10, 11};
  2717. enum bfu_floatprec {
  2718. FUP_INTEGER,
  2719. FUP_HASHES,
  2720. FUP_BTC,
  2721. };
  2722. static
  2723. int format_unit3(char *buf, size_t sz, enum bfu_floatprec fprec, const char *measurement, enum h2bs_fmt fmt, float hashrate, signed char unitin)
  2724. {
  2725. char *s = buf;
  2726. unsigned char prec, i, unit;
  2727. int rv = 0;
  2728. if (unitin == -1)
  2729. {
  2730. unit = 0;
  2731. hashrate_pick_unit(hashrate, &unit);
  2732. }
  2733. else
  2734. unit = unitin;
  2735. hashrate *= 1e12;
  2736. for (i = 0; i < unit; ++i)
  2737. hashrate /= 1000;
  2738. switch (fprec)
  2739. {
  2740. case FUP_HASHES:
  2741. // 100 but with tolerance for floating-point rounding, max "99.99" then "100.0"
  2742. if (hashrate >= 99.995 || unit < 6)
  2743. prec = 1;
  2744. else
  2745. prec = 2;
  2746. _SNP("%5.*f", prec, hashrate);
  2747. break;
  2748. case FUP_INTEGER:
  2749. _SNP("%3d", (int)hashrate);
  2750. break;
  2751. case FUP_BTC:
  2752. if (hashrate >= 99.995)
  2753. prec = 0;
  2754. else
  2755. prec = 2;
  2756. _SNP("%5.*f", prec, hashrate);
  2757. }
  2758. switch (fmt) {
  2759. case H2B_SPACED:
  2760. _SNP(" ");
  2761. case H2B_SHORT:
  2762. _SNP("%c%s", _unitchar[unit], measurement);
  2763. default:
  2764. break;
  2765. }
  2766. return rv;
  2767. }
  2768. #define format_unit2(buf, sz, floatprec, measurement, fmt, n, unit) \
  2769. format_unit3(buf, sz, floatprec ? FUP_HASHES : FUP_INTEGER, measurement, fmt, n, unit)
  2770. static
  2771. 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)
  2772. {
  2773. unsigned char unit = 0;
  2774. bool allzero = true;
  2775. int i;
  2776. size_t delimsz = 0;
  2777. char *buf = buflist[0];
  2778. size_t bufsz = bufszlist[0];
  2779. size_t itemwidth = (floatprec ? 5 : 3);
  2780. if (!isarray)
  2781. delimsz = strlen(delim);
  2782. for (i = 0; i < count; ++i)
  2783. if (numbers[i] != 0)
  2784. {
  2785. pick_unit(numbers[i], &unit);
  2786. allzero = false;
  2787. }
  2788. if (allzero)
  2789. unit = _unitbase;
  2790. --count;
  2791. for (i = 0; i < count; ++i)
  2792. {
  2793. format_unit2(buf, bufsz, floatprec, NULL, H2B_NOUNIT, numbers[i], unit);
  2794. if (isarray)
  2795. {
  2796. buf = buflist[i + 1];
  2797. bufsz = bufszlist[i + 1];
  2798. }
  2799. else
  2800. {
  2801. buf += itemwidth;
  2802. bufsz -= itemwidth;
  2803. if (delimsz > bufsz)
  2804. delimsz = bufsz;
  2805. memcpy(buf, delim, delimsz);
  2806. buf += delimsz;
  2807. bufsz -= delimsz;
  2808. }
  2809. }
  2810. // Last entry has the unit
  2811. format_unit2(buf, bufsz, floatprec, measurement, fmt, numbers[count], unit);
  2812. return buflist[0];
  2813. }
  2814. #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)
  2815. #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)
  2816. static
  2817. int percentf3(char * const buf, size_t sz, double p, const double t)
  2818. {
  2819. char *s = buf;
  2820. int rv = 0;
  2821. if (!p)
  2822. _SNP("none");
  2823. else
  2824. if (t <= p)
  2825. _SNP("100%%");
  2826. else
  2827. {
  2828. p /= t;
  2829. if (p < 0.00995) // 0.01 but with tolerance for floating-point rounding, max ".99%"
  2830. _SNP(".%02.0f%%", p * 10000); // ".01%"
  2831. else
  2832. if (p < 0.0995) // 0.1 but with tolerance for floating-point rounding, max "9.9%"
  2833. _SNP("%.1f%%", p * 100); // "9.1%"
  2834. else
  2835. _SNP("%3.0f%%", p * 100); // " 99%"
  2836. }
  2837. return rv;
  2838. }
  2839. #define percentf4(buf, bufsz, p, t) percentf3(buf, bufsz, p, p + t)
  2840. static
  2841. void test_decimal_width()
  2842. {
  2843. // The pipe character at end of each line should perfectly line up
  2844. char printbuf[512];
  2845. char testbuf1[64];
  2846. char testbuf2[64];
  2847. char testbuf3[64];
  2848. char testbuf4[64];
  2849. double testn;
  2850. int width;
  2851. int saved;
  2852. // Hotspots around 0.1 and 0.01
  2853. saved = -1;
  2854. for (testn = 0.09; testn <= 0.11; testn += 0.000001) {
  2855. percentf3(testbuf1, sizeof(testbuf1), testn, 1.0);
  2856. percentf3(testbuf2, sizeof(testbuf2), testn, 10.0);
  2857. width = snprintf(printbuf, sizeof(printbuf), "%10g %s %s |", testn, testbuf1, testbuf2);
  2858. if (unlikely((saved != -1) && (width != saved))) {
  2859. applog(LOG_ERR, "Test width mismatch in percentf3! %d not %d at %10g", width, saved, testn);
  2860. applog(LOG_ERR, "%s", printbuf);
  2861. }
  2862. saved = width;
  2863. }
  2864. // Hotspot around 100 (but test this in several units because format_unit2 also has unit<2 check)
  2865. saved = -1;
  2866. for (testn = 99.0; testn <= 101.0; testn += 0.0001) {
  2867. format_unit2(testbuf1, sizeof(testbuf1), true, "x", H2B_SHORT, testn , -1);
  2868. format_unit2(testbuf2, sizeof(testbuf2), true, "x", H2B_SHORT, testn * 1e3, -1);
  2869. format_unit2(testbuf3, sizeof(testbuf3), true, "x", H2B_SHORT, testn * 1e6, -1);
  2870. width = snprintf(printbuf, sizeof(printbuf), "%10g %s %s %s |", testn, testbuf1, testbuf2, testbuf3);
  2871. if (unlikely((saved != -1) && (width != saved))) {
  2872. applog(LOG_ERR, "Test width mismatch in format_unit2! %d not %d at %10g", width, saved, testn);
  2873. applog(LOG_ERR, "%s", printbuf);
  2874. }
  2875. saved = width;
  2876. }
  2877. // Hotspot around unit transition boundary in pick_unit
  2878. saved = -1;
  2879. for (testn = 999.0; testn <= 1001.0; testn += 0.0001) {
  2880. format_unit2(testbuf1, sizeof(testbuf1), true, "x", H2B_SHORT, testn , -1);
  2881. format_unit2(testbuf2, sizeof(testbuf2), true, "x", H2B_SHORT, testn * 1e3, -1);
  2882. format_unit2(testbuf3, sizeof(testbuf3), true, "x", H2B_SHORT, testn * 1e6, -1);
  2883. format_unit2(testbuf4, sizeof(testbuf4), true, "x", H2B_SHORT, testn * 1e9, -1);
  2884. width = snprintf(printbuf, sizeof(printbuf), "%10g %s %s %s %s |", testn, testbuf1, testbuf2, testbuf3, testbuf4);
  2885. if (unlikely((saved != -1) && (width != saved))) {
  2886. applog(LOG_ERR, "Test width mismatch in pick_unit! %d not %d at %10g", width, saved, testn);
  2887. applog(LOG_ERR, "%s", printbuf);
  2888. }
  2889. saved = width;
  2890. }
  2891. }
  2892. #ifdef HAVE_CURSES
  2893. static void adj_width(int var, int *length);
  2894. #endif
  2895. #ifdef HAVE_CURSES
  2896. static int awidth = 1, rwidth = 1, swidth = 1, hwwidth = 1;
  2897. static
  2898. 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)
  2899. {
  2900. char rejpcbuf[6];
  2901. char bnbuf[6];
  2902. adj_width(accepted, &awidth);
  2903. adj_width(rejected, &rwidth);
  2904. adj_width(stale, &swidth);
  2905. adj_width(hwerrs, &hwwidth);
  2906. percentf4(rejpcbuf, sizeof(rejpcbuf), wnotaccepted, waccepted);
  2907. percentf3(bnbuf, sizeof(bnbuf), bad_diff1, allnonces);
  2908. tailsprintf(buf, bufsz, "%s/%s/%s | A:%*d R:%*d+%*d(%s) HW:%*d/%s",
  2909. cHr, aHr, uHr,
  2910. awidth, accepted,
  2911. rwidth, rejected,
  2912. swidth, stale,
  2913. rejpcbuf,
  2914. hwwidth, hwerrs,
  2915. bnbuf
  2916. );
  2917. }
  2918. #endif
  2919. static inline
  2920. void temperature_column(char *buf, size_t bufsz, bool maybe_unicode, const float * const temp)
  2921. {
  2922. if (!(use_unicode && have_unicode_degrees))
  2923. maybe_unicode = false;
  2924. if (temp && *temp > 0.)
  2925. if (maybe_unicode)
  2926. snprintf(buf, bufsz, "%4.1f"U8_DEGREE"C", *temp);
  2927. else
  2928. snprintf(buf, bufsz, "%4.1fC", *temp);
  2929. else
  2930. {
  2931. if (temp)
  2932. snprintf(buf, bufsz, " ");
  2933. if (maybe_unicode)
  2934. tailsprintf(buf, bufsz, " ");
  2935. }
  2936. tailsprintf(buf, bufsz, " | ");
  2937. }
  2938. void get_statline3(char *buf, size_t bufsz, struct cgpu_info *cgpu, bool for_curses, bool opt_show_procs)
  2939. {
  2940. #ifndef HAVE_CURSES
  2941. assert(for_curses == false);
  2942. #endif
  2943. struct device_drv *drv = cgpu->drv;
  2944. enum h2bs_fmt hashrate_style = for_curses ? H2B_SHORT : H2B_SPACED;
  2945. char cHr[h2bs_fmt_size[H2B_NOUNIT]], aHr[h2bs_fmt_size[H2B_NOUNIT]], uHr[h2bs_fmt_size[hashrate_style]];
  2946. char rejpcbuf[6];
  2947. char bnbuf[6];
  2948. double dev_runtime;
  2949. if (!opt_show_procs)
  2950. cgpu = cgpu->device;
  2951. dev_runtime = cgpu_runtime(cgpu);
  2952. double rolling, mhashes;
  2953. int accepted, rejected, stale;
  2954. double waccepted;
  2955. double wnotaccepted;
  2956. int hwerrs;
  2957. double bad_diff1, good_diff1;
  2958. rolling = mhashes = waccepted = wnotaccepted = 0;
  2959. accepted = rejected = stale = hwerrs = bad_diff1 = good_diff1 = 0;
  2960. {
  2961. struct cgpu_info *slave = cgpu;
  2962. for (int i = 0; i < cgpu->procs; ++i, (slave = slave->next_proc))
  2963. {
  2964. slave->utility = slave->accepted / dev_runtime * 60;
  2965. slave->utility_diff1 = slave->diff_accepted / dev_runtime * 60;
  2966. rolling += slave->rolling;
  2967. mhashes += slave->total_mhashes;
  2968. if (opt_weighed_stats)
  2969. {
  2970. accepted += slave->diff_accepted;
  2971. rejected += slave->diff_rejected;
  2972. stale += slave->diff_stale;
  2973. }
  2974. else
  2975. {
  2976. accepted += slave->accepted;
  2977. rejected += slave->rejected;
  2978. stale += slave->stale;
  2979. }
  2980. waccepted += slave->diff_accepted;
  2981. wnotaccepted += slave->diff_rejected + slave->diff_stale;
  2982. hwerrs += slave->hw_errors;
  2983. bad_diff1 += slave->bad_diff1;
  2984. good_diff1 += slave->diff1;
  2985. if (opt_show_procs)
  2986. break;
  2987. }
  2988. }
  2989. double wtotal = (waccepted + wnotaccepted);
  2990. multi_format_unit_array2(
  2991. ((char*[]){cHr, aHr, uHr}),
  2992. ((size_t[]){h2bs_fmt_size[H2B_NOUNIT], h2bs_fmt_size[H2B_NOUNIT], h2bs_fmt_size[hashrate_style]}),
  2993. true, "h/s", hashrate_style,
  2994. 3,
  2995. 1e6*rolling,
  2996. 1e6*mhashes / dev_runtime,
  2997. utility_to_hashrate(good_diff1 * (wtotal ? (waccepted / wtotal) : 1) * 60 / dev_runtime));
  2998. // Processor representation
  2999. #ifdef HAVE_CURSES
  3000. if (for_curses)
  3001. {
  3002. if (opt_show_procs)
  3003. snprintf(buf, bufsz, " %"PRIprepr": ", cgpu->proc_repr);
  3004. else
  3005. snprintf(buf, bufsz, " %s: ", cgpu->dev_repr);
  3006. }
  3007. else
  3008. #endif
  3009. snprintf(buf, bufsz, "%s ", opt_show_procs ? cgpu->proc_repr_ns : cgpu->dev_repr_ns);
  3010. if (unlikely(cgpu->status == LIFE_INIT))
  3011. {
  3012. tailsprintf(buf, bufsz, "Initializing...");
  3013. return;
  3014. }
  3015. {
  3016. const size_t bufln = strlen(buf);
  3017. const size_t abufsz = (bufln >= bufsz) ? 0 : (bufsz - bufln);
  3018. if (likely(cgpu->status != LIFE_DEAD2) && drv->override_statline_temp2 && drv->override_statline_temp2(buf, bufsz, cgpu, opt_show_procs))
  3019. temperature_column(&buf[bufln], abufsz, for_curses, NULL);
  3020. else
  3021. {
  3022. float temp = cgpu->temp;
  3023. if (!opt_show_procs)
  3024. {
  3025. // Find the highest temperature of all processors
  3026. struct cgpu_info *proc = cgpu;
  3027. for (int i = 0; i < cgpu->procs; ++i, (proc = proc->next_proc))
  3028. if (proc->temp > temp)
  3029. temp = proc->temp;
  3030. }
  3031. temperature_column(&buf[bufln], abufsz, for_curses, &temp);
  3032. }
  3033. }
  3034. #ifdef HAVE_CURSES
  3035. if (for_curses)
  3036. {
  3037. const char *cHrStatsOpt[] = {AS_BAD("DEAD "), AS_BAD("SICK "), "OFF ", AS_BAD("REST "), AS_BAD(" ERR "), AS_BAD("WAIT "), cHr};
  3038. const char *cHrStats;
  3039. int cHrStatsI = (sizeof(cHrStatsOpt) / sizeof(*cHrStatsOpt)) - 1;
  3040. bool all_dead = true, all_off = true, all_rdrv = true;
  3041. struct cgpu_info *proc = cgpu;
  3042. for (int i = 0; i < cgpu->procs; ++i, (proc = proc->next_proc))
  3043. {
  3044. switch (cHrStatsI) {
  3045. default:
  3046. if (proc->status == LIFE_WAIT)
  3047. cHrStatsI = 5;
  3048. case 5:
  3049. if (proc->deven == DEV_RECOVER_ERR)
  3050. cHrStatsI = 4;
  3051. case 4:
  3052. if (proc->deven == DEV_RECOVER)
  3053. cHrStatsI = 3;
  3054. case 3:
  3055. if (proc->status == LIFE_SICK || proc->status == LIFE_DEAD || proc->status == LIFE_DEAD2)
  3056. {
  3057. cHrStatsI = 1;
  3058. all_off = false;
  3059. }
  3060. else
  3061. {
  3062. if (likely(proc->deven == DEV_ENABLED))
  3063. all_off = false;
  3064. if (proc->deven != DEV_RECOVER_DRV)
  3065. all_rdrv = false;
  3066. }
  3067. case 1:
  3068. break;
  3069. }
  3070. if (likely(proc->status != LIFE_DEAD && proc->status != LIFE_DEAD2))
  3071. all_dead = false;
  3072. if (opt_show_procs)
  3073. break;
  3074. }
  3075. if (unlikely(all_dead))
  3076. cHrStatsI = 0;
  3077. else
  3078. if (unlikely(all_off))
  3079. cHrStatsI = 2;
  3080. cHrStats = cHrStatsOpt[cHrStatsI];
  3081. if (cHrStatsI == 2 && all_rdrv)
  3082. cHrStats = " RST ";
  3083. format_statline(buf, bufsz,
  3084. cHrStats,
  3085. aHr, uHr,
  3086. accepted, rejected, stale,
  3087. wnotaccepted, waccepted,
  3088. hwerrs,
  3089. bad_diff1, bad_diff1 + good_diff1);
  3090. }
  3091. else
  3092. #endif
  3093. {
  3094. percentf4(rejpcbuf, sizeof(rejpcbuf), wnotaccepted, waccepted);
  3095. percentf4(bnbuf, sizeof(bnbuf), bad_diff1, good_diff1);
  3096. tailsprintf(buf, bufsz, "%ds:%s avg:%s u:%s | A:%d R:%d+%d(%s) HW:%d/%s",
  3097. opt_log_interval,
  3098. cHr, aHr, uHr,
  3099. accepted,
  3100. rejected,
  3101. stale,
  3102. rejpcbuf,
  3103. hwerrs,
  3104. bnbuf
  3105. );
  3106. }
  3107. }
  3108. #define get_statline(buf, bufsz, cgpu) get_statline3(buf, bufsz, cgpu, false, opt_show_procs)
  3109. #define get_statline2(buf, bufsz, cgpu, for_curses) get_statline3(buf, bufsz, cgpu, for_curses, opt_show_procs)
  3110. static void text_print_status(int thr_id)
  3111. {
  3112. struct cgpu_info *cgpu;
  3113. char logline[256];
  3114. cgpu = get_thr_cgpu(thr_id);
  3115. if (cgpu) {
  3116. get_statline(logline, sizeof(logline), cgpu);
  3117. printf("%s\n", logline);
  3118. }
  3119. }
  3120. #ifdef HAVE_CURSES
  3121. static int attr_bad = A_BOLD;
  3122. #ifdef WIN32
  3123. #define swprintf snwprintf
  3124. #endif
  3125. static
  3126. void bfg_waddstr(WINDOW *win, const char *s)
  3127. {
  3128. const char *p = s;
  3129. int32_t w;
  3130. int wlen;
  3131. unsigned char stop_ascii = (use_unicode ? '|' : 0x80);
  3132. while (true)
  3133. {
  3134. while (likely(p[0] == '\n' || (p[0] >= 0x20 && p[0] < stop_ascii)))
  3135. {
  3136. // Printable ASCII
  3137. ++p;
  3138. }
  3139. if (p != s)
  3140. waddnstr(win, s, p - s);
  3141. w = utf8_decode(p, &wlen);
  3142. if (unlikely(p[0] == '\xb5')) // HACK for Mu (SI prefix micro-)
  3143. {
  3144. w = unicode_micro;
  3145. wlen = 1;
  3146. }
  3147. s = p += wlen;
  3148. switch(w)
  3149. {
  3150. // NOTE: U+F000-U+F7FF are reserved for font hacks
  3151. case '\0':
  3152. return;
  3153. case 0xf000: // "bad" off
  3154. wattroff(win, attr_bad);
  3155. break;
  3156. case 0xf001: // "bad" on
  3157. wattron(win, attr_bad);
  3158. break;
  3159. #ifdef USE_UNICODE
  3160. case '|':
  3161. wadd_wch(win, WACS_VLINE);
  3162. break;
  3163. #endif
  3164. case 0x2500: // BOX DRAWINGS LIGHT HORIZONTAL
  3165. case 0x2534: // BOX DRAWINGS LIGHT UP AND HORIZONTAL
  3166. if (!use_unicode)
  3167. {
  3168. waddch(win, '-');
  3169. break;
  3170. }
  3171. #ifdef USE_UNICODE
  3172. wadd_wch(win, (w == 0x2500) ? WACS_HLINE : WACS_BTEE);
  3173. break;
  3174. #endif
  3175. case 0x2022:
  3176. if (w > WCHAR_MAX || !iswprint(w))
  3177. w = '*';
  3178. default:
  3179. if (w > WCHAR_MAX || !(iswprint(w) || w == '\n'))
  3180. {
  3181. #if REPLACEMENT_CHAR <= WCHAR_MAX
  3182. if (iswprint(REPLACEMENT_CHAR))
  3183. w = REPLACEMENT_CHAR;
  3184. else
  3185. #endif
  3186. w = '?';
  3187. }
  3188. {
  3189. #ifdef USE_UNICODE
  3190. wchar_t wbuf[0x10];
  3191. int wbuflen = sizeof(wbuf) / sizeof(*wbuf);
  3192. wbuflen = swprintf(wbuf, wbuflen, L"%lc", (wint_t)w);
  3193. waddnwstr(win, wbuf, wbuflen);
  3194. #else
  3195. wprintw(win, "%lc", (wint_t)w);
  3196. #endif
  3197. }
  3198. }
  3199. }
  3200. }
  3201. static inline
  3202. void bfg_hline(WINDOW *win, int y)
  3203. {
  3204. int maxx, __maybe_unused maxy;
  3205. getmaxyx(win, maxy, maxx);
  3206. #ifdef USE_UNICODE
  3207. if (use_unicode)
  3208. mvwhline_set(win, y, 0, WACS_HLINE, maxx);
  3209. else
  3210. #endif
  3211. mvwhline(win, y, 0, '-', maxx);
  3212. }
  3213. // Spaces until end of line, using current attributes (ie, not completely clear)
  3214. static
  3215. void bfg_wspctoeol(WINDOW * const win, const int offset)
  3216. {
  3217. int x, maxx;
  3218. int __maybe_unused y;
  3219. getmaxyx(win, y, maxx);
  3220. getyx(win, y, x);
  3221. const int space_count = (maxx - x) - offset;
  3222. // Check for negative - terminal too narrow
  3223. if (space_count <= 0)
  3224. return;
  3225. char buf[space_count];
  3226. memset(buf, ' ', space_count);
  3227. waddnstr(win, buf, space_count);
  3228. }
  3229. static int menu_attr = A_REVERSE;
  3230. #define CURBUFSIZ 256
  3231. #define cg_mvwprintw(win, y, x, fmt, ...) do { \
  3232. char tmp42[CURBUFSIZ]; \
  3233. snprintf(tmp42, sizeof(tmp42), fmt, ##__VA_ARGS__); \
  3234. wmove(win, y, x); \
  3235. bfg_waddstr(win, tmp42); \
  3236. } while (0)
  3237. #define cg_wprintw(win, fmt, ...) do { \
  3238. char tmp42[CURBUFSIZ]; \
  3239. snprintf(tmp42, sizeof(tmp42), fmt, ##__VA_ARGS__); \
  3240. bfg_waddstr(win, tmp42); \
  3241. } while (0)
  3242. /* Must be called with curses mutex lock held and curses_active */
  3243. static void curses_print_status(const int ts)
  3244. {
  3245. struct pool *pool = currentpool;
  3246. struct timeval now, tv;
  3247. float efficiency;
  3248. double income;
  3249. int logdiv;
  3250. efficiency = total_bytes_xfer ? total_diff_accepted * 2048. / total_bytes_xfer : 0.0;
  3251. wattron(statuswin, attr_title);
  3252. cg_mvwprintw(statuswin, 0, 0, " " PACKAGE " version " VERSION " - Started: %s", datestamp);
  3253. timer_set_now(&now);
  3254. {
  3255. unsigned int days, hours;
  3256. div_t d;
  3257. timersub(&now, &miner_started, &tv);
  3258. d = div(tv.tv_sec, 86400);
  3259. days = d.quot;
  3260. d = div(d.rem, 3600);
  3261. hours = d.quot;
  3262. d = div(d.rem, 60);
  3263. cg_wprintw(statuswin, " - [%3u day%c %02d:%02d:%02d]"
  3264. , days
  3265. , (days == 1) ? ' ' : 's'
  3266. , hours
  3267. , d.quot
  3268. , d.rem
  3269. );
  3270. }
  3271. bfg_wspctoeol(statuswin, 0);
  3272. wattroff(statuswin, attr_title);
  3273. wattron(statuswin, menu_attr);
  3274. wmove(statuswin, 1, 0);
  3275. bfg_waddstr(statuswin, " [M]anage devices [P]ool management [S]ettings [D]isplay options ");
  3276. bfg_wspctoeol(statuswin, 14);
  3277. bfg_waddstr(statuswin, "[H]elp [Q]uit ");
  3278. wattroff(statuswin, menu_attr);
  3279. if ((pool_strategy == POOL_LOADBALANCE || pool_strategy == POOL_BALANCE) && total_pools > 1) {
  3280. cg_mvwprintw(statuswin, 2, 0, " Connected to multiple pools with%s block change notify",
  3281. have_longpoll ? "": "out");
  3282. } else if (pool->has_stratum) {
  3283. cg_mvwprintw(statuswin, 2, 0, " Connected to %s diff %s with stratum as user %s",
  3284. pool->sockaddr_url, pool->diff, pool->rpc_user);
  3285. } else {
  3286. cg_mvwprintw(statuswin, 2, 0, " Connected to %s diff %s with%s LP as user %s",
  3287. pool->sockaddr_url, pool->diff, have_longpoll ? "": "out", pool->rpc_user);
  3288. }
  3289. wclrtoeol(statuswin);
  3290. cg_mvwprintw(statuswin, 3, 0, " Block: %s Diff:%s (%s) Started: %s",
  3291. current_hash, block_diff, net_hashrate, blocktime);
  3292. income = total_diff_accepted * 3600 * block_subsidy / total_secs / current_diff;
  3293. char bwstr[12], incomestr[13];
  3294. format_unit3(incomestr, sizeof(incomestr), FUP_BTC, "BTC/hr", H2B_SHORT, income/1e8, -1);
  3295. cg_mvwprintw(statuswin, 4, 0, " ST:%d F:%d NB:%d AS:%d BW:[%s] E:%.2f I:%s BS:%s",
  3296. ts,
  3297. total_go + total_ro,
  3298. new_blocks,
  3299. total_submitting,
  3300. multi_format_unit2(bwstr, sizeof(bwstr),
  3301. false, "B/s", H2B_SHORT, "/", 2,
  3302. (float)(total_bytes_rcvd / total_secs),
  3303. (float)(total_bytes_sent / total_secs)),
  3304. efficiency,
  3305. incomestr,
  3306. best_share);
  3307. wclrtoeol(statuswin);
  3308. mvwaddstr(statuswin, 5, 0, " ");
  3309. bfg_waddstr(statuswin, statusline);
  3310. wclrtoeol(statuswin);
  3311. logdiv = statusy - 1;
  3312. bfg_hline(statuswin, 6);
  3313. bfg_hline(statuswin, logdiv);
  3314. #ifdef USE_UNICODE
  3315. if (use_unicode)
  3316. {
  3317. int offset = 8 /* device */ + 5 /* temperature */ + 1 /* padding space */;
  3318. if (opt_show_procs && !opt_compact)
  3319. ++offset; // proc letter
  3320. if (have_unicode_degrees)
  3321. ++offset; // degrees symbol
  3322. mvwadd_wch(statuswin, 6, offset, WACS_PLUS);
  3323. mvwadd_wch(statuswin, logdiv, offset, WACS_BTEE);
  3324. offset += 24; // hashrates etc
  3325. mvwadd_wch(statuswin, 6, offset, WACS_PLUS);
  3326. mvwadd_wch(statuswin, logdiv, offset, WACS_BTEE);
  3327. }
  3328. #endif
  3329. }
  3330. static void adj_width(int var, int *length)
  3331. {
  3332. if ((int)(log10(var) + 1) > *length)
  3333. (*length)++;
  3334. }
  3335. static int dev_width;
  3336. static void curses_print_devstatus(struct cgpu_info *cgpu)
  3337. {
  3338. char logline[256];
  3339. int ypos;
  3340. if (opt_compact)
  3341. return;
  3342. /* Check this isn't out of the window size */
  3343. if (opt_show_procs)
  3344. ypos = cgpu->cgminer_id;
  3345. else
  3346. {
  3347. if (cgpu->proc_id)
  3348. return;
  3349. ypos = cgpu->device_line_id;
  3350. }
  3351. ypos += devsummaryYOffset;
  3352. if (ypos < 0)
  3353. return;
  3354. ypos += devcursor - 1;
  3355. if (ypos >= statusy - 1)
  3356. return;
  3357. if (wmove(statuswin, ypos, 0) == ERR)
  3358. return;
  3359. get_statline2(logline, sizeof(logline), cgpu, true);
  3360. if (selecting_device && (opt_show_procs ? (selected_device == cgpu->cgminer_id) : (devices[selected_device]->device == cgpu)))
  3361. wattron(statuswin, A_REVERSE);
  3362. bfg_waddstr(statuswin, logline);
  3363. wattroff(statuswin, A_REVERSE);
  3364. wclrtoeol(statuswin);
  3365. }
  3366. static
  3367. void _refresh_devstatus(const bool already_have_lock) {
  3368. if ((!opt_compact) && (already_have_lock || curses_active_locked())) {
  3369. int i;
  3370. if (unlikely(!total_devices))
  3371. {
  3372. const int ypos = devcursor - 1;
  3373. if (ypos < statusy - 1 && wmove(statuswin, ypos, 0) != ERR)
  3374. {
  3375. wattron(statuswin, attr_bad);
  3376. bfg_waddstr(statuswin, "NO DEVICES FOUND: Press 'M' and '+' to add");
  3377. wclrtoeol(statuswin);
  3378. wattroff(statuswin, attr_bad);
  3379. }
  3380. }
  3381. for (i = 0; i < total_devices; i++)
  3382. curses_print_devstatus(get_devices(i));
  3383. touchwin(statuswin);
  3384. wrefresh(statuswin);
  3385. if (!already_have_lock)
  3386. unlock_curses();
  3387. }
  3388. }
  3389. #define refresh_devstatus() _refresh_devstatus(false)
  3390. #endif
  3391. static void print_status(int thr_id)
  3392. {
  3393. if (!curses_active)
  3394. text_print_status(thr_id);
  3395. }
  3396. #ifdef HAVE_CURSES
  3397. static
  3398. bool set_statusy(int maxy)
  3399. {
  3400. if (loginput_size)
  3401. {
  3402. maxy -= loginput_size;
  3403. if (maxy < 0)
  3404. maxy = 0;
  3405. }
  3406. if (logstart < maxy)
  3407. maxy = logstart;
  3408. if (statusy == maxy)
  3409. return false;
  3410. statusy = maxy;
  3411. logcursor = statusy;
  3412. return true;
  3413. }
  3414. /* Check for window resize. Called with curses mutex locked */
  3415. static inline void change_logwinsize(void)
  3416. {
  3417. int x, y, logx, logy;
  3418. getmaxyx(mainwin, y, x);
  3419. if (x < 80 || y < 25)
  3420. return;
  3421. if (y > statusy + 2 && statusy < logstart) {
  3422. set_statusy(y - 2);
  3423. mvwin(logwin, logcursor, 0);
  3424. bfg_wresize(statuswin, statusy, x);
  3425. }
  3426. y -= logcursor;
  3427. getmaxyx(logwin, logy, logx);
  3428. /* Detect screen size change */
  3429. if (x != logx || y != logy)
  3430. bfg_wresize(logwin, y, x);
  3431. }
  3432. static void check_winsizes(void)
  3433. {
  3434. if (!use_curses)
  3435. return;
  3436. if (curses_active_locked()) {
  3437. int y, x;
  3438. x = getmaxx(statuswin);
  3439. if (set_statusy(LINES - 2))
  3440. {
  3441. erase();
  3442. bfg_wresize(statuswin, statusy, x);
  3443. getmaxyx(mainwin, y, x);
  3444. y -= logcursor;
  3445. bfg_wresize(logwin, y, x);
  3446. mvwin(logwin, logcursor, 0);
  3447. }
  3448. unlock_curses();
  3449. }
  3450. }
  3451. static int device_line_id_count;
  3452. static void switch_logsize(void)
  3453. {
  3454. if (curses_active_locked()) {
  3455. if (opt_compact) {
  3456. logstart = devcursor - 1;
  3457. logcursor = logstart + 1;
  3458. } else {
  3459. total_lines = (opt_show_procs ? total_devices : device_line_id_count) ?: 1;
  3460. logstart = devcursor + total_lines;
  3461. logcursor = logstart;
  3462. }
  3463. unlock_curses();
  3464. }
  3465. check_winsizes();
  3466. }
  3467. /* For mandatory printing when mutex is already locked */
  3468. void _wlog(const char *str)
  3469. {
  3470. static bool newline;
  3471. size_t end = strlen(str) - 1;
  3472. if (newline)
  3473. bfg_waddstr(logwin, "\n");
  3474. if (str[end] == '\n')
  3475. {
  3476. char *s;
  3477. newline = true;
  3478. s = alloca(end + 1);
  3479. memcpy(s, str, end);
  3480. s[end] = '\0';
  3481. str = s;
  3482. }
  3483. else
  3484. newline = false;
  3485. bfg_waddstr(logwin, str);
  3486. }
  3487. /* Mandatory printing */
  3488. void _wlogprint(const char *str)
  3489. {
  3490. if (curses_active_locked()) {
  3491. _wlog(str);
  3492. unlock_curses();
  3493. }
  3494. }
  3495. #endif
  3496. #ifdef HAVE_CURSES
  3497. bool _log_curses_only(int prio, const char *datetime, const char *str)
  3498. {
  3499. bool high_prio;
  3500. high_prio = (prio == LOG_WARNING || prio == LOG_ERR);
  3501. if (curses_active)
  3502. {
  3503. if (!loginput_size || high_prio) {
  3504. wlog(" %s %s\n", datetime, str);
  3505. if (high_prio) {
  3506. touchwin(logwin);
  3507. wrefresh(logwin);
  3508. }
  3509. }
  3510. return true;
  3511. }
  3512. return false;
  3513. }
  3514. void clear_logwin(void)
  3515. {
  3516. if (curses_active_locked()) {
  3517. wclear(logwin);
  3518. unlock_curses();
  3519. }
  3520. }
  3521. void logwin_update(void)
  3522. {
  3523. if (curses_active_locked()) {
  3524. touchwin(logwin);
  3525. wrefresh(logwin);
  3526. unlock_curses();
  3527. }
  3528. }
  3529. #endif
  3530. static void enable_pool(struct pool *pool)
  3531. {
  3532. if (pool->enabled != POOL_ENABLED) {
  3533. enabled_pools++;
  3534. pool->enabled = POOL_ENABLED;
  3535. }
  3536. }
  3537. #ifdef HAVE_CURSES
  3538. static void disable_pool(struct pool *pool)
  3539. {
  3540. if (pool->enabled == POOL_ENABLED)
  3541. enabled_pools--;
  3542. pool->enabled = POOL_DISABLED;
  3543. }
  3544. #endif
  3545. static void reject_pool(struct pool *pool)
  3546. {
  3547. if (pool->enabled == POOL_ENABLED)
  3548. enabled_pools--;
  3549. pool->enabled = POOL_REJECTING;
  3550. }
  3551. static uint64_t share_diff(const struct work *);
  3552. static
  3553. void share_result_msg(const struct work *work, const char *disp, const char *reason, bool resubmit, const char *worktime) {
  3554. struct cgpu_info *cgpu;
  3555. const unsigned char *hashpart = &work->hash[opt_scrypt ? 26 : 24];
  3556. char shrdiffdisp[16];
  3557. int tgtdiff = floor(work->work_difficulty);
  3558. char tgtdiffdisp[16];
  3559. char where[20];
  3560. cgpu = get_thr_cgpu(work->thr_id);
  3561. suffix_string(work->share_diff, shrdiffdisp, sizeof(shrdiffdisp), 0);
  3562. suffix_string(tgtdiff, tgtdiffdisp, sizeof(tgtdiffdisp), 0);
  3563. if (total_pools > 1)
  3564. snprintf(where, sizeof(where), " pool %d", work->pool->pool_no);
  3565. else
  3566. where[0] = '\0';
  3567. applog(LOG_NOTICE, "%s %02x%02x%02x%02x %"PRIprepr"%s Diff %s/%s%s %s%s",
  3568. disp,
  3569. (unsigned)hashpart[3], (unsigned)hashpart[2], (unsigned)hashpart[1], (unsigned)hashpart[0],
  3570. cgpu->proc_repr,
  3571. where,
  3572. shrdiffdisp, tgtdiffdisp,
  3573. reason,
  3574. resubmit ? "(resubmit)" : "",
  3575. worktime
  3576. );
  3577. }
  3578. static bool test_work_current(struct work *);
  3579. static void _submit_work_async(struct work *);
  3580. static
  3581. void maybe_local_submit(const struct work *work)
  3582. {
  3583. #if BLKMAKER_VERSION > 3
  3584. if (unlikely(work->block && work->tmpl))
  3585. {
  3586. // This is a block with a full template (GBT)
  3587. // Regardless of the result, submit to local bitcoind(s) as well
  3588. struct work *work_cp;
  3589. char *p;
  3590. for (int i = 0; i < total_pools; ++i)
  3591. {
  3592. p = strchr(pools[i]->rpc_url, '#');
  3593. if (likely(!(p && strstr(&p[1], "allblocks"))))
  3594. continue;
  3595. applog(LOG_DEBUG, "Attempting submission of full block to pool %d", pools[i]->pool_no);
  3596. work_cp = copy_work(work);
  3597. work_cp->pool = pools[i];
  3598. work_cp->do_foreign_submit = true;
  3599. _submit_work_async(work_cp);
  3600. }
  3601. }
  3602. #endif
  3603. }
  3604. /* Theoretically threads could race when modifying accepted and
  3605. * rejected values but the chance of two submits completing at the
  3606. * same time is zero so there is no point adding extra locking */
  3607. static void
  3608. share_result(json_t *val, json_t *res, json_t *err, const struct work *work,
  3609. /*char *hashshow,*/ bool resubmit, char *worktime)
  3610. {
  3611. struct pool *pool = work->pool;
  3612. struct cgpu_info *cgpu;
  3613. cgpu = get_thr_cgpu(work->thr_id);
  3614. if ((json_is_null(err) || !err) && (json_is_null(res) || json_is_true(res))) {
  3615. mutex_lock(&stats_lock);
  3616. cgpu->accepted++;
  3617. total_accepted++;
  3618. pool->accepted++;
  3619. cgpu->diff_accepted += work->work_difficulty;
  3620. total_diff_accepted += work->work_difficulty;
  3621. pool->diff_accepted += work->work_difficulty;
  3622. mutex_unlock(&stats_lock);
  3623. pool->seq_rejects = 0;
  3624. cgpu->last_share_pool = pool->pool_no;
  3625. cgpu->last_share_pool_time = time(NULL);
  3626. cgpu->last_share_diff = work->work_difficulty;
  3627. pool->last_share_time = cgpu->last_share_pool_time;
  3628. pool->last_share_diff = work->work_difficulty;
  3629. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  3630. if (!QUIET) {
  3631. share_result_msg(work, "Accepted", "", resubmit, worktime);
  3632. }
  3633. sharelog("accept", work);
  3634. if (opt_shares && total_diff_accepted >= opt_shares) {
  3635. applog(LOG_WARNING, "Successfully mined %d accepted shares as requested and exiting.", opt_shares);
  3636. kill_work();
  3637. return;
  3638. }
  3639. /* Detect if a pool that has been temporarily disabled for
  3640. * continually rejecting shares has started accepting shares.
  3641. * This will only happen with the work returned from a
  3642. * longpoll */
  3643. if (unlikely(pool->enabled == POOL_REJECTING)) {
  3644. applog(LOG_WARNING, "Rejecting pool %d now accepting shares, re-enabling!", pool->pool_no);
  3645. enable_pool(pool);
  3646. switch_pools(NULL);
  3647. }
  3648. if (unlikely(work->block)) {
  3649. // Force moving on to this new block :)
  3650. struct work fakework;
  3651. memset(&fakework, 0, sizeof(fakework));
  3652. fakework.pool = work->pool;
  3653. // Copy block version, bits, and time from share
  3654. memcpy(&fakework.data[ 0], &work->data[ 0], 4);
  3655. memcpy(&fakework.data[68], &work->data[68], 8);
  3656. // Set prevblock to winning hash (swap32'd)
  3657. swap32yes(&fakework.data[4], &work->hash[0], 32 / 4);
  3658. test_work_current(&fakework);
  3659. }
  3660. } else {
  3661. mutex_lock(&stats_lock);
  3662. cgpu->rejected++;
  3663. total_rejected++;
  3664. pool->rejected++;
  3665. cgpu->diff_rejected += work->work_difficulty;
  3666. total_diff_rejected += work->work_difficulty;
  3667. pool->diff_rejected += work->work_difficulty;
  3668. pool->seq_rejects++;
  3669. mutex_unlock(&stats_lock);
  3670. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  3671. if (!QUIET) {
  3672. char where[20];
  3673. char disposition[36] = "reject";
  3674. char reason[32];
  3675. strcpy(reason, "");
  3676. if (total_pools > 1)
  3677. snprintf(where, sizeof(where), "pool %d", work->pool->pool_no);
  3678. else
  3679. strcpy(where, "");
  3680. if (!json_is_string(res))
  3681. res = json_object_get(val, "reject-reason");
  3682. if (res) {
  3683. const char *reasontmp = json_string_value(res);
  3684. size_t reasonLen = strlen(reasontmp);
  3685. if (reasonLen > 28)
  3686. reasonLen = 28;
  3687. reason[0] = ' '; reason[1] = '(';
  3688. memcpy(2 + reason, reasontmp, reasonLen);
  3689. reason[reasonLen + 2] = ')'; reason[reasonLen + 3] = '\0';
  3690. memcpy(disposition + 7, reasontmp, reasonLen);
  3691. disposition[6] = ':'; disposition[reasonLen + 7] = '\0';
  3692. } else if (work->stratum && err && json_is_array(err)) {
  3693. json_t *reason_val = json_array_get(err, 1);
  3694. char *reason_str;
  3695. if (reason_val && json_is_string(reason_val)) {
  3696. reason_str = (char *)json_string_value(reason_val);
  3697. snprintf(reason, 31, " (%s)", reason_str);
  3698. }
  3699. }
  3700. share_result_msg(work, "Rejected", reason, resubmit, worktime);
  3701. sharelog(disposition, work);
  3702. }
  3703. /* Once we have more than a nominal amount of sequential rejects,
  3704. * at least 10 and more than 3 mins at the current utility,
  3705. * disable the pool because some pool error is likely to have
  3706. * ensued. Do not do this if we know the share just happened to
  3707. * be stale due to networking delays.
  3708. */
  3709. if (pool->seq_rejects > 10 && !work->stale && opt_disable_pool && enabled_pools > 1) {
  3710. double utility = total_accepted / total_secs * 60;
  3711. if (pool->seq_rejects > utility * 3) {
  3712. applog(LOG_WARNING, "Pool %d rejected %d sequential shares, disabling!",
  3713. pool->pool_no, pool->seq_rejects);
  3714. reject_pool(pool);
  3715. if (pool == current_pool())
  3716. switch_pools(NULL);
  3717. pool->seq_rejects = 0;
  3718. }
  3719. }
  3720. }
  3721. maybe_local_submit(work);
  3722. }
  3723. static char *submit_upstream_work_request(struct work *work)
  3724. {
  3725. char *hexstr = NULL;
  3726. char *s, *sd;
  3727. struct pool *pool = work->pool;
  3728. if (work->tmpl) {
  3729. json_t *req;
  3730. unsigned char data[80];
  3731. swap32yes(data, work->data, 80 / 4);
  3732. #if BLKMAKER_VERSION > 3
  3733. if (work->do_foreign_submit)
  3734. req = blkmk_submit_foreign_jansson(work->tmpl, data, work->dataid, le32toh(*((uint32_t*)&work->data[76])));
  3735. else
  3736. #endif
  3737. req = blkmk_submit_jansson(work->tmpl, data, work->dataid, le32toh(*((uint32_t*)&work->data[76])));
  3738. s = json_dumps(req, 0);
  3739. json_decref(req);
  3740. sd = malloc(161);
  3741. bin2hex(sd, data, 80);
  3742. } else {
  3743. /* build hex string */
  3744. hexstr = malloc((sizeof(work->data) * 2) + 1);
  3745. bin2hex(hexstr, work->data, sizeof(work->data));
  3746. /* build JSON-RPC request */
  3747. s = strdup("{\"method\": \"getwork\", \"params\": [ \"");
  3748. s = realloc_strcat(s, hexstr);
  3749. s = realloc_strcat(s, "\" ], \"id\":1}");
  3750. free(hexstr);
  3751. sd = s;
  3752. }
  3753. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->rpc_url, sd);
  3754. if (work->tmpl)
  3755. free(sd);
  3756. else
  3757. s = realloc_strcat(s, "\n");
  3758. return s;
  3759. }
  3760. static bool submit_upstream_work_completed(struct work *work, bool resubmit, struct timeval *ptv_submit, json_t *val) {
  3761. json_t *res, *err;
  3762. bool rc = false;
  3763. int thr_id = work->thr_id;
  3764. struct pool *pool = work->pool;
  3765. struct timeval tv_submit_reply;
  3766. time_t ts_submit_reply;
  3767. char worktime[200] = "";
  3768. cgtime(&tv_submit_reply);
  3769. ts_submit_reply = time(NULL);
  3770. if (unlikely(!val)) {
  3771. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  3772. if (!pool_tset(pool, &pool->submit_fail)) {
  3773. total_ro++;
  3774. pool->remotefail_occasions++;
  3775. applog(LOG_WARNING, "Pool %d communication failure, caching submissions", pool->pool_no);
  3776. }
  3777. goto out;
  3778. } else if (pool_tclear(pool, &pool->submit_fail))
  3779. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  3780. res = json_object_get(val, "result");
  3781. err = json_object_get(val, "error");
  3782. if (!QUIET) {
  3783. if (opt_worktime) {
  3784. char workclone[20];
  3785. struct tm _tm;
  3786. struct tm *tm, tm_getwork, tm_submit_reply;
  3787. tm = &_tm;
  3788. double getwork_time = tdiff((struct timeval *)&(work->tv_getwork_reply),
  3789. (struct timeval *)&(work->tv_getwork));
  3790. double getwork_to_work = tdiff((struct timeval *)&(work->tv_work_start),
  3791. (struct timeval *)&(work->tv_getwork_reply));
  3792. double work_time = tdiff((struct timeval *)&(work->tv_work_found),
  3793. (struct timeval *)&(work->tv_work_start));
  3794. double work_to_submit = tdiff(ptv_submit,
  3795. (struct timeval *)&(work->tv_work_found));
  3796. double submit_time = tdiff(&tv_submit_reply, ptv_submit);
  3797. int diffplaces = 3;
  3798. localtime_r(&work->ts_getwork, tm);
  3799. memcpy(&tm_getwork, tm, sizeof(struct tm));
  3800. localtime_r(&ts_submit_reply, tm);
  3801. memcpy(&tm_submit_reply, tm, sizeof(struct tm));
  3802. if (work->clone) {
  3803. snprintf(workclone, sizeof(workclone), "C:%1.3f",
  3804. tdiff((struct timeval *)&(work->tv_cloned),
  3805. (struct timeval *)&(work->tv_getwork_reply)));
  3806. }
  3807. else
  3808. strcpy(workclone, "O");
  3809. if (work->work_difficulty < 1)
  3810. diffplaces = 6;
  3811. snprintf(worktime, sizeof(worktime),
  3812. " <-%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",
  3813. (unsigned long)be32toh(*(uint32_t *)&(work->data[opt_scrypt ? 32 : 28])),
  3814. (unsigned long)be32toh(*(uint32_t *)&(work->data[opt_scrypt ? 28 : 24])),
  3815. work->getwork_mode, diffplaces, work->work_difficulty,
  3816. tm_getwork.tm_hour, tm_getwork.tm_min,
  3817. tm_getwork.tm_sec, getwork_time, workclone,
  3818. getwork_to_work, work_time, work_to_submit, submit_time,
  3819. tm_submit_reply.tm_hour, tm_submit_reply.tm_min,
  3820. tm_submit_reply.tm_sec);
  3821. }
  3822. }
  3823. share_result(val, res, err, work, resubmit, worktime);
  3824. if (!opt_realquiet)
  3825. print_status(thr_id);
  3826. if (!want_per_device_stats) {
  3827. char logline[256];
  3828. struct cgpu_info *cgpu;
  3829. cgpu = get_thr_cgpu(thr_id);
  3830. get_statline(logline, sizeof(logline), cgpu);
  3831. applog(LOG_INFO, "%s", logline);
  3832. }
  3833. json_decref(val);
  3834. rc = true;
  3835. out:
  3836. return rc;
  3837. }
  3838. /* Specifies whether we can use this pool for work or not. */
  3839. static bool pool_unworkable(struct pool *pool)
  3840. {
  3841. if (pool->idle)
  3842. return true;
  3843. if (pool->enabled != POOL_ENABLED)
  3844. return true;
  3845. if (pool->has_stratum && !pool->stratum_active)
  3846. return true;
  3847. return false;
  3848. }
  3849. /* In balanced mode, the amount of diff1 solutions per pool is monitored as a
  3850. * rolling average per 10 minutes and if pools start getting more, it biases
  3851. * away from them to distribute work evenly. The share count is reset to the
  3852. * rolling average every 10 minutes to not send all work to one pool after it
  3853. * has been disabled/out for an extended period. */
  3854. static struct pool *select_balanced(struct pool *cp)
  3855. {
  3856. int i, lowest = cp->shares;
  3857. struct pool *ret = cp;
  3858. for (i = 0; i < total_pools; i++) {
  3859. struct pool *pool = pools[i];
  3860. if (pool_unworkable(pool))
  3861. continue;
  3862. if (pool->shares < lowest) {
  3863. lowest = pool->shares;
  3864. ret = pool;
  3865. }
  3866. }
  3867. ret->shares++;
  3868. return ret;
  3869. }
  3870. static bool pool_active(struct pool *, bool pinging);
  3871. static void pool_died(struct pool *);
  3872. static struct pool *priority_pool(int choice);
  3873. static bool pool_unusable(struct pool *pool);
  3874. /* Select any active pool in a rotating fashion when loadbalance is chosen if
  3875. * it has any quota left. */
  3876. static inline struct pool *select_pool(bool lagging)
  3877. {
  3878. static int rotating_pool = 0;
  3879. struct pool *pool, *cp;
  3880. bool avail = false;
  3881. int tested, i;
  3882. cp = current_pool();
  3883. retry:
  3884. if (pool_strategy == POOL_BALANCE) {
  3885. pool = select_balanced(cp);
  3886. goto out;
  3887. }
  3888. if (pool_strategy != POOL_LOADBALANCE && (!lagging || opt_fail_only)) {
  3889. pool = cp;
  3890. goto out;
  3891. } else
  3892. pool = NULL;
  3893. for (i = 0; i < total_pools; i++) {
  3894. struct pool *tp = pools[i];
  3895. if (tp->quota_used < tp->quota_gcd) {
  3896. avail = true;
  3897. break;
  3898. }
  3899. }
  3900. /* There are no pools with quota, so reset them. */
  3901. if (!avail) {
  3902. for (i = 0; i < total_pools; i++)
  3903. pools[i]->quota_used = 0;
  3904. if (++rotating_pool >= total_pools)
  3905. rotating_pool = 0;
  3906. }
  3907. /* Try to find the first pool in the rotation that is usable */
  3908. tested = 0;
  3909. while (!pool && tested++ < total_pools) {
  3910. pool = pools[rotating_pool];
  3911. if (pool->quota_used++ < pool->quota_gcd) {
  3912. if (!pool_unworkable(pool))
  3913. break;
  3914. /* Failover-only flag for load-balance means distribute
  3915. * unused quota to priority pool 0. */
  3916. if (opt_fail_only)
  3917. priority_pool(0)->quota_used--;
  3918. }
  3919. pool = NULL;
  3920. if (++rotating_pool >= total_pools)
  3921. rotating_pool = 0;
  3922. }
  3923. /* If there are no alive pools with quota, choose according to
  3924. * priority. */
  3925. if (!pool) {
  3926. for (i = 0; i < total_pools; i++) {
  3927. struct pool *tp = priority_pool(i);
  3928. if (!pool_unusable(tp)) {
  3929. pool = tp;
  3930. break;
  3931. }
  3932. }
  3933. }
  3934. /* If still nothing is usable, use the current pool */
  3935. if (!pool)
  3936. pool = cp;
  3937. out:
  3938. if (cp != pool)
  3939. {
  3940. if (!pool_active(pool, false))
  3941. {
  3942. pool_died(pool);
  3943. goto retry;
  3944. }
  3945. pool_tclear(pool, &pool->idle);
  3946. }
  3947. applog(LOG_DEBUG, "Selecting pool %d for work", pool->pool_no);
  3948. return pool;
  3949. }
  3950. static double DIFFEXACTONE = 26959946667150639794667015087019630673637144422540572481103610249215.0;
  3951. static const uint64_t diffone = 0xFFFF000000000000ull;
  3952. static double target_diff(const unsigned char *target)
  3953. {
  3954. double targ = 0;
  3955. signed int i;
  3956. for (i = 31; i >= 0; --i)
  3957. targ = (targ * 0x100) + target[i];
  3958. return DIFFEXACTONE / (targ ?: 1);
  3959. }
  3960. /*
  3961. * Calculate the work share difficulty
  3962. */
  3963. static void calc_diff(struct work *work, int known)
  3964. {
  3965. struct cgminer_pool_stats *pool_stats = &(work->pool->cgminer_pool_stats);
  3966. double difficulty;
  3967. if (!known) {
  3968. work->work_difficulty = target_diff(work->target);
  3969. } else
  3970. work->work_difficulty = known;
  3971. difficulty = work->work_difficulty;
  3972. pool_stats->last_diff = difficulty;
  3973. suffix_string((uint64_t)difficulty, work->pool->diff, sizeof(work->pool->diff), 0);
  3974. if (difficulty == pool_stats->min_diff)
  3975. pool_stats->min_diff_count++;
  3976. else if (difficulty < pool_stats->min_diff || pool_stats->min_diff == 0) {
  3977. pool_stats->min_diff = difficulty;
  3978. pool_stats->min_diff_count = 1;
  3979. }
  3980. if (difficulty == pool_stats->max_diff)
  3981. pool_stats->max_diff_count++;
  3982. else if (difficulty > pool_stats->max_diff) {
  3983. pool_stats->max_diff = difficulty;
  3984. pool_stats->max_diff_count = 1;
  3985. }
  3986. }
  3987. static void get_benchmark_work(struct work *work)
  3988. {
  3989. // Use a random work block pulled from a pool
  3990. static uint8_t bench_block[] = { CGMINER_BENCHMARK_BLOCK };
  3991. size_t bench_size = sizeof(*work);
  3992. size_t work_size = sizeof(bench_block);
  3993. size_t min_size = (work_size < bench_size ? work_size : bench_size);
  3994. memset(work, 0, sizeof(*work));
  3995. memcpy(work, &bench_block, min_size);
  3996. work->mandatory = true;
  3997. work->pool = pools[0];
  3998. cgtime(&work->tv_getwork);
  3999. copy_time(&work->tv_getwork_reply, &work->tv_getwork);
  4000. work->getwork_mode = GETWORK_MODE_BENCHMARK;
  4001. calc_diff(work, 0);
  4002. }
  4003. static void wake_gws(void);
  4004. static void update_last_work(struct work *work)
  4005. {
  4006. if (!work->tmpl)
  4007. // Only save GBT jobs, since rollntime isn't coordinated well yet
  4008. return;
  4009. struct pool *pool = work->pool;
  4010. mutex_lock(&pool->last_work_lock);
  4011. if (pool->last_work_copy)
  4012. free_work(pool->last_work_copy);
  4013. pool->last_work_copy = copy_work(work);
  4014. pool->last_work_copy->work_restart_id = pool->work_restart_id;
  4015. mutex_unlock(&pool->last_work_lock);
  4016. }
  4017. static
  4018. void gbt_req_target(json_t *req)
  4019. {
  4020. json_t *j;
  4021. json_t *n;
  4022. if (!request_target_str)
  4023. return;
  4024. j = json_object_get(req, "params");
  4025. if (!j)
  4026. {
  4027. n = json_array();
  4028. if (!n)
  4029. return;
  4030. if (json_object_set_new(req, "params", n))
  4031. goto erradd;
  4032. j = n;
  4033. }
  4034. n = json_array_get(j, 0);
  4035. if (!n)
  4036. {
  4037. n = json_object();
  4038. if (!n)
  4039. return;
  4040. if (json_array_append_new(j, n))
  4041. goto erradd;
  4042. }
  4043. j = n;
  4044. n = json_string(request_target_str);
  4045. if (!n)
  4046. return;
  4047. if (json_object_set_new(j, "target", n))
  4048. goto erradd;
  4049. return;
  4050. erradd:
  4051. json_decref(n);
  4052. }
  4053. static char *prepare_rpc_req2(struct work *work, enum pool_protocol proto, const char *lpid, bool probe)
  4054. {
  4055. char *rpc_req;
  4056. clean_work(work);
  4057. switch (proto) {
  4058. case PLP_GETWORK:
  4059. work->getwork_mode = GETWORK_MODE_POOL;
  4060. return strdup(getwork_req);
  4061. case PLP_GETBLOCKTEMPLATE:
  4062. work->getwork_mode = GETWORK_MODE_GBT;
  4063. work->tmpl_refcount = malloc(sizeof(*work->tmpl_refcount));
  4064. if (!work->tmpl_refcount)
  4065. return NULL;
  4066. work->tmpl = blktmpl_create();
  4067. if (!work->tmpl)
  4068. goto gbtfail2;
  4069. *work->tmpl_refcount = 1;
  4070. gbt_capabilities_t caps = blktmpl_addcaps(work->tmpl);
  4071. if (!caps)
  4072. goto gbtfail;
  4073. caps |= GBT_LONGPOLL;
  4074. #if BLKMAKER_VERSION > 1
  4075. if (opt_coinbase_script.sz)
  4076. caps |= GBT_CBVALUE;
  4077. #endif
  4078. json_t *req = blktmpl_request_jansson(caps, lpid);
  4079. if (!req)
  4080. goto gbtfail;
  4081. if (probe)
  4082. gbt_req_target(req);
  4083. rpc_req = json_dumps(req, 0);
  4084. if (!rpc_req)
  4085. goto gbtfail;
  4086. json_decref(req);
  4087. return rpc_req;
  4088. default:
  4089. return NULL;
  4090. }
  4091. return NULL;
  4092. gbtfail:
  4093. blktmpl_free(work->tmpl);
  4094. work->tmpl = NULL;
  4095. gbtfail2:
  4096. free(work->tmpl_refcount);
  4097. work->tmpl_refcount = NULL;
  4098. return NULL;
  4099. }
  4100. #define prepare_rpc_req(work, proto, lpid) prepare_rpc_req2(work, proto, lpid, false)
  4101. #define prepare_rpc_req_probe(work, proto, lpid) prepare_rpc_req2(work, proto, lpid, true)
  4102. static const char *pool_protocol_name(enum pool_protocol proto)
  4103. {
  4104. switch (proto) {
  4105. case PLP_GETBLOCKTEMPLATE:
  4106. return "getblocktemplate";
  4107. case PLP_GETWORK:
  4108. return "getwork";
  4109. default:
  4110. return "UNKNOWN";
  4111. }
  4112. }
  4113. static enum pool_protocol pool_protocol_fallback(enum pool_protocol proto)
  4114. {
  4115. switch (proto) {
  4116. case PLP_GETBLOCKTEMPLATE:
  4117. if (want_getwork)
  4118. return PLP_GETWORK;
  4119. default:
  4120. return PLP_NONE;
  4121. }
  4122. }
  4123. static bool get_upstream_work(struct work *work, CURL *curl)
  4124. {
  4125. struct pool *pool = work->pool;
  4126. struct cgminer_pool_stats *pool_stats = &(pool->cgminer_pool_stats);
  4127. struct timeval tv_elapsed;
  4128. json_t *val = NULL;
  4129. bool rc = false;
  4130. char *url;
  4131. enum pool_protocol proto;
  4132. char *rpc_req;
  4133. if (pool->proto == PLP_NONE)
  4134. pool->proto = PLP_GETBLOCKTEMPLATE;
  4135. tryagain:
  4136. rpc_req = prepare_rpc_req(work, pool->proto, NULL);
  4137. work->pool = pool;
  4138. if (!rpc_req)
  4139. return false;
  4140. applog(LOG_DEBUG, "DBG: sending %s get RPC call: %s", pool->rpc_url, rpc_req);
  4141. url = pool->rpc_url;
  4142. cgtime(&work->tv_getwork);
  4143. val = json_rpc_call(curl, url, pool->rpc_userpass, rpc_req, false,
  4144. false, &work->rolltime, pool, false);
  4145. pool_stats->getwork_attempts++;
  4146. free(rpc_req);
  4147. if (likely(val)) {
  4148. rc = work_decode(pool, work, val);
  4149. if (unlikely(!rc))
  4150. applog(LOG_DEBUG, "Failed to decode work in get_upstream_work");
  4151. } else if (PLP_NONE != (proto = pool_protocol_fallback(pool->proto))) {
  4152. applog(LOG_WARNING, "Pool %u failed getblocktemplate request; falling back to getwork protocol", pool->pool_no);
  4153. pool->proto = proto;
  4154. goto tryagain;
  4155. } else
  4156. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  4157. cgtime(&work->tv_getwork_reply);
  4158. timersub(&(work->tv_getwork_reply), &(work->tv_getwork), &tv_elapsed);
  4159. pool_stats->getwork_wait_rolling += ((double)tv_elapsed.tv_sec + ((double)tv_elapsed.tv_usec / 1000000)) * 0.63;
  4160. pool_stats->getwork_wait_rolling /= 1.63;
  4161. timeradd(&tv_elapsed, &(pool_stats->getwork_wait), &(pool_stats->getwork_wait));
  4162. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_max), >)) {
  4163. pool_stats->getwork_wait_max.tv_sec = tv_elapsed.tv_sec;
  4164. pool_stats->getwork_wait_max.tv_usec = tv_elapsed.tv_usec;
  4165. }
  4166. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_min), <)) {
  4167. pool_stats->getwork_wait_min.tv_sec = tv_elapsed.tv_sec;
  4168. pool_stats->getwork_wait_min.tv_usec = tv_elapsed.tv_usec;
  4169. }
  4170. pool_stats->getwork_calls++;
  4171. work->pool = pool;
  4172. work->longpoll = false;
  4173. calc_diff(work, 0);
  4174. total_getworks++;
  4175. pool->getwork_requested++;
  4176. if (rc)
  4177. update_last_work(work);
  4178. if (likely(val))
  4179. json_decref(val);
  4180. return rc;
  4181. }
  4182. #ifdef HAVE_CURSES
  4183. static void disable_curses(void)
  4184. {
  4185. if (curses_active_locked()) {
  4186. use_curses = false;
  4187. curses_active = false;
  4188. leaveok(logwin, false);
  4189. leaveok(statuswin, false);
  4190. leaveok(mainwin, false);
  4191. nocbreak();
  4192. echo();
  4193. delwin(logwin);
  4194. delwin(statuswin);
  4195. delwin(mainwin);
  4196. endwin();
  4197. #ifdef WIN32
  4198. // Move the cursor to after curses output.
  4199. HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
  4200. CONSOLE_SCREEN_BUFFER_INFO csbi;
  4201. COORD coord;
  4202. if (GetConsoleScreenBufferInfo(hout, &csbi)) {
  4203. coord.X = 0;
  4204. coord.Y = csbi.dwSize.Y - 1;
  4205. SetConsoleCursorPosition(hout, coord);
  4206. }
  4207. #endif
  4208. unlock_curses();
  4209. }
  4210. }
  4211. #endif
  4212. static void __kill_work(void)
  4213. {
  4214. struct cgpu_info *cgpu;
  4215. struct thr_info *thr;
  4216. int i;
  4217. if (!successful_connect)
  4218. return;
  4219. applog(LOG_INFO, "Received kill message");
  4220. shutting_down = true;
  4221. applog(LOG_DEBUG, "Prompting submit_work thread to finish");
  4222. notifier_wake(submit_waiting_notifier);
  4223. #ifdef USE_LIBMICROHTTPD
  4224. httpsrv_stop();
  4225. #endif
  4226. applog(LOG_DEBUG, "Killing off watchpool thread");
  4227. /* Kill the watchpool thread */
  4228. thr = &control_thr[watchpool_thr_id];
  4229. thr_info_cancel(thr);
  4230. applog(LOG_DEBUG, "Killing off watchdog thread");
  4231. /* Kill the watchdog thread */
  4232. thr = &control_thr[watchdog_thr_id];
  4233. thr_info_cancel(thr);
  4234. applog(LOG_DEBUG, "Shutting down mining threads");
  4235. for (i = 0; i < mining_threads; i++) {
  4236. thr = get_thread(i);
  4237. if (!thr)
  4238. continue;
  4239. cgpu = thr->cgpu;
  4240. if (!cgpu)
  4241. continue;
  4242. if (!cgpu->threads)
  4243. continue;
  4244. cgpu->shutdown = true;
  4245. thr->work_restart = true;
  4246. notifier_wake(thr->notifier);
  4247. notifier_wake(thr->work_restart_notifier);
  4248. }
  4249. sleep(1);
  4250. applog(LOG_DEBUG, "Killing off mining threads");
  4251. /* Kill the mining threads*/
  4252. for (i = 0; i < mining_threads; i++) {
  4253. thr = get_thread(i);
  4254. if (!thr)
  4255. continue;
  4256. cgpu = thr->cgpu;
  4257. if (cgpu->threads)
  4258. {
  4259. applog(LOG_WARNING, "Killing %"PRIpreprv, thr->cgpu->proc_repr);
  4260. thr_info_cancel(thr);
  4261. }
  4262. cgpu->status = LIFE_DEAD2;
  4263. }
  4264. /* Stop the others */
  4265. applog(LOG_DEBUG, "Killing off API thread");
  4266. thr = &control_thr[api_thr_id];
  4267. thr_info_cancel(thr);
  4268. }
  4269. /* This should be the common exit path */
  4270. void kill_work(void)
  4271. {
  4272. __kill_work();
  4273. quit(0, "Shutdown signal received.");
  4274. }
  4275. static
  4276. #ifdef WIN32
  4277. #ifndef _WIN64
  4278. const
  4279. #endif
  4280. #endif
  4281. char **initial_args;
  4282. void _bfg_clean_up(bool);
  4283. void app_restart(void)
  4284. {
  4285. applog(LOG_WARNING, "Attempting to restart %s", packagename);
  4286. __kill_work();
  4287. _bfg_clean_up(true);
  4288. #if defined(unix) || defined(__APPLE__)
  4289. if (forkpid > 0) {
  4290. kill(forkpid, SIGTERM);
  4291. forkpid = 0;
  4292. }
  4293. #endif
  4294. execv(initial_args[0], initial_args);
  4295. applog(LOG_WARNING, "Failed to restart application");
  4296. }
  4297. static void sighandler(int __maybe_unused sig)
  4298. {
  4299. /* Restore signal handlers so we can still quit if kill_work fails */
  4300. sigaction(SIGTERM, &termhandler, NULL);
  4301. sigaction(SIGINT, &inthandler, NULL);
  4302. kill_work();
  4303. }
  4304. static void start_longpoll(void);
  4305. static void stop_longpoll(void);
  4306. /* Called with pool_lock held. Recruit an extra curl if none are available for
  4307. * this pool. */
  4308. static void recruit_curl(struct pool *pool)
  4309. {
  4310. struct curl_ent *ce = calloc(sizeof(struct curl_ent), 1);
  4311. if (unlikely(!ce))
  4312. quit(1, "Failed to calloc in recruit_curl");
  4313. ce->curl = curl_easy_init();
  4314. if (unlikely(!ce->curl))
  4315. quit(1, "Failed to init in recruit_curl");
  4316. LL_PREPEND(pool->curllist, ce);
  4317. pool->curls++;
  4318. }
  4319. /* Grab an available curl if there is one. If not, then recruit extra curls
  4320. * unless we are in a submit_fail situation, or we have opt_delaynet enabled
  4321. * and there are already 5 curls in circulation. Limit total number to the
  4322. * number of mining threads per pool as well to prevent blasting a pool during
  4323. * network delays/outages. */
  4324. static struct curl_ent *pop_curl_entry3(struct pool *pool, int blocking)
  4325. {
  4326. int curl_limit = opt_delaynet ? 5 : (mining_threads + opt_queue) * 2;
  4327. bool recruited = false;
  4328. struct curl_ent *ce;
  4329. mutex_lock(&pool->pool_lock);
  4330. retry:
  4331. if (!pool->curls) {
  4332. recruit_curl(pool);
  4333. recruited = true;
  4334. } else if (!pool->curllist) {
  4335. if (blocking < 2 && pool->curls >= curl_limit && (blocking || pool->curls >= opt_submit_threads)) {
  4336. if (!blocking) {
  4337. mutex_unlock(&pool->pool_lock);
  4338. return NULL;
  4339. }
  4340. pthread_cond_wait(&pool->cr_cond, &pool->pool_lock);
  4341. goto retry;
  4342. } else {
  4343. recruit_curl(pool);
  4344. recruited = true;
  4345. }
  4346. }
  4347. ce = pool->curllist;
  4348. LL_DELETE(pool->curllist, ce);
  4349. mutex_unlock(&pool->pool_lock);
  4350. if (recruited)
  4351. applog(LOG_DEBUG, "Recruited curl for pool %d", pool->pool_no);
  4352. return ce;
  4353. }
  4354. static struct curl_ent *pop_curl_entry2(struct pool *pool, bool blocking)
  4355. {
  4356. return pop_curl_entry3(pool, blocking ? 1 : 0);
  4357. }
  4358. __maybe_unused
  4359. static struct curl_ent *pop_curl_entry(struct pool *pool)
  4360. {
  4361. return pop_curl_entry3(pool, 1);
  4362. }
  4363. static void push_curl_entry(struct curl_ent *ce, struct pool *pool)
  4364. {
  4365. mutex_lock(&pool->pool_lock);
  4366. if (!ce || !ce->curl)
  4367. quithere(1, "Attempted to add NULL");
  4368. LL_PREPEND(pool->curllist, ce);
  4369. cgtime(&ce->tv);
  4370. pthread_cond_broadcast(&pool->cr_cond);
  4371. mutex_unlock(&pool->pool_lock);
  4372. }
  4373. bool stale_work(struct work *work, bool share);
  4374. static inline bool should_roll(struct work *work)
  4375. {
  4376. struct timeval now;
  4377. time_t expiry;
  4378. if (work->pool != current_pool() && pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE)
  4379. return false;
  4380. if (stale_work(work, false))
  4381. return false;
  4382. if (work->rolltime > opt_scantime)
  4383. expiry = work->rolltime;
  4384. else
  4385. expiry = opt_scantime;
  4386. expiry = expiry * 2 / 3;
  4387. /* We shouldn't roll if we're unlikely to get one shares' duration
  4388. * work out of doing so */
  4389. cgtime(&now);
  4390. if (now.tv_sec - work->tv_staged.tv_sec > expiry)
  4391. return false;
  4392. return true;
  4393. }
  4394. /* Limit rolls to 7000 to not beyond 2 hours in the future where bitcoind will
  4395. * reject blocks as invalid. */
  4396. static inline bool can_roll(struct work *work)
  4397. {
  4398. if (work->stratum)
  4399. return false;
  4400. if (!(work->pool && !work->clone))
  4401. return false;
  4402. if (work->tmpl) {
  4403. if (stale_work(work, false))
  4404. return false;
  4405. return blkmk_work_left(work->tmpl);
  4406. }
  4407. return (work->rolltime &&
  4408. work->rolls < 7000 && !stale_work(work, false));
  4409. }
  4410. static void roll_work(struct work *work)
  4411. {
  4412. if (work->tmpl) {
  4413. struct timeval tv_now;
  4414. cgtime(&tv_now);
  4415. if (blkmk_get_data(work->tmpl, work->data, 80, tv_now.tv_sec, NULL, &work->dataid) < 76)
  4416. applog(LOG_ERR, "Failed to get next data from template; spinning wheels!");
  4417. swap32yes(work->data, work->data, 80 / 4);
  4418. calc_midstate(work);
  4419. applog(LOG_DEBUG, "Successfully rolled extranonce to dataid %u", work->dataid);
  4420. } else {
  4421. uint32_t *work_ntime;
  4422. uint32_t ntime;
  4423. work_ntime = (uint32_t *)(work->data + 68);
  4424. ntime = be32toh(*work_ntime);
  4425. ntime++;
  4426. *work_ntime = htobe32(ntime);
  4427. applog(LOG_DEBUG, "Successfully rolled time header in work");
  4428. }
  4429. local_work++;
  4430. work->rolls++;
  4431. work->blk.nonce = 0;
  4432. /* This is now a different work item so it needs a different ID for the
  4433. * hashtable */
  4434. work->id = total_work++;
  4435. }
  4436. /* Duplicates any dynamically allocated arrays within the work struct to
  4437. * prevent a copied work struct from freeing ram belonging to another struct */
  4438. static void _copy_work(struct work *work, const struct work *base_work, int noffset)
  4439. {
  4440. int id = work->id;
  4441. clean_work(work);
  4442. memcpy(work, base_work, sizeof(struct work));
  4443. /* Keep the unique new id assigned during make_work to prevent copied
  4444. * work from having the same id. */
  4445. work->id = id;
  4446. if (base_work->job_id)
  4447. work->job_id = strdup(base_work->job_id);
  4448. if (base_work->nonce1)
  4449. work->nonce1 = strdup(base_work->nonce1);
  4450. bytes_cpy(&work->nonce2, &base_work->nonce2);
  4451. if (base_work->tmpl) {
  4452. struct pool *pool = work->pool;
  4453. mutex_lock(&pool->pool_lock);
  4454. ++*work->tmpl_refcount;
  4455. mutex_unlock(&pool->pool_lock);
  4456. }
  4457. if (noffset)
  4458. {
  4459. uint32_t *work_ntime = (uint32_t *)(work->data + 68);
  4460. uint32_t ntime = be32toh(*work_ntime);
  4461. ntime += noffset;
  4462. *work_ntime = htobe32(ntime);
  4463. }
  4464. }
  4465. /* Generates a copy of an existing work struct, creating fresh heap allocations
  4466. * for all dynamically allocated arrays within the struct */
  4467. struct work *copy_work(const struct work *base_work)
  4468. {
  4469. struct work *work = make_work();
  4470. _copy_work(work, base_work, 0);
  4471. return work;
  4472. }
  4473. void __copy_work(struct work *work, const struct work *base_work)
  4474. {
  4475. _copy_work(work, base_work, 0);
  4476. }
  4477. static struct work *make_clone(struct work *work)
  4478. {
  4479. struct work *work_clone = copy_work(work);
  4480. work_clone->clone = true;
  4481. cgtime((struct timeval *)&(work_clone->tv_cloned));
  4482. work_clone->longpoll = false;
  4483. work_clone->mandatory = false;
  4484. /* Make cloned work appear slightly older to bias towards keeping the
  4485. * master work item which can be further rolled */
  4486. work_clone->tv_staged.tv_sec -= 1;
  4487. return work_clone;
  4488. }
  4489. static void stage_work(struct work *work);
  4490. static bool clone_available(void)
  4491. {
  4492. struct work *work_clone = NULL, *work, *tmp;
  4493. bool cloned = false;
  4494. mutex_lock(stgd_lock);
  4495. if (!staged_rollable)
  4496. goto out_unlock;
  4497. HASH_ITER(hh, staged_work, work, tmp) {
  4498. if (can_roll(work) && should_roll(work)) {
  4499. roll_work(work);
  4500. work_clone = make_clone(work);
  4501. applog(LOG_DEBUG, "%s: Rolling work %d to %d", __func__, work->id, work_clone->id);
  4502. roll_work(work);
  4503. cloned = true;
  4504. break;
  4505. }
  4506. }
  4507. out_unlock:
  4508. mutex_unlock(stgd_lock);
  4509. if (cloned) {
  4510. applog(LOG_DEBUG, "Pushing cloned available work to stage thread");
  4511. stage_work(work_clone);
  4512. }
  4513. return cloned;
  4514. }
  4515. static void pool_died(struct pool *pool)
  4516. {
  4517. if (!pool_tset(pool, &pool->idle)) {
  4518. cgtime(&pool->tv_idle);
  4519. if (pool == current_pool()) {
  4520. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  4521. switch_pools(NULL);
  4522. } else
  4523. applog(LOG_INFO, "Pool %d %s failed to return work", pool->pool_no, pool->rpc_url);
  4524. }
  4525. }
  4526. bool stale_work(struct work *work, bool share)
  4527. {
  4528. unsigned work_expiry;
  4529. struct pool *pool;
  4530. uint32_t block_id;
  4531. unsigned getwork_delay;
  4532. if (opt_benchmark)
  4533. return false;
  4534. block_id = ((uint32_t*)work->data)[1];
  4535. pool = work->pool;
  4536. /* Technically the rolltime should be correct but some pools
  4537. * advertise a broken expire= that is lower than a meaningful
  4538. * scantime */
  4539. if (work->rolltime >= opt_scantime || work->tmpl)
  4540. work_expiry = work->rolltime;
  4541. else
  4542. work_expiry = opt_expiry;
  4543. unsigned max_expiry = (have_longpoll ? opt_expiry_lp : opt_expiry);
  4544. if (work_expiry > max_expiry)
  4545. work_expiry = max_expiry;
  4546. if (share) {
  4547. /* If the share isn't on this pool's latest block, it's stale */
  4548. if (pool->block_id && pool->block_id != block_id)
  4549. {
  4550. applog(LOG_DEBUG, "Share stale due to block mismatch (%08lx != %08lx)", (long)block_id, (long)pool->block_id);
  4551. return true;
  4552. }
  4553. /* If the pool doesn't want old shares, then any found in work before
  4554. * the most recent longpoll is stale */
  4555. if ((!pool->submit_old) && work->work_restart_id != pool->work_restart_id)
  4556. {
  4557. applog(LOG_DEBUG, "Share stale due to mandatory work update (%02x != %02x)", work->work_restart_id, pool->work_restart_id);
  4558. return true;
  4559. }
  4560. } else {
  4561. /* If this work isn't for the latest Bitcoin block, it's stale */
  4562. /* But only care about the current pool if failover-only */
  4563. if (enabled_pools <= 1 || opt_fail_only) {
  4564. if (pool->block_id && block_id != pool->block_id)
  4565. {
  4566. applog(LOG_DEBUG, "Work stale due to block mismatch (%08lx != 1 ? %08lx : %08lx)", (long)block_id, (long)pool->block_id, (long)current_block_id);
  4567. return true;
  4568. }
  4569. } else {
  4570. if (block_id != current_block_id)
  4571. {
  4572. applog(LOG_DEBUG, "Work stale due to block mismatch (%08lx != 0 ? %08lx : %08lx)", (long)block_id, (long)pool->block_id, (long)current_block_id);
  4573. return true;
  4574. }
  4575. }
  4576. /* If the pool has asked us to restart since this work, it's stale */
  4577. if (work->work_restart_id != pool->work_restart_id)
  4578. {
  4579. applog(LOG_DEBUG, "Work stale due to work update (%02x != %02x)", work->work_restart_id, pool->work_restart_id);
  4580. return true;
  4581. }
  4582. if (pool->has_stratum && work->job_id) {
  4583. bool same_job;
  4584. if (!pool->stratum_active || !pool->stratum_notify) {
  4585. applog(LOG_DEBUG, "Work stale due to stratum inactive");
  4586. return true;
  4587. }
  4588. same_job = true;
  4589. cg_rlock(&pool->data_lock);
  4590. if (strcmp(work->job_id, pool->swork.job_id))
  4591. same_job = false;
  4592. cg_runlock(&pool->data_lock);
  4593. if (!same_job) {
  4594. applog(LOG_DEBUG, "Work stale due to stratum job_id mismatch");
  4595. return true;
  4596. }
  4597. }
  4598. /* Factor in the average getwork delay of this pool, rounding it up to
  4599. * the nearest second */
  4600. getwork_delay = pool->cgminer_pool_stats.getwork_wait_rolling * 5 + 1;
  4601. if (unlikely(work_expiry <= getwork_delay + 5))
  4602. work_expiry = 5;
  4603. else
  4604. work_expiry -= getwork_delay;
  4605. }
  4606. int elapsed_since_staged = timer_elapsed(&work->tv_staged, NULL);
  4607. if (elapsed_since_staged > work_expiry) {
  4608. applog(LOG_DEBUG, "%s stale due to expiry (%d >= %u)", share?"Share":"Work", elapsed_since_staged, work_expiry);
  4609. return true;
  4610. }
  4611. /* If the user only wants strict failover, any work from a pool other than
  4612. * the current one is always considered stale */
  4613. if (opt_fail_only && !share && pool != current_pool() && !work->mandatory &&
  4614. pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  4615. applog(LOG_DEBUG, "Work stale due to fail only pool mismatch (pool %u vs %u)", pool->pool_no, current_pool()->pool_no);
  4616. return true;
  4617. }
  4618. return false;
  4619. }
  4620. static uint64_t share_diff(const struct work *work)
  4621. {
  4622. uint64_t ret;
  4623. bool new_best = false;
  4624. ret = target_diff(work->hash);
  4625. cg_wlock(&control_lock);
  4626. if (unlikely(ret > best_diff)) {
  4627. new_best = true;
  4628. best_diff = ret;
  4629. suffix_string(best_diff, best_share, sizeof(best_share), 0);
  4630. }
  4631. if (unlikely(ret > work->pool->best_diff))
  4632. work->pool->best_diff = ret;
  4633. cg_wunlock(&control_lock);
  4634. if (unlikely(new_best))
  4635. applog(LOG_INFO, "New best share: %s", best_share);
  4636. return ret;
  4637. }
  4638. static void regen_hash(struct work *work)
  4639. {
  4640. hash_data(work->hash, work->data);
  4641. }
  4642. static void rebuild_hash(struct work *work)
  4643. {
  4644. if (opt_scrypt)
  4645. scrypt_regenhash(work);
  4646. else
  4647. regen_hash(work);
  4648. work->share_diff = share_diff(work);
  4649. if (unlikely(work->share_diff >= current_diff)) {
  4650. work->block = true;
  4651. work->pool->solved++;
  4652. found_blocks++;
  4653. work->mandatory = true;
  4654. applog(LOG_NOTICE, "Found block for pool %d!", work->pool->pool_no);
  4655. }
  4656. }
  4657. static void submit_discard_share2(const char *reason, struct work *work)
  4658. {
  4659. struct cgpu_info *cgpu = get_thr_cgpu(work->thr_id);
  4660. sharelog(reason, work);
  4661. mutex_lock(&stats_lock);
  4662. ++total_stale;
  4663. ++cgpu->stale;
  4664. ++(work->pool->stale_shares);
  4665. total_diff_stale += work->work_difficulty;
  4666. cgpu->diff_stale += work->work_difficulty;
  4667. work->pool->diff_stale += work->work_difficulty;
  4668. mutex_unlock(&stats_lock);
  4669. }
  4670. static void submit_discard_share(struct work *work)
  4671. {
  4672. submit_discard_share2("discard", work);
  4673. }
  4674. struct submit_work_state {
  4675. struct work *work;
  4676. bool resubmit;
  4677. struct curl_ent *ce;
  4678. int failures;
  4679. struct timeval tv_staleexpire;
  4680. char *s;
  4681. struct timeval tv_submit;
  4682. struct submit_work_state *next;
  4683. };
  4684. static int my_curl_timer_set(__maybe_unused CURLM *curlm, long timeout_ms, void *userp)
  4685. {
  4686. long *p_timeout_us = userp;
  4687. const long max_ms = LONG_MAX / 1000;
  4688. if (max_ms < timeout_ms)
  4689. timeout_ms = max_ms;
  4690. *p_timeout_us = timeout_ms * 1000;
  4691. return 0;
  4692. }
  4693. static void sws_has_ce(struct submit_work_state *sws)
  4694. {
  4695. struct pool *pool = sws->work->pool;
  4696. sws->s = submit_upstream_work_request(sws->work);
  4697. cgtime(&sws->tv_submit);
  4698. json_rpc_call_async(sws->ce->curl, pool->rpc_url, pool->rpc_userpass, sws->s, false, pool, true, sws);
  4699. }
  4700. static struct submit_work_state *begin_submission(struct work *work)
  4701. {
  4702. struct pool *pool;
  4703. struct submit_work_state *sws = NULL;
  4704. pool = work->pool;
  4705. sws = malloc(sizeof(*sws));
  4706. *sws = (struct submit_work_state){
  4707. .work = work,
  4708. };
  4709. rebuild_hash(work);
  4710. if (stale_work(work, true)) {
  4711. work->stale = true;
  4712. if (opt_submit_stale)
  4713. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as user requested", pool->pool_no);
  4714. else if (pool->submit_old)
  4715. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as pool requested", pool->pool_no);
  4716. else {
  4717. applog(LOG_NOTICE, "Pool %d stale share detected, discarding", pool->pool_no);
  4718. submit_discard_share(work);
  4719. goto out;
  4720. }
  4721. timer_set_delay_from_now(&sws->tv_staleexpire, 300000000);
  4722. }
  4723. if (work->stratum) {
  4724. char *s;
  4725. s = malloc(1024);
  4726. sws->s = s;
  4727. } else {
  4728. /* submit solution to bitcoin via JSON-RPC */
  4729. sws->ce = pop_curl_entry2(pool, false);
  4730. if (sws->ce) {
  4731. sws_has_ce(sws);
  4732. } else {
  4733. sws->next = pool->sws_waiting_on_curl;
  4734. pool->sws_waiting_on_curl = sws;
  4735. if (sws->next)
  4736. applog(LOG_DEBUG, "submit_thread queuing submission");
  4737. else
  4738. applog(LOG_WARNING, "submit_thread queuing submissions (see --submit-threads)");
  4739. }
  4740. }
  4741. return sws;
  4742. out:
  4743. free(sws);
  4744. return NULL;
  4745. }
  4746. static bool retry_submission(struct submit_work_state *sws)
  4747. {
  4748. struct work *work = sws->work;
  4749. struct pool *pool = work->pool;
  4750. sws->resubmit = true;
  4751. if ((!work->stale) && stale_work(work, true)) {
  4752. work->stale = true;
  4753. if (opt_submit_stale)
  4754. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, will retry as user requested", pool->pool_no);
  4755. else if (pool->submit_old)
  4756. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, will retry as pool requested", pool->pool_no);
  4757. else {
  4758. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, discarding", pool->pool_no);
  4759. submit_discard_share(work);
  4760. return false;
  4761. }
  4762. timer_set_delay_from_now(&sws->tv_staleexpire, 300000000);
  4763. }
  4764. if (unlikely((opt_retries >= 0) && (++sws->failures > opt_retries))) {
  4765. applog(LOG_ERR, "Pool %d failed %d submission retries, discarding", pool->pool_no, opt_retries);
  4766. submit_discard_share(work);
  4767. return false;
  4768. }
  4769. else if (work->stale) {
  4770. if (unlikely(opt_retries < 0 && timer_passed(&sws->tv_staleexpire, NULL)))
  4771. {
  4772. applog(LOG_NOTICE, "Pool %d stale share failed to submit for 5 minutes, discarding", pool->pool_no);
  4773. submit_discard_share(work);
  4774. return false;
  4775. }
  4776. }
  4777. /* pause, then restart work-request loop */
  4778. applog(LOG_INFO, "json_rpc_call failed on submit_work, retrying");
  4779. cgtime(&sws->tv_submit);
  4780. json_rpc_call_async(sws->ce->curl, pool->rpc_url, pool->rpc_userpass, sws->s, false, pool, true, sws);
  4781. return true;
  4782. }
  4783. static void free_sws(struct submit_work_state *sws)
  4784. {
  4785. free(sws->s);
  4786. free_work(sws->work);
  4787. free(sws);
  4788. }
  4789. static void *submit_work_thread(__maybe_unused void *userdata)
  4790. {
  4791. int wip = 0;
  4792. CURLM *curlm;
  4793. long curlm_timeout_us = -1;
  4794. struct timeval curlm_timer;
  4795. struct submit_work_state *sws, **swsp;
  4796. struct submit_work_state *write_sws = NULL;
  4797. unsigned tsreduce = 0;
  4798. pthread_detach(pthread_self());
  4799. RenameThread("submit_work");
  4800. applog(LOG_DEBUG, "Creating extra submit work thread");
  4801. curlm = curl_multi_init();
  4802. curlm_timeout_us = -1;
  4803. curl_multi_setopt(curlm, CURLMOPT_TIMERDATA, &curlm_timeout_us);
  4804. curl_multi_setopt(curlm, CURLMOPT_TIMERFUNCTION, my_curl_timer_set);
  4805. fd_set rfds, wfds, efds;
  4806. int maxfd;
  4807. struct timeval tv_timeout, tv_now;
  4808. int n;
  4809. CURLMsg *cm;
  4810. FD_ZERO(&rfds);
  4811. while (1) {
  4812. mutex_lock(&submitting_lock);
  4813. total_submitting -= tsreduce;
  4814. tsreduce = 0;
  4815. if (FD_ISSET(submit_waiting_notifier[0], &rfds)) {
  4816. notifier_read(submit_waiting_notifier);
  4817. }
  4818. // Receive any new submissions
  4819. while (submit_waiting) {
  4820. struct work *work = submit_waiting;
  4821. DL_DELETE(submit_waiting, work);
  4822. if ( (sws = begin_submission(work)) ) {
  4823. if (sws->ce)
  4824. curl_multi_add_handle(curlm, sws->ce->curl);
  4825. else if (sws->s) {
  4826. sws->next = write_sws;
  4827. write_sws = sws;
  4828. }
  4829. ++wip;
  4830. }
  4831. else {
  4832. --total_submitting;
  4833. free_work(work);
  4834. }
  4835. }
  4836. if (unlikely(shutting_down && !wip))
  4837. break;
  4838. mutex_unlock(&submitting_lock);
  4839. FD_ZERO(&rfds);
  4840. FD_ZERO(&wfds);
  4841. FD_ZERO(&efds);
  4842. tv_timeout.tv_sec = -1;
  4843. // Setup cURL with select
  4844. // Need to call perform to ensure the timeout gets updated
  4845. curl_multi_perform(curlm, &n);
  4846. curl_multi_fdset(curlm, &rfds, &wfds, &efds, &maxfd);
  4847. if (curlm_timeout_us >= 0)
  4848. {
  4849. timer_set_delay_from_now(&curlm_timer, curlm_timeout_us);
  4850. reduce_timeout_to(&tv_timeout, &curlm_timer);
  4851. }
  4852. // Setup waiting stratum submissions with select
  4853. for (sws = write_sws; sws; sws = sws->next)
  4854. {
  4855. struct pool *pool = sws->work->pool;
  4856. int fd = pool->sock;
  4857. if (fd == INVSOCK || (!pool->stratum_init) || !pool->stratum_notify)
  4858. continue;
  4859. FD_SET(fd, &wfds);
  4860. set_maxfd(&maxfd, fd);
  4861. }
  4862. // Setup "submit waiting" notifier with select
  4863. FD_SET(submit_waiting_notifier[0], &rfds);
  4864. set_maxfd(&maxfd, submit_waiting_notifier[0]);
  4865. // Wait for something interesting to happen :)
  4866. cgtime(&tv_now);
  4867. if (select(maxfd+1, &rfds, &wfds, &efds, select_timeout(&tv_timeout, &tv_now)) < 0) {
  4868. FD_ZERO(&rfds);
  4869. continue;
  4870. }
  4871. // Handle any stratum ready-to-write results
  4872. for (swsp = &write_sws; (sws = *swsp); ) {
  4873. struct work *work = sws->work;
  4874. struct pool *pool = work->pool;
  4875. int fd = pool->sock;
  4876. bool sessionid_match;
  4877. if (fd == INVSOCK || (!pool->stratum_init) || (!pool->stratum_notify) || !FD_ISSET(fd, &wfds)) {
  4878. next_write_sws:
  4879. // TODO: Check if stale, possibly discard etc
  4880. swsp = &sws->next;
  4881. continue;
  4882. }
  4883. cg_rlock(&pool->data_lock);
  4884. // 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
  4885. // NOTE: Worst case scenario for a false positive: the pool rejects it as H-not-zero
  4886. sessionid_match = (!pool->nonce1) || !strcmp(work->nonce1, pool->nonce1);
  4887. cg_runlock(&pool->data_lock);
  4888. if (!sessionid_match)
  4889. {
  4890. applog(LOG_DEBUG, "No matching session id for resubmitting stratum share");
  4891. submit_discard_share2("disconnect", work);
  4892. ++tsreduce;
  4893. next_write_sws_del:
  4894. // Clear the fd from wfds, to avoid potentially blocking on other submissions to the same socket
  4895. FD_CLR(fd, &wfds);
  4896. // Delete sws for this submission, since we're done with it
  4897. *swsp = sws->next;
  4898. free_sws(sws);
  4899. --wip;
  4900. continue;
  4901. }
  4902. char *s = sws->s;
  4903. struct stratum_share *sshare = calloc(sizeof(struct stratum_share), 1);
  4904. int sshare_id;
  4905. uint32_t nonce;
  4906. char nonce2hex[(bytes_len(&work->nonce2) * 2) + 1];
  4907. char noncehex[9];
  4908. char ntimehex[9];
  4909. sshare->work = copy_work(work);
  4910. bin2hex(nonce2hex, bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  4911. nonce = *((uint32_t *)(work->data + 76));
  4912. bin2hex(noncehex, (const unsigned char *)&nonce, 4);
  4913. bin2hex(ntimehex, (void *)&work->data[68], 4);
  4914. mutex_lock(&sshare_lock);
  4915. /* Give the stratum share a unique id */
  4916. sshare_id =
  4917. sshare->id = swork_id++;
  4918. HASH_ADD_INT(stratum_shares, id, sshare);
  4919. snprintf(s, 1024, "{\"params\": [\"%s\", \"%s\", \"%s\", \"%s\", \"%s\"], \"id\": %d, \"method\": \"mining.submit\"}",
  4920. pool->rpc_user, work->job_id, nonce2hex, ntimehex, noncehex, sshare->id);
  4921. mutex_unlock(&sshare_lock);
  4922. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->stratum_url, s);
  4923. if (likely(stratum_send(pool, s, strlen(s)))) {
  4924. if (pool_tclear(pool, &pool->submit_fail))
  4925. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  4926. applog(LOG_DEBUG, "Successfully submitted, adding to stratum_shares db");
  4927. goto next_write_sws_del;
  4928. } else if (!pool_tset(pool, &pool->submit_fail)) {
  4929. // Undo stuff
  4930. mutex_lock(&sshare_lock);
  4931. // NOTE: Need to find it again in case something else has consumed it already (like the stratum-disconnect resubmitter...)
  4932. HASH_FIND_INT(stratum_shares, &sshare_id, sshare);
  4933. if (sshare)
  4934. HASH_DEL(stratum_shares, sshare);
  4935. mutex_unlock(&sshare_lock);
  4936. if (sshare)
  4937. {
  4938. free_work(sshare->work);
  4939. free(sshare);
  4940. }
  4941. applog(LOG_WARNING, "Pool %d stratum share submission failure", pool->pool_no);
  4942. total_ro++;
  4943. pool->remotefail_occasions++;
  4944. if (!sshare)
  4945. goto next_write_sws_del;
  4946. goto next_write_sws;
  4947. }
  4948. }
  4949. // Handle any cURL activities
  4950. curl_multi_perform(curlm, &n);
  4951. while( (cm = curl_multi_info_read(curlm, &n)) ) {
  4952. if (cm->msg == CURLMSG_DONE)
  4953. {
  4954. bool finished;
  4955. json_t *val = json_rpc_call_completed(cm->easy_handle, cm->data.result, false, NULL, &sws);
  4956. curl_multi_remove_handle(curlm, cm->easy_handle);
  4957. finished = submit_upstream_work_completed(sws->work, sws->resubmit, &sws->tv_submit, val);
  4958. if (!finished) {
  4959. if (retry_submission(sws))
  4960. curl_multi_add_handle(curlm, sws->ce->curl);
  4961. else
  4962. finished = true;
  4963. }
  4964. if (finished) {
  4965. --wip;
  4966. ++tsreduce;
  4967. struct pool *pool = sws->work->pool;
  4968. if (pool->sws_waiting_on_curl) {
  4969. pool->sws_waiting_on_curl->ce = sws->ce;
  4970. sws_has_ce(pool->sws_waiting_on_curl);
  4971. pool->sws_waiting_on_curl = pool->sws_waiting_on_curl->next;
  4972. curl_multi_add_handle(curlm, sws->ce->curl);
  4973. } else {
  4974. push_curl_entry(sws->ce, sws->work->pool);
  4975. }
  4976. free_sws(sws);
  4977. }
  4978. }
  4979. }
  4980. }
  4981. assert(!write_sws);
  4982. mutex_unlock(&submitting_lock);
  4983. curl_multi_cleanup(curlm);
  4984. applog(LOG_DEBUG, "submit_work thread exiting");
  4985. return NULL;
  4986. }
  4987. /* Find the pool that currently has the highest priority */
  4988. static struct pool *priority_pool(int choice)
  4989. {
  4990. struct pool *ret = NULL;
  4991. int i;
  4992. for (i = 0; i < total_pools; i++) {
  4993. struct pool *pool = pools[i];
  4994. if (pool->prio == choice) {
  4995. ret = pool;
  4996. break;
  4997. }
  4998. }
  4999. if (unlikely(!ret)) {
  5000. applog(LOG_ERR, "WTF No pool %d found!", choice);
  5001. return pools[choice];
  5002. }
  5003. return ret;
  5004. }
  5005. int prioritize_pools(char *param, int *pid)
  5006. {
  5007. char *ptr, *next;
  5008. int i, pr, prio = 0;
  5009. if (total_pools == 0) {
  5010. return MSG_NOPOOL;
  5011. }
  5012. if (param == NULL || *param == '\0') {
  5013. return MSG_MISPID;
  5014. }
  5015. bool pools_changed[total_pools];
  5016. int new_prio[total_pools];
  5017. for (i = 0; i < total_pools; ++i)
  5018. pools_changed[i] = false;
  5019. next = param;
  5020. while (next && *next) {
  5021. ptr = next;
  5022. next = strchr(ptr, ',');
  5023. if (next)
  5024. *(next++) = '\0';
  5025. i = atoi(ptr);
  5026. if (i < 0 || i >= total_pools) {
  5027. *pid = i;
  5028. return MSG_INVPID;
  5029. }
  5030. if (pools_changed[i]) {
  5031. *pid = i;
  5032. return MSG_DUPPID;
  5033. }
  5034. pools_changed[i] = true;
  5035. new_prio[i] = prio++;
  5036. }
  5037. // Only change them if no errors
  5038. for (i = 0; i < total_pools; i++) {
  5039. if (pools_changed[i])
  5040. pools[i]->prio = new_prio[i];
  5041. }
  5042. // In priority order, cycle through the unchanged pools and append them
  5043. for (pr = 0; pr < total_pools; pr++)
  5044. for (i = 0; i < total_pools; i++) {
  5045. if (!pools_changed[i] && pools[i]->prio == pr) {
  5046. pools[i]->prio = prio++;
  5047. pools_changed[i] = true;
  5048. break;
  5049. }
  5050. }
  5051. if (current_pool()->prio)
  5052. switch_pools(NULL);
  5053. return MSG_POOLPRIO;
  5054. }
  5055. void validate_pool_priorities(void)
  5056. {
  5057. // TODO: this should probably do some sort of logging
  5058. int i, j;
  5059. bool used[total_pools];
  5060. bool valid[total_pools];
  5061. for (i = 0; i < total_pools; i++)
  5062. used[i] = valid[i] = false;
  5063. for (i = 0; i < total_pools; i++) {
  5064. if (pools[i]->prio >=0 && pools[i]->prio < total_pools) {
  5065. if (!used[pools[i]->prio]) {
  5066. valid[i] = true;
  5067. used[pools[i]->prio] = true;
  5068. }
  5069. }
  5070. }
  5071. for (i = 0; i < total_pools; i++) {
  5072. if (!valid[i]) {
  5073. for (j = 0; j < total_pools; j++) {
  5074. if (!used[j]) {
  5075. applog(LOG_WARNING, "Pool %d priority changed from %d to %d", i, pools[i]->prio, j);
  5076. pools[i]->prio = j;
  5077. used[j] = true;
  5078. break;
  5079. }
  5080. }
  5081. }
  5082. }
  5083. }
  5084. static void clear_pool_work(struct pool *pool);
  5085. /* Specifies whether we can switch to this pool or not. */
  5086. static bool pool_unusable(struct pool *pool)
  5087. {
  5088. if (pool->idle)
  5089. return true;
  5090. if (pool->enabled != POOL_ENABLED)
  5091. return true;
  5092. return false;
  5093. }
  5094. void switch_pools(struct pool *selected)
  5095. {
  5096. struct pool *pool, *last_pool;
  5097. int i, pool_no, next_pool;
  5098. cg_wlock(&control_lock);
  5099. last_pool = currentpool;
  5100. pool_no = currentpool->pool_no;
  5101. /* Switch selected to pool number 0 and move the rest down */
  5102. if (selected) {
  5103. if (selected->prio != 0) {
  5104. for (i = 0; i < total_pools; i++) {
  5105. pool = pools[i];
  5106. if (pool->prio < selected->prio)
  5107. pool->prio++;
  5108. }
  5109. selected->prio = 0;
  5110. }
  5111. }
  5112. switch (pool_strategy) {
  5113. /* All of these set to the master pool */
  5114. case POOL_BALANCE:
  5115. case POOL_FAILOVER:
  5116. case POOL_LOADBALANCE:
  5117. for (i = 0; i < total_pools; i++) {
  5118. pool = priority_pool(i);
  5119. if (pool_unusable(pool))
  5120. continue;
  5121. pool_no = pool->pool_no;
  5122. break;
  5123. }
  5124. break;
  5125. /* Both of these simply increment and cycle */
  5126. case POOL_ROUNDROBIN:
  5127. case POOL_ROTATE:
  5128. if (selected && !selected->idle) {
  5129. pool_no = selected->pool_no;
  5130. break;
  5131. }
  5132. next_pool = pool_no;
  5133. /* Select the next alive pool */
  5134. for (i = 1; i < total_pools; i++) {
  5135. next_pool++;
  5136. if (next_pool >= total_pools)
  5137. next_pool = 0;
  5138. pool = pools[next_pool];
  5139. if (pool_unusable(pool))
  5140. continue;
  5141. pool_no = next_pool;
  5142. break;
  5143. }
  5144. break;
  5145. default:
  5146. break;
  5147. }
  5148. currentpool = pools[pool_no];
  5149. pool = currentpool;
  5150. cg_wunlock(&control_lock);
  5151. /* Set the lagging flag to avoid pool not providing work fast enough
  5152. * messages in failover only mode since we have to get all fresh work
  5153. * as in restart_threads */
  5154. if (opt_fail_only)
  5155. pool_tset(pool, &pool->lagging);
  5156. if (pool != last_pool)
  5157. {
  5158. pool->block_id = 0;
  5159. if (pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  5160. applog(LOG_WARNING, "Switching to pool %d %s", pool->pool_no, pool->rpc_url);
  5161. if (pool_localgen(pool) || opt_fail_only)
  5162. clear_pool_work(last_pool);
  5163. }
  5164. }
  5165. mutex_lock(&lp_lock);
  5166. pthread_cond_broadcast(&lp_cond);
  5167. mutex_unlock(&lp_lock);
  5168. }
  5169. static void discard_work(struct work *work)
  5170. {
  5171. if (!work->clone && !work->rolls && !work->mined) {
  5172. if (work->pool) {
  5173. work->pool->discarded_work++;
  5174. work->pool->quota_used--;
  5175. work->pool->works--;
  5176. }
  5177. total_discarded++;
  5178. applog(LOG_DEBUG, "Discarded work");
  5179. } else
  5180. applog(LOG_DEBUG, "Discarded cloned or rolled work");
  5181. free_work(work);
  5182. }
  5183. static void wake_gws(void)
  5184. {
  5185. mutex_lock(stgd_lock);
  5186. pthread_cond_signal(&gws_cond);
  5187. mutex_unlock(stgd_lock);
  5188. }
  5189. static void discard_stale(void)
  5190. {
  5191. struct work *work, *tmp;
  5192. int stale = 0;
  5193. mutex_lock(stgd_lock);
  5194. HASH_ITER(hh, staged_work, work, tmp) {
  5195. if (stale_work(work, false)) {
  5196. HASH_DEL(staged_work, work);
  5197. discard_work(work);
  5198. stale++;
  5199. staged_full = false;
  5200. }
  5201. }
  5202. pthread_cond_signal(&gws_cond);
  5203. mutex_unlock(stgd_lock);
  5204. if (stale)
  5205. applog(LOG_DEBUG, "Discarded %d stales that didn't match current hash", stale);
  5206. }
  5207. bool stale_work_future(struct work *work, bool share, unsigned long ustime)
  5208. {
  5209. bool rv;
  5210. struct timeval tv, orig;
  5211. ldiv_t d;
  5212. d = ldiv(ustime, 1000000);
  5213. tv = (struct timeval){
  5214. .tv_sec = d.quot,
  5215. .tv_usec = d.rem,
  5216. };
  5217. orig = work->tv_staged;
  5218. timersub(&orig, &tv, &work->tv_staged);
  5219. rv = stale_work(work, share);
  5220. work->tv_staged = orig;
  5221. return rv;
  5222. }
  5223. static void restart_threads(void)
  5224. {
  5225. struct pool *cp = current_pool();
  5226. int i;
  5227. struct thr_info *thr;
  5228. /* Artificially set the lagging flag to avoid pool not providing work
  5229. * fast enough messages after every long poll */
  5230. pool_tset(cp, &cp->lagging);
  5231. /* Discard staged work that is now stale */
  5232. discard_stale();
  5233. rd_lock(&mining_thr_lock);
  5234. for (i = 0; i < mining_threads; i++)
  5235. {
  5236. thr = mining_thr[i];
  5237. thr->work_restart = true;
  5238. }
  5239. for (i = 0; i < mining_threads; i++)
  5240. {
  5241. thr = mining_thr[i];
  5242. notifier_wake(thr->work_restart_notifier);
  5243. }
  5244. rd_unlock(&mining_thr_lock);
  5245. }
  5246. static
  5247. void blkhashstr(char *rv, const unsigned char *hash)
  5248. {
  5249. unsigned char hash_swap[32];
  5250. swap256(hash_swap, hash);
  5251. swap32tole(hash_swap, hash_swap, 32 / 4);
  5252. bin2hex(rv, hash_swap, 32);
  5253. }
  5254. static void set_curblock(char *hexstr, unsigned char *hash)
  5255. {
  5256. unsigned char hash_swap[32];
  5257. current_block_id = ((uint32_t*)hash)[0];
  5258. strcpy(current_block, hexstr);
  5259. swap256(hash_swap, hash);
  5260. swap32tole(hash_swap, hash_swap, 32 / 4);
  5261. cg_wlock(&ch_lock);
  5262. block_time = time(NULL);
  5263. __update_block_title(hash_swap);
  5264. free(current_fullhash);
  5265. current_fullhash = malloc(65);
  5266. bin2hex(current_fullhash, hash_swap, 32);
  5267. get_timestamp(blocktime, sizeof(blocktime), block_time);
  5268. cg_wunlock(&ch_lock);
  5269. applog(LOG_INFO, "New block: %s diff %s (%s)", current_hash, block_diff, net_hashrate);
  5270. }
  5271. /* Search to see if this string is from a block that has been seen before */
  5272. static bool block_exists(char *hexstr)
  5273. {
  5274. struct block *s;
  5275. rd_lock(&blk_lock);
  5276. HASH_FIND_STR(blocks, hexstr, s);
  5277. rd_unlock(&blk_lock);
  5278. if (s)
  5279. return true;
  5280. return false;
  5281. }
  5282. /* Tests if this work is from a block that has been seen before */
  5283. static inline bool from_existing_block(struct work *work)
  5284. {
  5285. char hexstr[37];
  5286. bool ret;
  5287. bin2hex(hexstr, work->data + 8, 18);
  5288. ret = block_exists(hexstr);
  5289. return ret;
  5290. }
  5291. static int block_sort(struct block *blocka, struct block *blockb)
  5292. {
  5293. return blocka->block_no - blockb->block_no;
  5294. }
  5295. static void set_blockdiff(const struct work *work)
  5296. {
  5297. unsigned char target[32];
  5298. double diff;
  5299. uint64_t diff64;
  5300. real_block_target(target, work->data);
  5301. diff = target_diff(target);
  5302. diff64 = diff;
  5303. suffix_string(diff64, block_diff, sizeof(block_diff), 0);
  5304. format_unit2(net_hashrate, sizeof(net_hashrate),
  5305. true, "h/s", H2B_SHORT, diff * 7158278, -1);
  5306. if (unlikely(current_diff != diff))
  5307. applog(LOG_NOTICE, "Network difficulty changed to %s (%s)", block_diff, net_hashrate);
  5308. current_diff = diff;
  5309. }
  5310. static bool test_work_current(struct work *work)
  5311. {
  5312. bool ret = true;
  5313. char hexstr[65];
  5314. if (work->mandatory)
  5315. return ret;
  5316. uint32_t block_id = ((uint32_t*)(work->data))[1];
  5317. /* Hack to work around dud work sneaking into test */
  5318. bin2hex(hexstr, work->data + 8, 18);
  5319. if (!strncmp(hexstr, "000000000000000000000000000000000000", 36))
  5320. goto out_free;
  5321. /* Search to see if this block exists yet and if not, consider it a
  5322. * new block and set the current block details to this one */
  5323. if (!block_exists(hexstr)) {
  5324. struct block *s = calloc(sizeof(struct block), 1);
  5325. int deleted_block = 0;
  5326. ret = false;
  5327. if (unlikely(!s))
  5328. quit (1, "test_work_current OOM");
  5329. strcpy(s->hash, hexstr);
  5330. s->block_no = new_blocks++;
  5331. wr_lock(&blk_lock);
  5332. /* Only keep the last hour's worth of blocks in memory since
  5333. * work from blocks before this is virtually impossible and we
  5334. * want to prevent memory usage from continually rising */
  5335. if (HASH_COUNT(blocks) > 6) {
  5336. struct block *oldblock;
  5337. HASH_SORT(blocks, block_sort);
  5338. oldblock = blocks;
  5339. deleted_block = oldblock->block_no;
  5340. HASH_DEL(blocks, oldblock);
  5341. free(oldblock);
  5342. }
  5343. HASH_ADD_STR(blocks, hash, s);
  5344. set_blockdiff(work);
  5345. wr_unlock(&blk_lock);
  5346. work->pool->block_id = block_id;
  5347. if (deleted_block)
  5348. applog(LOG_DEBUG, "Deleted block %d from database", deleted_block);
  5349. #if BLKMAKER_VERSION > 1
  5350. template_nonce = 0;
  5351. #endif
  5352. set_curblock(hexstr, &work->data[4]);
  5353. if (unlikely(new_blocks == 1))
  5354. goto out_free;
  5355. if (!work->stratum) {
  5356. if (work->longpoll) {
  5357. applog(LOG_NOTICE, "Longpoll from pool %d detected new block",
  5358. work->pool->pool_no);
  5359. } else if (have_longpoll)
  5360. applog(LOG_NOTICE, "New block detected on network before longpoll");
  5361. else
  5362. applog(LOG_NOTICE, "New block detected on network");
  5363. }
  5364. restart_threads();
  5365. } else {
  5366. bool restart = false;
  5367. struct pool *curpool = NULL;
  5368. if (unlikely(work->pool->block_id != block_id)) {
  5369. bool was_active = work->pool->block_id != 0;
  5370. work->pool->block_id = block_id;
  5371. if (!work->longpoll)
  5372. update_last_work(work);
  5373. if (was_active) { // Pool actively changed block
  5374. if (work->pool == (curpool = current_pool()))
  5375. restart = true;
  5376. if (block_id == current_block_id) {
  5377. // Caught up, only announce if this pool is the one in use
  5378. if (restart)
  5379. applog(LOG_NOTICE, "%s %d caught up to new block",
  5380. work->longpoll ? "Longpoll from pool" : "Pool",
  5381. work->pool->pool_no);
  5382. } else {
  5383. // Switched to a block we know, but not the latest... why?
  5384. // This might detect pools trying to double-spend or 51%,
  5385. // but let's not make any accusations until it's had time
  5386. // in the real world.
  5387. blkhashstr(hexstr, &work->data[4]);
  5388. applog(LOG_WARNING, "%s %d is issuing work for an old block: %s",
  5389. work->longpoll ? "Longpoll from pool" : "Pool",
  5390. work->pool->pool_no,
  5391. hexstr);
  5392. }
  5393. }
  5394. }
  5395. if (work->longpoll) {
  5396. ++work->pool->work_restart_id;
  5397. update_last_work(work);
  5398. if ((!restart) && work->pool == current_pool()) {
  5399. applog(
  5400. (opt_quiet_work_updates ? LOG_DEBUG : LOG_NOTICE),
  5401. "Longpoll from pool %d requested work update",
  5402. work->pool->pool_no);
  5403. restart = true;
  5404. }
  5405. }
  5406. if (restart)
  5407. restart_threads();
  5408. }
  5409. work->longpoll = false;
  5410. out_free:
  5411. return ret;
  5412. }
  5413. static int tv_sort(struct work *worka, struct work *workb)
  5414. {
  5415. return worka->tv_staged.tv_sec - workb->tv_staged.tv_sec;
  5416. }
  5417. static bool work_rollable(struct work *work)
  5418. {
  5419. return (!work->clone && work->rolltime);
  5420. }
  5421. static bool hash_push(struct work *work)
  5422. {
  5423. bool rc = true;
  5424. mutex_lock(stgd_lock);
  5425. if (work_rollable(work))
  5426. staged_rollable++;
  5427. if (likely(!getq->frozen)) {
  5428. HASH_ADD_INT(staged_work, id, work);
  5429. HASH_SORT(staged_work, tv_sort);
  5430. } else
  5431. rc = false;
  5432. pthread_cond_broadcast(&getq->cond);
  5433. mutex_unlock(stgd_lock);
  5434. return rc;
  5435. }
  5436. static void stage_work(struct work *work)
  5437. {
  5438. applog(LOG_DEBUG, "Pushing work %d from pool %d to hash queue",
  5439. work->id, work->pool->pool_no);
  5440. work->work_restart_id = work->pool->work_restart_id;
  5441. work->pool->last_work_time = time(NULL);
  5442. cgtime(&work->pool->tv_last_work_time);
  5443. test_work_current(work);
  5444. work->pool->works++;
  5445. hash_push(work);
  5446. }
  5447. #ifdef HAVE_CURSES
  5448. int curses_int(const char *query)
  5449. {
  5450. int ret;
  5451. char *cvar;
  5452. cvar = curses_input(query);
  5453. if (unlikely(!cvar))
  5454. return -1;
  5455. ret = atoi(cvar);
  5456. free(cvar);
  5457. return ret;
  5458. }
  5459. #endif
  5460. #ifdef HAVE_CURSES
  5461. static bool input_pool(bool live);
  5462. #endif
  5463. #ifdef HAVE_CURSES
  5464. static void display_pool_summary(struct pool *pool)
  5465. {
  5466. double efficiency = 0.0;
  5467. char xfer[17], bw[19];
  5468. int pool_secs;
  5469. if (curses_active_locked()) {
  5470. wlog("Pool: %s\n", pool->rpc_url);
  5471. if (pool->solved)
  5472. wlog("SOLVED %d BLOCK%s!\n", pool->solved, pool->solved > 1 ? "S" : "");
  5473. if (!pool->has_stratum)
  5474. wlog("%s own long-poll support\n", pool->lp_url ? "Has" : "Does not have");
  5475. wlog(" Queued work requests: %d\n", pool->getwork_requested);
  5476. wlog(" Share submissions: %d\n", pool->accepted + pool->rejected);
  5477. wlog(" Accepted shares: %d\n", pool->accepted);
  5478. wlog(" Rejected shares: %d + %d stale (%.2f%%)\n",
  5479. pool->rejected, pool->stale_shares,
  5480. (float)(pool->rejected + pool->stale_shares) / (float)(pool->rejected + pool->stale_shares + pool->accepted)
  5481. );
  5482. wlog(" Accepted difficulty shares: %1.f\n", pool->diff_accepted);
  5483. wlog(" Rejected difficulty shares: %1.f\n", pool->diff_rejected);
  5484. pool_secs = timer_elapsed(&pool->cgminer_stats.start_tv, NULL);
  5485. wlog(" Network transfer: %s (%s)\n",
  5486. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  5487. (float)pool->cgminer_pool_stats.net_bytes_received,
  5488. (float)pool->cgminer_pool_stats.net_bytes_sent),
  5489. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  5490. (float)(pool->cgminer_pool_stats.net_bytes_received / pool_secs),
  5491. (float)(pool->cgminer_pool_stats.net_bytes_sent / pool_secs)));
  5492. uint64_t pool_bytes_xfer = pool->cgminer_pool_stats.net_bytes_received + pool->cgminer_pool_stats.net_bytes_sent;
  5493. efficiency = pool_bytes_xfer ? pool->diff_accepted * 2048. / pool_bytes_xfer : 0.0;
  5494. wlog(" Efficiency (accepted * difficulty / 2 KB): %.2f\n", efficiency);
  5495. wlog(" Items worked on: %d\n", pool->works);
  5496. wlog(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  5497. wlog(" Unable to get work from server occasions: %d\n", pool->getfail_occasions);
  5498. wlog(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  5499. unlock_curses();
  5500. }
  5501. }
  5502. #endif
  5503. /* We can't remove the memory used for this struct pool because there may
  5504. * still be work referencing it. We just remove it from the pools list */
  5505. void remove_pool(struct pool *pool)
  5506. {
  5507. int i, last_pool = total_pools - 1;
  5508. struct pool *other;
  5509. /* Boost priority of any lower prio than this one */
  5510. for (i = 0; i < total_pools; i++) {
  5511. other = pools[i];
  5512. if (other->prio > pool->prio)
  5513. other->prio--;
  5514. }
  5515. if (pool->pool_no < last_pool) {
  5516. /* Swap the last pool for this one */
  5517. (pools[last_pool])->pool_no = pool->pool_no;
  5518. pools[pool->pool_no] = pools[last_pool];
  5519. }
  5520. /* Give it an invalid number */
  5521. pool->pool_no = total_pools;
  5522. pool->removed = true;
  5523. pool->has_stratum = false;
  5524. total_pools--;
  5525. }
  5526. /* add a mutex if this needs to be thread safe in the future */
  5527. static struct JE {
  5528. char *buf;
  5529. struct JE *next;
  5530. } *jedata = NULL;
  5531. static void json_escape_free()
  5532. {
  5533. struct JE *jeptr = jedata;
  5534. struct JE *jenext;
  5535. jedata = NULL;
  5536. while (jeptr) {
  5537. jenext = jeptr->next;
  5538. free(jeptr->buf);
  5539. free(jeptr);
  5540. jeptr = jenext;
  5541. }
  5542. }
  5543. static
  5544. char *json_escape(const char *str)
  5545. {
  5546. struct JE *jeptr;
  5547. char *buf, *ptr;
  5548. /* 2x is the max, may as well just allocate that */
  5549. ptr = buf = malloc(strlen(str) * 2 + 1);
  5550. jeptr = malloc(sizeof(*jeptr));
  5551. jeptr->buf = buf;
  5552. jeptr->next = jedata;
  5553. jedata = jeptr;
  5554. while (*str) {
  5555. if (*str == '\\' || *str == '"')
  5556. *(ptr++) = '\\';
  5557. *(ptr++) = *(str++);
  5558. }
  5559. *ptr = '\0';
  5560. return buf;
  5561. }
  5562. static
  5563. void _write_config_string_elist(FILE *fcfg, const char *configname, struct string_elist * const elist)
  5564. {
  5565. if (!elist)
  5566. return;
  5567. static struct string_elist *entry;
  5568. fprintf(fcfg, ",\n\"%s\" : [", configname);
  5569. bool first = true;
  5570. DL_FOREACH(elist, entry)
  5571. {
  5572. const char * const s = entry->string;
  5573. fprintf(fcfg, "%s\n\t\"%s\"", first ? "" : ",", json_escape(s));
  5574. first = false;
  5575. }
  5576. fprintf(fcfg, "\n]");
  5577. }
  5578. void write_config(FILE *fcfg)
  5579. {
  5580. int i;
  5581. /* Write pool values */
  5582. fputs("{\n\"pools\" : [", fcfg);
  5583. for(i = 0; i < total_pools; i++) {
  5584. struct pool *pool = pools[i];
  5585. if (pool->quota != 1) {
  5586. fprintf(fcfg, "%s\n\t{\n\t\t\"quota\" : \"%d;%s\",", i > 0 ? "," : "",
  5587. pool->quota,
  5588. json_escape(pool->rpc_url));
  5589. } else {
  5590. fprintf(fcfg, "%s\n\t{\n\t\t\"url\" : \"%s\",", i > 0 ? "," : "",
  5591. json_escape(pool->rpc_url));
  5592. }
  5593. if (pool->rpc_proxy)
  5594. fprintf(fcfg, "\n\t\t\"pool-proxy\" : \"%s\",", json_escape(pool->rpc_proxy));
  5595. fprintf(fcfg, "\n\t\t\"user\" : \"%s\",", json_escape(pool->rpc_user));
  5596. fprintf(fcfg, "\n\t\t\"pass\" : \"%s\",", json_escape(pool->rpc_pass));
  5597. fprintf(fcfg, "\n\t\t\"pool-priority\" : \"%d\"", pool->prio);
  5598. if (pool->force_rollntime)
  5599. fprintf(fcfg, ",\n\t\t\"force-rollntime\" : %d", pool->force_rollntime);
  5600. fprintf(fcfg, "\n\t}");
  5601. }
  5602. fputs("\n]\n", fcfg);
  5603. #ifdef HAVE_OPENCL
  5604. if (nDevs) {
  5605. /* Write GPU device values */
  5606. fputs(",\n\"intensity\" : \"", fcfg);
  5607. for(i = 0; i < nDevs; i++)
  5608. {
  5609. if (i > 0)
  5610. fputc(',', fcfg);
  5611. if (gpus[i].dynamic)
  5612. fputc('d', fcfg);
  5613. else
  5614. fprintf(fcfg, "%d", gpus[i].intensity);
  5615. }
  5616. fputs("\",\n\"vectors\" : \"", fcfg);
  5617. for(i = 0; i < nDevs; i++)
  5618. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  5619. gpus[i].vwidth);
  5620. fputs("\",\n\"worksize\" : \"", fcfg);
  5621. for(i = 0; i < nDevs; i++)
  5622. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  5623. (int)gpus[i].work_size);
  5624. fputs("\",\n\"kernel\" : \"", fcfg);
  5625. for(i = 0; i < nDevs; i++) {
  5626. fprintf(fcfg, "%s", i > 0 ? "," : "");
  5627. switch (gpus[i].kernel) {
  5628. case KL_NONE: // Shouldn't happen
  5629. break;
  5630. case KL_POCLBM:
  5631. fprintf(fcfg, "poclbm");
  5632. break;
  5633. case KL_PHATK:
  5634. fprintf(fcfg, "phatk");
  5635. break;
  5636. case KL_DIAKGCN:
  5637. fprintf(fcfg, "diakgcn");
  5638. break;
  5639. case KL_DIABLO:
  5640. fprintf(fcfg, "diablo");
  5641. break;
  5642. case KL_SCRYPT:
  5643. fprintf(fcfg, "scrypt");
  5644. break;
  5645. }
  5646. }
  5647. #ifdef USE_SCRYPT
  5648. fputs("\",\n\"lookup-gap\" : \"", fcfg);
  5649. for(i = 0; i < nDevs; i++)
  5650. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  5651. (int)gpus[i].opt_lg);
  5652. fputs("\",\n\"thread-concurrency\" : \"", fcfg);
  5653. for(i = 0; i < nDevs; i++)
  5654. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  5655. (int)gpus[i].opt_tc);
  5656. fputs("\",\n\"shaders\" : \"", fcfg);
  5657. for(i = 0; i < nDevs; i++)
  5658. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  5659. (int)gpus[i].shaders);
  5660. #endif
  5661. #ifdef HAVE_ADL
  5662. fputs("\",\n\"gpu-engine\" : \"", fcfg);
  5663. for(i = 0; i < nDevs; i++)
  5664. fprintf(fcfg, "%s%d-%d", i > 0 ? "," : "", gpus[i].min_engine, gpus[i].gpu_engine);
  5665. fputs("\",\n\"gpu-fan\" : \"", fcfg);
  5666. for(i = 0; i < nDevs; i++)
  5667. fprintf(fcfg, "%s%d-%d", i > 0 ? "," : "", gpus[i].min_fan, gpus[i].gpu_fan);
  5668. fputs("\",\n\"gpu-memclock\" : \"", fcfg);
  5669. for(i = 0; i < nDevs; i++)
  5670. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_memclock);
  5671. fputs("\",\n\"gpu-memdiff\" : \"", fcfg);
  5672. for(i = 0; i < nDevs; i++)
  5673. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_memdiff);
  5674. fputs("\",\n\"gpu-powertune\" : \"", fcfg);
  5675. for(i = 0; i < nDevs; i++)
  5676. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_powertune);
  5677. fputs("\",\n\"gpu-vddc\" : \"", fcfg);
  5678. for(i = 0; i < nDevs; i++)
  5679. fprintf(fcfg, "%s%1.3f", i > 0 ? "," : "", gpus[i].gpu_vddc);
  5680. fputs("\",\n\"temp-overheat\" : \"", fcfg);
  5681. for(i = 0; i < nDevs; i++)
  5682. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].adl.overtemp);
  5683. #endif
  5684. fputs("\"", fcfg);
  5685. }
  5686. #endif
  5687. #ifdef HAVE_ADL
  5688. if (opt_reorder)
  5689. fprintf(fcfg, ",\n\"gpu-reorder\" : true");
  5690. #endif
  5691. #ifdef WANT_CPUMINE
  5692. fprintf(fcfg, ",\n\"algo\" : \"%s\"", algo_names[opt_algo]);
  5693. #endif
  5694. /* Simple bool and int options */
  5695. struct opt_table *opt;
  5696. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  5697. char *p, *name = strdup(opt->names);
  5698. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  5699. if (p[1] != '-')
  5700. continue;
  5701. if (opt->type & OPT_NOARG &&
  5702. ((void *)opt->cb == (void *)opt_set_bool || (void *)opt->cb == (void *)opt_set_invbool) &&
  5703. (*(bool *)opt->u.arg == ((void *)opt->cb == (void *)opt_set_bool)))
  5704. fprintf(fcfg, ",\n\"%s\" : true", p+2);
  5705. if (opt->type & OPT_HASARG &&
  5706. ((void *)opt->cb_arg == (void *)set_int_0_to_9999 ||
  5707. (void *)opt->cb_arg == (void *)set_int_1_to_65535 ||
  5708. (void *)opt->cb_arg == (void *)set_int_0_to_10 ||
  5709. (void *)opt->cb_arg == (void *)set_int_1_to_10) &&
  5710. opt->desc != opt_hidden &&
  5711. 0 <= *(int *)opt->u.arg)
  5712. fprintf(fcfg, ",\n\"%s\" : \"%d\"", p+2, *(int *)opt->u.arg);
  5713. }
  5714. }
  5715. /* Special case options */
  5716. if (request_target_str)
  5717. {
  5718. if (request_pdiff == (long)request_pdiff)
  5719. fprintf(fcfg, ",\n\"request-diff\" : %ld", (long)request_pdiff);
  5720. else
  5721. fprintf(fcfg, ",\n\"request-diff\" : %f", request_pdiff);
  5722. }
  5723. fprintf(fcfg, ",\n\"shares\" : \"%d\"", opt_shares);
  5724. if (pool_strategy == POOL_BALANCE)
  5725. fputs(",\n\"balance\" : true", fcfg);
  5726. if (pool_strategy == POOL_LOADBALANCE)
  5727. fputs(",\n\"load-balance\" : true", fcfg);
  5728. if (pool_strategy == POOL_ROUNDROBIN)
  5729. fputs(",\n\"round-robin\" : true", fcfg);
  5730. if (pool_strategy == POOL_ROTATE)
  5731. fprintf(fcfg, ",\n\"rotate\" : \"%d\"", opt_rotate_period);
  5732. #if defined(unix) || defined(__APPLE__)
  5733. if (opt_stderr_cmd && *opt_stderr_cmd)
  5734. fprintf(fcfg, ",\n\"monitor\" : \"%s\"", json_escape(opt_stderr_cmd));
  5735. #endif // defined(unix)
  5736. if (opt_kernel_path && *opt_kernel_path) {
  5737. char *kpath = strdup(opt_kernel_path);
  5738. if (kpath[strlen(kpath)-1] == '/')
  5739. kpath[strlen(kpath)-1] = 0;
  5740. fprintf(fcfg, ",\n\"kernel-path\" : \"%s\"", json_escape(kpath));
  5741. free(kpath);
  5742. }
  5743. if (schedstart.enable)
  5744. fprintf(fcfg, ",\n\"sched-time\" : \"%d:%d\"", schedstart.tm.tm_hour, schedstart.tm.tm_min);
  5745. if (schedstop.enable)
  5746. fprintf(fcfg, ",\n\"stop-time\" : \"%d:%d\"", schedstop.tm.tm_hour, schedstop.tm.tm_min);
  5747. if (opt_socks_proxy && *opt_socks_proxy)
  5748. fprintf(fcfg, ",\n\"socks-proxy\" : \"%s\"", json_escape(opt_socks_proxy));
  5749. _write_config_string_elist(fcfg, "scan", scan_devices);
  5750. #ifdef USE_LIBMICROHTTPD
  5751. if (httpsrv_port != -1)
  5752. fprintf(fcfg, ",\n\"http-port\" : %d", httpsrv_port);
  5753. #endif
  5754. #ifdef USE_LIBEVENT
  5755. if (stratumsrv_port != -1)
  5756. fprintf(fcfg, ",\n\"stratum-port\" : %d", stratumsrv_port);
  5757. #endif
  5758. _write_config_string_elist(fcfg, "device", opt_devices_enabled_list);
  5759. _write_config_string_elist(fcfg, "set-device", opt_set_device_list);
  5760. if (opt_api_allow)
  5761. fprintf(fcfg, ",\n\"api-allow\" : \"%s\"", json_escape(opt_api_allow));
  5762. if (strcmp(opt_api_mcast_addr, API_MCAST_ADDR) != 0)
  5763. fprintf(fcfg, ",\n\"api-mcast-addr\" : \"%s\"", json_escape(opt_api_mcast_addr));
  5764. if (strcmp(opt_api_mcast_code, API_MCAST_CODE) != 0)
  5765. fprintf(fcfg, ",\n\"api-mcast-code\" : \"%s\"", json_escape(opt_api_mcast_code));
  5766. if (*opt_api_mcast_des)
  5767. fprintf(fcfg, ",\n\"api-mcast-des\" : \"%s\"", json_escape(opt_api_mcast_des));
  5768. if (strcmp(opt_api_description, PACKAGE_STRING) != 0)
  5769. fprintf(fcfg, ",\n\"api-description\" : \"%s\"", json_escape(opt_api_description));
  5770. if (opt_api_groups)
  5771. fprintf(fcfg, ",\n\"api-groups\" : \"%s\"", json_escape(opt_api_groups));
  5772. fputs("\n}\n", fcfg);
  5773. json_escape_free();
  5774. }
  5775. void zero_bestshare(void)
  5776. {
  5777. int i;
  5778. best_diff = 0;
  5779. memset(best_share, 0, 8);
  5780. suffix_string(best_diff, best_share, sizeof(best_share), 0);
  5781. for (i = 0; i < total_pools; i++) {
  5782. struct pool *pool = pools[i];
  5783. pool->best_diff = 0;
  5784. }
  5785. }
  5786. void zero_stats(void)
  5787. {
  5788. int i;
  5789. applog(LOG_DEBUG, "Zeroing stats");
  5790. cgtime(&total_tv_start);
  5791. miner_started = total_tv_start;
  5792. total_rolling = 0;
  5793. total_mhashes_done = 0;
  5794. total_getworks = 0;
  5795. total_accepted = 0;
  5796. total_rejected = 0;
  5797. hw_errors = 0;
  5798. total_stale = 0;
  5799. total_discarded = 0;
  5800. total_bytes_rcvd = total_bytes_sent = 0;
  5801. new_blocks = 0;
  5802. local_work = 0;
  5803. total_go = 0;
  5804. total_ro = 0;
  5805. total_secs = 1.0;
  5806. total_diff1 = 0;
  5807. total_bad_diff1 = 0;
  5808. found_blocks = 0;
  5809. total_diff_accepted = 0;
  5810. total_diff_rejected = 0;
  5811. total_diff_stale = 0;
  5812. #ifdef HAVE_CURSES
  5813. awidth = rwidth = swidth = hwwidth = 1;
  5814. #endif
  5815. for (i = 0; i < total_pools; i++) {
  5816. struct pool *pool = pools[i];
  5817. pool->getwork_requested = 0;
  5818. pool->accepted = 0;
  5819. pool->rejected = 0;
  5820. pool->solved = 0;
  5821. pool->getwork_requested = 0;
  5822. pool->stale_shares = 0;
  5823. pool->discarded_work = 0;
  5824. pool->getfail_occasions = 0;
  5825. pool->remotefail_occasions = 0;
  5826. pool->last_share_time = 0;
  5827. pool->diff1 = 0;
  5828. pool->diff_accepted = 0;
  5829. pool->diff_rejected = 0;
  5830. pool->diff_stale = 0;
  5831. pool->last_share_diff = 0;
  5832. pool->cgminer_stats.start_tv = total_tv_start;
  5833. pool->cgminer_stats.getwork_calls = 0;
  5834. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  5835. pool->cgminer_stats.getwork_wait_max.tv_sec = 0;
  5836. pool->cgminer_stats.getwork_wait_max.tv_usec = 0;
  5837. pool->cgminer_pool_stats.getwork_calls = 0;
  5838. pool->cgminer_pool_stats.getwork_attempts = 0;
  5839. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  5840. pool->cgminer_pool_stats.getwork_wait_max.tv_sec = 0;
  5841. pool->cgminer_pool_stats.getwork_wait_max.tv_usec = 0;
  5842. pool->cgminer_pool_stats.min_diff = 0;
  5843. pool->cgminer_pool_stats.max_diff = 0;
  5844. pool->cgminer_pool_stats.min_diff_count = 0;
  5845. pool->cgminer_pool_stats.max_diff_count = 0;
  5846. pool->cgminer_pool_stats.times_sent = 0;
  5847. pool->cgminer_pool_stats.bytes_sent = 0;
  5848. pool->cgminer_pool_stats.net_bytes_sent = 0;
  5849. pool->cgminer_pool_stats.times_received = 0;
  5850. pool->cgminer_pool_stats.bytes_received = 0;
  5851. pool->cgminer_pool_stats.net_bytes_received = 0;
  5852. }
  5853. zero_bestshare();
  5854. for (i = 0; i < total_devices; ++i) {
  5855. struct cgpu_info *cgpu = get_devices(i);
  5856. mutex_lock(&hash_lock);
  5857. cgpu->total_mhashes = 0;
  5858. cgpu->accepted = 0;
  5859. cgpu->rejected = 0;
  5860. cgpu->stale = 0;
  5861. cgpu->hw_errors = 0;
  5862. cgpu->utility = 0.0;
  5863. cgpu->utility_diff1 = 0;
  5864. cgpu->last_share_pool_time = 0;
  5865. cgpu->bad_diff1 = 0;
  5866. cgpu->diff1 = 0;
  5867. cgpu->diff_accepted = 0;
  5868. cgpu->diff_rejected = 0;
  5869. cgpu->diff_stale = 0;
  5870. cgpu->last_share_diff = 0;
  5871. cgpu->thread_fail_init_count = 0;
  5872. cgpu->thread_zero_hash_count = 0;
  5873. cgpu->thread_fail_queue_count = 0;
  5874. cgpu->dev_sick_idle_60_count = 0;
  5875. cgpu->dev_dead_idle_600_count = 0;
  5876. cgpu->dev_nostart_count = 0;
  5877. cgpu->dev_over_heat_count = 0;
  5878. cgpu->dev_thermal_cutoff_count = 0;
  5879. cgpu->dev_comms_error_count = 0;
  5880. cgpu->dev_throttle_count = 0;
  5881. cgpu->cgminer_stats.start_tv = total_tv_start;
  5882. cgpu->cgminer_stats.getwork_calls = 0;
  5883. cgpu->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  5884. cgpu->cgminer_stats.getwork_wait_max.tv_sec = 0;
  5885. cgpu->cgminer_stats.getwork_wait_max.tv_usec = 0;
  5886. mutex_unlock(&hash_lock);
  5887. }
  5888. }
  5889. #ifdef HAVE_CURSES
  5890. static
  5891. void loginput_mode(const int size)
  5892. {
  5893. clear_logwin();
  5894. loginput_size = size;
  5895. check_winsizes();
  5896. }
  5897. static void display_pools(void)
  5898. {
  5899. struct pool *pool;
  5900. int selected, i, j;
  5901. char input;
  5902. loginput_mode(7 + total_pools);
  5903. immedok(logwin, true);
  5904. updated:
  5905. for (j = 0; j < total_pools; j++) {
  5906. for (i = 0; i < total_pools; i++) {
  5907. pool = pools[i];
  5908. if (pool->prio != j)
  5909. continue;
  5910. if (pool == current_pool())
  5911. wattron(logwin, A_BOLD);
  5912. if (pool->enabled != POOL_ENABLED)
  5913. wattron(logwin, A_DIM);
  5914. wlogprint("%d: ", pool->prio);
  5915. switch (pool->enabled) {
  5916. case POOL_ENABLED:
  5917. wlogprint("Enabled ");
  5918. break;
  5919. case POOL_DISABLED:
  5920. wlogprint("Disabled ");
  5921. break;
  5922. case POOL_REJECTING:
  5923. wlogprint("Rejectin ");
  5924. break;
  5925. }
  5926. if (pool->idle)
  5927. wlogprint("Dead ");
  5928. else
  5929. if (pool->has_stratum)
  5930. wlogprint("Strtm");
  5931. else
  5932. if (pool->lp_url && pool->proto != pool->lp_proto)
  5933. wlogprint("Mixed");
  5934. else
  5935. switch (pool->proto) {
  5936. case PLP_GETBLOCKTEMPLATE:
  5937. wlogprint(" GBT ");
  5938. break;
  5939. case PLP_GETWORK:
  5940. wlogprint("GWork");
  5941. break;
  5942. default:
  5943. wlogprint("Alive");
  5944. }
  5945. wlogprint(" Quota %d Pool %d: %s User:%s\n",
  5946. pool->quota,
  5947. pool->pool_no,
  5948. pool->rpc_url, pool->rpc_user);
  5949. wattroff(logwin, A_BOLD | A_DIM);
  5950. break; //for (i = 0; i < total_pools; i++)
  5951. }
  5952. }
  5953. retry:
  5954. wlogprint("\nCurrent pool management strategy: %s\n",
  5955. strategies[pool_strategy].s);
  5956. if (pool_strategy == POOL_ROTATE)
  5957. wlogprint("Set to rotate every %d minutes\n", opt_rotate_period);
  5958. wlogprint("[F]ailover only %s\n", opt_fail_only ? "enabled" : "disabled");
  5959. wlogprint("Pool [A]dd [R]emove [D]isable [E]nable [P]rioritize [Q]uota change\n");
  5960. wlogprint("[C]hange management strategy [S]witch pool [I]nformation\n");
  5961. wlogprint("Or press any other key to continue\n");
  5962. logwin_update();
  5963. input = getch();
  5964. if (!strncasecmp(&input, "a", 1)) {
  5965. input_pool(true);
  5966. goto updated;
  5967. } else if (!strncasecmp(&input, "r", 1)) {
  5968. if (total_pools <= 1) {
  5969. wlogprint("Cannot remove last pool");
  5970. goto retry;
  5971. }
  5972. selected = curses_int("Select pool number");
  5973. if (selected < 0 || selected >= total_pools) {
  5974. wlogprint("Invalid selection\n");
  5975. goto retry;
  5976. }
  5977. pool = pools[selected];
  5978. if (pool == current_pool())
  5979. switch_pools(NULL);
  5980. if (pool == current_pool()) {
  5981. wlogprint("Unable to remove pool due to activity\n");
  5982. goto retry;
  5983. }
  5984. disable_pool(pool);
  5985. remove_pool(pool);
  5986. goto updated;
  5987. } else if (!strncasecmp(&input, "s", 1)) {
  5988. selected = curses_int("Select pool number");
  5989. if (selected < 0 || selected >= total_pools) {
  5990. wlogprint("Invalid selection\n");
  5991. goto retry;
  5992. }
  5993. pool = pools[selected];
  5994. enable_pool(pool);
  5995. switch_pools(pool);
  5996. goto updated;
  5997. } else if (!strncasecmp(&input, "d", 1)) {
  5998. if (enabled_pools <= 1) {
  5999. wlogprint("Cannot disable last pool");
  6000. goto retry;
  6001. }
  6002. selected = curses_int("Select pool number");
  6003. if (selected < 0 || selected >= total_pools) {
  6004. wlogprint("Invalid selection\n");
  6005. goto retry;
  6006. }
  6007. pool = pools[selected];
  6008. disable_pool(pool);
  6009. if (pool == current_pool())
  6010. switch_pools(NULL);
  6011. goto updated;
  6012. } else if (!strncasecmp(&input, "e", 1)) {
  6013. selected = curses_int("Select pool number");
  6014. if (selected < 0 || selected >= total_pools) {
  6015. wlogprint("Invalid selection\n");
  6016. goto retry;
  6017. }
  6018. pool = pools[selected];
  6019. enable_pool(pool);
  6020. if (pool->prio < current_pool()->prio)
  6021. switch_pools(pool);
  6022. goto updated;
  6023. } else if (!strncasecmp(&input, "c", 1)) {
  6024. for (i = 0; i <= TOP_STRATEGY; i++)
  6025. wlogprint("%d: %s\n", i, strategies[i].s);
  6026. selected = curses_int("Select strategy number type");
  6027. if (selected < 0 || selected > TOP_STRATEGY) {
  6028. wlogprint("Invalid selection\n");
  6029. goto retry;
  6030. }
  6031. if (selected == POOL_ROTATE) {
  6032. opt_rotate_period = curses_int("Select interval in minutes");
  6033. if (opt_rotate_period < 0 || opt_rotate_period > 9999) {
  6034. opt_rotate_period = 0;
  6035. wlogprint("Invalid selection\n");
  6036. goto retry;
  6037. }
  6038. }
  6039. pool_strategy = selected;
  6040. switch_pools(NULL);
  6041. goto updated;
  6042. } else if (!strncasecmp(&input, "i", 1)) {
  6043. selected = curses_int("Select pool number");
  6044. if (selected < 0 || selected >= total_pools) {
  6045. wlogprint("Invalid selection\n");
  6046. goto retry;
  6047. }
  6048. pool = pools[selected];
  6049. display_pool_summary(pool);
  6050. goto retry;
  6051. } else if (!strncasecmp(&input, "q", 1)) {
  6052. selected = curses_int("Select pool number");
  6053. if (selected < 0 || selected >= total_pools) {
  6054. wlogprint("Invalid selection\n");
  6055. goto retry;
  6056. }
  6057. pool = pools[selected];
  6058. selected = curses_int("Set quota");
  6059. if (selected < 0) {
  6060. wlogprint("Invalid negative quota\n");
  6061. goto retry;
  6062. }
  6063. pool->quota = selected;
  6064. adjust_quota_gcd();
  6065. goto updated;
  6066. } else if (!strncasecmp(&input, "f", 1)) {
  6067. opt_fail_only ^= true;
  6068. goto updated;
  6069. } else if (!strncasecmp(&input, "p", 1)) {
  6070. char *prilist = curses_input("Enter new pool priority (comma separated list)");
  6071. if (!prilist)
  6072. {
  6073. wlogprint("Not changing priorities\n");
  6074. goto retry;
  6075. }
  6076. int res = prioritize_pools(prilist, &i);
  6077. free(prilist);
  6078. switch (res) {
  6079. case MSG_NOPOOL:
  6080. wlogprint("No pools\n");
  6081. goto retry;
  6082. case MSG_MISPID:
  6083. wlogprint("Missing pool id parameter\n");
  6084. goto retry;
  6085. case MSG_INVPID:
  6086. wlogprint("Invalid pool id %d - range is 0 - %d\n", i, total_pools - 1);
  6087. goto retry;
  6088. case MSG_DUPPID:
  6089. wlogprint("Duplicate pool specified %d\n", i);
  6090. goto retry;
  6091. case MSG_POOLPRIO:
  6092. default:
  6093. goto updated;
  6094. }
  6095. }
  6096. immedok(logwin, false);
  6097. loginput_mode(0);
  6098. }
  6099. static const char *summary_detail_level_str(void)
  6100. {
  6101. if (opt_compact)
  6102. return "compact";
  6103. if (opt_show_procs)
  6104. return "processors";
  6105. return "devices";
  6106. }
  6107. static void display_options(void)
  6108. {
  6109. int selected;
  6110. char input;
  6111. immedok(logwin, true);
  6112. loginput_mode(12);
  6113. retry:
  6114. clear_logwin();
  6115. wlogprint("[N]ormal [C]lear [S]ilent mode (disable all output)\n");
  6116. wlogprint("[D]ebug:%s\n[P]er-device:%s\n[Q]uiet:%s\n[V]erbose:%s\n"
  6117. "[R]PC debug:%s\n[W]orkTime details:%s\nsu[M]mary detail level:%s\n"
  6118. "[L]og interval:%d\nS[T]atistical counts: %s\n[Z]ero statistics\n",
  6119. opt_debug_console ? "on" : "off",
  6120. want_per_device_stats? "on" : "off",
  6121. opt_quiet ? "on" : "off",
  6122. opt_log_output ? "on" : "off",
  6123. opt_protocol ? "on" : "off",
  6124. opt_worktime ? "on" : "off",
  6125. summary_detail_level_str(),
  6126. opt_log_interval,
  6127. opt_weighed_stats ? "weighed" : "absolute");
  6128. wlogprint("Select an option or any other key to return\n");
  6129. logwin_update();
  6130. input = getch();
  6131. if (!strncasecmp(&input, "q", 1)) {
  6132. opt_quiet ^= true;
  6133. wlogprint("Quiet mode %s\n", opt_quiet ? "enabled" : "disabled");
  6134. goto retry;
  6135. } else if (!strncasecmp(&input, "v", 1)) {
  6136. opt_log_output ^= true;
  6137. if (opt_log_output)
  6138. opt_quiet = false;
  6139. wlogprint("Verbose mode %s\n", opt_log_output ? "enabled" : "disabled");
  6140. goto retry;
  6141. } else if (!strncasecmp(&input, "n", 1)) {
  6142. opt_log_output = false;
  6143. opt_debug_console = false;
  6144. opt_quiet = false;
  6145. opt_protocol = false;
  6146. opt_compact = false;
  6147. opt_show_procs = false;
  6148. devsummaryYOffset = 0;
  6149. want_per_device_stats = false;
  6150. wlogprint("Output mode reset to normal\n");
  6151. switch_logsize();
  6152. goto retry;
  6153. } else if (!strncasecmp(&input, "d", 1)) {
  6154. opt_debug = true;
  6155. opt_debug_console ^= true;
  6156. opt_log_output = opt_debug_console;
  6157. if (opt_debug_console)
  6158. opt_quiet = false;
  6159. wlogprint("Debug mode %s\n", opt_debug_console ? "enabled" : "disabled");
  6160. goto retry;
  6161. } else if (!strncasecmp(&input, "m", 1)) {
  6162. if (opt_compact)
  6163. opt_compact = false;
  6164. else
  6165. if (!opt_show_procs)
  6166. opt_show_procs = true;
  6167. else
  6168. {
  6169. opt_compact = true;
  6170. opt_show_procs = false;
  6171. devsummaryYOffset = 0;
  6172. }
  6173. wlogprint("su[M]mary detail level changed to: %s\n", summary_detail_level_str());
  6174. switch_logsize();
  6175. goto retry;
  6176. } else if (!strncasecmp(&input, "p", 1)) {
  6177. want_per_device_stats ^= true;
  6178. opt_log_output = want_per_device_stats;
  6179. wlogprint("Per-device stats %s\n", want_per_device_stats ? "enabled" : "disabled");
  6180. goto retry;
  6181. } else if (!strncasecmp(&input, "r", 1)) {
  6182. opt_protocol ^= true;
  6183. if (opt_protocol)
  6184. opt_quiet = false;
  6185. wlogprint("RPC protocol debugging %s\n", opt_protocol ? "enabled" : "disabled");
  6186. goto retry;
  6187. } else if (!strncasecmp(&input, "c", 1))
  6188. clear_logwin();
  6189. else if (!strncasecmp(&input, "l", 1)) {
  6190. selected = curses_int("Interval in seconds");
  6191. if (selected < 0 || selected > 9999) {
  6192. wlogprint("Invalid selection\n");
  6193. goto retry;
  6194. }
  6195. opt_log_interval = selected;
  6196. wlogprint("Log interval set to %d seconds\n", opt_log_interval);
  6197. goto retry;
  6198. } else if (!strncasecmp(&input, "s", 1)) {
  6199. opt_realquiet = true;
  6200. } else if (!strncasecmp(&input, "w", 1)) {
  6201. opt_worktime ^= true;
  6202. wlogprint("WorkTime details %s\n", opt_worktime ? "enabled" : "disabled");
  6203. goto retry;
  6204. } else if (!strncasecmp(&input, "t", 1)) {
  6205. opt_weighed_stats ^= true;
  6206. wlogprint("Now displaying %s statistics\n", opt_weighed_stats ? "weighed" : "absolute");
  6207. goto retry;
  6208. } else if (!strncasecmp(&input, "z", 1)) {
  6209. zero_stats();
  6210. goto retry;
  6211. }
  6212. immedok(logwin, false);
  6213. loginput_mode(0);
  6214. }
  6215. #endif
  6216. void default_save_file(char *filename)
  6217. {
  6218. #if defined(unix) || defined(__APPLE__)
  6219. if (getenv("HOME") && *getenv("HOME")) {
  6220. strcpy(filename, getenv("HOME"));
  6221. strcat(filename, "/");
  6222. }
  6223. else
  6224. strcpy(filename, "");
  6225. strcat(filename, ".bfgminer/");
  6226. mkdir(filename, 0777);
  6227. #else
  6228. strcpy(filename, "");
  6229. #endif
  6230. strcat(filename, def_conf);
  6231. }
  6232. #ifdef HAVE_CURSES
  6233. static void set_options(void)
  6234. {
  6235. int selected;
  6236. char input;
  6237. immedok(logwin, true);
  6238. loginput_mode(8);
  6239. retry:
  6240. wlogprint("\n[L]ongpoll: %s\n", want_longpoll ? "On" : "Off");
  6241. wlogprint("[Q]ueue: %d\n[S]cantime: %d\n[E]xpiry: %d\n[R]etries: %d\n"
  6242. "[W]rite config file\n[B]FGMiner restart\n",
  6243. opt_queue, opt_scantime, opt_expiry, opt_retries);
  6244. wlogprint("Select an option or any other key to return\n");
  6245. logwin_update();
  6246. input = getch();
  6247. if (!strncasecmp(&input, "q", 1)) {
  6248. selected = curses_int("Extra work items to queue");
  6249. if (selected < 0 || selected > 9999) {
  6250. wlogprint("Invalid selection\n");
  6251. goto retry;
  6252. }
  6253. opt_queue = selected;
  6254. goto retry;
  6255. } else if (!strncasecmp(&input, "l", 1)) {
  6256. if (want_longpoll)
  6257. stop_longpoll();
  6258. else
  6259. start_longpoll();
  6260. applog(LOG_WARNING, "Longpoll %s", want_longpoll ? "enabled" : "disabled");
  6261. goto retry;
  6262. } else if (!strncasecmp(&input, "s", 1)) {
  6263. selected = curses_int("Set scantime in seconds");
  6264. if (selected < 0 || selected > 9999) {
  6265. wlogprint("Invalid selection\n");
  6266. goto retry;
  6267. }
  6268. opt_scantime = selected;
  6269. goto retry;
  6270. } else if (!strncasecmp(&input, "e", 1)) {
  6271. selected = curses_int("Set expiry time in seconds");
  6272. if (selected < 0 || selected > 9999) {
  6273. wlogprint("Invalid selection\n");
  6274. goto retry;
  6275. }
  6276. opt_expiry = selected;
  6277. goto retry;
  6278. } else if (!strncasecmp(&input, "r", 1)) {
  6279. selected = curses_int("Retries before failing (-1 infinite)");
  6280. if (selected < -1 || selected > 9999) {
  6281. wlogprint("Invalid selection\n");
  6282. goto retry;
  6283. }
  6284. opt_retries = selected;
  6285. goto retry;
  6286. } else if (!strncasecmp(&input, "w", 1)) {
  6287. FILE *fcfg;
  6288. char *str, filename[PATH_MAX], prompt[PATH_MAX + 50];
  6289. default_save_file(filename);
  6290. snprintf(prompt, sizeof(prompt), "Config filename to write (Enter for default) [%s]", filename);
  6291. str = curses_input(prompt);
  6292. if (str) {
  6293. struct stat statbuf;
  6294. strcpy(filename, str);
  6295. free(str);
  6296. if (!stat(filename, &statbuf)) {
  6297. wlogprint("File exists, overwrite?\n");
  6298. input = getch();
  6299. if (strncasecmp(&input, "y", 1))
  6300. goto retry;
  6301. }
  6302. }
  6303. fcfg = fopen(filename, "w");
  6304. if (!fcfg) {
  6305. wlogprint("Cannot open or create file\n");
  6306. goto retry;
  6307. }
  6308. write_config(fcfg);
  6309. fclose(fcfg);
  6310. goto retry;
  6311. } else if (!strncasecmp(&input, "b", 1)) {
  6312. wlogprint("Are you sure?\n");
  6313. input = getch();
  6314. if (!strncasecmp(&input, "y", 1))
  6315. app_restart();
  6316. else
  6317. clear_logwin();
  6318. } else
  6319. clear_logwin();
  6320. loginput_mode(0);
  6321. immedok(logwin, false);
  6322. }
  6323. int scan_serial(const char *);
  6324. static
  6325. void _managetui_msg(const char *repr, const char **msg)
  6326. {
  6327. if (*msg)
  6328. {
  6329. applog(LOG_DEBUG, "ManageTUI: %"PRIpreprv": %s", repr, *msg);
  6330. wattron(logwin, A_BOLD);
  6331. wlogprint("%s", *msg);
  6332. wattroff(logwin, A_BOLD);
  6333. *msg = NULL;
  6334. }
  6335. logwin_update();
  6336. }
  6337. void manage_device(void)
  6338. {
  6339. char logline[256];
  6340. const char *msg = NULL;
  6341. struct cgpu_info *cgpu;
  6342. const struct device_drv *drv;
  6343. selecting_device = true;
  6344. immedok(logwin, true);
  6345. loginput_mode(12);
  6346. devchange:
  6347. if (unlikely(!total_devices))
  6348. {
  6349. clear_logwin();
  6350. wlogprint("(no devices)\n");
  6351. wlogprint("[Plus] Add device(s) [Enter] Close device manager\n");
  6352. _managetui_msg("(none)", &msg);
  6353. int input = getch();
  6354. switch (input)
  6355. {
  6356. case '+': case '=': // add new device
  6357. goto addnew;
  6358. default:
  6359. goto out;
  6360. }
  6361. }
  6362. cgpu = devices[selected_device];
  6363. drv = cgpu->drv;
  6364. refresh_devstatus();
  6365. refresh:
  6366. clear_logwin();
  6367. wlogprint("Select processor to manage using up/down arrow keys\n");
  6368. get_statline3(logline, sizeof(logline), cgpu, true, true);
  6369. wattron(logwin, A_BOLD);
  6370. wlogprint("%s", logline);
  6371. wattroff(logwin, A_BOLD);
  6372. wlogprint("\n");
  6373. if (cgpu->dev_manufacturer)
  6374. wlogprint(" %s from %s\n", (cgpu->dev_product ?: "Device"), cgpu->dev_manufacturer);
  6375. else
  6376. if (cgpu->dev_product)
  6377. wlogprint(" %s\n", cgpu->dev_product);
  6378. if (cgpu->dev_serial)
  6379. wlogprint("Serial: %s\n", cgpu->dev_serial);
  6380. if (cgpu->kname)
  6381. wlogprint("Kernel: %s\n", cgpu->kname);
  6382. if (drv->proc_wlogprint_status && likely(cgpu->status != LIFE_INIT))
  6383. drv->proc_wlogprint_status(cgpu);
  6384. wlogprint("\n");
  6385. // TODO: Last share at TIMESTAMP on pool N
  6386. // TODO: Custom device info/commands
  6387. if (cgpu->deven != DEV_ENABLED)
  6388. wlogprint("[E]nable ");
  6389. if (cgpu->deven != DEV_DISABLED)
  6390. wlogprint("[D]isable ");
  6391. if (drv->identify_device)
  6392. wlogprint("[I]dentify ");
  6393. if (drv->proc_tui_wlogprint_choices && likely(cgpu->status != LIFE_INIT))
  6394. drv->proc_tui_wlogprint_choices(cgpu);
  6395. wlogprint("\n");
  6396. wlogprint("[Slash] Find processor [Plus] Add device(s) [Enter] Close device manager\n");
  6397. _managetui_msg(cgpu->proc_repr, &msg);
  6398. while (true)
  6399. {
  6400. int input = getch();
  6401. applog(LOG_DEBUG, "ManageTUI: %"PRIpreprv": (choice %d)", cgpu->proc_repr, input);
  6402. switch (input) {
  6403. case 'd': case 'D':
  6404. if (cgpu->deven == DEV_DISABLED)
  6405. msg = "Processor already disabled\n";
  6406. else
  6407. {
  6408. cgpu->deven = DEV_DISABLED;
  6409. msg = "Processor being disabled\n";
  6410. }
  6411. goto refresh;
  6412. case 'e': case 'E':
  6413. if (cgpu->deven == DEV_ENABLED)
  6414. msg = "Processor already enabled\n";
  6415. else
  6416. {
  6417. proc_enable(cgpu);
  6418. msg = "Processor being enabled\n";
  6419. }
  6420. goto refresh;
  6421. case 'i': case 'I':
  6422. if (drv->identify_device && drv->identify_device(cgpu))
  6423. msg = "Identify command sent\n";
  6424. else
  6425. goto key_default;
  6426. goto refresh;
  6427. case KEY_DOWN:
  6428. if (selected_device >= total_devices - 1)
  6429. break;
  6430. ++selected_device;
  6431. goto devchange;
  6432. case KEY_UP:
  6433. if (selected_device <= 0)
  6434. break;
  6435. --selected_device;
  6436. goto devchange;
  6437. case KEY_NPAGE:
  6438. {
  6439. if (selected_device >= total_devices - 1)
  6440. break;
  6441. struct cgpu_info *mdev = devices[selected_device]->device;
  6442. do {
  6443. ++selected_device;
  6444. } while (devices[selected_device]->device == mdev && selected_device < total_devices - 1);
  6445. goto devchange;
  6446. }
  6447. case KEY_PPAGE:
  6448. {
  6449. if (selected_device <= 0)
  6450. break;
  6451. struct cgpu_info *mdev = devices[selected_device]->device;
  6452. do {
  6453. --selected_device;
  6454. } while (devices[selected_device]->device == mdev && selected_device > 0);
  6455. goto devchange;
  6456. }
  6457. case '/': case '?': // find device
  6458. {
  6459. static char *pattern = NULL;
  6460. char *newpattern = curses_input("Enter pattern");
  6461. if (newpattern)
  6462. {
  6463. free(pattern);
  6464. pattern = newpattern;
  6465. }
  6466. else
  6467. if (!pattern)
  6468. pattern = calloc(1, 1);
  6469. int match = cgpu_search(pattern, selected_device + 1);
  6470. if (match == -1)
  6471. {
  6472. msg = "Couldn't find device\n";
  6473. goto refresh;
  6474. }
  6475. selected_device = match;
  6476. goto devchange;
  6477. }
  6478. case '+': case '=': // add new device
  6479. {
  6480. addnew:
  6481. clear_logwin();
  6482. _wlogprint(
  6483. "Enter \"auto\", \"all\", or a serial port to probe for mining devices.\n"
  6484. "Prefix by a driver name and colon to only probe a specific driver.\n"
  6485. "For example: erupter:"
  6486. #ifdef WIN32
  6487. "\\\\.\\COM40"
  6488. #elif defined(__APPLE__)
  6489. "/dev/cu.SLAB_USBtoUART"
  6490. #else
  6491. "/dev/ttyUSB39"
  6492. #endif
  6493. "\n"
  6494. );
  6495. char *scanser = curses_input("Enter target");
  6496. if (scan_serial(scanser))
  6497. {
  6498. selected_device = total_devices - 1;
  6499. msg = "Device scan succeeded\n";
  6500. }
  6501. else
  6502. msg = "No new devices found\n";
  6503. goto devchange;
  6504. }
  6505. case 'Q': case 'q':
  6506. case KEY_BREAK: case KEY_BACKSPACE: case KEY_CANCEL: case KEY_CLOSE: case KEY_EXIT:
  6507. case '\x1b': // ESC
  6508. case KEY_ENTER:
  6509. case '\r': // Ctrl-M on Windows, with nonl
  6510. #ifdef PADENTER
  6511. case PADENTER: // pdcurses, used by Enter key on Windows with nonl
  6512. #endif
  6513. case '\n':
  6514. goto out;
  6515. default:
  6516. ;
  6517. key_default:
  6518. if (drv->proc_tui_handle_choice && likely(drv_ready(cgpu)))
  6519. {
  6520. msg = drv->proc_tui_handle_choice(cgpu, input);
  6521. if (msg)
  6522. goto refresh;
  6523. }
  6524. }
  6525. }
  6526. out:
  6527. selecting_device = false;
  6528. loginput_mode(0);
  6529. immedok(logwin, false);
  6530. }
  6531. void show_help(void)
  6532. {
  6533. loginput_mode(10);
  6534. // NOTE: wlogprint is a macro with a buffer limit
  6535. _wlogprint(
  6536. "ST: work in queue | F: network fails | NB: new blocks detected\n"
  6537. "AS: shares being submitted | BW: bandwidth (up/down)\n"
  6538. "E: # shares * diff per 2kB bw | U: shares/minute | BS: best share ever found\n"
  6539. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6540. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6541. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6542. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_BTEE
  6543. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6544. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6545. U8_HLINE U8_HLINE U8_HLINE U8_BTEE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6546. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6547. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6548. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6549. "\n"
  6550. "devices/processors hashing (only for totals line), hottest temperature\n"
  6551. );
  6552. wlogprint(
  6553. "hashrates: %ds decaying / all-time average / all-time average (effective)\n"
  6554. , opt_log_interval);
  6555. _wlogprint(
  6556. "A: accepted shares | R: rejected+discarded(%% of total)\n"
  6557. "HW: hardware errors / %% nonces invalid\n"
  6558. "\n"
  6559. "Press any key to clear"
  6560. );
  6561. logwin_update();
  6562. getch();
  6563. loginput_mode(0);
  6564. }
  6565. static void *input_thread(void __maybe_unused *userdata)
  6566. {
  6567. RenameThread("input");
  6568. if (!curses_active)
  6569. return NULL;
  6570. while (1) {
  6571. int input;
  6572. input = getch();
  6573. switch (input) {
  6574. case 'h': case 'H': case '?':
  6575. case KEY_F(1):
  6576. show_help();
  6577. break;
  6578. case 'q': case 'Q':
  6579. kill_work();
  6580. return NULL;
  6581. case 'd': case 'D':
  6582. display_options();
  6583. break;
  6584. case 'm': case 'M':
  6585. manage_device();
  6586. break;
  6587. case 'p': case 'P':
  6588. display_pools();
  6589. break;
  6590. case 's': case 'S':
  6591. set_options();
  6592. break;
  6593. #ifdef HAVE_CURSES
  6594. case KEY_DOWN:
  6595. {
  6596. const int visible_lines = logcursor - devcursor;
  6597. const int invisible_lines = total_lines - visible_lines;
  6598. if (devsummaryYOffset <= -invisible_lines)
  6599. break;
  6600. devsummaryYOffset -= 2;
  6601. }
  6602. case KEY_UP:
  6603. if (devsummaryYOffset == 0)
  6604. break;
  6605. ++devsummaryYOffset;
  6606. refresh_devstatus();
  6607. break;
  6608. case KEY_NPAGE:
  6609. {
  6610. const int visible_lines = logcursor - devcursor;
  6611. const int invisible_lines = total_lines - visible_lines;
  6612. if (devsummaryYOffset - visible_lines <= -invisible_lines)
  6613. devsummaryYOffset = -invisible_lines;
  6614. else
  6615. devsummaryYOffset -= visible_lines;
  6616. refresh_devstatus();
  6617. break;
  6618. }
  6619. case KEY_PPAGE:
  6620. {
  6621. const int visible_lines = logcursor - devcursor;
  6622. if (devsummaryYOffset + visible_lines >= 0)
  6623. devsummaryYOffset = 0;
  6624. else
  6625. devsummaryYOffset += visible_lines;
  6626. refresh_devstatus();
  6627. break;
  6628. }
  6629. #endif
  6630. }
  6631. if (opt_realquiet) {
  6632. disable_curses();
  6633. break;
  6634. }
  6635. }
  6636. return NULL;
  6637. }
  6638. #endif
  6639. static void *api_thread(void *userdata)
  6640. {
  6641. struct thr_info *mythr = userdata;
  6642. pthread_detach(pthread_self());
  6643. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  6644. RenameThread("rpc");
  6645. api(api_thr_id);
  6646. mythr->has_pth = false;
  6647. return NULL;
  6648. }
  6649. void thread_reportin(struct thr_info *thr)
  6650. {
  6651. cgtime(&thr->last);
  6652. thr->cgpu->status = LIFE_WELL;
  6653. thr->getwork = 0;
  6654. thr->cgpu->device_last_well = time(NULL);
  6655. }
  6656. void thread_reportout(struct thr_info *thr)
  6657. {
  6658. thr->getwork = time(NULL);
  6659. }
  6660. static void hashmeter(int thr_id, struct timeval *diff,
  6661. uint64_t hashes_done)
  6662. {
  6663. char logstatusline[256];
  6664. struct timeval temp_tv_end, total_diff;
  6665. double secs;
  6666. double local_secs;
  6667. static double local_mhashes_done = 0;
  6668. double local_mhashes = (double)hashes_done / 1000000.0;
  6669. bool showlog = false;
  6670. char cHr[h2bs_fmt_size[H2B_NOUNIT]], aHr[h2bs_fmt_size[H2B_NOUNIT]], uHr[h2bs_fmt_size[H2B_SPACED]];
  6671. char rejpcbuf[6];
  6672. char bnbuf[6];
  6673. struct thr_info *thr;
  6674. /* Update the last time this thread reported in */
  6675. if (thr_id >= 0) {
  6676. thr = get_thread(thr_id);
  6677. cgtime(&(thr->last));
  6678. thr->cgpu->device_last_well = time(NULL);
  6679. }
  6680. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  6681. /* So we can call hashmeter from a non worker thread */
  6682. if (thr_id >= 0) {
  6683. struct cgpu_info *cgpu = thr->cgpu;
  6684. int threadobj = cgpu->threads ?: 1;
  6685. double thread_rolling = 0.0;
  6686. int i;
  6687. applog(LOG_DEBUG, "[thread %d: %"PRIu64" hashes, %.1f khash/sec]",
  6688. thr_id, hashes_done, hashes_done / 1000 / secs);
  6689. /* Rolling average for each thread and each device */
  6690. decay_time(&thr->rolling, local_mhashes / secs, secs);
  6691. for (i = 0; i < threadobj; i++)
  6692. thread_rolling += cgpu->thr[i]->rolling;
  6693. mutex_lock(&hash_lock);
  6694. decay_time(&cgpu->rolling, thread_rolling, secs);
  6695. cgpu->total_mhashes += local_mhashes;
  6696. mutex_unlock(&hash_lock);
  6697. // If needed, output detailed, per-device stats
  6698. if (want_per_device_stats) {
  6699. struct timeval now;
  6700. struct timeval elapsed;
  6701. struct timeval *last_msg_tv = opt_show_procs ? &thr->cgpu->last_message_tv : &thr->cgpu->device->last_message_tv;
  6702. cgtime(&now);
  6703. timersub(&now, last_msg_tv, &elapsed);
  6704. if (opt_log_interval <= elapsed.tv_sec) {
  6705. struct cgpu_info *cgpu = thr->cgpu;
  6706. char logline[255];
  6707. *last_msg_tv = now;
  6708. get_statline(logline, sizeof(logline), cgpu);
  6709. if (!curses_active) {
  6710. printf("%s \r", logline);
  6711. fflush(stdout);
  6712. } else
  6713. applog(LOG_INFO, "%s", logline);
  6714. }
  6715. }
  6716. }
  6717. /* Totals are updated by all threads so can race without locking */
  6718. mutex_lock(&hash_lock);
  6719. cgtime(&temp_tv_end);
  6720. timersub(&temp_tv_end, &total_tv_end, &total_diff);
  6721. total_mhashes_done += local_mhashes;
  6722. local_mhashes_done += local_mhashes;
  6723. /* Only update with opt_log_interval */
  6724. if (total_diff.tv_sec < opt_log_interval)
  6725. goto out_unlock;
  6726. showlog = true;
  6727. cgtime(&total_tv_end);
  6728. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  6729. decay_time(&total_rolling, local_mhashes_done / local_secs, local_secs);
  6730. global_hashrate = ((unsigned long long)lround(total_rolling)) * 1000000;
  6731. timersub(&total_tv_end, &total_tv_start, &total_diff);
  6732. total_secs = (double)total_diff.tv_sec +
  6733. ((double)total_diff.tv_usec / 1000000.0);
  6734. double wtotal = (total_diff_accepted + total_diff_rejected + total_diff_stale);
  6735. multi_format_unit_array2(
  6736. ((char*[]){cHr, aHr, uHr}),
  6737. ((size_t[]){h2bs_fmt_size[H2B_NOUNIT], h2bs_fmt_size[H2B_NOUNIT], h2bs_fmt_size[H2B_SPACED]}),
  6738. true, "h/s", H2B_SHORT,
  6739. 3,
  6740. 1e6*total_rolling,
  6741. 1e6*total_mhashes_done / total_secs,
  6742. utility_to_hashrate(total_diff1 * (wtotal ? (total_diff_accepted / wtotal) : 1) * 60 / total_secs));
  6743. int ui_accepted, ui_rejected, ui_stale;
  6744. if (opt_weighed_stats)
  6745. {
  6746. ui_accepted = total_diff_accepted;
  6747. ui_rejected = total_diff_rejected;
  6748. ui_stale = total_diff_stale;
  6749. }
  6750. else
  6751. {
  6752. ui_accepted = total_accepted;
  6753. ui_rejected = total_rejected;
  6754. ui_stale = total_stale;
  6755. }
  6756. #ifdef HAVE_CURSES
  6757. if (curses_active_locked()) {
  6758. float temp = 0;
  6759. struct cgpu_info *proc, *last_working_dev = NULL;
  6760. int i, working_devs = 0, working_procs = 0;
  6761. int divx;
  6762. bool bad = false;
  6763. // Find the highest temperature of all processors
  6764. for (i = 0; i < total_devices; ++i)
  6765. {
  6766. proc = get_devices(i);
  6767. if (proc->temp > temp)
  6768. temp = proc->temp;
  6769. if (unlikely(proc->deven == DEV_DISABLED))
  6770. ; // Just need to block it off from both conditions
  6771. else
  6772. if (likely(proc->status == LIFE_WELL && proc->deven == DEV_ENABLED))
  6773. {
  6774. if (proc->rolling > .1)
  6775. {
  6776. ++working_procs;
  6777. if (proc->device != last_working_dev)
  6778. {
  6779. ++working_devs;
  6780. last_working_dev = proc->device;
  6781. }
  6782. }
  6783. }
  6784. else
  6785. bad = true;
  6786. }
  6787. if (working_devs == working_procs)
  6788. snprintf(statusline, sizeof(statusline), "%s%d ", bad ? U8_BAD_START : "", working_devs);
  6789. else
  6790. snprintf(statusline, sizeof(statusline), "%s%d/%d ", bad ? U8_BAD_START : "", working_devs, working_procs);
  6791. divx = 7;
  6792. if (opt_show_procs && !opt_compact)
  6793. ++divx;
  6794. if (bad)
  6795. {
  6796. divx += sizeof(U8_BAD_START)-1;
  6797. strcpy(&statusline[divx], U8_BAD_END);
  6798. divx += sizeof(U8_BAD_END)-1;
  6799. }
  6800. temperature_column(&statusline[divx], sizeof(statusline)-divx, true, &temp);
  6801. format_statline(statusline, sizeof(statusline),
  6802. cHr, aHr,
  6803. uHr,
  6804. ui_accepted,
  6805. ui_rejected,
  6806. ui_stale,
  6807. total_diff_rejected + total_diff_stale, total_diff_accepted,
  6808. hw_errors,
  6809. total_bad_diff1, total_bad_diff1 + total_diff1);
  6810. unlock_curses();
  6811. }
  6812. #endif
  6813. // Add a space
  6814. memmove(&uHr[6], &uHr[5], strlen(&uHr[5]) + 1);
  6815. uHr[5] = ' ';
  6816. percentf4(rejpcbuf, sizeof(rejpcbuf), total_diff_rejected + total_diff_stale, total_diff_accepted);
  6817. percentf4(bnbuf, sizeof(bnbuf), total_bad_diff1, total_diff1);
  6818. snprintf(logstatusline, sizeof(logstatusline),
  6819. "%s%ds:%s avg:%s u:%s | A:%d R:%d+%d(%s) HW:%d/%s",
  6820. want_per_device_stats ? "ALL " : "",
  6821. opt_log_interval,
  6822. cHr, aHr,
  6823. uHr,
  6824. ui_accepted,
  6825. ui_rejected,
  6826. ui_stale,
  6827. rejpcbuf,
  6828. hw_errors,
  6829. bnbuf
  6830. );
  6831. local_mhashes_done = 0;
  6832. out_unlock:
  6833. mutex_unlock(&hash_lock);
  6834. if (showlog) {
  6835. if (!curses_active) {
  6836. printf("%s \r", logstatusline);
  6837. fflush(stdout);
  6838. } else
  6839. applog(LOG_INFO, "%s", logstatusline);
  6840. }
  6841. }
  6842. void hashmeter2(struct thr_info *thr)
  6843. {
  6844. struct timeval tv_now, tv_elapsed;
  6845. timerclear(&thr->tv_hashes_done);
  6846. cgtime(&tv_now);
  6847. timersub(&tv_now, &thr->tv_lastupdate, &tv_elapsed);
  6848. /* Update the hashmeter at most 5 times per second */
  6849. if ((thr->hashes_done && (tv_elapsed.tv_sec > 0 || tv_elapsed.tv_usec > 200000)) ||
  6850. tv_elapsed.tv_sec >= opt_log_interval) {
  6851. hashmeter(thr->id, &tv_elapsed, thr->hashes_done);
  6852. thr->hashes_done = 0;
  6853. thr->tv_lastupdate = tv_now;
  6854. }
  6855. }
  6856. static void stratum_share_result(json_t *val, json_t *res_val, json_t *err_val,
  6857. struct stratum_share *sshare)
  6858. {
  6859. struct work *work = sshare->work;
  6860. share_result(val, res_val, err_val, work, false, "");
  6861. }
  6862. /* Parses stratum json responses and tries to find the id that the request
  6863. * matched to and treat it accordingly. */
  6864. bool parse_stratum_response(struct pool *pool, char *s)
  6865. {
  6866. json_t *val = NULL, *err_val, *res_val, *id_val;
  6867. struct stratum_share *sshare;
  6868. json_error_t err;
  6869. bool ret = false;
  6870. int id;
  6871. val = JSON_LOADS(s, &err);
  6872. if (!val) {
  6873. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  6874. goto out;
  6875. }
  6876. res_val = json_object_get(val, "result");
  6877. err_val = json_object_get(val, "error");
  6878. id_val = json_object_get(val, "id");
  6879. if (json_is_null(id_val) || !id_val) {
  6880. char *ss;
  6881. if (err_val)
  6882. ss = json_dumps(err_val, JSON_INDENT(3));
  6883. else
  6884. ss = strdup("(unknown reason)");
  6885. applog(LOG_INFO, "JSON-RPC non method decode failed: %s", ss);
  6886. free(ss);
  6887. goto out;
  6888. }
  6889. if (!json_is_integer(id_val)) {
  6890. if (json_is_string(id_val)
  6891. && !strncmp(json_string_value(id_val), "txlist", 6))
  6892. {
  6893. const bool is_array = json_is_array(res_val);
  6894. applog(LOG_DEBUG, "Received %s for pool %u job %s",
  6895. is_array ? "transaction list" : "no-transaction-list response",
  6896. pool->pool_no, &json_string_value(id_val)[6]);
  6897. if (strcmp(json_string_value(id_val) + 6, pool->swork.job_id) || !is_array)
  6898. // We only care about a transaction list for the current job id
  6899. goto fishy;
  6900. // Check that the transactions actually hash to the merkle links
  6901. {
  6902. unsigned maxtx = 1 << pool->swork.merkles;
  6903. unsigned mintx = maxtx >> 1;
  6904. --maxtx;
  6905. unsigned acttx = (unsigned)json_array_size(res_val);
  6906. if (acttx < mintx || acttx > maxtx) {
  6907. applog(LOG_WARNING, "Pool %u is sending mismatched block contents to us (%u is not %u-%u)",
  6908. pool->pool_no, acttx, mintx, maxtx);
  6909. goto fishy;
  6910. }
  6911. // TODO: Check hashes match actual merkle links
  6912. }
  6913. pool_set_opaque(pool, false);
  6914. timer_unset(&pool->swork.tv_transparency);
  6915. fishy:
  6916. ret = true;
  6917. }
  6918. goto out;
  6919. }
  6920. id = json_integer_value(id_val);
  6921. mutex_lock(&sshare_lock);
  6922. HASH_FIND_INT(stratum_shares, &id, sshare);
  6923. if (sshare)
  6924. HASH_DEL(stratum_shares, sshare);
  6925. mutex_unlock(&sshare_lock);
  6926. if (!sshare) {
  6927. double pool_diff;
  6928. /* Since the share is untracked, we can only guess at what the
  6929. * work difficulty is based on the current pool diff. */
  6930. cg_rlock(&pool->data_lock);
  6931. pool_diff = pool->swork.diff;
  6932. cg_runlock(&pool->data_lock);
  6933. if (json_is_true(res_val)) {
  6934. applog(LOG_NOTICE, "Accepted untracked stratum share from pool %d", pool->pool_no);
  6935. /* We don't know what device this came from so we can't
  6936. * attribute the work to the relevant cgpu */
  6937. mutex_lock(&stats_lock);
  6938. total_accepted++;
  6939. pool->accepted++;
  6940. total_diff_accepted += pool_diff;
  6941. pool->diff_accepted += pool_diff;
  6942. mutex_unlock(&stats_lock);
  6943. } else {
  6944. applog(LOG_NOTICE, "Rejected untracked stratum share from pool %d", pool->pool_no);
  6945. mutex_lock(&stats_lock);
  6946. total_rejected++;
  6947. pool->rejected++;
  6948. total_diff_rejected += pool_diff;
  6949. pool->diff_rejected += pool_diff;
  6950. mutex_unlock(&stats_lock);
  6951. }
  6952. goto out;
  6953. }
  6954. else {
  6955. mutex_lock(&submitting_lock);
  6956. --total_submitting;
  6957. mutex_unlock(&submitting_lock);
  6958. }
  6959. stratum_share_result(val, res_val, err_val, sshare);
  6960. free_work(sshare->work);
  6961. free(sshare);
  6962. ret = true;
  6963. out:
  6964. if (val)
  6965. json_decref(val);
  6966. return ret;
  6967. }
  6968. static void shutdown_stratum(struct pool *pool)
  6969. {
  6970. // Shut down Stratum as if we never had it
  6971. pool->stratum_active = false;
  6972. pool->stratum_init = false;
  6973. pool->has_stratum = false;
  6974. shutdown(pool->sock, SHUT_RDWR);
  6975. free(pool->stratum_url);
  6976. if (pool->sockaddr_url == pool->stratum_url)
  6977. pool->sockaddr_url = NULL;
  6978. pool->stratum_url = NULL;
  6979. }
  6980. void clear_stratum_shares(struct pool *pool)
  6981. {
  6982. int my_mining_threads = mining_threads; // Cached outside of locking
  6983. struct stratum_share *sshare, *tmpshare;
  6984. struct work *work;
  6985. struct cgpu_info *cgpu;
  6986. double diff_cleared = 0;
  6987. double thr_diff_cleared[my_mining_threads];
  6988. int cleared = 0;
  6989. int thr_cleared[my_mining_threads];
  6990. // NOTE: This is per-thread rather than per-device to avoid getting devices lock in stratum_shares loop
  6991. for (int i = 0; i < my_mining_threads; ++i)
  6992. {
  6993. thr_diff_cleared[i] = 0;
  6994. thr_cleared[i] = 0;
  6995. }
  6996. mutex_lock(&sshare_lock);
  6997. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  6998. work = sshare->work;
  6999. if (sshare->work->pool == pool && work->thr_id < my_mining_threads) {
  7000. HASH_DEL(stratum_shares, sshare);
  7001. sharelog("disconnect", work);
  7002. diff_cleared += sshare->work->work_difficulty;
  7003. thr_diff_cleared[work->thr_id] += work->work_difficulty;
  7004. ++thr_cleared[work->thr_id];
  7005. free_work(sshare->work);
  7006. free(sshare);
  7007. cleared++;
  7008. }
  7009. }
  7010. mutex_unlock(&sshare_lock);
  7011. if (cleared) {
  7012. applog(LOG_WARNING, "Lost %d shares due to stratum disconnect on pool %d", cleared, pool->pool_no);
  7013. mutex_lock(&stats_lock);
  7014. pool->stale_shares += cleared;
  7015. total_stale += cleared;
  7016. pool->diff_stale += diff_cleared;
  7017. total_diff_stale += diff_cleared;
  7018. for (int i = 0; i < my_mining_threads; ++i)
  7019. if (thr_cleared[i])
  7020. {
  7021. cgpu = get_thr_cgpu(i);
  7022. cgpu->diff_stale += thr_diff_cleared[i];
  7023. cgpu->stale += thr_cleared[i];
  7024. }
  7025. mutex_unlock(&stats_lock);
  7026. mutex_lock(&submitting_lock);
  7027. total_submitting -= cleared;
  7028. mutex_unlock(&submitting_lock);
  7029. }
  7030. }
  7031. static void resubmit_stratum_shares(struct pool *pool)
  7032. {
  7033. struct stratum_share *sshare, *tmpshare;
  7034. struct work *work;
  7035. unsigned resubmitted = 0;
  7036. mutex_lock(&sshare_lock);
  7037. mutex_lock(&submitting_lock);
  7038. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  7039. if (sshare->work->pool != pool)
  7040. continue;
  7041. HASH_DEL(stratum_shares, sshare);
  7042. work = sshare->work;
  7043. DL_APPEND(submit_waiting, work);
  7044. free(sshare);
  7045. ++resubmitted;
  7046. }
  7047. mutex_unlock(&submitting_lock);
  7048. mutex_unlock(&sshare_lock);
  7049. if (resubmitted) {
  7050. notifier_wake(submit_waiting_notifier);
  7051. applog(LOG_DEBUG, "Resubmitting %u shares due to stratum disconnect on pool %u", resubmitted, pool->pool_no);
  7052. }
  7053. }
  7054. static void clear_pool_work(struct pool *pool)
  7055. {
  7056. struct work *work, *tmp;
  7057. int cleared = 0;
  7058. mutex_lock(stgd_lock);
  7059. HASH_ITER(hh, staged_work, work, tmp) {
  7060. if (work->pool == pool) {
  7061. HASH_DEL(staged_work, work);
  7062. free_work(work);
  7063. cleared++;
  7064. staged_full = false;
  7065. }
  7066. }
  7067. mutex_unlock(stgd_lock);
  7068. }
  7069. static int cp_prio(void)
  7070. {
  7071. int prio;
  7072. cg_rlock(&control_lock);
  7073. prio = currentpool->prio;
  7074. cg_runlock(&control_lock);
  7075. return prio;
  7076. }
  7077. /* We only need to maintain a secondary pool connection when we need the
  7078. * capacity to get work from the backup pools while still on the primary */
  7079. static bool cnx_needed(struct pool *pool)
  7080. {
  7081. struct pool *cp;
  7082. if (pool->enabled != POOL_ENABLED)
  7083. return false;
  7084. /* Balance strategies need all pools online */
  7085. if (pool_strategy == POOL_BALANCE)
  7086. return true;
  7087. if (pool_strategy == POOL_LOADBALANCE)
  7088. return true;
  7089. /* Idle stratum pool needs something to kick it alive again */
  7090. if (pool->has_stratum && pool->idle)
  7091. return true;
  7092. /* Getwork pools without opt_fail_only need backup pools up to be able
  7093. * to leak shares */
  7094. cp = current_pool();
  7095. if (cp == pool)
  7096. return true;
  7097. if (!pool_localgen(cp) && (!opt_fail_only || !cp->hdr_path))
  7098. return true;
  7099. /* Keep the connection open to allow any stray shares to be submitted
  7100. * on switching pools for 2 minutes. */
  7101. if (!timer_passed(&pool->tv_last_work_time, NULL))
  7102. return true;
  7103. /* If the pool has only just come to life and is higher priority than
  7104. * the current pool keep the connection open so we can fail back to
  7105. * it. */
  7106. if (pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  7107. return true;
  7108. if (pool_unworkable(cp))
  7109. return true;
  7110. /* We've run out of work, bring anything back to life. */
  7111. if (no_work)
  7112. return true;
  7113. return false;
  7114. }
  7115. static void wait_lpcurrent(struct pool *pool);
  7116. static void pool_resus(struct pool *pool);
  7117. static void gen_stratum_work(struct pool *pool, struct work *work);
  7118. static void stratum_resumed(struct pool *pool)
  7119. {
  7120. if (!pool->stratum_notify)
  7121. return;
  7122. if (pool_tclear(pool, &pool->idle)) {
  7123. applog(LOG_INFO, "Stratum connection to pool %d resumed", pool->pool_no);
  7124. pool_resus(pool);
  7125. }
  7126. }
  7127. static bool supports_resume(struct pool *pool)
  7128. {
  7129. bool ret;
  7130. cg_rlock(&pool->data_lock);
  7131. ret = (pool->sessionid != NULL);
  7132. cg_runlock(&pool->data_lock);
  7133. return ret;
  7134. }
  7135. /* One stratum thread per pool that has stratum waits on the socket checking
  7136. * for new messages and for the integrity of the socket connection. We reset
  7137. * the connection based on the integrity of the receive side only as the send
  7138. * side will eventually expire data it fails to send. */
  7139. static void *stratum_thread(void *userdata)
  7140. {
  7141. struct pool *pool = (struct pool *)userdata;
  7142. pthread_detach(pthread_self());
  7143. char threadname[20];
  7144. snprintf(threadname, 20, "stratum%u", pool->pool_no);
  7145. RenameThread(threadname);
  7146. srand(time(NULL) + (intptr_t)userdata);
  7147. while (42) {
  7148. struct timeval timeout;
  7149. int sel_ret;
  7150. fd_set rd;
  7151. char *s;
  7152. int sock;
  7153. if (unlikely(!pool->has_stratum))
  7154. break;
  7155. /* Check to see whether we need to maintain this connection
  7156. * indefinitely or just bring it up when we switch to this
  7157. * pool */
  7158. while (true)
  7159. {
  7160. sock = pool->sock;
  7161. if (sock == INVSOCK)
  7162. applog(LOG_DEBUG, "Pool %u: Invalid socket, suspending",
  7163. pool->pool_no);
  7164. else
  7165. if (!sock_full(pool) && !cnx_needed(pool))
  7166. applog(LOG_DEBUG, "Pool %u: Connection not needed, suspending",
  7167. pool->pool_no);
  7168. else
  7169. break;
  7170. suspend_stratum(pool);
  7171. clear_stratum_shares(pool);
  7172. clear_pool_work(pool);
  7173. wait_lpcurrent(pool);
  7174. if (!restart_stratum(pool)) {
  7175. pool_died(pool);
  7176. while (!restart_stratum(pool)) {
  7177. if (pool->removed)
  7178. goto out;
  7179. cgsleep_ms(30000);
  7180. }
  7181. }
  7182. }
  7183. FD_ZERO(&rd);
  7184. FD_SET(sock, &rd);
  7185. timeout.tv_sec = 120;
  7186. timeout.tv_usec = 0;
  7187. /* If we fail to receive any notify messages for 2 minutes we
  7188. * assume the connection has been dropped and treat this pool
  7189. * as dead */
  7190. if (!sock_full(pool) && (sel_ret = select(sock + 1, &rd, NULL, NULL, &timeout)) < 1) {
  7191. applog(LOG_DEBUG, "Stratum select failed on pool %d with value %d", pool->pool_no, sel_ret);
  7192. s = NULL;
  7193. } else
  7194. s = recv_line(pool);
  7195. if (!s) {
  7196. if (!pool->has_stratum)
  7197. break;
  7198. applog(LOG_NOTICE, "Stratum connection to pool %d interrupted", pool->pool_no);
  7199. pool->getfail_occasions++;
  7200. total_go++;
  7201. mutex_lock(&pool->stratum_lock);
  7202. pool->stratum_active = pool->stratum_notify = false;
  7203. pool->sock = INVSOCK;
  7204. mutex_unlock(&pool->stratum_lock);
  7205. /* If the socket to our stratum pool disconnects, all
  7206. * submissions need to be discarded or resent. */
  7207. if (!supports_resume(pool))
  7208. clear_stratum_shares(pool);
  7209. else
  7210. resubmit_stratum_shares(pool);
  7211. clear_pool_work(pool);
  7212. if (pool == current_pool())
  7213. restart_threads();
  7214. if (restart_stratum(pool))
  7215. continue;
  7216. shutdown_stratum(pool);
  7217. pool_died(pool);
  7218. break;
  7219. }
  7220. /* Check this pool hasn't died while being a backup pool and
  7221. * has not had its idle flag cleared */
  7222. stratum_resumed(pool);
  7223. if (!parse_method(pool, s) && !parse_stratum_response(pool, s))
  7224. applog(LOG_INFO, "Unknown stratum msg: %s", s);
  7225. free(s);
  7226. if (pool->swork.clean) {
  7227. struct work *work = make_work();
  7228. /* Generate a single work item to update the current
  7229. * block database */
  7230. pool->swork.clean = false;
  7231. gen_stratum_work(pool, work);
  7232. /* Try to extract block height from coinbase scriptSig */
  7233. uint8_t *bin_height = &bytes_buf(&pool->swork.coinbase)[4 /*version*/ + 1 /*txin count*/ + 36 /*prevout*/ + 1 /*scriptSig len*/ + 1 /*push opcode*/];
  7234. unsigned char cb_height_sz;
  7235. cb_height_sz = bin_height[-1];
  7236. if (cb_height_sz == 3) {
  7237. // FIXME: The block number will overflow this by AD 2173
  7238. uint32_t block_id = ((uint32_t*)work->data)[1];
  7239. uint32_t height = 0;
  7240. memcpy(&height, bin_height, 3);
  7241. height = le32toh(height);
  7242. have_block_height(block_id, height);
  7243. }
  7244. ++pool->work_restart_id;
  7245. if (test_work_current(work)) {
  7246. /* Only accept a work update if this stratum
  7247. * connection is from the current pool */
  7248. if (pool == current_pool()) {
  7249. restart_threads();
  7250. applog(
  7251. (opt_quiet_work_updates ? LOG_DEBUG : LOG_NOTICE),
  7252. "Stratum from pool %d requested work update", pool->pool_no);
  7253. }
  7254. } else
  7255. applog(LOG_NOTICE, "Stratum from pool %d detected new block", pool->pool_no);
  7256. free_work(work);
  7257. }
  7258. if (timer_passed(&pool->swork.tv_transparency, NULL)) {
  7259. // More than 4 timmills past since requested transactions
  7260. timer_unset(&pool->swork.tv_transparency);
  7261. pool_set_opaque(pool, true);
  7262. }
  7263. }
  7264. out:
  7265. return NULL;
  7266. }
  7267. static void init_stratum_thread(struct pool *pool)
  7268. {
  7269. have_longpoll = true;
  7270. if (unlikely(pthread_create(&pool->stratum_thread, NULL, stratum_thread, (void *)pool)))
  7271. quit(1, "Failed to create stratum thread");
  7272. }
  7273. static void *longpoll_thread(void *userdata);
  7274. static bool stratum_works(struct pool *pool)
  7275. {
  7276. applog(LOG_INFO, "Testing pool %d stratum %s", pool->pool_no, pool->stratum_url);
  7277. if (!extract_sockaddr(pool->stratum_url, &pool->sockaddr_url, &pool->stratum_port))
  7278. return false;
  7279. if (pool->stratum_active)
  7280. return true;
  7281. if (!initiate_stratum(pool))
  7282. return false;
  7283. return true;
  7284. }
  7285. static bool pool_active(struct pool *pool, bool pinging)
  7286. {
  7287. struct timeval tv_getwork, tv_getwork_reply;
  7288. bool ret = false;
  7289. json_t *val;
  7290. CURL *curl;
  7291. int rolltime;
  7292. char *rpc_req;
  7293. struct work *work;
  7294. enum pool_protocol proto;
  7295. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  7296. /* This is the central point we activate stratum when we can */
  7297. curl = curl_easy_init();
  7298. if (unlikely(!curl)) {
  7299. applog(LOG_ERR, "CURL initialisation failed");
  7300. return false;
  7301. }
  7302. if (!(want_gbt || want_getwork))
  7303. goto nohttp;
  7304. work = make_work();
  7305. /* Probe for GBT support on first pass */
  7306. proto = want_gbt ? PLP_GETBLOCKTEMPLATE : PLP_GETWORK;
  7307. tryagain:
  7308. rpc_req = prepare_rpc_req_probe(work, proto, NULL);
  7309. work->pool = pool;
  7310. if (!rpc_req)
  7311. goto out;
  7312. pool->probed = false;
  7313. cgtime(&tv_getwork);
  7314. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  7315. true, false, &rolltime, pool, false);
  7316. cgtime(&tv_getwork_reply);
  7317. free(rpc_req);
  7318. /* Detect if a http getwork pool has an X-Stratum header at startup,
  7319. * and if so, switch to that in preference to getwork if it works */
  7320. if (pool->stratum_url && want_stratum && (pool->has_stratum || stratum_works(pool))) {
  7321. if (!pool->has_stratum) {
  7322. applog(LOG_NOTICE, "Switching pool %d %s to %s", pool->pool_no, pool->rpc_url, pool->stratum_url);
  7323. if (!pool->rpc_url)
  7324. pool->rpc_url = strdup(pool->stratum_url);
  7325. pool->has_stratum = true;
  7326. }
  7327. free_work(work);
  7328. if (val)
  7329. json_decref(val);
  7330. retry_stratum:
  7331. curl_easy_cleanup(curl);
  7332. /* We create the stratum thread for each pool just after
  7333. * successful authorisation. Once the init flag has been set
  7334. * we never unset it and the stratum thread is responsible for
  7335. * setting/unsetting the active flag */
  7336. bool init = pool_tset(pool, &pool->stratum_init);
  7337. if (!init) {
  7338. bool ret = initiate_stratum(pool) && auth_stratum(pool);
  7339. if (ret)
  7340. {
  7341. detect_algo = 2;
  7342. init_stratum_thread(pool);
  7343. }
  7344. else
  7345. pool_tclear(pool, &pool->stratum_init);
  7346. return ret;
  7347. }
  7348. return pool->stratum_active;
  7349. }
  7350. else if (pool->has_stratum)
  7351. shutdown_stratum(pool);
  7352. if (val) {
  7353. bool rc;
  7354. json_t *res;
  7355. res = json_object_get(val, "result");
  7356. if ((!json_is_object(res)) || (proto == PLP_GETBLOCKTEMPLATE && !json_object_get(res, "bits")))
  7357. goto badwork;
  7358. work->rolltime = rolltime;
  7359. rc = work_decode(pool, work, val);
  7360. if (rc) {
  7361. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  7362. pool->pool_no, pool->rpc_url);
  7363. work->pool = pool;
  7364. copy_time(&work->tv_getwork, &tv_getwork);
  7365. copy_time(&work->tv_getwork_reply, &tv_getwork_reply);
  7366. work->getwork_mode = GETWORK_MODE_TESTPOOL;
  7367. calc_diff(work, 0);
  7368. update_last_work(work);
  7369. applog(LOG_DEBUG, "Pushing pooltest work to base pool");
  7370. stage_work(work);
  7371. total_getworks++;
  7372. pool->getwork_requested++;
  7373. ret = true;
  7374. cgtime(&pool->tv_idle);
  7375. } else {
  7376. badwork:
  7377. json_decref(val);
  7378. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher work from pool %u %s",
  7379. pool->pool_no, pool->rpc_url);
  7380. pool->proto = proto = pool_protocol_fallback(proto);
  7381. if (PLP_NONE != proto)
  7382. goto tryagain;
  7383. free_work(work);
  7384. goto out;
  7385. }
  7386. json_decref(val);
  7387. if (proto != pool->proto) {
  7388. pool->proto = proto;
  7389. applog(LOG_INFO, "Selected %s protocol for pool %u", pool_protocol_name(proto), pool->pool_no);
  7390. }
  7391. if (pool->lp_url)
  7392. goto out;
  7393. /* Decipher the longpoll URL, if any, and store it in ->lp_url */
  7394. const struct blktmpl_longpoll_req *lp;
  7395. if (work->tmpl && (lp = blktmpl_get_longpoll(work->tmpl))) {
  7396. // NOTE: work_decode takes care of lp id
  7397. pool->lp_url = lp->uri ? absolute_uri(lp->uri, pool->rpc_url) : pool->rpc_url;
  7398. if (!pool->lp_url)
  7399. {
  7400. ret = false;
  7401. goto out;
  7402. }
  7403. pool->lp_proto = PLP_GETBLOCKTEMPLATE;
  7404. }
  7405. else
  7406. if (pool->hdr_path && want_getwork) {
  7407. pool->lp_url = absolute_uri(pool->hdr_path, pool->rpc_url);
  7408. if (!pool->lp_url)
  7409. {
  7410. ret = false;
  7411. goto out;
  7412. }
  7413. pool->lp_proto = PLP_GETWORK;
  7414. } else
  7415. pool->lp_url = NULL;
  7416. if (want_longpoll && !pool->lp_started) {
  7417. pool->lp_started = true;
  7418. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  7419. quit(1, "Failed to create pool longpoll thread");
  7420. }
  7421. } else if (PLP_NONE != (proto = pool_protocol_fallback(proto))) {
  7422. pool->proto = proto;
  7423. goto tryagain;
  7424. } else {
  7425. free_work(work);
  7426. nohttp:
  7427. /* If we failed to parse a getwork, this could be a stratum
  7428. * url without the prefix stratum+tcp:// so let's check it */
  7429. if (extract_sockaddr(pool->rpc_url, &pool->sockaddr_url, &pool->stratum_port) && initiate_stratum(pool)) {
  7430. pool->has_stratum = true;
  7431. goto retry_stratum;
  7432. }
  7433. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  7434. pool->pool_no, pool->rpc_url);
  7435. if (!pinging)
  7436. applog(LOG_WARNING, "Pool %u slow/down or URL or credentials invalid", pool->pool_no);
  7437. }
  7438. out:
  7439. curl_easy_cleanup(curl);
  7440. return ret;
  7441. }
  7442. static void pool_resus(struct pool *pool)
  7443. {
  7444. if (pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  7445. applog(LOG_WARNING, "Pool %d %s alive, testing stability", pool->pool_no, pool->rpc_url);
  7446. else
  7447. applog(LOG_INFO, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  7448. }
  7449. static struct work *hash_pop(void)
  7450. {
  7451. struct work *work = NULL, *tmp;
  7452. int hc;
  7453. struct timespec ts;
  7454. retry:
  7455. mutex_lock(stgd_lock);
  7456. while (!HASH_COUNT(staged_work))
  7457. {
  7458. if (unlikely(staged_full))
  7459. {
  7460. if (likely(opt_queue < 10 + mining_threads))
  7461. {
  7462. ++opt_queue;
  7463. applog(LOG_WARNING, "Staged work underrun; increasing queue minimum to %d", opt_queue);
  7464. }
  7465. else
  7466. applog(LOG_WARNING, "Staged work underrun; not automatically increasing above %d", opt_queue);
  7467. staged_full = false; // Let it fill up before triggering an underrun again
  7468. no_work = true;
  7469. }
  7470. ts = (struct timespec){ .tv_sec = opt_log_interval, };
  7471. pthread_cond_signal(&gws_cond);
  7472. if (ETIMEDOUT == pthread_cond_timedwait(&getq->cond, stgd_lock, &ts))
  7473. {
  7474. run_cmd(cmd_idle);
  7475. pthread_cond_signal(&gws_cond);
  7476. pthread_cond_wait(&getq->cond, stgd_lock);
  7477. }
  7478. }
  7479. no_work = false;
  7480. hc = HASH_COUNT(staged_work);
  7481. /* Find clone work if possible, to allow masters to be reused */
  7482. if (hc > staged_rollable) {
  7483. HASH_ITER(hh, staged_work, work, tmp) {
  7484. if (!work_rollable(work))
  7485. break;
  7486. }
  7487. } else
  7488. work = staged_work;
  7489. if (can_roll(work) && should_roll(work))
  7490. {
  7491. // Instead of consuming it, force it to be cloned and grab the clone
  7492. mutex_unlock(stgd_lock);
  7493. clone_available();
  7494. goto retry;
  7495. }
  7496. HASH_DEL(staged_work, work);
  7497. if (work_rollable(work))
  7498. staged_rollable--;
  7499. /* Signal the getwork scheduler to look for more work */
  7500. pthread_cond_signal(&gws_cond);
  7501. /* Signal hash_pop again in case there are mutliple hash_pop waiters */
  7502. pthread_cond_signal(&getq->cond);
  7503. mutex_unlock(stgd_lock);
  7504. work->pool->last_work_time = time(NULL);
  7505. cgtime(&work->pool->tv_last_work_time);
  7506. return work;
  7507. }
  7508. /* Clones work by rolling it if possible, and returning a clone instead of the
  7509. * original work item which gets staged again to possibly be rolled again in
  7510. * the future */
  7511. static struct work *clone_work(struct work *work)
  7512. {
  7513. int mrs = mining_threads + opt_queue - total_staged();
  7514. struct work *work_clone;
  7515. bool cloned;
  7516. if (mrs < 1)
  7517. return work;
  7518. cloned = false;
  7519. work_clone = make_clone(work);
  7520. while (mrs-- > 0 && can_roll(work) && should_roll(work)) {
  7521. applog(LOG_DEBUG, "Pushing rolled converted work to stage thread");
  7522. stage_work(work_clone);
  7523. roll_work(work);
  7524. work_clone = make_clone(work);
  7525. /* Roll it again to prevent duplicates should this be used
  7526. * directly later on */
  7527. roll_work(work);
  7528. cloned = true;
  7529. }
  7530. if (cloned) {
  7531. stage_work(work);
  7532. return work_clone;
  7533. }
  7534. free_work(work_clone);
  7535. return work;
  7536. }
  7537. void gen_hash(unsigned char *data, unsigned char *hash, int len)
  7538. {
  7539. unsigned char hash1[32];
  7540. sha256(data, len, hash1);
  7541. sha256(hash1, 32, hash);
  7542. }
  7543. /* Diff 1 is a 256 bit unsigned integer of
  7544. * 0x00000000ffff0000000000000000000000000000000000000000000000000000
  7545. * so we use a big endian 64 bit unsigned integer centred on the 5th byte to
  7546. * cover a huge range of difficulty targets, though not all 256 bits' worth */
  7547. static void bdiff_target_leadzero(unsigned char *target, double diff)
  7548. {
  7549. uint64_t *data64, h64;
  7550. double d64;
  7551. d64 = diffone;
  7552. d64 /= diff;
  7553. d64 = ceil(d64);
  7554. h64 = d64;
  7555. memset(target, 0, 32);
  7556. if (d64 < 18446744073709551616.0) {
  7557. unsigned char *rtarget = target;
  7558. memset(rtarget, 0, 32);
  7559. if (opt_scrypt)
  7560. data64 = (uint64_t *)(rtarget + 2);
  7561. else
  7562. data64 = (uint64_t *)(rtarget + 4);
  7563. *data64 = htobe64(h64);
  7564. } else {
  7565. /* Support for the classic all FFs just-below-1 diff */
  7566. if (opt_scrypt)
  7567. memset(&target[2], 0xff, 30);
  7568. else
  7569. memset(&target[4], 0xff, 28);
  7570. }
  7571. }
  7572. void set_target(unsigned char *dest_target, double diff)
  7573. {
  7574. unsigned char rtarget[32];
  7575. bdiff_target_leadzero(rtarget, diff);
  7576. swab256(dest_target, rtarget);
  7577. if (opt_debug) {
  7578. char htarget[65];
  7579. bin2hex(htarget, rtarget, 32);
  7580. applog(LOG_DEBUG, "Generated target %s", htarget);
  7581. }
  7582. }
  7583. void stratum_work_cpy(struct stratum_work * const dst, const struct stratum_work * const src)
  7584. {
  7585. *dst = *src;
  7586. dst->job_id = strdup(src->job_id);
  7587. bytes_cpy(&dst->coinbase, &src->coinbase);
  7588. bytes_cpy(&dst->merkle_bin, &src->merkle_bin);
  7589. }
  7590. void stratum_work_clean(struct stratum_work * const swork)
  7591. {
  7592. free(swork->job_id);
  7593. bytes_free(&swork->coinbase);
  7594. bytes_free(&swork->merkle_bin);
  7595. }
  7596. /* Generates stratum based work based on the most recent notify information
  7597. * from the pool. This will keep generating work while a pool is down so we use
  7598. * other means to detect when the pool has died in stratum_thread */
  7599. static void gen_stratum_work(struct pool *pool, struct work *work)
  7600. {
  7601. clean_work(work);
  7602. cg_wlock(&pool->data_lock);
  7603. pool->swork.data_lock_p = &pool->data_lock;
  7604. bytes_resize(&work->nonce2, pool->n2size);
  7605. if (pool->nonce2sz < pool->n2size)
  7606. memset(&bytes_buf(&work->nonce2)[pool->nonce2sz], 0, pool->n2size - pool->nonce2sz);
  7607. memcpy(bytes_buf(&work->nonce2),
  7608. #ifdef WORDS_BIGENDIAN
  7609. // NOTE: On big endian, the most significant bits are stored at the end, so skip the LSBs
  7610. &((char*)&pool->nonce2)[pool->nonce2off],
  7611. #else
  7612. &pool->nonce2,
  7613. #endif
  7614. pool->nonce2sz);
  7615. pool->nonce2++;
  7616. work->pool = pool;
  7617. work->work_restart_id = work->pool->work_restart_id;
  7618. gen_stratum_work2(work, &pool->swork, pool->nonce1);
  7619. cgtime(&work->tv_staged);
  7620. }
  7621. void gen_stratum_work2(struct work *work, struct stratum_work *swork, const char *nonce1)
  7622. {
  7623. unsigned char *coinbase, merkle_root[32], merkle_sha[64];
  7624. uint8_t *merkle_bin;
  7625. uint32_t *data32, *swap32;
  7626. int i;
  7627. /* Generate coinbase */
  7628. coinbase = bytes_buf(&swork->coinbase);
  7629. memcpy(&coinbase[swork->nonce2_offset], bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  7630. /* Downgrade to a read lock to read off the variables */
  7631. if (swork->data_lock_p)
  7632. cg_dwlock(swork->data_lock_p);
  7633. /* Generate merkle root */
  7634. gen_hash(coinbase, merkle_root, bytes_len(&swork->coinbase));
  7635. memcpy(merkle_sha, merkle_root, 32);
  7636. merkle_bin = bytes_buf(&swork->merkle_bin);
  7637. for (i = 0; i < swork->merkles; ++i, merkle_bin += 32) {
  7638. memcpy(merkle_sha + 32, merkle_bin, 32);
  7639. gen_hash(merkle_sha, merkle_root, 64);
  7640. memcpy(merkle_sha, merkle_root, 32);
  7641. }
  7642. data32 = (uint32_t *)merkle_sha;
  7643. swap32 = (uint32_t *)merkle_root;
  7644. flip32(swap32, data32);
  7645. memcpy(&work->data[0], swork->header1, 36);
  7646. memcpy(&work->data[36], merkle_root, 32);
  7647. *((uint32_t*)&work->data[68]) = htobe32(swork->ntime + timer_elapsed(&swork->tv_received, NULL));
  7648. memcpy(&work->data[72], swork->diffbits, 4);
  7649. memset(&work->data[76], 0, 4); // nonce
  7650. memcpy(&work->data[80], workpadding_bin, 48);
  7651. /* Store the stratum work diff to check it still matches the pool's
  7652. * stratum diff when submitting shares */
  7653. work->sdiff = swork->diff;
  7654. /* Copy parameters required for share submission */
  7655. work->job_id = strdup(swork->job_id);
  7656. work->nonce1 = strdup(nonce1);
  7657. if (swork->data_lock_p)
  7658. cg_runlock(swork->data_lock_p);
  7659. if (opt_debug)
  7660. {
  7661. char header[161];
  7662. char nonce2hex[(bytes_len(&work->nonce2) * 2) + 1];
  7663. bin2hex(header, work->data, 80);
  7664. bin2hex(nonce2hex, bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  7665. applog(LOG_DEBUG, "Generated stratum header %s", header);
  7666. applog(LOG_DEBUG, "Work job_id %s nonce2 %s", work->job_id, nonce2hex);
  7667. }
  7668. calc_midstate(work);
  7669. set_target(work->target, work->sdiff);
  7670. local_work++;
  7671. work->stratum = true;
  7672. work->blk.nonce = 0;
  7673. work->id = total_work++;
  7674. work->longpoll = false;
  7675. work->getwork_mode = GETWORK_MODE_STRATUM;
  7676. /* Nominally allow a driver to ntime roll 60 seconds */
  7677. work->drv_rolllimit = 60;
  7678. calc_diff(work, 0);
  7679. }
  7680. void request_work(struct thr_info *thr)
  7681. {
  7682. struct cgpu_info *cgpu = thr->cgpu;
  7683. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  7684. /* Tell the watchdog thread this thread is waiting on getwork and
  7685. * should not be restarted */
  7686. thread_reportout(thr);
  7687. // HACK: Since get_work still blocks, reportout all processors dependent on this thread
  7688. for (struct cgpu_info *proc = thr->cgpu->next_proc; proc; proc = proc->next_proc)
  7689. {
  7690. if (proc->threads)
  7691. break;
  7692. thread_reportout(proc->thr[0]);
  7693. }
  7694. cgtime(&dev_stats->_get_start);
  7695. }
  7696. // FIXME: Make this non-blocking (and remove HACK above)
  7697. struct work *get_work(struct thr_info *thr)
  7698. {
  7699. const int thr_id = thr->id;
  7700. struct cgpu_info *cgpu = thr->cgpu;
  7701. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  7702. struct cgminer_stats *pool_stats;
  7703. struct timeval tv_get;
  7704. struct work *work = NULL;
  7705. applog(LOG_DEBUG, "%"PRIpreprv": Popping work from get queue to get work", cgpu->proc_repr);
  7706. while (!work) {
  7707. work = hash_pop();
  7708. if (stale_work(work, false)) {
  7709. staged_full = false; // It wasn't really full, since it was stale :(
  7710. discard_work(work);
  7711. work = NULL;
  7712. wake_gws();
  7713. }
  7714. }
  7715. applog(LOG_DEBUG, "%"PRIpreprv": Got work %d from get queue to get work for thread %d",
  7716. cgpu->proc_repr, work->id, thr_id);
  7717. work->thr_id = thr_id;
  7718. thread_reportin(thr);
  7719. // HACK: Since get_work still blocks, reportin all processors dependent on this thread
  7720. for (struct cgpu_info *proc = thr->cgpu->next_proc; proc; proc = proc->next_proc)
  7721. {
  7722. if (proc->threads)
  7723. break;
  7724. thread_reportin(proc->thr[0]);
  7725. }
  7726. work->mined = true;
  7727. work->blk.nonce = 0;
  7728. cgtime(&tv_get);
  7729. timersub(&tv_get, &dev_stats->_get_start, &tv_get);
  7730. timeradd(&tv_get, &dev_stats->getwork_wait, &dev_stats->getwork_wait);
  7731. if (timercmp(&tv_get, &dev_stats->getwork_wait_max, >))
  7732. dev_stats->getwork_wait_max = tv_get;
  7733. if (timercmp(&tv_get, &dev_stats->getwork_wait_min, <))
  7734. dev_stats->getwork_wait_min = tv_get;
  7735. ++dev_stats->getwork_calls;
  7736. pool_stats = &(work->pool->cgminer_stats);
  7737. timeradd(&tv_get, &pool_stats->getwork_wait, &pool_stats->getwork_wait);
  7738. if (timercmp(&tv_get, &pool_stats->getwork_wait_max, >))
  7739. pool_stats->getwork_wait_max = tv_get;
  7740. if (timercmp(&tv_get, &pool_stats->getwork_wait_min, <))
  7741. pool_stats->getwork_wait_min = tv_get;
  7742. ++pool_stats->getwork_calls;
  7743. if (work->work_difficulty < 1)
  7744. {
  7745. if (unlikely(work->work_difficulty < cgpu->min_nonce_diff))
  7746. {
  7747. applog(LOG_WARNING, "%"PRIpreprv": Using work with lower difficulty than device supports",
  7748. cgpu->proc_repr);
  7749. work->nonce_diff = cgpu->min_nonce_diff;
  7750. }
  7751. else
  7752. work->nonce_diff = work->work_difficulty;
  7753. }
  7754. else
  7755. work->nonce_diff = 1;
  7756. return work;
  7757. }
  7758. static
  7759. void _submit_work_async(struct work *work)
  7760. {
  7761. applog(LOG_DEBUG, "Pushing submit work to work thread");
  7762. mutex_lock(&submitting_lock);
  7763. ++total_submitting;
  7764. DL_APPEND(submit_waiting, work);
  7765. mutex_unlock(&submitting_lock);
  7766. notifier_wake(submit_waiting_notifier);
  7767. }
  7768. /* Submit a copy of the tested, statistic recorded work item asynchronously */
  7769. static void submit_work_async2(struct work *work, struct timeval *tv_work_found)
  7770. {
  7771. if (tv_work_found)
  7772. copy_time(&work->tv_work_found, tv_work_found);
  7773. _submit_work_async(work);
  7774. }
  7775. void inc_hw_errors3(struct thr_info *thr, const struct work *work, const uint32_t *bad_nonce_p, float nonce_diff)
  7776. {
  7777. struct cgpu_info * const cgpu = thr->cgpu;
  7778. if (bad_nonce_p)
  7779. {
  7780. if (bad_nonce_p == UNKNOWN_NONCE)
  7781. applog(LOG_DEBUG, "%"PRIpreprv": invalid nonce - HW error",
  7782. cgpu->proc_repr);
  7783. else
  7784. applog(LOG_DEBUG, "%"PRIpreprv": invalid nonce (%08lx) - HW error",
  7785. cgpu->proc_repr, (unsigned long)be32toh(*bad_nonce_p));
  7786. }
  7787. mutex_lock(&stats_lock);
  7788. hw_errors++;
  7789. ++cgpu->hw_errors;
  7790. if (bad_nonce_p)
  7791. {
  7792. total_bad_diff1 += nonce_diff;
  7793. cgpu->bad_diff1 += nonce_diff;
  7794. }
  7795. mutex_unlock(&stats_lock);
  7796. if (thr->cgpu->drv->hw_error)
  7797. thr->cgpu->drv->hw_error(thr);
  7798. }
  7799. enum test_nonce2_result hashtest2(struct work *work, bool checktarget)
  7800. {
  7801. uint32_t *hash2_32 = (uint32_t *)&work->hash[0];
  7802. hash_data(work->hash, work->data);
  7803. if (hash2_32[7] != 0)
  7804. return TNR_BAD;
  7805. if (!checktarget)
  7806. return TNR_GOOD;
  7807. if (!hash_target_check_v(work->hash, work->target))
  7808. return TNR_HIGH;
  7809. return TNR_GOOD;
  7810. }
  7811. enum test_nonce2_result _test_nonce2(struct work *work, uint32_t nonce, bool checktarget)
  7812. {
  7813. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  7814. *work_nonce = htole32(nonce);
  7815. #ifdef USE_SCRYPT
  7816. if (opt_scrypt)
  7817. // NOTE: Depends on scrypt_test return matching enum values
  7818. return scrypt_test(work->data, work->target, nonce);
  7819. #endif
  7820. return hashtest2(work, checktarget);
  7821. }
  7822. /* Returns true if nonce for work was a valid share */
  7823. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  7824. {
  7825. return submit_noffset_nonce(thr, work, nonce, 0);
  7826. }
  7827. /* Allows drivers to submit work items where the driver has changed the ntime
  7828. * value by noffset. Must be only used with a work protocol that does not ntime
  7829. * roll itself intrinsically to generate work (eg stratum). We do not touch
  7830. * the original work struct, but the copy of it only. */
  7831. bool submit_noffset_nonce(struct thr_info *thr, struct work *work_in, uint32_t nonce,
  7832. int noffset)
  7833. {
  7834. struct work *work = make_work();
  7835. _copy_work(work, work_in, noffset);
  7836. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  7837. struct timeval tv_work_found;
  7838. enum test_nonce2_result res;
  7839. bool ret = true;
  7840. thread_reportout(thr);
  7841. cgtime(&tv_work_found);
  7842. *work_nonce = htole32(nonce);
  7843. work->thr_id = thr->id;
  7844. /* Do one last check before attempting to submit the work */
  7845. /* Side effect: sets work->data for us */
  7846. res = test_nonce2(work, nonce);
  7847. if (unlikely(res == TNR_BAD))
  7848. {
  7849. inc_hw_errors(thr, work, nonce);
  7850. ret = false;
  7851. goto out;
  7852. }
  7853. mutex_lock(&stats_lock);
  7854. total_diff1 += work->nonce_diff;
  7855. thr ->cgpu->diff1 += work->nonce_diff;
  7856. work->pool->diff1 += work->nonce_diff;
  7857. thr->cgpu->last_device_valid_work = time(NULL);
  7858. mutex_unlock(&stats_lock);
  7859. if (noncelog_file)
  7860. noncelog(work);
  7861. if (res == TNR_HIGH)
  7862. {
  7863. // Share above target, normal
  7864. /* Check the diff of the share, even if it didn't reach the
  7865. * target, just to set the best share value if it's higher. */
  7866. share_diff(work);
  7867. goto out;
  7868. }
  7869. submit_work_async2(work, &tv_work_found);
  7870. work = NULL; // Taken by submit_work_async2
  7871. out:
  7872. if (work)
  7873. free_work(work);
  7874. thread_reportin(thr);
  7875. return ret;
  7876. }
  7877. bool abandon_work(struct work *work, struct timeval *wdiff, uint64_t hashes)
  7878. {
  7879. if (wdiff->tv_sec > opt_scantime ||
  7880. work->blk.nonce >= MAXTHREADS - hashes ||
  7881. hashes >= 0xfffffffe ||
  7882. stale_work(work, false))
  7883. return true;
  7884. return false;
  7885. }
  7886. void __thr_being_msg(int prio, struct thr_info *thr, const char *being)
  7887. {
  7888. struct cgpu_info *proc = thr->cgpu;
  7889. if (proc->threads > 1)
  7890. applog(prio, "%"PRIpreprv" (thread %d) %s", proc->proc_repr, thr->id, being);
  7891. else
  7892. applog(prio, "%"PRIpreprv" %s", proc->proc_repr, being);
  7893. }
  7894. // Called by asynchronous minerloops, when they find their processor should be disabled
  7895. void mt_disable_start(struct thr_info *mythr)
  7896. {
  7897. struct cgpu_info *cgpu = mythr->cgpu;
  7898. struct device_drv *drv = cgpu->drv;
  7899. if (drv->thread_disable)
  7900. drv->thread_disable(mythr);
  7901. hashmeter2(mythr);
  7902. if (mythr->prev_work)
  7903. free_work(mythr->prev_work);
  7904. mythr->prev_work = mythr->work;
  7905. mythr->work = NULL;
  7906. mythr->_job_transition_in_progress = false;
  7907. __thr_being_msg(LOG_WARNING, mythr, "being disabled");
  7908. mythr->rolling = mythr->cgpu->rolling = 0;
  7909. thread_reportout(mythr);
  7910. mythr->_mt_disable_called = true;
  7911. }
  7912. /* Put a new unqueued work item in cgpu->unqueued_work under cgpu->qlock till
  7913. * the driver tells us it's full so that it may extract the work item using
  7914. * the get_queued() function which adds it to the hashtable on
  7915. * cgpu->queued_work. */
  7916. static void fill_queue(struct thr_info *mythr, struct cgpu_info *cgpu, struct device_drv *drv, const int thr_id)
  7917. {
  7918. thread_reportout(mythr);
  7919. do {
  7920. bool need_work;
  7921. /* Do this lockless just to know if we need more unqueued work. */
  7922. need_work = (!cgpu->unqueued_work);
  7923. /* get_work is a blocking function so do it outside of lock
  7924. * to prevent deadlocks with other locks. */
  7925. if (need_work) {
  7926. struct work *work = get_work(mythr);
  7927. wr_lock(&cgpu->qlock);
  7928. /* Check we haven't grabbed work somehow between
  7929. * checking and picking up the lock. */
  7930. if (likely(!cgpu->unqueued_work))
  7931. cgpu->unqueued_work = work;
  7932. else
  7933. need_work = false;
  7934. wr_unlock(&cgpu->qlock);
  7935. if (unlikely(!need_work))
  7936. discard_work(work);
  7937. }
  7938. /* The queue_full function should be used by the driver to
  7939. * actually place work items on the physical device if it
  7940. * does have a queue. */
  7941. } while (drv->queue_full && !drv->queue_full(cgpu));
  7942. }
  7943. /* Add a work item to a cgpu's queued hashlist */
  7944. void __add_queued(struct cgpu_info *cgpu, struct work *work)
  7945. {
  7946. cgpu->queued_count++;
  7947. HASH_ADD_INT(cgpu->queued_work, id, work);
  7948. }
  7949. /* This function is for retrieving one work item from the unqueued pointer and
  7950. * adding it to the hashtable of queued work. Code using this function must be
  7951. * able to handle NULL as a return which implies there is no work available. */
  7952. struct work *get_queued(struct cgpu_info *cgpu)
  7953. {
  7954. struct work *work = NULL;
  7955. wr_lock(&cgpu->qlock);
  7956. if (cgpu->unqueued_work) {
  7957. work = cgpu->unqueued_work;
  7958. __add_queued(cgpu, work);
  7959. cgpu->unqueued_work = NULL;
  7960. }
  7961. wr_unlock(&cgpu->qlock);
  7962. return work;
  7963. }
  7964. void add_queued(struct cgpu_info *cgpu, struct work *work)
  7965. {
  7966. wr_lock(&cgpu->qlock);
  7967. __add_queued(cgpu, work);
  7968. wr_unlock(&cgpu->qlock);
  7969. }
  7970. /* Get fresh work and add it to cgpu's queued hashlist */
  7971. struct work *get_queue_work(struct thr_info *thr, struct cgpu_info *cgpu, int thr_id)
  7972. {
  7973. struct work *work = get_work(thr);
  7974. add_queued(cgpu, work);
  7975. return work;
  7976. }
  7977. /* This function is for finding an already queued work item in the
  7978. * given que hashtable. Code using this function must be able
  7979. * to handle NULL as a return which implies there is no matching work.
  7980. * The calling function must lock access to the que if it is required.
  7981. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  7982. struct work *__find_work_bymidstate(struct work *que, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  7983. {
  7984. struct work *work, *tmp, *ret = NULL;
  7985. HASH_ITER(hh, que, work, tmp) {
  7986. if (memcmp(work->midstate, midstate, midstatelen) == 0 &&
  7987. memcmp(work->data + offset, data, datalen) == 0) {
  7988. ret = work;
  7989. break;
  7990. }
  7991. }
  7992. return ret;
  7993. }
  7994. /* This function is for finding an already queued work item in the
  7995. * device's queued_work hashtable. Code using this function must be able
  7996. * to handle NULL as a return which implies there is no matching work.
  7997. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  7998. struct work *find_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  7999. {
  8000. struct work *ret;
  8001. rd_lock(&cgpu->qlock);
  8002. ret = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  8003. rd_unlock(&cgpu->qlock);
  8004. return ret;
  8005. }
  8006. struct work *clone_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  8007. {
  8008. struct work *work, *ret = NULL;
  8009. rd_lock(&cgpu->qlock);
  8010. work = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  8011. if (work)
  8012. ret = copy_work(work);
  8013. rd_unlock(&cgpu->qlock);
  8014. return ret;
  8015. }
  8016. void __work_completed(struct cgpu_info *cgpu, struct work *work)
  8017. {
  8018. cgpu->queued_count--;
  8019. HASH_DEL(cgpu->queued_work, work);
  8020. }
  8021. /* This function should be used by queued device drivers when they're sure
  8022. * the work struct is no longer in use. */
  8023. void work_completed(struct cgpu_info *cgpu, struct work *work)
  8024. {
  8025. wr_lock(&cgpu->qlock);
  8026. __work_completed(cgpu, work);
  8027. wr_unlock(&cgpu->qlock);
  8028. free_work(work);
  8029. }
  8030. /* Combines find_queued_work_bymidstate and work_completed in one function
  8031. * withOUT destroying the work so the driver must free it. */
  8032. struct work *take_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  8033. {
  8034. struct work *work;
  8035. wr_lock(&cgpu->qlock);
  8036. work = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  8037. if (work)
  8038. __work_completed(cgpu, work);
  8039. wr_unlock(&cgpu->qlock);
  8040. return work;
  8041. }
  8042. static void flush_queue(struct cgpu_info *cgpu)
  8043. {
  8044. struct work *work = NULL;
  8045. wr_lock(&cgpu->qlock);
  8046. work = cgpu->unqueued_work;
  8047. cgpu->unqueued_work = NULL;
  8048. wr_unlock(&cgpu->qlock);
  8049. if (work) {
  8050. free_work(work);
  8051. applog(LOG_DEBUG, "Discarded queued work item");
  8052. }
  8053. }
  8054. /* This version of hash work is for devices that are fast enough to always
  8055. * perform a full nonce range and need a queue to maintain the device busy.
  8056. * Work creation and destruction is not done from within this function
  8057. * directly. */
  8058. void hash_queued_work(struct thr_info *mythr)
  8059. {
  8060. const long cycle = opt_log_interval / 5 ? : 1;
  8061. struct timeval tv_start = {0, 0}, tv_end;
  8062. struct cgpu_info *cgpu = mythr->cgpu;
  8063. struct device_drv *drv = cgpu->drv;
  8064. const int thr_id = mythr->id;
  8065. int64_t hashes_done = 0;
  8066. if (unlikely(cgpu->deven != DEV_ENABLED))
  8067. mt_disable(mythr);
  8068. while (likely(!cgpu->shutdown)) {
  8069. struct timeval diff;
  8070. int64_t hashes;
  8071. fill_queue(mythr, cgpu, drv, thr_id);
  8072. thread_reportin(mythr);
  8073. hashes = drv->scanwork(mythr);
  8074. /* Reset the bool here in case the driver looks for it
  8075. * synchronously in the scanwork loop. */
  8076. mythr->work_restart = false;
  8077. if (unlikely(hashes == -1 )) {
  8078. applog(LOG_ERR, "%s %d failure, disabling!", drv->name, cgpu->device_id);
  8079. cgpu->deven = DEV_DISABLED;
  8080. dev_error(cgpu, REASON_THREAD_ZERO_HASH);
  8081. mt_disable(mythr);
  8082. }
  8083. hashes_done += hashes;
  8084. cgtime(&tv_end);
  8085. timersub(&tv_end, &tv_start, &diff);
  8086. if (diff.tv_sec >= cycle) {
  8087. hashmeter(thr_id, &diff, hashes_done);
  8088. hashes_done = 0;
  8089. copy_time(&tv_start, &tv_end);
  8090. }
  8091. if (unlikely(mythr->pause || cgpu->deven != DEV_ENABLED))
  8092. mt_disable(mythr);
  8093. if (unlikely(mythr->work_restart)) {
  8094. flush_queue(cgpu);
  8095. if (drv->flush_work)
  8096. drv->flush_work(cgpu);
  8097. }
  8098. }
  8099. // cgpu->deven = DEV_DISABLED; set in miner_thread
  8100. }
  8101. // Called by minerloop, when it is re-enabling a processor
  8102. void mt_disable_finish(struct thr_info *mythr)
  8103. {
  8104. struct device_drv *drv = mythr->cgpu->drv;
  8105. thread_reportin(mythr);
  8106. __thr_being_msg(LOG_WARNING, mythr, "being re-enabled");
  8107. if (drv->thread_enable)
  8108. drv->thread_enable(mythr);
  8109. mythr->_mt_disable_called = false;
  8110. }
  8111. // Called by synchronous minerloops, when they find their processor should be disabled
  8112. // Calls mt_disable_start, waits until it's re-enabled, then calls mt_disable_finish
  8113. void mt_disable(struct thr_info *mythr)
  8114. {
  8115. const struct cgpu_info * const cgpu = mythr->cgpu;
  8116. mt_disable_start(mythr);
  8117. applog(LOG_DEBUG, "Waiting for wakeup notification in miner thread");
  8118. do {
  8119. notifier_read(mythr->notifier);
  8120. } while (mythr->pause || cgpu->deven != DEV_ENABLED);
  8121. mt_disable_finish(mythr);
  8122. }
  8123. enum {
  8124. STAT_SLEEP_INTERVAL = 1,
  8125. STAT_CTR_INTERVAL = 10000000,
  8126. FAILURE_INTERVAL = 30,
  8127. };
  8128. /* Stage another work item from the work returned in a longpoll */
  8129. 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)
  8130. {
  8131. bool rc;
  8132. work->rolltime = rolltime;
  8133. rc = work_decode(pool, work, val);
  8134. if (unlikely(!rc)) {
  8135. applog(LOG_ERR, "Could not convert longpoll data to work");
  8136. free_work(work);
  8137. return;
  8138. }
  8139. total_getworks++;
  8140. pool->getwork_requested++;
  8141. work->pool = pool;
  8142. copy_time(&work->tv_getwork, tv_lp);
  8143. copy_time(&work->tv_getwork_reply, tv_lp_reply);
  8144. calc_diff(work, 0);
  8145. if (pool->enabled == POOL_REJECTING)
  8146. work->mandatory = true;
  8147. work->longpoll = true;
  8148. work->getwork_mode = GETWORK_MODE_LP;
  8149. update_last_work(work);
  8150. /* We'll be checking this work item twice, but we already know it's
  8151. * from a new block so explicitly force the new block detection now
  8152. * rather than waiting for it to hit the stage thread. This also
  8153. * allows testwork to know whether LP discovered the block or not. */
  8154. test_work_current(work);
  8155. /* Don't use backup LPs as work if we have failover-only enabled. Use
  8156. * the longpoll work from a pool that has been rejecting shares as a
  8157. * way to detect when the pool has recovered.
  8158. */
  8159. if (pool != current_pool() && opt_fail_only && pool->enabled != POOL_REJECTING) {
  8160. free_work(work);
  8161. return;
  8162. }
  8163. work = clone_work(work);
  8164. applog(LOG_DEBUG, "Pushing converted work to stage thread");
  8165. stage_work(work);
  8166. applog(LOG_DEBUG, "Converted longpoll data to work");
  8167. }
  8168. /* If we want longpoll, enable it for the chosen default pool, or, if
  8169. * the pool does not support longpoll, find the first one that does
  8170. * and use its longpoll support */
  8171. static struct pool *select_longpoll_pool(struct pool *cp)
  8172. {
  8173. int i;
  8174. if (cp->lp_url)
  8175. return cp;
  8176. for (i = 0; i < total_pools; i++) {
  8177. struct pool *pool = pools[i];
  8178. if (pool->has_stratum || pool->lp_url)
  8179. return pool;
  8180. }
  8181. return NULL;
  8182. }
  8183. /* This will make the longpoll thread wait till it's the current pool, or it
  8184. * has been flagged as rejecting, before attempting to open any connections.
  8185. */
  8186. static void wait_lpcurrent(struct pool *pool)
  8187. {
  8188. while (!cnx_needed(pool) && (pool->enabled == POOL_DISABLED ||
  8189. (pool != current_pool() && pool_strategy != POOL_LOADBALANCE &&
  8190. pool_strategy != POOL_BALANCE))) {
  8191. mutex_lock(&lp_lock);
  8192. pthread_cond_wait(&lp_cond, &lp_lock);
  8193. mutex_unlock(&lp_lock);
  8194. }
  8195. }
  8196. static curl_socket_t save_curl_socket(void *vpool, __maybe_unused curlsocktype purpose, struct curl_sockaddr *addr) {
  8197. struct pool *pool = vpool;
  8198. curl_socket_t sock = socket(addr->family, addr->socktype, addr->protocol);
  8199. pool->lp_socket = sock;
  8200. return sock;
  8201. }
  8202. static void *longpoll_thread(void *userdata)
  8203. {
  8204. struct pool *cp = (struct pool *)userdata;
  8205. /* This *pool is the source of the actual longpoll, not the pool we've
  8206. * tied it to */
  8207. struct timeval start, reply, end;
  8208. struct pool *pool = NULL;
  8209. char threadname[20];
  8210. CURL *curl = NULL;
  8211. int failures = 0;
  8212. char *lp_url;
  8213. int rolltime;
  8214. #ifndef HAVE_PTHREAD_CANCEL
  8215. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  8216. #endif
  8217. snprintf(threadname, 20, "longpoll%u", cp->pool_no);
  8218. RenameThread(threadname);
  8219. curl = curl_easy_init();
  8220. if (unlikely(!curl)) {
  8221. applog(LOG_ERR, "CURL initialisation failed");
  8222. return NULL;
  8223. }
  8224. retry_pool:
  8225. pool = select_longpoll_pool(cp);
  8226. if (!pool) {
  8227. applog(LOG_WARNING, "No suitable long-poll found for %s", cp->rpc_url);
  8228. while (!pool) {
  8229. cgsleep_ms(60000);
  8230. pool = select_longpoll_pool(cp);
  8231. }
  8232. }
  8233. if (pool->has_stratum) {
  8234. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  8235. cp->rpc_url, pool->rpc_url);
  8236. goto out;
  8237. }
  8238. /* Any longpoll from any pool is enough for this to be true */
  8239. have_longpoll = true;
  8240. wait_lpcurrent(cp);
  8241. {
  8242. lp_url = pool->lp_url;
  8243. if (cp == pool)
  8244. applog(LOG_WARNING, "Long-polling activated for %s (%s)", lp_url, pool_protocol_name(pool->lp_proto));
  8245. else
  8246. applog(LOG_WARNING, "Long-polling activated for %s via %s (%s)", cp->rpc_url, lp_url, pool_protocol_name(pool->lp_proto));
  8247. }
  8248. while (42) {
  8249. json_t *val, *soval;
  8250. struct work *work = make_work();
  8251. char *lpreq;
  8252. lpreq = prepare_rpc_req(work, pool->lp_proto, pool->lp_id);
  8253. work->pool = pool;
  8254. if (!lpreq)
  8255. {
  8256. free_work(work);
  8257. goto lpfail;
  8258. }
  8259. wait_lpcurrent(cp);
  8260. cgtime(&start);
  8261. /* Longpoll connections can be persistent for a very long time
  8262. * and any number of issues could have come up in the meantime
  8263. * so always establish a fresh connection instead of relying on
  8264. * a persistent one. */
  8265. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  8266. curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, save_curl_socket);
  8267. curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, pool);
  8268. val = json_rpc_call(curl, lp_url, pool->rpc_userpass,
  8269. lpreq, false, true, &rolltime, pool, false);
  8270. pool->lp_socket = CURL_SOCKET_BAD;
  8271. cgtime(&reply);
  8272. free(lpreq);
  8273. if (likely(val)) {
  8274. soval = json_object_get(json_object_get(val, "result"), "submitold");
  8275. if (soval)
  8276. pool->submit_old = json_is_true(soval);
  8277. else
  8278. pool->submit_old = false;
  8279. convert_to_work(val, rolltime, pool, work, &start, &reply);
  8280. failures = 0;
  8281. json_decref(val);
  8282. } else {
  8283. /* Some pools regularly drop the longpoll request so
  8284. * only see this as longpoll failure if it happens
  8285. * immediately and just restart it the rest of the
  8286. * time. */
  8287. cgtime(&end);
  8288. free_work(work);
  8289. if (end.tv_sec - start.tv_sec > 30)
  8290. continue;
  8291. if (failures == 1)
  8292. applog(LOG_WARNING, "longpoll failed for %s, retrying every 30s", lp_url);
  8293. lpfail:
  8294. cgsleep_ms(30000);
  8295. }
  8296. if (pool != cp) {
  8297. pool = select_longpoll_pool(cp);
  8298. if (pool->has_stratum) {
  8299. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  8300. cp->rpc_url, pool->rpc_url);
  8301. break;
  8302. }
  8303. if (unlikely(!pool))
  8304. goto retry_pool;
  8305. }
  8306. if (unlikely(pool->removed))
  8307. break;
  8308. }
  8309. out:
  8310. curl_easy_cleanup(curl);
  8311. return NULL;
  8312. }
  8313. static void stop_longpoll(void)
  8314. {
  8315. int i;
  8316. want_longpoll = false;
  8317. for (i = 0; i < total_pools; ++i)
  8318. {
  8319. struct pool *pool = pools[i];
  8320. if (unlikely(!pool->lp_started))
  8321. continue;
  8322. pool->lp_started = false;
  8323. pthread_cancel(pool->longpoll_thread);
  8324. }
  8325. have_longpoll = false;
  8326. }
  8327. static void start_longpoll(void)
  8328. {
  8329. int i;
  8330. want_longpoll = true;
  8331. for (i = 0; i < total_pools; ++i)
  8332. {
  8333. struct pool *pool = pools[i];
  8334. if (unlikely(pool->removed || pool->lp_started || !pool->lp_url))
  8335. continue;
  8336. pool->lp_started = true;
  8337. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  8338. quit(1, "Failed to create pool longpoll thread");
  8339. }
  8340. }
  8341. void reinit_device(struct cgpu_info *cgpu)
  8342. {
  8343. if (cgpu->drv->reinit_device)
  8344. cgpu->drv->reinit_device(cgpu);
  8345. }
  8346. static struct timeval rotate_tv;
  8347. /* We reap curls if they are unused for over a minute */
  8348. static void reap_curl(struct pool *pool)
  8349. {
  8350. struct curl_ent *ent, *iter;
  8351. struct timeval now;
  8352. int reaped = 0;
  8353. cgtime(&now);
  8354. mutex_lock(&pool->pool_lock);
  8355. LL_FOREACH_SAFE(pool->curllist, ent, iter) {
  8356. if (pool->curls < 2)
  8357. break;
  8358. if (now.tv_sec - ent->tv.tv_sec > 300) {
  8359. reaped++;
  8360. pool->curls--;
  8361. LL_DELETE(pool->curllist, ent);
  8362. curl_easy_cleanup(ent->curl);
  8363. free(ent);
  8364. }
  8365. }
  8366. mutex_unlock(&pool->pool_lock);
  8367. if (reaped)
  8368. applog(LOG_DEBUG, "Reaped %d curl%s from pool %d", reaped, reaped > 1 ? "s" : "", pool->pool_no);
  8369. }
  8370. static void *watchpool_thread(void __maybe_unused *userdata)
  8371. {
  8372. int intervals = 0;
  8373. #ifndef HAVE_PTHREAD_CANCEL
  8374. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  8375. #endif
  8376. RenameThread("watchpool");
  8377. while (42) {
  8378. struct timeval now;
  8379. int i;
  8380. if (++intervals > 20)
  8381. intervals = 0;
  8382. cgtime(&now);
  8383. for (i = 0; i < total_pools; i++) {
  8384. struct pool *pool = pools[i];
  8385. if (!opt_benchmark)
  8386. reap_curl(pool);
  8387. /* Get a rolling utility per pool over 10 mins */
  8388. if (intervals > 19) {
  8389. int shares = pool->diff1 - pool->last_shares;
  8390. pool->last_shares = pool->diff1;
  8391. pool->utility = (pool->utility + (double)shares * 0.63) / 1.63;
  8392. pool->shares = pool->utility;
  8393. }
  8394. if (pool->enabled == POOL_DISABLED)
  8395. continue;
  8396. /* Don't start testing any pools if the test threads
  8397. * from startup are still doing their first attempt. */
  8398. if (unlikely(pool->testing)) {
  8399. pthread_join(pool->test_thread, NULL);
  8400. }
  8401. /* Test pool is idle once every minute */
  8402. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 30) {
  8403. cgtime(&pool->tv_idle);
  8404. if (pool_active(pool, true) && pool_tclear(pool, &pool->idle))
  8405. pool_resus(pool);
  8406. }
  8407. /* Only switch pools if the failback pool has been
  8408. * alive for more than 5 minutes to prevent
  8409. * intermittently failing pools from being used. */
  8410. if (!pool->idle && pool_strategy == POOL_FAILOVER && pool->prio < cp_prio() &&
  8411. now.tv_sec - pool->tv_idle.tv_sec > 300) {
  8412. applog(LOG_WARNING, "Pool %d %s stable for 5 mins",
  8413. pool->pool_no, pool->rpc_url);
  8414. switch_pools(NULL);
  8415. }
  8416. }
  8417. if (current_pool()->idle)
  8418. switch_pools(NULL);
  8419. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  8420. cgtime(&rotate_tv);
  8421. switch_pools(NULL);
  8422. }
  8423. cgsleep_ms(30000);
  8424. }
  8425. return NULL;
  8426. }
  8427. void mt_enable(struct thr_info *thr)
  8428. {
  8429. applog(LOG_DEBUG, "Waking up thread %d", thr->id);
  8430. notifier_wake(thr->notifier);
  8431. }
  8432. void proc_enable(struct cgpu_info *cgpu)
  8433. {
  8434. int j;
  8435. cgpu->deven = DEV_ENABLED;
  8436. for (j = cgpu->threads ?: 1; j--; )
  8437. mt_enable(cgpu->thr[j]);
  8438. }
  8439. #define device_recovered(cgpu) proc_enable(cgpu)
  8440. void cgpu_set_defaults(struct cgpu_info * const cgpu)
  8441. {
  8442. struct string_elist *setstr_elist;
  8443. const char *p, *p2;
  8444. char replybuf[0x2000];
  8445. size_t L;
  8446. DL_FOREACH(opt_set_device_list, setstr_elist)
  8447. {
  8448. const char * const setstr = setstr_elist->string;
  8449. p = strchr(setstr, ':');
  8450. if (!p)
  8451. p = setstr;
  8452. {
  8453. L = p - setstr;
  8454. char pattern[L + 1];
  8455. if (L)
  8456. memcpy(pattern, setstr, L);
  8457. pattern[L] = '\0';
  8458. if (!cgpu_match(pattern, cgpu))
  8459. continue;
  8460. }
  8461. applog(LOG_DEBUG, "%"PRIpreprv": %s: Matched with set default: %s",
  8462. cgpu->proc_repr, __func__, setstr);
  8463. if (p[0] == ':')
  8464. ++p;
  8465. p2 = strchr(p, '=');
  8466. if (!p2)
  8467. {
  8468. L = strlen(p);
  8469. p2 = "";
  8470. }
  8471. else
  8472. {
  8473. L = p2 - p;
  8474. ++p2;
  8475. }
  8476. char opt[L + 1];
  8477. if (L)
  8478. memcpy(opt, p, L);
  8479. opt[L] = '\0';
  8480. L = strlen(p2);
  8481. char setval[L + 1];
  8482. if (L)
  8483. memcpy(setval, p2, L);
  8484. setval[L] = '\0';
  8485. enum bfg_set_device_replytype success;
  8486. p = proc_set_device(cgpu, opt, setval, replybuf, &success);
  8487. switch (success)
  8488. {
  8489. case SDR_OK:
  8490. applog(LOG_DEBUG, "%"PRIpreprv": Applied rule %s%s%s",
  8491. cgpu->proc_repr, setstr,
  8492. p ? ": " : "", p ?: "");
  8493. break;
  8494. case SDR_ERR:
  8495. case SDR_HELP:
  8496. case SDR_UNKNOWN:
  8497. applog(LOG_WARNING, "%"PRIpreprv": Applying rule %s: %s",
  8498. cgpu->proc_repr, setstr, p);
  8499. break;
  8500. case SDR_AUTO:
  8501. case SDR_NOSUPP:
  8502. applog(LOG_WARNING, "%"PRIpreprv": set_device is not implemented (trying to apply rule: %s)",
  8503. cgpu->proc_repr, setstr);
  8504. }
  8505. }
  8506. cgpu->already_set_defaults = true;
  8507. }
  8508. 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)
  8509. {
  8510. struct device_drv dummy_drv = *drv;
  8511. struct cgpu_info dummy_cgpu = {
  8512. .drv = &dummy_drv,
  8513. .device = &dummy_cgpu,
  8514. .device_id = -1,
  8515. .proc_id = -1,
  8516. .device_data = userp,
  8517. .device_path = devpath,
  8518. .dev_serial = serial,
  8519. };
  8520. strcpy(dummy_cgpu.proc_repr, drv->name);
  8521. switch (mode)
  8522. {
  8523. case 0:
  8524. dummy_drv.set_device = datap;
  8525. break;
  8526. case 1:
  8527. dummy_drv.set_device = NULL;
  8528. dummy_cgpu.set_device_funcs = datap;
  8529. break;
  8530. }
  8531. cgpu_set_defaults(&dummy_cgpu);
  8532. }
  8533. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  8534. * the screen at regular intervals, and restarts threads if they appear to have
  8535. * died. */
  8536. #define WATCHDOG_SICK_TIME 60
  8537. #define WATCHDOG_DEAD_TIME 600
  8538. #define WATCHDOG_SICK_COUNT (WATCHDOG_SICK_TIME/WATCHDOG_INTERVAL)
  8539. #define WATCHDOG_DEAD_COUNT (WATCHDOG_DEAD_TIME/WATCHDOG_INTERVAL)
  8540. static void *watchdog_thread(void __maybe_unused *userdata)
  8541. {
  8542. const unsigned int interval = WATCHDOG_INTERVAL;
  8543. struct timeval zero_tv;
  8544. #ifndef HAVE_PTHREAD_CANCEL
  8545. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  8546. #endif
  8547. RenameThread("watchdog");
  8548. memset(&zero_tv, 0, sizeof(struct timeval));
  8549. cgtime(&rotate_tv);
  8550. while (1) {
  8551. int i;
  8552. struct timeval now;
  8553. sleep(interval);
  8554. discard_stale();
  8555. hashmeter(-1, &zero_tv, 0);
  8556. #ifdef HAVE_CURSES
  8557. const int ts = total_staged();
  8558. if (curses_active_locked()) {
  8559. change_logwinsize();
  8560. curses_print_status(ts);
  8561. _refresh_devstatus(true);
  8562. touchwin(logwin);
  8563. wrefresh(logwin);
  8564. unlock_curses();
  8565. }
  8566. #endif
  8567. cgtime(&now);
  8568. if (!sched_paused && !should_run()) {
  8569. applog(LOG_WARNING, "Pausing execution as per stop time %02d:%02d scheduled",
  8570. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  8571. if (!schedstart.enable) {
  8572. quit(0, "Terminating execution as planned");
  8573. break;
  8574. }
  8575. applog(LOG_WARNING, "Will restart execution as scheduled at %02d:%02d",
  8576. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  8577. sched_paused = true;
  8578. rd_lock(&mining_thr_lock);
  8579. for (i = 0; i < mining_threads; i++)
  8580. mining_thr[i]->pause = true;
  8581. rd_unlock(&mining_thr_lock);
  8582. } else if (sched_paused && should_run()) {
  8583. applog(LOG_WARNING, "Restarting execution as per start time %02d:%02d scheduled",
  8584. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  8585. if (schedstop.enable)
  8586. applog(LOG_WARNING, "Will pause execution as scheduled at %02d:%02d",
  8587. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  8588. sched_paused = false;
  8589. for (i = 0; i < mining_threads; i++) {
  8590. struct thr_info *thr;
  8591. thr = get_thread(i);
  8592. thr->pause = false;
  8593. }
  8594. for (i = 0; i < total_devices; ++i)
  8595. {
  8596. struct cgpu_info *cgpu = get_devices(i);
  8597. /* Don't touch disabled devices */
  8598. if (cgpu->deven == DEV_DISABLED)
  8599. continue;
  8600. proc_enable(cgpu);
  8601. }
  8602. }
  8603. for (i = 0; i < total_devices; ++i) {
  8604. struct cgpu_info *cgpu = get_devices(i);
  8605. if (!cgpu->disable_watchdog)
  8606. bfg_watchdog(cgpu, &now);
  8607. }
  8608. }
  8609. return NULL;
  8610. }
  8611. void bfg_watchdog(struct cgpu_info * const cgpu, struct timeval * const tvp_now)
  8612. {
  8613. struct thr_info *thr = cgpu->thr[0];
  8614. enum dev_enable *denable;
  8615. char *dev_str = cgpu->proc_repr;
  8616. int gpu;
  8617. if (likely(drv_ready(cgpu)))
  8618. {
  8619. if (unlikely(!cgpu->already_set_defaults))
  8620. cgpu_set_defaults(cgpu);
  8621. if (cgpu->drv->get_stats)
  8622. cgpu->drv->get_stats(cgpu);
  8623. }
  8624. gpu = cgpu->device_id;
  8625. denable = &cgpu->deven;
  8626. #ifdef HAVE_ADL
  8627. if (adl_active && cgpu->has_adl)
  8628. gpu_autotune(gpu, denable);
  8629. if (opt_debug && cgpu->has_adl) {
  8630. int engineclock = 0, memclock = 0, activity = 0, fanspeed = 0, fanpercent = 0, powertune = 0;
  8631. float temp = 0, vddc = 0;
  8632. if (gpu_stats(gpu, &temp, &engineclock, &memclock, &vddc, &activity, &fanspeed, &fanpercent, &powertune))
  8633. applog(LOG_DEBUG, "%.1f C F: %d%%(%dRPM) E: %dMHz M: %dMHz V: %.3fV A: %d%% P: %d%%",
  8634. temp, fanpercent, fanspeed, engineclock, memclock, vddc, activity, powertune);
  8635. }
  8636. #endif
  8637. /* Thread is disabled */
  8638. if (*denable == DEV_DISABLED)
  8639. return;
  8640. else
  8641. if (*denable == DEV_RECOVER_ERR) {
  8642. if (opt_restart && timer_elapsed(&cgpu->tv_device_last_not_well, NULL) > cgpu->reinit_backoff) {
  8643. applog(LOG_NOTICE, "Attempting to reinitialize %s",
  8644. dev_str);
  8645. if (cgpu->reinit_backoff < 300)
  8646. cgpu->reinit_backoff *= 2;
  8647. device_recovered(cgpu);
  8648. }
  8649. return;
  8650. }
  8651. else
  8652. if (*denable == DEV_RECOVER) {
  8653. if (opt_restart && cgpu->temp < cgpu->targettemp) {
  8654. applog(LOG_NOTICE, "%s recovered to temperature below target, re-enabling",
  8655. dev_str);
  8656. device_recovered(cgpu);
  8657. }
  8658. dev_error_update(cgpu, REASON_DEV_THERMAL_CUTOFF);
  8659. return;
  8660. }
  8661. else
  8662. if (cgpu->temp > cgpu->cutofftemp)
  8663. {
  8664. applog(LOG_WARNING, "%s hit thermal cutoff limit, disabling!",
  8665. dev_str);
  8666. *denable = DEV_RECOVER;
  8667. dev_error(cgpu, REASON_DEV_THERMAL_CUTOFF);
  8668. run_cmd(cmd_idle);
  8669. }
  8670. if (thr->getwork) {
  8671. if (cgpu->status == LIFE_WELL && thr->getwork < tvp_now->tv_sec - opt_log_interval) {
  8672. int thrid;
  8673. bool cgpu_idle = true;
  8674. thr->rolling = 0;
  8675. for (thrid = 0; thrid < cgpu->threads; ++thrid)
  8676. if (!cgpu->thr[thrid]->getwork)
  8677. cgpu_idle = false;
  8678. if (cgpu_idle) {
  8679. cgpu->rolling = 0;
  8680. cgpu->status = LIFE_WAIT;
  8681. }
  8682. }
  8683. return;
  8684. }
  8685. else if (cgpu->status == LIFE_WAIT)
  8686. cgpu->status = LIFE_WELL;
  8687. #ifdef WANT_CPUMINE
  8688. if (!strcmp(cgpu->drv->dname, "cpu"))
  8689. return;
  8690. #endif
  8691. if (cgpu->status != LIFE_WELL && (tvp_now->tv_sec - thr->last.tv_sec < WATCHDOG_SICK_TIME)) {
  8692. if (likely(cgpu->status != LIFE_INIT && cgpu->status != LIFE_INIT2))
  8693. applog(LOG_ERR, "%s: Recovered, declaring WELL!", dev_str);
  8694. cgpu->status = LIFE_WELL;
  8695. cgpu->device_last_well = time(NULL);
  8696. } else if (cgpu->status == LIFE_WELL && (tvp_now->tv_sec - thr->last.tv_sec > WATCHDOG_SICK_TIME)) {
  8697. thr->rolling = cgpu->rolling = 0;
  8698. cgpu->status = LIFE_SICK;
  8699. applog(LOG_ERR, "%s: Idle for more than 60 seconds, declaring SICK!", dev_str);
  8700. cgtime(&thr->sick);
  8701. dev_error(cgpu, REASON_DEV_SICK_IDLE_60);
  8702. run_cmd(cmd_sick);
  8703. #ifdef HAVE_ADL
  8704. if (adl_active && cgpu->has_adl && gpu_activity(gpu) > 50) {
  8705. applog(LOG_ERR, "GPU still showing activity suggesting a hard hang.");
  8706. applog(LOG_ERR, "Will not attempt to auto-restart it.");
  8707. } else
  8708. #endif
  8709. if (opt_restart && cgpu->drv->reinit_device) {
  8710. applog(LOG_ERR, "%s: Attempting to restart", dev_str);
  8711. reinit_device(cgpu);
  8712. }
  8713. } else if (cgpu->status == LIFE_SICK && (tvp_now->tv_sec - thr->last.tv_sec > WATCHDOG_DEAD_TIME)) {
  8714. cgpu->status = LIFE_DEAD;
  8715. applog(LOG_ERR, "%s: Not responded for more than 10 minutes, declaring DEAD!", dev_str);
  8716. cgtime(&thr->sick);
  8717. dev_error(cgpu, REASON_DEV_DEAD_IDLE_600);
  8718. run_cmd(cmd_dead);
  8719. } else if (tvp_now->tv_sec - thr->sick.tv_sec > 60 &&
  8720. (cgpu->status == LIFE_SICK || cgpu->status == LIFE_DEAD)) {
  8721. /* Attempt to restart a GPU that's sick or dead once every minute */
  8722. cgtime(&thr->sick);
  8723. #ifdef HAVE_ADL
  8724. if (adl_active && cgpu->has_adl && gpu_activity(gpu) > 50) {
  8725. /* Again do not attempt to restart a device that may have hard hung */
  8726. } else
  8727. #endif
  8728. if (opt_restart)
  8729. reinit_device(cgpu);
  8730. }
  8731. }
  8732. static void log_print_status(struct cgpu_info *cgpu)
  8733. {
  8734. char logline[255];
  8735. get_statline(logline, sizeof(logline), cgpu);
  8736. applog(LOG_WARNING, "%s", logline);
  8737. }
  8738. void print_summary(void)
  8739. {
  8740. struct timeval diff;
  8741. int hours, mins, secs, i;
  8742. double utility, efficiency = 0.0;
  8743. char xfer[17], bw[19];
  8744. int pool_secs;
  8745. timersub(&total_tv_end, &total_tv_start, &diff);
  8746. hours = diff.tv_sec / 3600;
  8747. mins = (diff.tv_sec % 3600) / 60;
  8748. secs = diff.tv_sec % 60;
  8749. utility = total_accepted / total_secs * 60;
  8750. efficiency = total_bytes_xfer ? total_diff_accepted * 2048. / total_bytes_xfer : 0.0;
  8751. applog(LOG_WARNING, "\nSummary of runtime statistics:\n");
  8752. applog(LOG_WARNING, "Started at %s", datestamp);
  8753. if (total_pools == 1)
  8754. applog(LOG_WARNING, "Pool: %s", pools[0]->rpc_url);
  8755. #ifdef WANT_CPUMINE
  8756. if (opt_n_threads)
  8757. applog(LOG_WARNING, "CPU hasher algorithm used: %s", algo_names[opt_algo]);
  8758. #endif
  8759. applog(LOG_WARNING, "Runtime: %d hrs : %d mins : %d secs", hours, mins, secs);
  8760. applog(LOG_WARNING, "Average hashrate: %.1f Megahash/s", total_mhashes_done / total_secs);
  8761. applog(LOG_WARNING, "Solved blocks: %d", found_blocks);
  8762. applog(LOG_WARNING, "Best share difficulty: %s", best_share);
  8763. applog(LOG_WARNING, "Share submissions: %d", total_accepted + total_rejected);
  8764. applog(LOG_WARNING, "Accepted shares: %d", total_accepted);
  8765. applog(LOG_WARNING, "Rejected shares: %d + %d stale (%.2f%%)",
  8766. total_rejected, total_stale,
  8767. (float)(total_rejected + total_stale) / (float)(total_rejected + total_stale + total_accepted)
  8768. );
  8769. applog(LOG_WARNING, "Accepted difficulty shares: %1.f", total_diff_accepted);
  8770. applog(LOG_WARNING, "Rejected difficulty shares: %1.f", total_diff_rejected);
  8771. applog(LOG_WARNING, "Hardware errors: %d", hw_errors);
  8772. applog(LOG_WARNING, "Network transfer: %s (%s)",
  8773. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  8774. (float)total_bytes_rcvd,
  8775. (float)total_bytes_sent),
  8776. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  8777. (float)(total_bytes_rcvd / total_secs),
  8778. (float)(total_bytes_sent / total_secs)));
  8779. applog(LOG_WARNING, "Efficiency (accepted shares * difficulty / 2 KB): %.2f", efficiency);
  8780. applog(LOG_WARNING, "Utility (accepted shares / min): %.2f/min\n", utility);
  8781. applog(LOG_WARNING, "Unable to get work from server occasions: %d", total_go);
  8782. applog(LOG_WARNING, "Work items generated locally: %d", local_work);
  8783. applog(LOG_WARNING, "Submitting work remotely delay occasions: %d", total_ro);
  8784. applog(LOG_WARNING, "New blocks detected on network: %d\n", new_blocks);
  8785. if (total_pools > 1) {
  8786. for (i = 0; i < total_pools; i++) {
  8787. struct pool *pool = pools[i];
  8788. applog(LOG_WARNING, "Pool: %s", pool->rpc_url);
  8789. if (pool->solved)
  8790. applog(LOG_WARNING, "SOLVED %d BLOCK%s!", pool->solved, pool->solved > 1 ? "S" : "");
  8791. applog(LOG_WARNING, " Share submissions: %d", pool->accepted + pool->rejected);
  8792. applog(LOG_WARNING, " Accepted shares: %d", pool->accepted);
  8793. applog(LOG_WARNING, " Rejected shares: %d + %d stale (%.2f%%)",
  8794. pool->rejected, pool->stale_shares,
  8795. (float)(pool->rejected + pool->stale_shares) / (float)(pool->rejected + pool->stale_shares + pool->accepted)
  8796. );
  8797. applog(LOG_WARNING, " Accepted difficulty shares: %1.f", pool->diff_accepted);
  8798. applog(LOG_WARNING, " Rejected difficulty shares: %1.f", pool->diff_rejected);
  8799. pool_secs = timer_elapsed(&pool->cgminer_stats.start_tv, NULL);
  8800. applog(LOG_WARNING, " Network transfer: %s (%s)",
  8801. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  8802. (float)pool->cgminer_pool_stats.net_bytes_received,
  8803. (float)pool->cgminer_pool_stats.net_bytes_sent),
  8804. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  8805. (float)(pool->cgminer_pool_stats.net_bytes_received / pool_secs),
  8806. (float)(pool->cgminer_pool_stats.net_bytes_sent / pool_secs)));
  8807. uint64_t pool_bytes_xfer = pool->cgminer_pool_stats.net_bytes_received + pool->cgminer_pool_stats.net_bytes_sent;
  8808. efficiency = pool_bytes_xfer ? pool->diff_accepted * 2048. / pool_bytes_xfer : 0.0;
  8809. applog(LOG_WARNING, " Efficiency (accepted * difficulty / 2 KB): %.2f", efficiency);
  8810. applog(LOG_WARNING, " Items worked on: %d", pool->works);
  8811. applog(LOG_WARNING, " Unable to get work from server occasions: %d", pool->getfail_occasions);
  8812. applog(LOG_WARNING, " Submitting work remotely delay occasions: %d\n", pool->remotefail_occasions);
  8813. }
  8814. }
  8815. applog(LOG_WARNING, "Summary of per device statistics:\n");
  8816. for (i = 0; i < total_devices; ++i) {
  8817. struct cgpu_info *cgpu = get_devices(i);
  8818. if ((!cgpu->proc_id) && cgpu->procs > 1)
  8819. {
  8820. // Device summary line
  8821. opt_show_procs = false;
  8822. log_print_status(cgpu);
  8823. opt_show_procs = true;
  8824. }
  8825. log_print_status(cgpu);
  8826. }
  8827. if (opt_shares) {
  8828. applog(LOG_WARNING, "Mined %.0f accepted shares of %d requested\n", total_diff_accepted, opt_shares);
  8829. if (opt_shares > total_diff_accepted)
  8830. applog(LOG_WARNING, "WARNING - Mined only %.0f shares of %d requested.", total_diff_accepted, opt_shares);
  8831. }
  8832. applog(LOG_WARNING, " ");
  8833. fflush(stderr);
  8834. fflush(stdout);
  8835. }
  8836. void _bfg_clean_up(bool restarting)
  8837. {
  8838. #ifdef HAVE_OPENCL
  8839. clear_adl(nDevs);
  8840. #endif
  8841. #ifdef HAVE_LIBUSB
  8842. if (likely(have_libusb))
  8843. libusb_exit(NULL);
  8844. #endif
  8845. cgtime(&total_tv_end);
  8846. #ifdef WIN32
  8847. timeEndPeriod(1);
  8848. #endif
  8849. if (!restarting) {
  8850. /* Attempting to disable curses or print a summary during a
  8851. * restart can lead to a deadlock. */
  8852. #ifdef HAVE_CURSES
  8853. disable_curses();
  8854. #endif
  8855. if (!opt_realquiet && successful_connect)
  8856. print_summary();
  8857. }
  8858. if (opt_n_threads)
  8859. free(cpus);
  8860. curl_global_cleanup();
  8861. #ifdef WIN32
  8862. WSACleanup();
  8863. #endif
  8864. }
  8865. void _quit(int status)
  8866. {
  8867. if (status) {
  8868. const char *ev = getenv("__BFGMINER_SEGFAULT_ERRQUIT");
  8869. if (unlikely(ev && ev[0] && ev[0] != '0')) {
  8870. int *p = NULL;
  8871. // NOTE debugger can bypass with: p = &p
  8872. *p = status; // Segfault, hopefully dumping core
  8873. }
  8874. }
  8875. #if defined(unix) || defined(__APPLE__)
  8876. if (forkpid > 0) {
  8877. kill(forkpid, SIGTERM);
  8878. forkpid = 0;
  8879. }
  8880. #endif
  8881. exit(status);
  8882. }
  8883. #ifdef HAVE_CURSES
  8884. char *curses_input(const char *query)
  8885. {
  8886. char *input;
  8887. echo();
  8888. input = malloc(255);
  8889. if (!input)
  8890. quit(1, "Failed to malloc input");
  8891. leaveok(logwin, false);
  8892. wlogprint("%s:\n", query);
  8893. wgetnstr(logwin, input, 255);
  8894. if (!strlen(input))
  8895. {
  8896. free(input);
  8897. input = NULL;
  8898. }
  8899. leaveok(logwin, true);
  8900. noecho();
  8901. return input;
  8902. }
  8903. #endif
  8904. static bool pools_active = false;
  8905. static void *test_pool_thread(void *arg)
  8906. {
  8907. struct pool *pool = (struct pool *)arg;
  8908. if (pool_active(pool, false)) {
  8909. pool_tset(pool, &pool->lagging);
  8910. pool_tclear(pool, &pool->idle);
  8911. bool first_pool = false;
  8912. cg_wlock(&control_lock);
  8913. if (!pools_active) {
  8914. currentpool = pool;
  8915. if (pool->pool_no != 0)
  8916. first_pool = true;
  8917. pools_active = true;
  8918. }
  8919. cg_wunlock(&control_lock);
  8920. if (unlikely(first_pool))
  8921. applog(LOG_NOTICE, "Switching to pool %d %s - first alive pool", pool->pool_no, pool->rpc_url);
  8922. else
  8923. applog(LOG_NOTICE, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  8924. switch_pools(NULL);
  8925. } else
  8926. pool_died(pool);
  8927. pool->testing = false;
  8928. return NULL;
  8929. }
  8930. /* Always returns true that the pool details were added unless we are not
  8931. * live, implying this is the only pool being added, so if no pools are
  8932. * active it returns false. */
  8933. bool add_pool_details(struct pool *pool, bool live, char *url, char *user, char *pass)
  8934. {
  8935. size_t siz;
  8936. pool->rpc_url = url;
  8937. pool->rpc_user = user;
  8938. pool->rpc_pass = pass;
  8939. siz = strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2;
  8940. pool->rpc_userpass = malloc(siz);
  8941. if (!pool->rpc_userpass)
  8942. quit(1, "Failed to malloc userpass");
  8943. snprintf(pool->rpc_userpass, siz, "%s:%s", pool->rpc_user, pool->rpc_pass);
  8944. pool->testing = true;
  8945. pool->idle = true;
  8946. enable_pool(pool);
  8947. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  8948. if (!live) {
  8949. pthread_join(pool->test_thread, NULL);
  8950. return pools_active;
  8951. }
  8952. return true;
  8953. }
  8954. #ifdef HAVE_CURSES
  8955. static bool input_pool(bool live)
  8956. {
  8957. char *url = NULL, *user = NULL, *pass = NULL;
  8958. struct pool *pool;
  8959. bool ret = false;
  8960. immedok(logwin, true);
  8961. wlogprint("Input server details.\n");
  8962. url = curses_input("URL");
  8963. if (!url)
  8964. goto out;
  8965. user = curses_input("Username");
  8966. if (!user)
  8967. goto out;
  8968. pass = curses_input("Password");
  8969. if (!pass)
  8970. pass = calloc(1, 1);
  8971. pool = add_pool();
  8972. if (!detect_stratum(pool, url) && strncmp(url, "http://", 7) &&
  8973. strncmp(url, "https://", 8)) {
  8974. char *httpinput;
  8975. httpinput = malloc(256);
  8976. if (!httpinput)
  8977. quit(1, "Failed to malloc httpinput");
  8978. strcpy(httpinput, "http://");
  8979. strncat(httpinput, url, 248);
  8980. free(url);
  8981. url = httpinput;
  8982. }
  8983. ret = add_pool_details(pool, live, url, user, pass);
  8984. out:
  8985. immedok(logwin, false);
  8986. if (!ret) {
  8987. if (url)
  8988. free(url);
  8989. if (user)
  8990. free(user);
  8991. if (pass)
  8992. free(pass);
  8993. }
  8994. return ret;
  8995. }
  8996. #endif
  8997. #if defined(unix) || defined(__APPLE__)
  8998. static void fork_monitor()
  8999. {
  9000. // Make a pipe: [readFD, writeFD]
  9001. int pfd[2];
  9002. int r = pipe(pfd);
  9003. if (r < 0) {
  9004. perror("pipe - failed to create pipe for --monitor");
  9005. exit(1);
  9006. }
  9007. // Make stderr write end of pipe
  9008. fflush(stderr);
  9009. r = dup2(pfd[1], 2);
  9010. if (r < 0) {
  9011. perror("dup2 - failed to alias stderr to write end of pipe for --monitor");
  9012. exit(1);
  9013. }
  9014. r = close(pfd[1]);
  9015. if (r < 0) {
  9016. perror("close - failed to close write end of pipe for --monitor");
  9017. exit(1);
  9018. }
  9019. // Don't allow a dying monitor to kill the main process
  9020. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  9021. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  9022. if (SIG_ERR == sr0 || SIG_ERR == sr1) {
  9023. perror("signal - failed to edit signal mask for --monitor");
  9024. exit(1);
  9025. }
  9026. // Fork a child process
  9027. forkpid = fork();
  9028. if (forkpid < 0) {
  9029. perror("fork - failed to fork child process for --monitor");
  9030. exit(1);
  9031. }
  9032. // Child: launch monitor command
  9033. if (0 == forkpid) {
  9034. // Make stdin read end of pipe
  9035. r = dup2(pfd[0], 0);
  9036. if (r < 0) {
  9037. perror("dup2 - in child, failed to alias read end of pipe to stdin for --monitor");
  9038. exit(1);
  9039. }
  9040. close(pfd[0]);
  9041. if (r < 0) {
  9042. perror("close - in child, failed to close read end of pipe for --monitor");
  9043. exit(1);
  9044. }
  9045. // Launch user specified command
  9046. execl("/bin/bash", "/bin/bash", "-c", opt_stderr_cmd, (char*)NULL);
  9047. perror("execl - in child failed to exec user specified command for --monitor");
  9048. exit(1);
  9049. }
  9050. // Parent: clean up unused fds and bail
  9051. r = close(pfd[0]);
  9052. if (r < 0) {
  9053. perror("close - failed to close read end of pipe for --monitor");
  9054. exit(1);
  9055. }
  9056. }
  9057. #endif // defined(unix)
  9058. #ifdef HAVE_CURSES
  9059. #ifdef USE_UNICODE
  9060. static
  9061. wchar_t select_unicode_char(const wchar_t *opt)
  9062. {
  9063. for ( ; *opt; ++opt)
  9064. if (iswprint(*opt))
  9065. return *opt;
  9066. return '?';
  9067. }
  9068. #endif
  9069. void enable_curses(void) {
  9070. int x;
  9071. __maybe_unused int y;
  9072. lock_curses();
  9073. if (curses_active) {
  9074. unlock_curses();
  9075. return;
  9076. }
  9077. #ifdef USE_UNICODE
  9078. if (use_unicode)
  9079. {
  9080. setlocale(LC_CTYPE, "");
  9081. if (iswprint(0xb0))
  9082. have_unicode_degrees = true;
  9083. unicode_micro = select_unicode_char(L"\xb5\u03bcu");
  9084. }
  9085. #endif
  9086. mainwin = initscr();
  9087. start_color();
  9088. #if defined(PDCURSES) || defined(NCURSES_VERSION)
  9089. if (ERR != use_default_colors())
  9090. default_bgcolor = -1;
  9091. #endif
  9092. if (has_colors() && ERR != init_pair(1, COLOR_WHITE, COLOR_BLUE))
  9093. {
  9094. menu_attr = COLOR_PAIR(1);
  9095. if (ERR != init_pair(2, COLOR_RED, default_bgcolor))
  9096. attr_bad |= COLOR_PAIR(2);
  9097. }
  9098. keypad(mainwin, true);
  9099. getmaxyx(mainwin, y, x);
  9100. statuswin = newwin(logstart, x, 0, 0);
  9101. leaveok(statuswin, true);
  9102. // For whatever reason, PDCurses crashes if the logwin is initialized to height y-logcursor
  9103. // We resize the window later anyway, so just start it off at 1 :)
  9104. logwin = newwin(1, 0, logcursor, 0);
  9105. idlok(logwin, true);
  9106. scrollok(logwin, true);
  9107. leaveok(logwin, true);
  9108. cbreak();
  9109. noecho();
  9110. nonl();
  9111. curses_active = true;
  9112. statusy = logstart;
  9113. unlock_curses();
  9114. }
  9115. #endif
  9116. /* TODO: fix need a dummy CPU device_drv even if no support for CPU mining */
  9117. #ifndef WANT_CPUMINE
  9118. struct device_drv cpu_drv;
  9119. struct device_drv cpu_drv = {
  9120. .name = "CPU",
  9121. };
  9122. #endif
  9123. static int cgminer_id_count = 0;
  9124. static int device_line_id_count;
  9125. void register_device(struct cgpu_info *cgpu)
  9126. {
  9127. cgpu->deven = DEV_ENABLED;
  9128. wr_lock(&devices_lock);
  9129. devices[cgpu->cgminer_id = cgminer_id_count++] = cgpu;
  9130. wr_unlock(&devices_lock);
  9131. if (!cgpu->proc_id)
  9132. cgpu->device_line_id = device_line_id_count++;
  9133. mining_threads += cgpu->threads ?: 1;
  9134. #ifdef HAVE_CURSES
  9135. adj_width(mining_threads, &dev_width);
  9136. #endif
  9137. rwlock_init(&cgpu->qlock);
  9138. cgpu->queued_work = NULL;
  9139. }
  9140. struct _cgpu_devid_counter {
  9141. char name[4];
  9142. int lastid;
  9143. UT_hash_handle hh;
  9144. };
  9145. void renumber_cgpu(struct cgpu_info *cgpu)
  9146. {
  9147. static struct _cgpu_devid_counter *devids = NULL;
  9148. struct _cgpu_devid_counter *d;
  9149. HASH_FIND_STR(devids, cgpu->drv->name, d);
  9150. if (d)
  9151. cgpu->device_id = ++d->lastid;
  9152. else {
  9153. d = malloc(sizeof(*d));
  9154. memcpy(d->name, cgpu->drv->name, sizeof(d->name));
  9155. cgpu->device_id = d->lastid = 0;
  9156. HASH_ADD_STR(devids, name, d);
  9157. }
  9158. }
  9159. static bool my_blkmaker_sha256_callback(void *digest, const void *buffer, size_t length)
  9160. {
  9161. sha256(buffer, length, digest);
  9162. return true;
  9163. }
  9164. #ifndef HAVE_PTHREAD_CANCEL
  9165. extern void setup_pthread_cancel_workaround();
  9166. extern struct sigaction pcwm_orig_term_handler;
  9167. #endif
  9168. bool bfg_need_detect_rescan;
  9169. extern void probe_device(struct lowlevel_device_info *);
  9170. static
  9171. void drv_detect_all()
  9172. {
  9173. rescan:
  9174. bfg_need_detect_rescan = false;
  9175. #ifdef HAVE_BFG_LOWLEVEL
  9176. struct lowlevel_device_info * const infolist = lowlevel_scan(), *info, *infotmp;
  9177. LL_FOREACH_SAFE(infolist, info, infotmp)
  9178. probe_device(info);
  9179. LL_FOREACH_SAFE(infolist, info, infotmp)
  9180. pthread_join(info->probe_pth, NULL);
  9181. #endif
  9182. struct driver_registration *reg, *tmp;
  9183. const int algomatch = opt_scrypt ? POW_SCRYPT : POW_SHA256D;
  9184. BFG_FOREACH_DRIVER_BY_PRIORITY(reg, tmp)
  9185. {
  9186. const struct device_drv * const drv = reg->drv;
  9187. const supported_algos_t algos = drv->supported_algos ?: POW_SHA256D;
  9188. if (0 == (algos & algomatch) || !drv->drv_detect)
  9189. continue;
  9190. drv->drv_detect();
  9191. }
  9192. #ifdef HAVE_BFG_LOWLEVEL
  9193. lowlevel_scan_free();
  9194. #endif
  9195. if (bfg_need_detect_rescan)
  9196. {
  9197. applog(LOG_DEBUG, "Device rescan requested");
  9198. goto rescan;
  9199. }
  9200. }
  9201. static
  9202. void allocate_cgpu(struct cgpu_info *cgpu, unsigned int *kp)
  9203. {
  9204. struct thr_info *thr;
  9205. int j;
  9206. struct device_drv *api = cgpu->drv;
  9207. if (!cgpu->devtype)
  9208. cgpu->devtype = "PGA";
  9209. cgpu->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  9210. int threadobj = cgpu->threads;
  9211. if (!threadobj)
  9212. // Create a fake thread object to handle hashmeter etc
  9213. threadobj = 1;
  9214. cgpu->thr = calloc(threadobj + 1, sizeof(*cgpu->thr));
  9215. cgpu->thr[threadobj] = NULL;
  9216. cgpu->status = LIFE_INIT;
  9217. if (opt_devices_enabled_list)
  9218. {
  9219. struct string_elist *enablestr_elist;
  9220. cgpu->deven = DEV_DISABLED;
  9221. DL_FOREACH(opt_devices_enabled_list, enablestr_elist)
  9222. {
  9223. const char * const enablestr = enablestr_elist->string;
  9224. if (cgpu_match(enablestr, cgpu))
  9225. {
  9226. cgpu->deven = DEV_ENABLED;
  9227. break;
  9228. }
  9229. }
  9230. }
  9231. cgpu->max_hashes = 0;
  9232. BFGINIT(cgpu->min_nonce_diff, 1);
  9233. // Setup thread structs before starting any of the threads, in case they try to interact
  9234. for (j = 0; j < threadobj; ++j, ++*kp) {
  9235. thr = get_thread(*kp);
  9236. thr->id = *kp;
  9237. thr->cgpu = cgpu;
  9238. thr->device_thread = j;
  9239. thr->work_restart_notifier[1] = INVSOCK;
  9240. thr->mutex_request[1] = INVSOCK;
  9241. thr->_job_transition_in_progress = true;
  9242. timerclear(&thr->tv_morework);
  9243. thr->scanhash_working = true;
  9244. thr->hashes_done = 0;
  9245. timerclear(&thr->tv_hashes_done);
  9246. cgtime(&thr->tv_lastupdate);
  9247. thr->tv_poll.tv_sec = -1;
  9248. thr->_max_nonce = api->can_limit_work ? api->can_limit_work(thr) : 0xffffffff;
  9249. cgpu->thr[j] = thr;
  9250. }
  9251. if (!cgpu->device->threads)
  9252. notifier_init_invalid(cgpu->thr[0]->notifier);
  9253. else
  9254. if (!cgpu->threads)
  9255. memcpy(&cgpu->thr[0]->notifier, &cgpu->device->thr[0]->notifier, sizeof(cgpu->thr[0]->notifier));
  9256. else
  9257. for (j = 0; j < cgpu->threads; ++j)
  9258. {
  9259. thr = cgpu->thr[j];
  9260. notifier_init(thr->notifier);
  9261. }
  9262. }
  9263. static
  9264. void start_cgpu(struct cgpu_info *cgpu)
  9265. {
  9266. struct thr_info *thr;
  9267. int j;
  9268. for (j = 0; j < cgpu->threads; ++j) {
  9269. thr = cgpu->thr[j];
  9270. /* Enable threads for devices set not to mine but disable
  9271. * their queue in case we wish to enable them later */
  9272. if (cgpu->drv->thread_prepare && !cgpu->drv->thread_prepare(thr))
  9273. continue;
  9274. thread_reportout(thr);
  9275. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  9276. quit(1, "thread %d create failed", thr->id);
  9277. notifier_wake(thr->notifier);
  9278. }
  9279. if (cgpu->deven == DEV_ENABLED)
  9280. proc_enable(cgpu);
  9281. }
  9282. static
  9283. void _scan_serial(void *p)
  9284. {
  9285. const char *s = p;
  9286. struct string_elist *iter, *tmp;
  9287. struct string_elist *orig_scan_devices = scan_devices;
  9288. if (s)
  9289. {
  9290. // Make temporary scan_devices list
  9291. scan_devices = NULL;
  9292. string_elist_add("noauto", &scan_devices);
  9293. add_serial(s);
  9294. }
  9295. drv_detect_all();
  9296. if (s)
  9297. {
  9298. DL_FOREACH_SAFE(scan_devices, iter, tmp)
  9299. {
  9300. string_elist_del(&scan_devices, iter);
  9301. }
  9302. scan_devices = orig_scan_devices;
  9303. }
  9304. }
  9305. #ifdef HAVE_BFG_LOWLEVEL
  9306. static
  9307. bool _probe_device_match(const struct lowlevel_device_info * const info, const char * const ser)
  9308. {
  9309. if (!(false
  9310. || (info->serial && !strcasecmp(ser, info->serial))
  9311. || (info->path && !strcasecmp(ser, info->path ))
  9312. || (info->devid && !strcasecmp(ser, info->devid ))
  9313. ))
  9314. {
  9315. char *devid = devpath_to_devid(ser);
  9316. if (!devid)
  9317. return false;
  9318. const bool different = strcmp(info->devid, devid);
  9319. free(devid);
  9320. if (different)
  9321. return false;
  9322. }
  9323. return true;
  9324. }
  9325. static
  9326. const struct device_drv *_probe_device_find_drv(const char * const _dname, const size_t dnamelen)
  9327. {
  9328. struct driver_registration *dreg;
  9329. char dname[dnamelen];
  9330. int i;
  9331. for (i = 0; i < dnamelen; ++i)
  9332. dname[i] = tolower(_dname[i]);
  9333. BFG_FIND_DRV_BY_DNAME(dreg, dname, dnamelen);
  9334. if (!dreg)
  9335. {
  9336. for (i = 0; i < dnamelen; ++i)
  9337. dname[i] = toupper(_dname[i]);
  9338. BFG_FIND_DRV_BY_NAME(dreg, dname, dnamelen);
  9339. if (!dreg)
  9340. return NULL;
  9341. }
  9342. return dreg->drv;
  9343. }
  9344. static
  9345. bool _probe_device_internal(struct lowlevel_device_info * const info, const char * const dname, const size_t dnamelen)
  9346. {
  9347. const struct device_drv * const drv = _probe_device_find_drv(dname, dnamelen);
  9348. if (!(drv && drv->lowl_probe))
  9349. return false;
  9350. return drv->lowl_probe(info);
  9351. }
  9352. static
  9353. void *probe_device_thread(void *p)
  9354. {
  9355. struct lowlevel_device_info * const infolist = p;
  9356. struct lowlevel_device_info *info = infolist;
  9357. {
  9358. char threadname[5 + strlen(info->devid) + 1];
  9359. sprintf(threadname, "probe_%s", info->devid);
  9360. RenameThread(threadname);
  9361. }
  9362. // If already in use, ignore
  9363. if (bfg_claim_any(NULL, NULL, info->devid))
  9364. applogr(NULL, LOG_DEBUG, "%s: \"%s\" already in use",
  9365. __func__, info->product);
  9366. // if lowlevel device matches specific user assignment, probe requested driver(s)
  9367. struct string_elist *sd_iter, *sd_tmp;
  9368. struct driver_registration *dreg, *dreg_tmp;
  9369. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  9370. {
  9371. const char * const dname = sd_iter->string;
  9372. const char * const colon = strpbrk(dname, ":@");
  9373. if (!(colon && colon != dname))
  9374. continue;
  9375. const char * const ser = &colon[1];
  9376. LL_FOREACH2(infolist, info, same_devid_next)
  9377. {
  9378. if (!_probe_device_match(info, ser))
  9379. continue;
  9380. const size_t dnamelen = (colon - dname);
  9381. if (_probe_device_internal(info, dname, dnamelen))
  9382. return NULL;
  9383. }
  9384. }
  9385. // probe driver(s) with auto enabled and matching VID/PID/Product/etc of device
  9386. BFG_FOREACH_DRIVER_BY_PRIORITY(dreg, dreg_tmp)
  9387. {
  9388. const struct device_drv * const drv = dreg->drv;
  9389. // Check for "noauto" flag
  9390. // NOTE: driver-specific configuration overrides general
  9391. bool doauto = true;
  9392. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  9393. {
  9394. const char * const dname = sd_iter->string;
  9395. // NOTE: Only checking flags here, NOT path/serial, so @ is unacceptable
  9396. const char *colon = strchr(dname, ':');
  9397. if (!colon)
  9398. colon = &dname[-1];
  9399. if (strcasecmp("noauto", &colon[1]) && strcasecmp("auto", &colon[1]))
  9400. continue;
  9401. const ssize_t dnamelen = (colon - dname);
  9402. if (dnamelen >= 0 && _probe_device_find_drv(dname, dnamelen) != drv)
  9403. continue;
  9404. doauto = (tolower(colon[1]) == 'a');
  9405. if (dnamelen != -1)
  9406. break;
  9407. }
  9408. if (doauto && drv->lowl_match)
  9409. {
  9410. LL_FOREACH2(infolist, info, same_devid_next)
  9411. {
  9412. if (!drv->lowl_match(info))
  9413. continue;
  9414. if (drv->lowl_probe(info))
  9415. return NULL;
  9416. }
  9417. }
  9418. }
  9419. // probe driver(s) with 'all' enabled
  9420. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  9421. {
  9422. const char * const dname = sd_iter->string;
  9423. // NOTE: Only checking flags here, NOT path/serial, so @ is unacceptable
  9424. const char * const colon = strchr(dname, ':');
  9425. if (!colon)
  9426. {
  9427. LL_FOREACH2(infolist, info, same_devid_next)
  9428. {
  9429. if (
  9430. #ifdef NEED_BFG_LOWL_VCOM
  9431. (info->lowl == &lowl_vcom && !strcasecmp(dname, "all")) ||
  9432. #endif
  9433. _probe_device_match(info, (dname[0] == '@') ? &dname[1] : dname))
  9434. {
  9435. BFG_FOREACH_DRIVER_BY_PRIORITY(dreg, dreg_tmp)
  9436. {
  9437. const struct device_drv * const drv = dreg->drv;
  9438. if (drv->lowl_probe_by_name_only)
  9439. continue;
  9440. if (!drv->lowl_probe)
  9441. continue;
  9442. if (drv->lowl_probe(info))
  9443. return NULL;
  9444. }
  9445. break;
  9446. }
  9447. }
  9448. continue;
  9449. }
  9450. if (strcasecmp(&colon[1], "all"))
  9451. continue;
  9452. const size_t dnamelen = (colon - dname);
  9453. LL_FOREACH2(infolist, info, same_devid_next)
  9454. {
  9455. if (_probe_device_internal(info, dname, dnamelen))
  9456. return NULL;
  9457. }
  9458. }
  9459. return NULL;
  9460. }
  9461. void probe_device(struct lowlevel_device_info * const info)
  9462. {
  9463. pthread_create(&info->probe_pth, NULL, probe_device_thread, info);
  9464. }
  9465. #endif
  9466. int create_new_cgpus(void (*addfunc)(void*), void *arg)
  9467. {
  9468. static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  9469. int devcount, i, mining_threads_new = 0;
  9470. unsigned int k;
  9471. struct cgpu_info *cgpu;
  9472. struct thr_info *thr;
  9473. void *p;
  9474. mutex_lock(&mutex);
  9475. devcount = total_devices;
  9476. addfunc(arg);
  9477. if (!total_devices_new)
  9478. goto out;
  9479. wr_lock(&devices_lock);
  9480. p = realloc(devices, sizeof(struct cgpu_info *) * (total_devices + total_devices_new + 1));
  9481. if (unlikely(!p))
  9482. {
  9483. wr_unlock(&devices_lock);
  9484. applog(LOG_ERR, "scan_serial: realloc failed trying to grow devices array");
  9485. goto out;
  9486. }
  9487. devices = p;
  9488. wr_unlock(&devices_lock);
  9489. for (i = 0; i < total_devices_new; ++i)
  9490. {
  9491. cgpu = devices_new[i];
  9492. mining_threads_new += cgpu->threads ?: 1;
  9493. }
  9494. wr_lock(&mining_thr_lock);
  9495. mining_threads_new += mining_threads;
  9496. p = realloc(mining_thr, sizeof(struct thr_info *) * mining_threads_new);
  9497. if (unlikely(!p))
  9498. {
  9499. wr_unlock(&mining_thr_lock);
  9500. applog(LOG_ERR, "scan_serial: realloc failed trying to grow mining_thr");
  9501. goto out;
  9502. }
  9503. mining_thr = p;
  9504. wr_unlock(&mining_thr_lock);
  9505. for (i = mining_threads; i < mining_threads_new; ++i) {
  9506. mining_thr[i] = calloc(1, sizeof(*thr));
  9507. if (!mining_thr[i])
  9508. {
  9509. applog(LOG_ERR, "scan_serial: Failed to calloc mining_thr[%d]", i);
  9510. for ( ; --i >= mining_threads; )
  9511. free(mining_thr[i]);
  9512. goto out;
  9513. }
  9514. }
  9515. k = mining_threads;
  9516. for (i = 0; i < total_devices_new; ++i)
  9517. {
  9518. cgpu = devices_new[i];
  9519. allocate_cgpu(cgpu, &k);
  9520. }
  9521. for (i = 0; i < total_devices_new; ++i)
  9522. {
  9523. cgpu = devices_new[i];
  9524. start_cgpu(cgpu);
  9525. register_device(cgpu);
  9526. ++total_devices;
  9527. }
  9528. #ifdef HAVE_CURSES
  9529. switch_logsize();
  9530. #endif
  9531. out:
  9532. total_devices_new = 0;
  9533. devcount = total_devices - devcount;
  9534. mutex_unlock(&mutex);
  9535. return devcount;
  9536. }
  9537. int scan_serial(const char *s)
  9538. {
  9539. return create_new_cgpus(_scan_serial, (void*)s);
  9540. }
  9541. static void probe_pools(void)
  9542. {
  9543. int i;
  9544. for (i = 0; i < total_pools; i++) {
  9545. struct pool *pool = pools[i];
  9546. pool->testing = true;
  9547. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  9548. }
  9549. }
  9550. static void raise_fd_limits(void)
  9551. {
  9552. #ifdef HAVE_SETRLIMIT
  9553. struct rlimit fdlimit;
  9554. unsigned long old_soft_limit;
  9555. char frombuf[0x10] = "unlimited";
  9556. char hardbuf[0x10] = "unlimited";
  9557. if (getrlimit(RLIMIT_NOFILE, &fdlimit))
  9558. applogr(, LOG_DEBUG, "setrlimit: Failed to getrlimit(RLIMIT_NOFILE)");
  9559. old_soft_limit = fdlimit.rlim_cur;
  9560. if (fdlimit.rlim_max > FD_SETSIZE || fdlimit.rlim_max == RLIM_INFINITY)
  9561. fdlimit.rlim_cur = FD_SETSIZE;
  9562. else
  9563. fdlimit.rlim_cur = fdlimit.rlim_max;
  9564. if (fdlimit.rlim_max != RLIM_INFINITY)
  9565. snprintf(hardbuf, sizeof(hardbuf), "%lu", (unsigned long)fdlimit.rlim_max);
  9566. if (old_soft_limit != RLIM_INFINITY)
  9567. snprintf(frombuf, sizeof(frombuf), "%lu", old_soft_limit);
  9568. if (fdlimit.rlim_cur == old_soft_limit)
  9569. applogr(, LOG_DEBUG, "setrlimit: Soft fd limit not being changed from %lu (FD_SETSIZE=%lu; hard limit=%s)",
  9570. old_soft_limit, (unsigned long)FD_SETSIZE, hardbuf);
  9571. if (setrlimit(RLIMIT_NOFILE, &fdlimit))
  9572. applogr(, LOG_DEBUG, "setrlimit: Failed to change soft fd limit from %s to %lu (FD_SETSIZE=%lu; hard limit=%s)",
  9573. frombuf, (unsigned long)fdlimit.rlim_cur, (unsigned long)FD_SETSIZE, hardbuf);
  9574. applog(LOG_DEBUG, "setrlimit: Changed soft fd limit from %s to %lu (FD_SETSIZE=%lu; hard limit=%s)",
  9575. frombuf, (unsigned long)fdlimit.rlim_cur, (unsigned long)FD_SETSIZE, hardbuf);
  9576. #else
  9577. applog(LOG_DEBUG, "setrlimit: Not supported by platform");
  9578. #endif
  9579. }
  9580. extern void bfg_init_threadlocal();
  9581. extern void stratumsrv_start();
  9582. int main(int argc, char *argv[])
  9583. {
  9584. struct sigaction handler;
  9585. struct thr_info *thr;
  9586. struct block *block;
  9587. unsigned int k;
  9588. int i;
  9589. char *s;
  9590. #ifdef WIN32
  9591. LoadLibrary("backtrace.dll");
  9592. #endif
  9593. blkmk_sha256_impl = my_blkmaker_sha256_callback;
  9594. bfg_init_threadlocal();
  9595. #ifndef HAVE_PTHREAD_CANCEL
  9596. setup_pthread_cancel_workaround();
  9597. #endif
  9598. bfg_init_checksums();
  9599. #ifdef WIN32
  9600. {
  9601. WSADATA wsa;
  9602. i = WSAStartup(MAKEWORD(2, 2), &wsa);
  9603. if (i)
  9604. quit(1, "Failed to initialise Winsock: %s", bfg_strerror(i, BST_SOCKET));
  9605. }
  9606. #endif
  9607. /* This dangerous functions tramples random dynamically allocated
  9608. * variables so do it before anything at all */
  9609. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  9610. quit(1, "Failed to curl_global_init");
  9611. initial_args = malloc(sizeof(char *) * (argc + 1));
  9612. for (i = 0; i < argc; i++)
  9613. initial_args[i] = strdup(argv[i]);
  9614. initial_args[argc] = NULL;
  9615. mutex_init(&hash_lock);
  9616. mutex_init(&console_lock);
  9617. cglock_init(&control_lock);
  9618. mutex_init(&stats_lock);
  9619. mutex_init(&sharelog_lock);
  9620. cglock_init(&ch_lock);
  9621. mutex_init(&sshare_lock);
  9622. rwlock_init(&blk_lock);
  9623. rwlock_init(&netacc_lock);
  9624. rwlock_init(&mining_thr_lock);
  9625. rwlock_init(&devices_lock);
  9626. mutex_init(&lp_lock);
  9627. if (unlikely(pthread_cond_init(&lp_cond, NULL)))
  9628. quit(1, "Failed to pthread_cond_init lp_cond");
  9629. if (unlikely(pthread_cond_init(&gws_cond, NULL)))
  9630. quit(1, "Failed to pthread_cond_init gws_cond");
  9631. notifier_init(submit_waiting_notifier);
  9632. snprintf(packagename, sizeof(packagename), "%s %s", PACKAGE, VERSION);
  9633. #ifdef WANT_CPUMINE
  9634. init_max_name_len();
  9635. #endif
  9636. handler.sa_handler = &sighandler;
  9637. handler.sa_flags = 0;
  9638. sigemptyset(&handler.sa_mask);
  9639. #ifdef HAVE_PTHREAD_CANCEL
  9640. sigaction(SIGTERM, &handler, &termhandler);
  9641. #else
  9642. // Need to let pthread_cancel emulation handle SIGTERM first
  9643. termhandler = pcwm_orig_term_handler;
  9644. pcwm_orig_term_handler = handler;
  9645. #endif
  9646. sigaction(SIGINT, &handler, &inthandler);
  9647. #ifndef WIN32
  9648. signal(SIGPIPE, SIG_IGN);
  9649. #else
  9650. timeBeginPeriod(1);
  9651. #endif
  9652. opt_kernel_path = CGMINER_PREFIX;
  9653. cgminer_path = alloca(PATH_MAX);
  9654. s = strdup(argv[0]);
  9655. strcpy(cgminer_path, dirname(s));
  9656. free(s);
  9657. strcat(cgminer_path, "/");
  9658. #ifdef WANT_CPUMINE
  9659. // Hack to make cgminer silent when called recursively on WIN32
  9660. int skip_to_bench = 0;
  9661. #if defined(WIN32)
  9662. char buf[32];
  9663. if (GetEnvironmentVariable("BFGMINER_BENCH_ALGO", buf, 16))
  9664. skip_to_bench = 1;
  9665. if (GetEnvironmentVariable("CGMINER_BENCH_ALGO", buf, 16))
  9666. skip_to_bench = 1;
  9667. #endif // defined(WIN32)
  9668. #endif
  9669. devcursor = 8;
  9670. logstart = devcursor;
  9671. logcursor = logstart;
  9672. block = calloc(sizeof(struct block), 1);
  9673. if (unlikely(!block))
  9674. quit (1, "main OOM");
  9675. for (i = 0; i < 36; i++)
  9676. strcat(block->hash, "0");
  9677. HASH_ADD_STR(blocks, hash, block);
  9678. strcpy(current_block, block->hash);
  9679. mutex_init(&submitting_lock);
  9680. #ifdef HAVE_OPENCL
  9681. memset(gpus, 0, sizeof(gpus));
  9682. for (i = 0; i < MAX_GPUDEVICES; i++)
  9683. gpus[i].dynamic = true;
  9684. #endif
  9685. schedstart.tm.tm_sec = 1;
  9686. schedstop .tm.tm_sec = 1;
  9687. /* parse command line */
  9688. opt_register_table(opt_config_table,
  9689. "Options for both config file and command line");
  9690. opt_register_table(opt_cmdline_table,
  9691. "Options for command line only");
  9692. opt_parse(&argc, argv, applog_and_exit);
  9693. if (argc != 1)
  9694. quit(1, "Unexpected extra commandline arguments");
  9695. if (!config_loaded)
  9696. load_default_config();
  9697. #ifndef HAVE_PTHREAD_CANCEL
  9698. // Can't do this any earlier, or config isn't loaded
  9699. applog(LOG_DEBUG, "pthread_cancel workaround in use");
  9700. #endif
  9701. #ifdef HAVE_PWD_H
  9702. struct passwd *user_info = NULL;
  9703. if (opt_setuid != NULL) {
  9704. if ((user_info = getpwnam(opt_setuid)) == NULL) {
  9705. quit(1, "Unable to find setuid user information");
  9706. }
  9707. }
  9708. #endif
  9709. #ifdef HAVE_CHROOT
  9710. if (chroot_dir != NULL) {
  9711. #ifdef HAVE_PWD_H
  9712. if (user_info == NULL && getuid() == 0) {
  9713. applog(LOG_WARNING, "Running as root inside chroot");
  9714. }
  9715. #endif
  9716. if (chroot(chroot_dir) != 0) {
  9717. quit(1, "Unable to chroot");
  9718. }
  9719. if (chdir("/"))
  9720. quit(1, "Unable to chdir to chroot");
  9721. }
  9722. #endif
  9723. #ifdef HAVE_PWD_H
  9724. if (user_info != NULL) {
  9725. if (setgid((*user_info).pw_gid) != 0)
  9726. quit(1, "Unable to setgid");
  9727. if (setuid((*user_info).pw_uid) != 0)
  9728. quit(1, "Unable to setuid");
  9729. }
  9730. #endif
  9731. raise_fd_limits();
  9732. if (opt_benchmark) {
  9733. struct pool *pool;
  9734. if (opt_scrypt)
  9735. quit(1, "Cannot use benchmark mode with scrypt");
  9736. want_longpoll = false;
  9737. pool = add_pool();
  9738. pool->rpc_url = malloc(255);
  9739. strcpy(pool->rpc_url, "Benchmark");
  9740. pool->rpc_user = pool->rpc_url;
  9741. pool->rpc_pass = pool->rpc_url;
  9742. enable_pool(pool);
  9743. pool->idle = false;
  9744. successful_connect = true;
  9745. }
  9746. if (opt_unittest) {
  9747. test_cgpu_match();
  9748. test_intrange();
  9749. test_decimal_width();
  9750. utf8_test();
  9751. }
  9752. #ifdef HAVE_CURSES
  9753. if (opt_realquiet || opt_display_devs)
  9754. use_curses = false;
  9755. setlocale(LC_ALL, "C");
  9756. if (use_curses)
  9757. enable_curses();
  9758. #endif
  9759. #ifdef HAVE_LIBUSB
  9760. int err = libusb_init(NULL);
  9761. if (err)
  9762. applog(LOG_WARNING, "libusb_init() failed err %d", err);
  9763. else
  9764. have_libusb = true;
  9765. #endif
  9766. applog(LOG_WARNING, "Started %s", packagename);
  9767. if (cnfbuf) {
  9768. applog(LOG_NOTICE, "Loaded configuration file %s", cnfbuf);
  9769. switch (fileconf_load) {
  9770. case 0:
  9771. applog(LOG_WARNING, "Fatal JSON error in configuration file.");
  9772. applog(LOG_WARNING, "Configuration file could not be used.");
  9773. break;
  9774. case -1:
  9775. applog(LOG_WARNING, "Error in configuration file, partially loaded.");
  9776. if (use_curses)
  9777. applog(LOG_WARNING, "Start BFGMiner with -T to see what failed to load.");
  9778. break;
  9779. default:
  9780. break;
  9781. }
  9782. free(cnfbuf);
  9783. cnfbuf = NULL;
  9784. }
  9785. i = strlen(opt_kernel_path) + 2;
  9786. char __kernel_path[i];
  9787. snprintf(__kernel_path, i, "%s/", opt_kernel_path);
  9788. opt_kernel_path = __kernel_path;
  9789. if (want_per_device_stats)
  9790. opt_log_output = true;
  9791. #ifdef WANT_CPUMINE
  9792. #ifdef USE_SCRYPT
  9793. if (opt_scrypt)
  9794. set_scrypt_algo(&opt_algo);
  9795. else
  9796. #endif
  9797. if (0 <= opt_bench_algo) {
  9798. double rate = bench_algo_stage3(opt_bench_algo);
  9799. if (!skip_to_bench)
  9800. printf("%.5f (%s)\n", rate, algo_names[opt_bench_algo]);
  9801. else {
  9802. // Write result to shared memory for parent
  9803. #if defined(WIN32)
  9804. char unique_name[64];
  9805. if (GetEnvironmentVariable("BFGMINER_SHARED_MEM", unique_name, 32) || GetEnvironmentVariable("CGMINER_SHARED_MEM", unique_name, 32)) {
  9806. HANDLE map_handle = CreateFileMapping(
  9807. INVALID_HANDLE_VALUE, // use paging file
  9808. NULL, // default security attributes
  9809. PAGE_READWRITE, // read/write access
  9810. 0, // size: high 32-bits
  9811. 4096, // size: low 32-bits
  9812. unique_name // name of map object
  9813. );
  9814. if (NULL != map_handle) {
  9815. void *shared_mem = MapViewOfFile(
  9816. map_handle, // object to map view of
  9817. FILE_MAP_WRITE, // read/write access
  9818. 0, // high offset: map from
  9819. 0, // low offset: beginning
  9820. 0 // default: map entire file
  9821. );
  9822. if (NULL != shared_mem)
  9823. CopyMemory(shared_mem, &rate, sizeof(rate));
  9824. (void)UnmapViewOfFile(shared_mem);
  9825. }
  9826. (void)CloseHandle(map_handle);
  9827. }
  9828. #endif
  9829. }
  9830. exit(0);
  9831. }
  9832. #endif
  9833. bfg_devapi_init();
  9834. drv_detect_all();
  9835. total_devices = total_devices_new;
  9836. devices = devices_new;
  9837. total_devices_new = 0;
  9838. devices_new = NULL;
  9839. if (opt_display_devs) {
  9840. int devcount = 0;
  9841. applog(LOG_ERR, "Devices detected:");
  9842. for (i = 0; i < total_devices; ++i) {
  9843. struct cgpu_info *cgpu = devices[i];
  9844. char buf[0x100];
  9845. if (cgpu->device != cgpu)
  9846. continue;
  9847. if (cgpu->name)
  9848. snprintf(buf, sizeof(buf), " %s", cgpu->name);
  9849. else
  9850. if (cgpu->dev_manufacturer)
  9851. snprintf(buf, sizeof(buf), " %s by %s", (cgpu->dev_product ?: "Device"), cgpu->dev_manufacturer);
  9852. else
  9853. if (cgpu->dev_product)
  9854. snprintf(buf, sizeof(buf), " %s", cgpu->dev_product);
  9855. else
  9856. strcpy(buf, " Device");
  9857. tailsprintf(buf, sizeof(buf), " (driver=%s; procs=%d", cgpu->drv->dname, cgpu->procs);
  9858. if (cgpu->dev_serial)
  9859. tailsprintf(buf, sizeof(buf), "; serial=%s", cgpu->dev_serial);
  9860. if (cgpu->device_path)
  9861. tailsprintf(buf, sizeof(buf), "; path=%s", cgpu->device_path);
  9862. tailsprintf(buf, sizeof(buf), ")");
  9863. _applog(LOG_NOTICE, buf);
  9864. ++devcount;
  9865. }
  9866. quit(0, "%d devices listed", devcount);
  9867. }
  9868. mining_threads = 0;
  9869. for (i = 0; i < total_devices; ++i)
  9870. register_device(devices[i]);
  9871. if (!total_devices) {
  9872. applog(LOG_WARNING, "No devices detected!");
  9873. if (use_curses)
  9874. applog(LOG_WARNING, "Waiting for devices; press 'M+' to add, or 'Q' to quit");
  9875. else
  9876. applog(LOG_WARNING, "Waiting for devices");
  9877. }
  9878. #ifdef HAVE_CURSES
  9879. switch_logsize();
  9880. #endif
  9881. if (!total_pools) {
  9882. applog(LOG_WARNING, "Need to specify at least one pool server.");
  9883. #ifdef HAVE_CURSES
  9884. if (!use_curses || !input_pool(false))
  9885. #endif
  9886. quit(1, "Pool setup failed");
  9887. }
  9888. for (i = 0; i < total_pools; i++) {
  9889. struct pool *pool = pools[i];
  9890. size_t siz;
  9891. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  9892. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  9893. if (!pool->rpc_url)
  9894. quit(1, "No URI supplied for pool %u", i);
  9895. if (!pool->rpc_userpass) {
  9896. if (!pool->rpc_user || !pool->rpc_pass)
  9897. quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  9898. siz = strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2;
  9899. pool->rpc_userpass = malloc(siz);
  9900. if (!pool->rpc_userpass)
  9901. quit(1, "Failed to malloc userpass");
  9902. snprintf(pool->rpc_userpass, siz, "%s:%s", pool->rpc_user, pool->rpc_pass);
  9903. }
  9904. }
  9905. /* Set the currentpool to pool with priority 0 */
  9906. validate_pool_priorities();
  9907. for (i = 0; i < total_pools; i++) {
  9908. struct pool *pool = pools[i];
  9909. if (!pool->prio)
  9910. currentpool = pool;
  9911. }
  9912. #ifdef HAVE_SYSLOG_H
  9913. if (use_syslog)
  9914. openlog(PACKAGE, LOG_PID, LOG_USER);
  9915. #endif
  9916. #if defined(unix) || defined(__APPLE__)
  9917. if (opt_stderr_cmd)
  9918. fork_monitor();
  9919. #endif // defined(unix)
  9920. mining_thr = calloc(mining_threads, sizeof(thr));
  9921. if (!mining_thr)
  9922. quit(1, "Failed to calloc mining_thr");
  9923. for (i = 0; i < mining_threads; i++) {
  9924. mining_thr[i] = calloc(1, sizeof(*thr));
  9925. if (!mining_thr[i])
  9926. quit(1, "Failed to calloc mining_thr[%d]", i);
  9927. }
  9928. total_control_threads = 6;
  9929. control_thr = calloc(total_control_threads, sizeof(*thr));
  9930. if (!control_thr)
  9931. quit(1, "Failed to calloc control_thr");
  9932. gwsched_thr_id = 0;
  9933. /* Create a unique get work queue */
  9934. getq = tq_new();
  9935. if (!getq)
  9936. quit(1, "Failed to create getq");
  9937. /* We use the getq mutex as the staged lock */
  9938. stgd_lock = &getq->mutex;
  9939. if (opt_benchmark)
  9940. goto begin_bench;
  9941. for (i = 0; i < total_pools; i++) {
  9942. struct pool *pool = pools[i];
  9943. enable_pool(pool);
  9944. pool->idle = true;
  9945. }
  9946. applog(LOG_NOTICE, "Probing for an alive pool");
  9947. do {
  9948. bool still_testing;
  9949. int i;
  9950. /* Look for at least one active pool before starting */
  9951. probe_pools();
  9952. do {
  9953. sleep(1);
  9954. if (pools_active)
  9955. break;
  9956. still_testing = false;
  9957. for (int i = 0; i < total_pools; ++i)
  9958. if (pools[i]->testing)
  9959. still_testing = true;
  9960. } while (still_testing);
  9961. if (!pools_active) {
  9962. applog(LOG_ERR, "No servers were found that could be used to get work from.");
  9963. applog(LOG_ERR, "Please check the details from the list below of the servers you have input");
  9964. applog(LOG_ERR, "Most likely you have input the wrong URL, forgotten to add a port, or have not set up workers");
  9965. for (i = 0; i < total_pools; i++) {
  9966. struct pool *pool;
  9967. pool = pools[i];
  9968. applog(LOG_WARNING, "Pool: %d URL: %s User: %s Password: %s",
  9969. i, pool->rpc_url, pool->rpc_user, pool->rpc_pass);
  9970. }
  9971. #ifdef HAVE_CURSES
  9972. if (use_curses) {
  9973. halfdelay(150);
  9974. applog(LOG_ERR, "Press any key to exit, or BFGMiner will try again in 15s.");
  9975. if (getch() != ERR)
  9976. quit(0, "No servers could be used! Exiting.");
  9977. cbreak();
  9978. } else
  9979. #endif
  9980. quit(0, "No servers could be used! Exiting.");
  9981. }
  9982. } while (!pools_active);
  9983. #ifdef USE_SCRYPT
  9984. if (detect_algo == 1 && !opt_scrypt) {
  9985. applog(LOG_NOTICE, "Detected scrypt algorithm");
  9986. opt_scrypt = true;
  9987. }
  9988. #endif
  9989. detect_algo = 0;
  9990. begin_bench:
  9991. total_mhashes_done = 0;
  9992. for (i = 0; i < total_devices; i++) {
  9993. struct cgpu_info *cgpu = devices[i];
  9994. cgpu->rolling = cgpu->total_mhashes = 0;
  9995. }
  9996. cgtime(&total_tv_start);
  9997. cgtime(&total_tv_end);
  9998. miner_started = total_tv_start;
  9999. time_t miner_start_ts = time(NULL);
  10000. if (schedstart.tm.tm_sec)
  10001. localtime_r(&miner_start_ts, &schedstart.tm);
  10002. if (schedstop.tm.tm_sec)
  10003. localtime_r(&miner_start_ts, &schedstop .tm);
  10004. get_datestamp(datestamp, sizeof(datestamp), miner_start_ts);
  10005. // Initialise processors and threads
  10006. k = 0;
  10007. for (i = 0; i < total_devices; ++i) {
  10008. struct cgpu_info *cgpu = devices[i];
  10009. allocate_cgpu(cgpu, &k);
  10010. }
  10011. // Start threads
  10012. for (i = 0; i < total_devices; ++i) {
  10013. struct cgpu_info *cgpu = devices[i];
  10014. start_cgpu(cgpu);
  10015. }
  10016. #ifdef HAVE_OPENCL
  10017. for (i = 0; i < nDevs; i++)
  10018. pause_dynamic_threads(i);
  10019. #endif
  10020. #ifdef WANT_CPUMINE
  10021. applog(LOG_INFO, "%d cpu miner threads started, "
  10022. "using SHA256 '%s' algorithm.",
  10023. opt_n_threads,
  10024. algo_names[opt_algo]);
  10025. #endif
  10026. cgtime(&total_tv_start);
  10027. cgtime(&total_tv_end);
  10028. {
  10029. pthread_t submit_thread;
  10030. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, NULL)))
  10031. quit(1, "submit_work thread create failed");
  10032. }
  10033. watchpool_thr_id = 1;
  10034. thr = &control_thr[watchpool_thr_id];
  10035. /* start watchpool thread */
  10036. if (thr_info_create(thr, NULL, watchpool_thread, NULL))
  10037. quit(1, "watchpool thread create failed");
  10038. pthread_detach(thr->pth);
  10039. watchdog_thr_id = 2;
  10040. thr = &control_thr[watchdog_thr_id];
  10041. /* start watchdog thread */
  10042. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  10043. quit(1, "watchdog thread create failed");
  10044. pthread_detach(thr->pth);
  10045. #ifdef HAVE_OPENCL
  10046. /* Create reinit gpu thread */
  10047. gpur_thr_id = 3;
  10048. thr = &control_thr[gpur_thr_id];
  10049. thr->q = tq_new();
  10050. if (!thr->q)
  10051. quit(1, "tq_new failed for gpur_thr_id");
  10052. if (thr_info_create(thr, NULL, reinit_gpu, thr))
  10053. quit(1, "reinit_gpu thread create failed");
  10054. #endif
  10055. /* Create API socket thread */
  10056. api_thr_id = 4;
  10057. thr = &control_thr[api_thr_id];
  10058. if (thr_info_create(thr, NULL, api_thread, thr))
  10059. quit(1, "API thread create failed");
  10060. #ifdef USE_LIBMICROHTTPD
  10061. if (httpsrv_port != -1)
  10062. httpsrv_start(httpsrv_port);
  10063. #endif
  10064. #ifdef USE_LIBEVENT
  10065. if (stratumsrv_port != -1)
  10066. stratumsrv_start();
  10067. #endif
  10068. #ifdef HAVE_CURSES
  10069. /* Create curses input thread for keyboard input. Create this last so
  10070. * that we know all threads are created since this can call kill_work
  10071. * to try and shut down ll previous threads. */
  10072. input_thr_id = 5;
  10073. thr = &control_thr[input_thr_id];
  10074. if (thr_info_create(thr, NULL, input_thread, thr))
  10075. quit(1, "input thread create failed");
  10076. pthread_detach(thr->pth);
  10077. #endif
  10078. /* Just to be sure */
  10079. if (total_control_threads != 6)
  10080. quit(1, "incorrect total_control_threads (%d) should be 7", total_control_threads);
  10081. /* Once everything is set up, main() becomes the getwork scheduler */
  10082. while (42) {
  10083. int ts, max_staged = opt_queue;
  10084. struct pool *pool, *cp;
  10085. bool lagging = false;
  10086. struct curl_ent *ce;
  10087. struct work *work;
  10088. cp = current_pool();
  10089. /* If the primary pool is a getwork pool and cannot roll work,
  10090. * try to stage one extra work per mining thread */
  10091. if (!pool_localgen(cp) && !staged_rollable)
  10092. max_staged += mining_threads;
  10093. mutex_lock(stgd_lock);
  10094. ts = __total_staged();
  10095. if (!pool_localgen(cp) && !ts && !opt_fail_only)
  10096. lagging = true;
  10097. /* Wait until hash_pop tells us we need to create more work */
  10098. if (ts > max_staged) {
  10099. staged_full = true;
  10100. pthread_cond_wait(&gws_cond, stgd_lock);
  10101. ts = __total_staged();
  10102. }
  10103. mutex_unlock(stgd_lock);
  10104. if (ts > max_staged)
  10105. continue;
  10106. work = make_work();
  10107. if (lagging && !pool_tset(cp, &cp->lagging)) {
  10108. applog(LOG_WARNING, "Pool %d not providing work fast enough", cp->pool_no);
  10109. cp->getfail_occasions++;
  10110. total_go++;
  10111. }
  10112. pool = select_pool(lagging);
  10113. retry:
  10114. if (pool->has_stratum) {
  10115. while (!pool->stratum_active || !pool->stratum_notify) {
  10116. struct pool *altpool = select_pool(true);
  10117. if (altpool == pool && pool->has_stratum)
  10118. cgsleep_ms(5000);
  10119. pool = altpool;
  10120. goto retry;
  10121. }
  10122. gen_stratum_work(pool, work);
  10123. applog(LOG_DEBUG, "Generated stratum work");
  10124. stage_work(work);
  10125. continue;
  10126. }
  10127. if (pool->last_work_copy) {
  10128. mutex_lock(&pool->last_work_lock);
  10129. struct work *last_work = pool->last_work_copy;
  10130. if (!last_work)
  10131. {}
  10132. else
  10133. if (can_roll(last_work) && should_roll(last_work)) {
  10134. struct timeval tv_now;
  10135. cgtime(&tv_now);
  10136. free_work(work);
  10137. work = make_clone(pool->last_work_copy);
  10138. mutex_unlock(&pool->last_work_lock);
  10139. roll_work(work);
  10140. 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));
  10141. stage_work(work);
  10142. continue;
  10143. } else if (last_work->tmpl && pool->proto == PLP_GETBLOCKTEMPLATE && blkmk_work_left(last_work->tmpl) > (unsigned long)mining_threads) {
  10144. // Don't free last_work_copy, since it is used to detect upstream provides plenty of work per template
  10145. } else {
  10146. free_work(last_work);
  10147. pool->last_work_copy = NULL;
  10148. }
  10149. mutex_unlock(&pool->last_work_lock);
  10150. }
  10151. if (clone_available()) {
  10152. applog(LOG_DEBUG, "Cloned getwork work");
  10153. free_work(work);
  10154. continue;
  10155. }
  10156. if (opt_benchmark) {
  10157. get_benchmark_work(work);
  10158. applog(LOG_DEBUG, "Generated benchmark work");
  10159. stage_work(work);
  10160. continue;
  10161. }
  10162. work->pool = pool;
  10163. ce = pop_curl_entry3(pool, 2);
  10164. /* obtain new work from bitcoin via JSON-RPC */
  10165. if (!get_upstream_work(work, ce->curl)) {
  10166. struct pool *next_pool;
  10167. /* Make sure the pool just hasn't stopped serving
  10168. * requests but is up as we'll keep hammering it */
  10169. push_curl_entry(ce, pool);
  10170. ++pool->seq_getfails;
  10171. pool_died(pool);
  10172. next_pool = select_pool(!opt_fail_only);
  10173. if (pool == next_pool) {
  10174. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, retrying in 5s", pool->pool_no);
  10175. cgsleep_ms(5000);
  10176. } else {
  10177. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, failover activated", pool->pool_no);
  10178. pool = next_pool;
  10179. }
  10180. goto retry;
  10181. }
  10182. if (ts >= max_staged)
  10183. pool_tclear(pool, &pool->lagging);
  10184. if (pool_tclear(pool, &pool->idle))
  10185. pool_resus(pool);
  10186. applog(LOG_DEBUG, "Generated getwork work");
  10187. stage_work(work);
  10188. push_curl_entry(ce, pool);
  10189. }
  10190. return 0;
  10191. }