miner.c 232 KB

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