miner.c 255 KB

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