miner.c 233 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032
  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;
  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. gettimeofday(&tv, NULL);
  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. gettimeofday(&work->tv_staged, NULL);
  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. cg_rlock(&ch_lock);
  2188. mvwprintw(statuswin, 5, 0, " Block: %s Diff:%s (%s) Started: %s",
  2189. current_hash, block_diff, net_hashrate, blocktime);
  2190. cg_runlock(&ch_lock);
  2191. mvwhline(statuswin, 6, 0, '-', 80);
  2192. mvwhline(statuswin, statusy - 1, 0, '-', 80);
  2193. mvwprintw(statuswin, devcursor - 1, 1, "[P]ool management %s[S]ettings [D]isplay options [Q]uit",
  2194. have_opencl ? "[G]PU management " : "");
  2195. }
  2196. static void adj_width(int var, int *length)
  2197. {
  2198. if ((int)(log10(var) + 1) > *length)
  2199. (*length)++;
  2200. }
  2201. static int dev_width;
  2202. static void curses_print_devstatus(int thr_id)
  2203. {
  2204. struct cgpu_info *cgpu;
  2205. char logline[256];
  2206. int ypos;
  2207. if (opt_compact)
  2208. return;
  2209. cgpu = get_thr_cgpu(thr_id);
  2210. /* Check this isn't out of the window size */
  2211. if (opt_show_procs)
  2212. ypos = cgpu->cgminer_id;
  2213. else
  2214. {
  2215. if (cgpu->proc_id)
  2216. return;
  2217. ypos = cgpu->device_line_id;
  2218. }
  2219. ypos += devsummaryYOffset;
  2220. if (ypos < 0)
  2221. return;
  2222. ypos += devcursor;
  2223. if (ypos >= statusy - 1)
  2224. return;
  2225. if (wmove(statuswin, ypos, 0) == ERR)
  2226. return;
  2227. get_statline2(logline, cgpu, true);
  2228. waddstr(statuswin, logline);
  2229. wclrtoeol(statuswin);
  2230. }
  2231. #endif
  2232. static void print_status(int thr_id)
  2233. {
  2234. if (!curses_active)
  2235. text_print_status(thr_id);
  2236. }
  2237. #ifdef HAVE_CURSES
  2238. /* Check for window resize. Called with curses mutex locked */
  2239. static inline void change_logwinsize(void)
  2240. {
  2241. int x, y, logx, logy;
  2242. getmaxyx(mainwin, y, x);
  2243. if (x < 80 || y < 25)
  2244. return;
  2245. if (y > statusy + 2 && statusy < logstart) {
  2246. if (y - 2 < logstart)
  2247. statusy = y - 2;
  2248. else
  2249. statusy = logstart;
  2250. logcursor = statusy + 1;
  2251. mvwin(logwin, logcursor, 0);
  2252. wresize(statuswin, statusy, x);
  2253. }
  2254. y -= logcursor;
  2255. getmaxyx(logwin, logy, logx);
  2256. /* Detect screen size change */
  2257. if (x != logx || y != logy)
  2258. wresize(logwin, y, x);
  2259. }
  2260. static void check_winsizes(void)
  2261. {
  2262. if (!use_curses)
  2263. return;
  2264. if (curses_active_locked()) {
  2265. int y, x;
  2266. erase();
  2267. x = getmaxx(statuswin);
  2268. if (logstart > LINES - 2)
  2269. statusy = LINES - 2;
  2270. else
  2271. statusy = logstart;
  2272. logcursor = statusy + 1;
  2273. wresize(statuswin, statusy, x);
  2274. getmaxyx(mainwin, y, x);
  2275. y -= logcursor;
  2276. wresize(logwin, y, x);
  2277. mvwin(logwin, logcursor, 0);
  2278. unlock_curses();
  2279. }
  2280. }
  2281. static int device_line_id_count;
  2282. static void switch_compact(void)
  2283. {
  2284. if (opt_compact) {
  2285. logstart = devcursor + 1;
  2286. logcursor = logstart + 1;
  2287. } else {
  2288. total_lines = (opt_show_procs ? total_devices : device_line_id_count);
  2289. logstart = devcursor + total_lines + 1;
  2290. logcursor = logstart + 1;
  2291. }
  2292. check_winsizes();
  2293. }
  2294. #define change_summarywinsize switch_compact
  2295. /* For mandatory printing when mutex is already locked */
  2296. void wlog(const char *f, ...)
  2297. {
  2298. va_list ap;
  2299. va_start(ap, f);
  2300. vw_printw(logwin, f, ap);
  2301. va_end(ap);
  2302. }
  2303. /* Mandatory printing */
  2304. void wlogprint(const char *f, ...)
  2305. {
  2306. va_list ap;
  2307. if (curses_active_locked()) {
  2308. va_start(ap, f);
  2309. vw_printw(logwin, f, ap);
  2310. va_end(ap);
  2311. unlock_curses();
  2312. }
  2313. }
  2314. #endif
  2315. #ifdef HAVE_CURSES
  2316. bool log_curses_only(int prio, const char *f, va_list ap)
  2317. {
  2318. bool high_prio;
  2319. high_prio = (prio == LOG_WARNING || prio == LOG_ERR);
  2320. if (curses_active_locked()) {
  2321. if (!opt_loginput || high_prio) {
  2322. vw_printw(logwin, f, ap);
  2323. if (high_prio) {
  2324. touchwin(logwin);
  2325. wrefresh(logwin);
  2326. }
  2327. }
  2328. unlock_curses();
  2329. return true;
  2330. }
  2331. return false;
  2332. }
  2333. void clear_logwin(void)
  2334. {
  2335. if (curses_active_locked()) {
  2336. wclear(logwin);
  2337. unlock_curses();
  2338. }
  2339. }
  2340. #endif
  2341. /* Returns true if the regenerated work->hash solves a block */
  2342. static bool solves_block(const struct work *work)
  2343. {
  2344. unsigned char target[32];
  2345. real_block_target(target, work->data);
  2346. return hash_target_check(work->hash, target);
  2347. }
  2348. static void enable_pool(struct pool *pool)
  2349. {
  2350. if (pool->enabled != POOL_ENABLED) {
  2351. enabled_pools++;
  2352. pool->enabled = POOL_ENABLED;
  2353. }
  2354. }
  2355. #ifdef HAVE_CURSES
  2356. static void disable_pool(struct pool *pool)
  2357. {
  2358. if (pool->enabled == POOL_ENABLED)
  2359. enabled_pools--;
  2360. pool->enabled = POOL_DISABLED;
  2361. }
  2362. #endif
  2363. static void reject_pool(struct pool *pool)
  2364. {
  2365. if (pool->enabled == POOL_ENABLED)
  2366. enabled_pools--;
  2367. pool->enabled = POOL_REJECTING;
  2368. }
  2369. static uint64_t share_diff(const struct work *);
  2370. static
  2371. void share_result_msg(const struct work *work, const char *disp, const char *reason, bool resubmit, const char *worktime) {
  2372. struct cgpu_info *cgpu;
  2373. const unsigned char *hashpart = &work->hash[opt_scrypt ? 26 : 24];
  2374. uint64_t shrdiff = share_diff(work);
  2375. char shrdiffdisp[16];
  2376. int tgtdiff = floor(work->work_difficulty);
  2377. char tgtdiffdisp[16];
  2378. char where[20];
  2379. cgpu = get_thr_cgpu(work->thr_id);
  2380. suffix_string(shrdiff, shrdiffdisp, 0);
  2381. suffix_string(tgtdiff, tgtdiffdisp, 0);
  2382. if (total_pools > 1)
  2383. sprintf(where, " pool %d", work->pool->pool_no);
  2384. else
  2385. where[0] = '\0';
  2386. applog(LOG_NOTICE, "%s %02x%02x%02x%02x %"PRIprepr"%s Diff %s/%s%s %s%s",
  2387. disp,
  2388. (unsigned)hashpart[3], (unsigned)hashpart[2], (unsigned)hashpart[1], (unsigned)hashpart[0],
  2389. cgpu->proc_repr,
  2390. where,
  2391. shrdiffdisp, tgtdiffdisp,
  2392. reason,
  2393. resubmit ? "(resubmit)" : "",
  2394. worktime
  2395. );
  2396. }
  2397. static bool test_work_current(struct work *);
  2398. static void _submit_work_async(struct work *);
  2399. static
  2400. void maybe_local_submit(const struct work *work)
  2401. {
  2402. #if BLKMAKER_VERSION > 3
  2403. if (unlikely(work->block && work->tmpl))
  2404. {
  2405. // This is a block with a full template (GBT)
  2406. // Regardless of the result, submit to local bitcoind(s) as well
  2407. struct work *work_cp;
  2408. char *p;
  2409. for (int i = 0; i < total_pools; ++i)
  2410. {
  2411. p = strchr(pools[i]->rpc_url, '#');
  2412. if (likely(!(p && strstr(&p[1], "allblocks"))))
  2413. continue;
  2414. work_cp = copy_work(work);
  2415. work_cp->pool = pools[i];
  2416. work_cp->do_foreign_submit = true;
  2417. _submit_work_async(work_cp);
  2418. }
  2419. }
  2420. #endif
  2421. }
  2422. /* Theoretically threads could race when modifying accepted and
  2423. * rejected values but the chance of two submits completing at the
  2424. * same time is zero so there is no point adding extra locking */
  2425. static void
  2426. share_result(json_t *val, json_t *res, json_t *err, const struct work *work,
  2427. /*char *hashshow,*/ bool resubmit, char *worktime)
  2428. {
  2429. struct pool *pool = work->pool;
  2430. struct cgpu_info *cgpu;
  2431. cgpu = get_thr_cgpu(work->thr_id);
  2432. if ((json_is_null(err) || !err) && (json_is_null(res) || json_is_true(res))) {
  2433. mutex_lock(&stats_lock);
  2434. cgpu->accepted++;
  2435. total_accepted++;
  2436. pool->accepted++;
  2437. cgpu->diff_accepted += work->work_difficulty;
  2438. total_diff_accepted += work->work_difficulty;
  2439. pool->diff_accepted += work->work_difficulty;
  2440. mutex_unlock(&stats_lock);
  2441. pool->seq_rejects = 0;
  2442. cgpu->last_share_pool = pool->pool_no;
  2443. cgpu->last_share_pool_time = time(NULL);
  2444. cgpu->last_share_diff = work->work_difficulty;
  2445. pool->last_share_time = cgpu->last_share_pool_time;
  2446. pool->last_share_diff = work->work_difficulty;
  2447. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  2448. if (!QUIET) {
  2449. share_result_msg(work, "Accepted", "", resubmit, worktime);
  2450. }
  2451. sharelog("accept", work);
  2452. if (opt_shares && total_accepted >= opt_shares) {
  2453. applog(LOG_WARNING, "Successfully mined %d accepted shares as requested and exiting.", opt_shares);
  2454. kill_work();
  2455. return;
  2456. }
  2457. /* Detect if a pool that has been temporarily disabled for
  2458. * continually rejecting shares has started accepting shares.
  2459. * This will only happen with the work returned from a
  2460. * longpoll */
  2461. if (unlikely(pool->enabled == POOL_REJECTING)) {
  2462. applog(LOG_WARNING, "Rejecting pool %d now accepting shares, re-enabling!", pool->pool_no);
  2463. enable_pool(pool);
  2464. switch_pools(NULL);
  2465. }
  2466. if (unlikely(work->block)) {
  2467. // Force moving on to this new block :)
  2468. struct work fakework;
  2469. memset(&fakework, 0, sizeof(fakework));
  2470. fakework.pool = work->pool;
  2471. // Copy block version, bits, and time from share
  2472. memcpy(&fakework.data[ 0], &work->data[ 0], 4);
  2473. memcpy(&fakework.data[68], &work->data[68], 8);
  2474. // Set prevblock to winning hash (swap32'd)
  2475. swap32yes(&fakework.data[4], &work->hash[0], 32 / 4);
  2476. test_work_current(&fakework);
  2477. }
  2478. } else {
  2479. mutex_lock(&stats_lock);
  2480. cgpu->rejected++;
  2481. total_rejected++;
  2482. pool->rejected++;
  2483. cgpu->diff_rejected += work->work_difficulty;
  2484. total_diff_rejected += work->work_difficulty;
  2485. pool->diff_rejected += work->work_difficulty;
  2486. pool->seq_rejects++;
  2487. mutex_unlock(&stats_lock);
  2488. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  2489. if (!QUIET) {
  2490. char where[20];
  2491. char disposition[36] = "reject";
  2492. char reason[32];
  2493. strcpy(reason, "");
  2494. if (total_pools > 1)
  2495. sprintf(where, "pool %d", work->pool->pool_no);
  2496. else
  2497. strcpy(where, "");
  2498. if (!json_is_string(res))
  2499. res = json_object_get(val, "reject-reason");
  2500. if (res) {
  2501. const char *reasontmp = json_string_value(res);
  2502. size_t reasonLen = strlen(reasontmp);
  2503. if (reasonLen > 28)
  2504. reasonLen = 28;
  2505. reason[0] = ' '; reason[1] = '(';
  2506. memcpy(2 + reason, reasontmp, reasonLen);
  2507. reason[reasonLen + 2] = ')'; reason[reasonLen + 3] = '\0';
  2508. memcpy(disposition + 7, reasontmp, reasonLen);
  2509. disposition[6] = ':'; disposition[reasonLen + 7] = '\0';
  2510. } else if (work->stratum && err && json_is_array(err)) {
  2511. json_t *reason_val = json_array_get(err, 1);
  2512. char *reason_str;
  2513. if (reason_val && json_is_string(reason_val)) {
  2514. reason_str = (char *)json_string_value(reason_val);
  2515. snprintf(reason, 31, " (%s)", reason_str);
  2516. }
  2517. }
  2518. share_result_msg(work, "Rejected", reason, resubmit, worktime);
  2519. sharelog(disposition, work);
  2520. }
  2521. /* Once we have more than a nominal amount of sequential rejects,
  2522. * at least 10 and more than 3 mins at the current utility,
  2523. * disable the pool because some pool error is likely to have
  2524. * ensued. Do not do this if we know the share just happened to
  2525. * be stale due to networking delays.
  2526. */
  2527. if (pool->seq_rejects > 10 && !work->stale && opt_disable_pool && enabled_pools > 1) {
  2528. double utility = total_accepted / total_secs * 60;
  2529. if (pool->seq_rejects > utility * 3) {
  2530. applog(LOG_WARNING, "Pool %d rejected %d sequential shares, disabling!",
  2531. pool->pool_no, pool->seq_rejects);
  2532. reject_pool(pool);
  2533. if (pool == current_pool())
  2534. switch_pools(NULL);
  2535. pool->seq_rejects = 0;
  2536. }
  2537. }
  2538. }
  2539. maybe_local_submit(work);
  2540. }
  2541. static const uint64_t diffone = 0xFFFF000000000000ull;
  2542. static double target_diff(const unsigned char *target);
  2543. static uint64_t share_diff(const struct work *work)
  2544. {
  2545. uint64_t ret;
  2546. bool new_best = false;
  2547. ret = target_diff(work->hash);
  2548. cg_wlock(&control_lock);
  2549. if (unlikely(ret > best_diff)) {
  2550. new_best = true;
  2551. best_diff = ret;
  2552. suffix_string(best_diff, best_share, 0);
  2553. }
  2554. if (unlikely(ret > work->pool->best_diff))
  2555. work->pool->best_diff = ret;
  2556. cg_wunlock(&control_lock);
  2557. if (unlikely(new_best))
  2558. applog(LOG_INFO, "New best share: %s", best_share);
  2559. return ret;
  2560. }
  2561. static char *submit_upstream_work_request(struct work *work)
  2562. {
  2563. char *hexstr = NULL;
  2564. char *s, *sd;
  2565. struct pool *pool = work->pool;
  2566. if (work->tmpl) {
  2567. json_t *req;
  2568. unsigned char data[80];
  2569. swap32yes(data, work->data, 80 / 4);
  2570. #if BLKMAKER_VERSION > 3
  2571. if (work->do_foreign_submit)
  2572. req = blkmk_submit_foreign_jansson(work->tmpl, data, work->dataid, le32toh(*((uint32_t*)&work->data[76])));
  2573. else
  2574. #endif
  2575. req = blkmk_submit_jansson(work->tmpl, data, work->dataid, le32toh(*((uint32_t*)&work->data[76])));
  2576. s = json_dumps(req, 0);
  2577. json_decref(req);
  2578. sd = bin2hex(data, 80);
  2579. } else {
  2580. /* build hex string */
  2581. hexstr = bin2hex(work->data, sizeof(work->data));
  2582. /* build JSON-RPC request */
  2583. s = strdup("{\"method\": \"getwork\", \"params\": [ \"");
  2584. s = realloc_strcat(s, hexstr);
  2585. s = realloc_strcat(s, "\" ], \"id\":1}");
  2586. free(hexstr);
  2587. sd = s;
  2588. }
  2589. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->rpc_url, sd);
  2590. if (work->tmpl)
  2591. free(sd);
  2592. else
  2593. s = realloc_strcat(s, "\n");
  2594. return s;
  2595. }
  2596. static bool submit_upstream_work_completed(struct work *work, bool resubmit, struct timeval *ptv_submit, json_t *val) {
  2597. json_t *res, *err;
  2598. bool rc = false;
  2599. int thr_id = work->thr_id;
  2600. struct pool *pool = work->pool;
  2601. struct timeval tv_submit_reply;
  2602. char worktime[200] = "";
  2603. gettimeofday(&tv_submit_reply, NULL);
  2604. if (unlikely(!val)) {
  2605. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  2606. if (!pool_tset(pool, &pool->submit_fail)) {
  2607. total_ro++;
  2608. pool->remotefail_occasions++;
  2609. applog(LOG_WARNING, "Pool %d communication failure, caching submissions", pool->pool_no);
  2610. }
  2611. goto out;
  2612. } else if (pool_tclear(pool, &pool->submit_fail))
  2613. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  2614. res = json_object_get(val, "result");
  2615. err = json_object_get(val, "error");
  2616. if (!QUIET) {
  2617. if (opt_worktime) {
  2618. char workclone[20];
  2619. struct tm _tm;
  2620. struct tm *tm, tm_getwork, tm_submit_reply;
  2621. tm = &_tm;
  2622. double getwork_time = tdiff((struct timeval *)&(work->tv_getwork_reply),
  2623. (struct timeval *)&(work->tv_getwork));
  2624. double getwork_to_work = tdiff((struct timeval *)&(work->tv_work_start),
  2625. (struct timeval *)&(work->tv_getwork_reply));
  2626. double work_time = tdiff((struct timeval *)&(work->tv_work_found),
  2627. (struct timeval *)&(work->tv_work_start));
  2628. double work_to_submit = tdiff(ptv_submit,
  2629. (struct timeval *)&(work->tv_work_found));
  2630. double submit_time = tdiff(&tv_submit_reply, ptv_submit);
  2631. int diffplaces = 3;
  2632. localtime_r(&(work->tv_getwork.tv_sec), tm);
  2633. memcpy(&tm_getwork, tm, sizeof(struct tm));
  2634. localtime_r(&(tv_submit_reply.tv_sec), tm);
  2635. memcpy(&tm_submit_reply, tm, sizeof(struct tm));
  2636. if (work->clone) {
  2637. sprintf(workclone, "C:%1.3f",
  2638. tdiff((struct timeval *)&(work->tv_cloned),
  2639. (struct timeval *)&(work->tv_getwork_reply)));
  2640. }
  2641. else
  2642. strcpy(workclone, "O");
  2643. if (work->work_difficulty < 1)
  2644. diffplaces = 6;
  2645. 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",
  2646. (unsigned long)swab32(*(uint32_t *)&(work->data[opt_scrypt ? 32 : 28])),
  2647. (unsigned long)swab32(*(uint32_t *)&(work->data[opt_scrypt ? 28 : 24])),
  2648. work->getwork_mode, diffplaces, work->work_difficulty,
  2649. tm_getwork.tm_hour, tm_getwork.tm_min,
  2650. tm_getwork.tm_sec, getwork_time, workclone,
  2651. getwork_to_work, work_time, work_to_submit, submit_time,
  2652. tm_submit_reply.tm_hour, tm_submit_reply.tm_min,
  2653. tm_submit_reply.tm_sec);
  2654. }
  2655. }
  2656. share_result(val, res, err, work, resubmit, worktime);
  2657. if (!opt_realquiet)
  2658. print_status(thr_id);
  2659. if (!want_per_device_stats) {
  2660. char logline[256];
  2661. struct cgpu_info *cgpu;
  2662. cgpu = get_thr_cgpu(thr_id);
  2663. get_statline(logline, cgpu);
  2664. applog(LOG_INFO, "%s", logline);
  2665. }
  2666. json_decref(val);
  2667. rc = true;
  2668. out:
  2669. return rc;
  2670. }
  2671. /* Specifies whether we can use this pool for work or not. */
  2672. static bool pool_unworkable(struct pool *pool)
  2673. {
  2674. if (pool->idle)
  2675. return true;
  2676. if (pool->enabled != POOL_ENABLED)
  2677. return true;
  2678. if (pool->has_stratum && !pool->stratum_active)
  2679. return true;
  2680. return false;
  2681. }
  2682. /* In balanced mode, the amount of diff1 solutions per pool is monitored as a
  2683. * rolling average per 10 minutes and if pools start getting more, it biases
  2684. * away from them to distribute work evenly. The share count is reset to the
  2685. * rolling average every 10 minutes to not send all work to one pool after it
  2686. * has been disabled/out for an extended period. */
  2687. static struct pool *select_balanced(struct pool *cp)
  2688. {
  2689. int i, lowest = cp->shares;
  2690. struct pool *ret = cp;
  2691. for (i = 0; i < total_pools; i++) {
  2692. struct pool *pool = pools[i];
  2693. if (pool_unworkable(pool))
  2694. continue;
  2695. if (pool->shares < lowest) {
  2696. lowest = pool->shares;
  2697. ret = pool;
  2698. }
  2699. }
  2700. ret->shares++;
  2701. return ret;
  2702. }
  2703. static bool pool_active(struct pool *, bool pinging);
  2704. static void pool_died(struct pool *);
  2705. /* Select any active pool in a rotating fashion when loadbalance is chosen */
  2706. static inline struct pool *select_pool(bool lagging)
  2707. {
  2708. static int rotating_pool = 0;
  2709. struct pool *pool, *cp;
  2710. int tested;
  2711. cp = current_pool();
  2712. retry:
  2713. if (pool_strategy == POOL_BALANCE)
  2714. {
  2715. pool = select_balanced(cp);
  2716. goto have_pool;
  2717. }
  2718. if (pool_strategy != POOL_LOADBALANCE && (!lagging || opt_fail_only))
  2719. pool = cp;
  2720. else
  2721. pool = NULL;
  2722. /* Try to find the first pool in the rotation that is usable */
  2723. tested = 0;
  2724. while (!pool && tested++ < total_pools) {
  2725. if (++rotating_pool >= total_pools)
  2726. rotating_pool = 0;
  2727. pool = pools[rotating_pool];
  2728. if (!pool_unworkable(pool))
  2729. break;
  2730. pool = NULL;
  2731. }
  2732. /* If still nothing is usable, use the current pool */
  2733. if (!pool)
  2734. pool = cp;
  2735. have_pool:
  2736. if (cp != pool)
  2737. {
  2738. if (!pool_active(pool, false))
  2739. {
  2740. pool_died(pool);
  2741. goto retry;
  2742. }
  2743. pool_tclear(pool, &pool->idle);
  2744. }
  2745. return pool;
  2746. }
  2747. static double DIFFEXACTONE = 26959946667150639794667015087019630673637144422540572481103610249215.0;
  2748. static double target_diff(const unsigned char *target)
  2749. {
  2750. double targ = 0;
  2751. signed int i;
  2752. for (i = 31; i >= 0; --i)
  2753. targ = (targ * 0x100) + target[i];
  2754. return DIFFEXACTONE / (targ ?: 1);
  2755. }
  2756. /*
  2757. * Calculate the work share difficulty
  2758. */
  2759. static void calc_diff(struct work *work, int known)
  2760. {
  2761. struct cgminer_pool_stats *pool_stats = &(work->pool->cgminer_pool_stats);
  2762. double difficulty;
  2763. if (!known) {
  2764. work->work_difficulty = target_diff(work->target);
  2765. } else
  2766. work->work_difficulty = known;
  2767. difficulty = work->work_difficulty;
  2768. pool_stats->last_diff = difficulty;
  2769. suffix_string((uint64_t)difficulty, work->pool->diff, 0);
  2770. if (difficulty == pool_stats->min_diff)
  2771. pool_stats->min_diff_count++;
  2772. else if (difficulty < pool_stats->min_diff || pool_stats->min_diff == 0) {
  2773. pool_stats->min_diff = difficulty;
  2774. pool_stats->min_diff_count = 1;
  2775. }
  2776. if (difficulty == pool_stats->max_diff)
  2777. pool_stats->max_diff_count++;
  2778. else if (difficulty > pool_stats->max_diff) {
  2779. pool_stats->max_diff = difficulty;
  2780. pool_stats->max_diff_count = 1;
  2781. }
  2782. }
  2783. static void get_benchmark_work(struct work *work)
  2784. {
  2785. // Use a random work block pulled from a pool
  2786. static uint8_t bench_block[] = { CGMINER_BENCHMARK_BLOCK };
  2787. size_t bench_size = sizeof(*work);
  2788. size_t work_size = sizeof(bench_block);
  2789. size_t min_size = (work_size < bench_size ? work_size : bench_size);
  2790. memset(work, 0, sizeof(*work));
  2791. memcpy(work, &bench_block, min_size);
  2792. work->mandatory = true;
  2793. work->pool = pools[0];
  2794. gettimeofday(&(work->tv_getwork), NULL);
  2795. memcpy(&(work->tv_getwork_reply), &(work->tv_getwork), sizeof(struct timeval));
  2796. work->getwork_mode = GETWORK_MODE_BENCHMARK;
  2797. calc_diff(work, 0);
  2798. }
  2799. static void wake_gws(void);
  2800. static void update_last_work(struct work *work)
  2801. {
  2802. if (!work->tmpl)
  2803. // Only save GBT jobs, since rollntime isn't coordinated well yet
  2804. return;
  2805. struct pool *pool = work->pool;
  2806. mutex_lock(&pool->last_work_lock);
  2807. if (pool->last_work_copy)
  2808. free_work(pool->last_work_copy);
  2809. pool->last_work_copy = copy_work(work);
  2810. pool->last_work_copy->work_restart_id = pool->work_restart_id;
  2811. mutex_unlock(&pool->last_work_lock);
  2812. }
  2813. static
  2814. void gbt_req_target(json_t *req)
  2815. {
  2816. json_t *j;
  2817. json_t *n;
  2818. if (!request_target_str)
  2819. return;
  2820. j = json_object_get(req, "params");
  2821. if (!j)
  2822. {
  2823. n = json_array();
  2824. if (!n)
  2825. return;
  2826. if (json_object_set_new(req, "params", n))
  2827. goto erradd;
  2828. j = n;
  2829. }
  2830. n = json_array_get(j, 0);
  2831. if (!n)
  2832. {
  2833. n = json_object();
  2834. if (!n)
  2835. return;
  2836. if (json_array_append_new(j, n))
  2837. goto erradd;
  2838. }
  2839. j = n;
  2840. n = json_string(request_target_str);
  2841. if (!n)
  2842. return;
  2843. if (json_object_set_new(j, "target", n))
  2844. goto erradd;
  2845. return;
  2846. erradd:
  2847. json_decref(n);
  2848. }
  2849. static char *prepare_rpc_req2(struct work *work, enum pool_protocol proto, const char *lpid, bool probe)
  2850. {
  2851. char *rpc_req;
  2852. clean_work(work);
  2853. switch (proto) {
  2854. case PLP_GETWORK:
  2855. work->getwork_mode = GETWORK_MODE_POOL;
  2856. return strdup(getwork_req);
  2857. case PLP_GETBLOCKTEMPLATE:
  2858. work->getwork_mode = GETWORK_MODE_GBT;
  2859. work->tmpl_refcount = malloc(sizeof(*work->tmpl_refcount));
  2860. if (!work->tmpl_refcount)
  2861. return NULL;
  2862. work->tmpl = blktmpl_create();
  2863. if (!work->tmpl)
  2864. goto gbtfail2;
  2865. *work->tmpl_refcount = 1;
  2866. gbt_capabilities_t caps = blktmpl_addcaps(work->tmpl);
  2867. if (!caps)
  2868. goto gbtfail;
  2869. caps |= GBT_LONGPOLL;
  2870. json_t *req = blktmpl_request_jansson(caps, lpid);
  2871. if (!req)
  2872. goto gbtfail;
  2873. if (probe)
  2874. gbt_req_target(req);
  2875. rpc_req = json_dumps(req, 0);
  2876. if (!rpc_req)
  2877. goto gbtfail;
  2878. json_decref(req);
  2879. return rpc_req;
  2880. default:
  2881. return NULL;
  2882. }
  2883. return NULL;
  2884. gbtfail:
  2885. blktmpl_free(work->tmpl);
  2886. work->tmpl = NULL;
  2887. gbtfail2:
  2888. free(work->tmpl_refcount);
  2889. work->tmpl_refcount = NULL;
  2890. return NULL;
  2891. }
  2892. #define prepare_rpc_req(work, proto, lpid) prepare_rpc_req2(work, proto, lpid, false)
  2893. #define prepare_rpc_req_probe(work, proto, lpid) prepare_rpc_req2(work, proto, lpid, true)
  2894. static const char *pool_protocol_name(enum pool_protocol proto)
  2895. {
  2896. switch (proto) {
  2897. case PLP_GETBLOCKTEMPLATE:
  2898. return "getblocktemplate";
  2899. case PLP_GETWORK:
  2900. return "getwork";
  2901. default:
  2902. return "UNKNOWN";
  2903. }
  2904. }
  2905. static enum pool_protocol pool_protocol_fallback(enum pool_protocol proto)
  2906. {
  2907. switch (proto) {
  2908. case PLP_GETBLOCKTEMPLATE:
  2909. if (want_getwork)
  2910. return PLP_GETWORK;
  2911. default:
  2912. return PLP_NONE;
  2913. }
  2914. }
  2915. static bool get_upstream_work(struct work *work, CURL *curl)
  2916. {
  2917. struct pool *pool = work->pool;
  2918. struct cgminer_pool_stats *pool_stats = &(pool->cgminer_pool_stats);
  2919. struct timeval tv_elapsed;
  2920. json_t *val = NULL;
  2921. bool rc = false;
  2922. char *url;
  2923. enum pool_protocol proto;
  2924. char *rpc_req;
  2925. if (pool->proto == PLP_NONE)
  2926. pool->proto = PLP_GETBLOCKTEMPLATE;
  2927. tryagain:
  2928. rpc_req = prepare_rpc_req(work, pool->proto, NULL);
  2929. work->pool = pool;
  2930. if (!rpc_req)
  2931. return false;
  2932. applog(LOG_DEBUG, "DBG: sending %s get RPC call: %s", pool->rpc_url, rpc_req);
  2933. url = pool->rpc_url;
  2934. gettimeofday(&(work->tv_getwork), NULL);
  2935. val = json_rpc_call(curl, url, pool->rpc_userpass, rpc_req, false,
  2936. false, &work->rolltime, pool, false);
  2937. pool_stats->getwork_attempts++;
  2938. free(rpc_req);
  2939. if (likely(val)) {
  2940. rc = work_decode(pool, work, val);
  2941. if (unlikely(!rc))
  2942. applog(LOG_DEBUG, "Failed to decode work in get_upstream_work");
  2943. } else if (PLP_NONE != (proto = pool_protocol_fallback(pool->proto))) {
  2944. applog(LOG_WARNING, "Pool %u failed getblocktemplate request; falling back to getwork protocol", pool->pool_no);
  2945. pool->proto = proto;
  2946. goto tryagain;
  2947. } else
  2948. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  2949. gettimeofday(&(work->tv_getwork_reply), NULL);
  2950. timersub(&(work->tv_getwork_reply), &(work->tv_getwork), &tv_elapsed);
  2951. pool_stats->getwork_wait_rolling += ((double)tv_elapsed.tv_sec + ((double)tv_elapsed.tv_usec / 1000000)) * 0.63;
  2952. pool_stats->getwork_wait_rolling /= 1.63;
  2953. timeradd(&tv_elapsed, &(pool_stats->getwork_wait), &(pool_stats->getwork_wait));
  2954. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_max), >)) {
  2955. pool_stats->getwork_wait_max.tv_sec = tv_elapsed.tv_sec;
  2956. pool_stats->getwork_wait_max.tv_usec = tv_elapsed.tv_usec;
  2957. }
  2958. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_min), <)) {
  2959. pool_stats->getwork_wait_min.tv_sec = tv_elapsed.tv_sec;
  2960. pool_stats->getwork_wait_min.tv_usec = tv_elapsed.tv_usec;
  2961. }
  2962. pool_stats->getwork_calls++;
  2963. work->pool = pool;
  2964. work->longpoll = false;
  2965. calc_diff(work, 0);
  2966. total_getworks++;
  2967. pool->getwork_requested++;
  2968. if (rc)
  2969. update_last_work(work);
  2970. if (likely(val))
  2971. json_decref(val);
  2972. return rc;
  2973. }
  2974. #ifdef HAVE_CURSES
  2975. static void disable_curses(void)
  2976. {
  2977. if (curses_active_locked()) {
  2978. curses_active = false;
  2979. leaveok(logwin, false);
  2980. leaveok(statuswin, false);
  2981. leaveok(mainwin, false);
  2982. nocbreak();
  2983. echo();
  2984. delwin(logwin);
  2985. delwin(statuswin);
  2986. delwin(mainwin);
  2987. endwin();
  2988. #ifdef WIN32
  2989. // Move the cursor to after curses output.
  2990. HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
  2991. CONSOLE_SCREEN_BUFFER_INFO csbi;
  2992. COORD coord;
  2993. if (GetConsoleScreenBufferInfo(hout, &csbi)) {
  2994. coord.X = 0;
  2995. coord.Y = csbi.dwSize.Y - 1;
  2996. SetConsoleCursorPosition(hout, coord);
  2997. }
  2998. #endif
  2999. unlock_curses();
  3000. }
  3001. }
  3002. #endif
  3003. static void __kill_work(void)
  3004. {
  3005. struct thr_info *thr;
  3006. int i;
  3007. if (!successful_connect)
  3008. return;
  3009. applog(LOG_INFO, "Received kill message");
  3010. shutting_down = true;
  3011. applog(LOG_DEBUG, "Prompting submit_work thread to finish");
  3012. notifier_wake(submit_waiting_notifier);
  3013. applog(LOG_DEBUG, "Killing off watchpool thread");
  3014. /* Kill the watchpool thread */
  3015. thr = &control_thr[watchpool_thr_id];
  3016. thr_info_cancel(thr);
  3017. applog(LOG_DEBUG, "Killing off watchdog thread");
  3018. /* Kill the watchdog thread */
  3019. thr = &control_thr[watchdog_thr_id];
  3020. thr_info_cancel(thr);
  3021. applog(LOG_DEBUG, "Stopping mining threads");
  3022. /* Stop the mining threads*/
  3023. for (i = 0; i < mining_threads; i++) {
  3024. thr = get_thread(i);
  3025. if (thr->cgpu->threads)
  3026. thr_info_freeze(thr);
  3027. thr->pause = true;
  3028. }
  3029. nmsleep(1000);
  3030. applog(LOG_DEBUG, "Killing off mining threads");
  3031. /* Kill the mining threads*/
  3032. for (i = 0; i < mining_threads; i++) {
  3033. thr = get_thread(i);
  3034. if (thr->cgpu->threads)
  3035. thr_info_cancel(thr);
  3036. }
  3037. applog(LOG_DEBUG, "Killing off stage thread");
  3038. /* Stop the others */
  3039. thr = &control_thr[stage_thr_id];
  3040. thr_info_cancel(thr);
  3041. applog(LOG_DEBUG, "Killing off API thread");
  3042. thr = &control_thr[api_thr_id];
  3043. thr_info_cancel(thr);
  3044. }
  3045. /* This should be the common exit path */
  3046. void kill_work(void)
  3047. {
  3048. __kill_work();
  3049. quit(0, "Shutdown signal received.");
  3050. }
  3051. static
  3052. #ifdef WIN32
  3053. #ifndef _WIN64
  3054. const
  3055. #endif
  3056. #endif
  3057. char **initial_args;
  3058. static void clean_up(void);
  3059. void app_restart(void)
  3060. {
  3061. applog(LOG_WARNING, "Attempting to restart %s", packagename);
  3062. __kill_work();
  3063. clean_up();
  3064. #if defined(unix)
  3065. if (forkpid > 0) {
  3066. kill(forkpid, SIGTERM);
  3067. forkpid = 0;
  3068. }
  3069. #endif
  3070. execv(initial_args[0], initial_args);
  3071. applog(LOG_WARNING, "Failed to restart application");
  3072. }
  3073. static void sighandler(int __maybe_unused sig)
  3074. {
  3075. /* Restore signal handlers so we can still quit if kill_work fails */
  3076. sigaction(SIGTERM, &termhandler, NULL);
  3077. sigaction(SIGINT, &inthandler, NULL);
  3078. kill_work();
  3079. }
  3080. static void start_longpoll(void);
  3081. static void stop_longpoll(void);
  3082. /* Called with pool_lock held. Recruit an extra curl if none are available for
  3083. * this pool. */
  3084. static void recruit_curl(struct pool *pool)
  3085. {
  3086. struct curl_ent *ce = calloc(sizeof(struct curl_ent), 1);
  3087. if (unlikely(!ce))
  3088. quit(1, "Failed to calloc in recruit_curl");
  3089. ce->curl = curl_easy_init();
  3090. if (unlikely(!ce->curl))
  3091. quit(1, "Failed to init in recruit_curl");
  3092. list_add(&ce->node, &pool->curlring);
  3093. pool->curls++;
  3094. applog(LOG_DEBUG, "Recruited curl %d for pool %d", pool->curls, pool->pool_no);
  3095. }
  3096. /* Grab an available curl if there is one. If not, then recruit extra curls
  3097. * unless we are in a submit_fail situation, or we have opt_delaynet enabled
  3098. * and there are already 5 curls in circulation. Limit total number to the
  3099. * number of mining threads per pool as well to prevent blasting a pool during
  3100. * network delays/outages. */
  3101. static struct curl_ent *pop_curl_entry3(struct pool *pool, int blocking)
  3102. {
  3103. int curl_limit = opt_delaynet ? 5 : (mining_threads + opt_queue) * 2;
  3104. struct curl_ent *ce;
  3105. mutex_lock(&pool->pool_lock);
  3106. retry:
  3107. if (!pool->curls)
  3108. recruit_curl(pool);
  3109. else if (list_empty(&pool->curlring)) {
  3110. if (blocking < 2 && pool->curls >= curl_limit && (blocking || pool->curls >= opt_submit_threads)) {
  3111. if (!blocking) {
  3112. mutex_unlock(&pool->pool_lock);
  3113. return NULL;
  3114. }
  3115. pthread_cond_wait(&pool->cr_cond, &pool->pool_lock);
  3116. goto retry;
  3117. } else
  3118. recruit_curl(pool);
  3119. }
  3120. ce = list_entry(pool->curlring.next, struct curl_ent, node);
  3121. list_del(&ce->node);
  3122. mutex_unlock(&pool->pool_lock);
  3123. return ce;
  3124. }
  3125. static struct curl_ent *pop_curl_entry2(struct pool *pool, bool blocking)
  3126. {
  3127. return pop_curl_entry3(pool, blocking ? 1 : 0);
  3128. }
  3129. __maybe_unused
  3130. static struct curl_ent *pop_curl_entry(struct pool *pool)
  3131. {
  3132. return pop_curl_entry3(pool, 1);
  3133. }
  3134. static void push_curl_entry(struct curl_ent *ce, struct pool *pool)
  3135. {
  3136. mutex_lock(&pool->pool_lock);
  3137. if (!ce || !ce->curl)
  3138. quit(1, "Attempted to add NULL in push_curl_entry");
  3139. list_add_tail(&ce->node, &pool->curlring);
  3140. gettimeofday(&ce->tv, NULL);
  3141. pthread_cond_broadcast(&pool->cr_cond);
  3142. mutex_unlock(&pool->pool_lock);
  3143. }
  3144. bool stale_work(struct work *work, bool share);
  3145. static inline bool should_roll(struct work *work)
  3146. {
  3147. struct timeval now;
  3148. time_t expiry;
  3149. if (work->pool != current_pool() && pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE)
  3150. return false;
  3151. if (stale_work(work, false))
  3152. return false;
  3153. if (work->rolltime > opt_scantime)
  3154. expiry = work->rolltime;
  3155. else
  3156. expiry = opt_scantime;
  3157. expiry = expiry * 2 / 3;
  3158. /* We shouldn't roll if we're unlikely to get one shares' duration
  3159. * work out of doing so */
  3160. gettimeofday(&now, NULL);
  3161. if (now.tv_sec - work->tv_staged.tv_sec > expiry)
  3162. return false;
  3163. return true;
  3164. }
  3165. /* Limit rolls to 7000 to not beyond 2 hours in the future where bitcoind will
  3166. * reject blocks as invalid. */
  3167. static inline bool can_roll(struct work *work)
  3168. {
  3169. if (work->stratum)
  3170. return false;
  3171. if (!(work->pool && !work->clone))
  3172. return false;
  3173. if (work->tmpl) {
  3174. if (stale_work(work, false))
  3175. return false;
  3176. return blkmk_work_left(work->tmpl);
  3177. }
  3178. return (work->rolltime &&
  3179. work->rolls < 7000 && !stale_work(work, false));
  3180. }
  3181. static void roll_work(struct work *work)
  3182. {
  3183. if (work->tmpl) {
  3184. if (blkmk_get_data(work->tmpl, work->data, 80, time(NULL), NULL, &work->dataid) < 76)
  3185. applog(LOG_ERR, "Failed to get next data from template; spinning wheels!");
  3186. swap32yes(work->data, work->data, 80 / 4);
  3187. calc_midstate(work);
  3188. applog(LOG_DEBUG, "Successfully rolled extranonce to dataid %u", work->dataid);
  3189. } else {
  3190. uint32_t *work_ntime;
  3191. uint32_t ntime;
  3192. work_ntime = (uint32_t *)(work->data + 68);
  3193. ntime = be32toh(*work_ntime);
  3194. ntime++;
  3195. *work_ntime = htobe32(ntime);
  3196. applog(LOG_DEBUG, "Successfully rolled time header in work");
  3197. }
  3198. local_work++;
  3199. work->rolls++;
  3200. work->blk.nonce = 0;
  3201. /* This is now a different work item so it needs a different ID for the
  3202. * hashtable */
  3203. work->id = total_work++;
  3204. }
  3205. /* Duplicates any dynamically allocated arrays within the work struct to
  3206. * prevent a copied work struct from freeing ram belonging to another struct */
  3207. void __copy_work(struct work *work, const struct work *base_work)
  3208. {
  3209. int id = work->id;
  3210. clean_work(work);
  3211. memcpy(work, base_work, sizeof(struct work));
  3212. /* Keep the unique new id assigned during make_work to prevent copied
  3213. * work from having the same id. */
  3214. work->id = id;
  3215. if (base_work->job_id)
  3216. work->job_id = strdup(base_work->job_id);
  3217. if (base_work->nonce1)
  3218. work->nonce1 = strdup(base_work->nonce1);
  3219. if (base_work->nonce2)
  3220. work->nonce2 = strdup(base_work->nonce2);
  3221. if (base_work->ntime)
  3222. work->ntime = strdup(base_work->ntime);
  3223. if (base_work->tmpl) {
  3224. struct pool *pool = work->pool;
  3225. mutex_lock(&pool->pool_lock);
  3226. ++*work->tmpl_refcount;
  3227. mutex_unlock(&pool->pool_lock);
  3228. }
  3229. }
  3230. /* Generates a copy of an existing work struct, creating fresh heap allocations
  3231. * for all dynamically allocated arrays within the struct */
  3232. struct work *copy_work(const struct work *base_work)
  3233. {
  3234. struct work *work = make_work();
  3235. __copy_work(work, base_work);
  3236. return work;
  3237. }
  3238. static struct work *make_clone(struct work *work)
  3239. {
  3240. struct work *work_clone = copy_work(work);
  3241. work_clone->clone = true;
  3242. gettimeofday((struct timeval *)&(work_clone->tv_cloned), NULL);
  3243. work_clone->longpoll = false;
  3244. work_clone->mandatory = false;
  3245. /* Make cloned work appear slightly older to bias towards keeping the
  3246. * master work item which can be further rolled */
  3247. work_clone->tv_staged.tv_sec -= 1;
  3248. return work_clone;
  3249. }
  3250. static void stage_work(struct work *work);
  3251. static bool clone_available(void)
  3252. {
  3253. struct work *work_clone = NULL, *work, *tmp;
  3254. bool cloned = false;
  3255. mutex_lock(stgd_lock);
  3256. if (!staged_rollable)
  3257. goto out_unlock;
  3258. HASH_ITER(hh, staged_work, work, tmp) {
  3259. if (can_roll(work) && should_roll(work)) {
  3260. roll_work(work);
  3261. work_clone = make_clone(work);
  3262. roll_work(work);
  3263. applog(LOG_DEBUG, "Pushing cloned available work to stage thread");
  3264. cloned = true;
  3265. break;
  3266. }
  3267. }
  3268. out_unlock:
  3269. mutex_unlock(stgd_lock);
  3270. if (cloned)
  3271. stage_work(work_clone);
  3272. return cloned;
  3273. }
  3274. static void pool_died(struct pool *pool)
  3275. {
  3276. if (!pool_tset(pool, &pool->idle)) {
  3277. gettimeofday(&pool->tv_idle, NULL);
  3278. if (pool == current_pool()) {
  3279. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  3280. switch_pools(NULL);
  3281. } else
  3282. applog(LOG_INFO, "Pool %d %s failed to return work", pool->pool_no, pool->rpc_url);
  3283. }
  3284. }
  3285. bool stale_work(struct work *work, bool share)
  3286. {
  3287. unsigned work_expiry;
  3288. struct pool *pool;
  3289. uint32_t block_id;
  3290. unsigned getwork_delay;
  3291. if (opt_benchmark)
  3292. return false;
  3293. block_id = ((uint32_t*)work->data)[1];
  3294. pool = work->pool;
  3295. /* Technically the rolltime should be correct but some pools
  3296. * advertise a broken expire= that is lower than a meaningful
  3297. * scantime */
  3298. if (work->rolltime >= opt_scantime || work->tmpl)
  3299. work_expiry = work->rolltime;
  3300. else
  3301. work_expiry = opt_expiry;
  3302. unsigned max_expiry = (have_longpoll ? opt_expiry_lp : opt_expiry);
  3303. if (work_expiry > max_expiry)
  3304. work_expiry = max_expiry;
  3305. if (share) {
  3306. /* If the share isn't on this pool's latest block, it's stale */
  3307. if (pool->block_id && pool->block_id != block_id)
  3308. {
  3309. applog(LOG_DEBUG, "Share stale due to block mismatch (%08lx != %08lx)", (long)block_id, (long)pool->block_id);
  3310. return true;
  3311. }
  3312. /* If the pool doesn't want old shares, then any found in work before
  3313. * the most recent longpoll is stale */
  3314. if ((!pool->submit_old) && work->work_restart_id != pool->work_restart_id)
  3315. {
  3316. applog(LOG_DEBUG, "Share stale due to mandatory work update (%02x != %02x)", work->work_restart_id, pool->work_restart_id);
  3317. return true;
  3318. }
  3319. } else {
  3320. /* If this work isn't for the latest Bitcoin block, it's stale */
  3321. /* But only care about the current pool if failover-only */
  3322. if (enabled_pools <= 1 || opt_fail_only) {
  3323. if (pool->block_id && block_id != pool->block_id)
  3324. {
  3325. applog(LOG_DEBUG, "Work stale due to block mismatch (%08lx != 1 ? %08lx : %08lx)", (long)block_id, (long)pool->block_id, (long)current_block_id);
  3326. return true;
  3327. }
  3328. } else {
  3329. if (block_id != current_block_id)
  3330. {
  3331. applog(LOG_DEBUG, "Work stale due to block mismatch (%08lx != 0 ? %08lx : %08lx)", (long)block_id, (long)pool->block_id, (long)current_block_id);
  3332. return true;
  3333. }
  3334. }
  3335. /* If the pool has asked us to restart since this work, it's stale */
  3336. if (work->work_restart_id != pool->work_restart_id)
  3337. {
  3338. applog(LOG_DEBUG, "Work stale due to work update (%02x != %02x)", work->work_restart_id, pool->work_restart_id);
  3339. return true;
  3340. }
  3341. if (pool->has_stratum && work->job_id) {
  3342. bool same_job;
  3343. if (!pool->stratum_active || !pool->stratum_notify) {
  3344. applog(LOG_DEBUG, "Work stale due to stratum inactive");
  3345. return true;
  3346. }
  3347. same_job = true;
  3348. cg_rlock(&pool->data_lock);
  3349. if (strcmp(work->job_id, pool->swork.job_id))
  3350. same_job = false;
  3351. cg_runlock(&pool->data_lock);
  3352. if (!same_job) {
  3353. applog(LOG_DEBUG, "Work stale due to stratum job_id mismatch");
  3354. return true;
  3355. }
  3356. }
  3357. /* Factor in the average getwork delay of this pool, rounding it up to
  3358. * the nearest second */
  3359. getwork_delay = pool->cgminer_pool_stats.getwork_wait_rolling * 5 + 1;
  3360. if (unlikely(work_expiry <= getwork_delay + 5))
  3361. work_expiry = 5;
  3362. else
  3363. work_expiry -= getwork_delay;
  3364. }
  3365. double elapsed_since_staged = difftime(time(NULL), work->tv_staged.tv_sec);
  3366. if (elapsed_since_staged > work_expiry) {
  3367. applog(LOG_DEBUG, "%s stale due to expiry (%.0f >= %u)", share?"Share":"Work", elapsed_since_staged, work_expiry);
  3368. return true;
  3369. }
  3370. /* If the user only wants strict failover, any work from a pool other than
  3371. * the current one is always considered stale */
  3372. if (opt_fail_only && !share && pool != current_pool() && !work->mandatory &&
  3373. pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  3374. applog(LOG_DEBUG, "Work stale due to fail only pool mismatch (pool %u vs %u)", pool->pool_no, current_pool()->pool_no);
  3375. return true;
  3376. }
  3377. return false;
  3378. }
  3379. static void regen_hash(struct work *work)
  3380. {
  3381. hash_data(work->hash, work->data);
  3382. }
  3383. static void check_solve(struct work *work)
  3384. {
  3385. if (opt_scrypt)
  3386. scrypt_outputhash(work);
  3387. else
  3388. regen_hash(work);
  3389. work->block = solves_block(work);
  3390. if (unlikely(work->block)) {
  3391. work->pool->solved++;
  3392. found_blocks++;
  3393. work->mandatory = true;
  3394. applog(LOG_NOTICE, "Found block for pool %d!", work->pool->pool_no);
  3395. }
  3396. }
  3397. static void submit_discard_share2(const char *reason, struct work *work)
  3398. {
  3399. sharelog(reason, work);
  3400. mutex_lock(&stats_lock);
  3401. ++total_stale;
  3402. ++(work->pool->stale_shares);
  3403. total_diff_stale += work->work_difficulty;
  3404. work->pool->diff_stale += work->work_difficulty;
  3405. mutex_unlock(&stats_lock);
  3406. }
  3407. static void submit_discard_share(struct work *work)
  3408. {
  3409. submit_discard_share2("discard", work);
  3410. }
  3411. struct submit_work_state {
  3412. struct work *work;
  3413. bool resubmit;
  3414. struct curl_ent *ce;
  3415. int failures;
  3416. time_t staleexpire;
  3417. char *s;
  3418. struct timeval tv_submit;
  3419. struct submit_work_state *next;
  3420. };
  3421. static int my_curl_timer_set(__maybe_unused CURLM *curlm, long timeout_ms, void *userp)
  3422. {
  3423. long *p_timeout_us = userp;
  3424. const long max_ms = LONG_MAX / 1000;
  3425. if (max_ms < timeout_ms)
  3426. timeout_ms = max_ms;
  3427. *p_timeout_us = timeout_ms * 1000;
  3428. return 0;
  3429. }
  3430. static void sws_has_ce(struct submit_work_state *sws)
  3431. {
  3432. struct pool *pool = sws->work->pool;
  3433. sws->s = submit_upstream_work_request(sws->work);
  3434. gettimeofday(&sws->tv_submit, NULL);
  3435. json_rpc_call_async(sws->ce->curl, pool->rpc_url, pool->rpc_userpass, sws->s, false, pool, true, sws);
  3436. }
  3437. static struct submit_work_state *begin_submission(struct work *work)
  3438. {
  3439. struct pool *pool;
  3440. struct submit_work_state *sws = NULL;
  3441. pool = work->pool;
  3442. sws = malloc(sizeof(*sws));
  3443. *sws = (struct submit_work_state){
  3444. .work = work,
  3445. };
  3446. check_solve(work);
  3447. if (stale_work(work, true)) {
  3448. work->stale = true;
  3449. if (opt_submit_stale)
  3450. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as user requested", pool->pool_no);
  3451. else if (pool->submit_old)
  3452. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as pool requested", pool->pool_no);
  3453. else {
  3454. applog(LOG_NOTICE, "Pool %d stale share detected, discarding", pool->pool_no);
  3455. submit_discard_share(work);
  3456. goto out;
  3457. }
  3458. sws->staleexpire = time(NULL) + 300;
  3459. }
  3460. if (work->stratum) {
  3461. char *s;
  3462. s = malloc(1024);
  3463. sws->s = s;
  3464. } else {
  3465. /* submit solution to bitcoin via JSON-RPC */
  3466. sws->ce = pop_curl_entry2(pool, false);
  3467. if (sws->ce) {
  3468. sws_has_ce(sws);
  3469. } else {
  3470. sws->next = pool->sws_waiting_on_curl;
  3471. pool->sws_waiting_on_curl = sws;
  3472. if (sws->next)
  3473. applog(LOG_DEBUG, "submit_thread queuing submission");
  3474. else
  3475. applog(LOG_WARNING, "submit_thread queuing submissions (see --submit-threads)");
  3476. }
  3477. }
  3478. return sws;
  3479. out:
  3480. free(sws);
  3481. return NULL;
  3482. }
  3483. static bool retry_submission(struct submit_work_state *sws)
  3484. {
  3485. struct work *work = sws->work;
  3486. struct pool *pool = work->pool;
  3487. sws->resubmit = true;
  3488. if ((!work->stale) && stale_work(work, true)) {
  3489. work->stale = true;
  3490. if (opt_submit_stale)
  3491. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, will retry as user requested", pool->pool_no);
  3492. else if (pool->submit_old)
  3493. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, will retry as pool requested", pool->pool_no);
  3494. else {
  3495. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, discarding", pool->pool_no);
  3496. submit_discard_share(work);
  3497. return false;
  3498. }
  3499. sws->staleexpire = time(NULL) + 300;
  3500. }
  3501. if (unlikely((opt_retries >= 0) && (++sws->failures > opt_retries))) {
  3502. applog(LOG_ERR, "Pool %d failed %d submission retries, discarding", pool->pool_no, opt_retries);
  3503. submit_discard_share(work);
  3504. return false;
  3505. }
  3506. else if (work->stale) {
  3507. if (unlikely(opt_retries < 0 && sws->staleexpire <= time(NULL))) {
  3508. applog(LOG_NOTICE, "Pool %d stale share failed to submit for 5 minutes, discarding", pool->pool_no);
  3509. submit_discard_share(work);
  3510. return false;
  3511. }
  3512. }
  3513. /* pause, then restart work-request loop */
  3514. applog(LOG_INFO, "json_rpc_call failed on submit_work, retrying");
  3515. gettimeofday(&sws->tv_submit, NULL);
  3516. json_rpc_call_async(sws->ce->curl, pool->rpc_url, pool->rpc_userpass, sws->s, false, pool, true, sws);
  3517. return true;
  3518. }
  3519. static void free_sws(struct submit_work_state *sws)
  3520. {
  3521. free(sws->s);
  3522. free_work(sws->work);
  3523. free(sws);
  3524. }
  3525. static void *submit_work_thread(__maybe_unused void *userdata)
  3526. {
  3527. int wip = 0;
  3528. CURLM *curlm;
  3529. long curlm_timeout_us = -1;
  3530. struct timeval curlm_timer;
  3531. struct submit_work_state *sws, **swsp;
  3532. struct submit_work_state *write_sws = NULL;
  3533. unsigned tsreduce = 0;
  3534. pthread_detach(pthread_self());
  3535. RenameThread("submit_work");
  3536. applog(LOG_DEBUG, "Creating extra submit work thread");
  3537. curlm = curl_multi_init();
  3538. curlm_timeout_us = -1;
  3539. curl_multi_setopt(curlm, CURLMOPT_TIMERDATA, &curlm_timeout_us);
  3540. curl_multi_setopt(curlm, CURLMOPT_TIMERFUNCTION, my_curl_timer_set);
  3541. fd_set rfds, wfds, efds;
  3542. int maxfd;
  3543. struct timeval tv_timeout, tv_now;
  3544. int n;
  3545. CURLMsg *cm;
  3546. FD_ZERO(&rfds);
  3547. while (1) {
  3548. mutex_lock(&submitting_lock);
  3549. total_submitting -= tsreduce;
  3550. tsreduce = 0;
  3551. if (FD_ISSET(submit_waiting_notifier[0], &rfds)) {
  3552. notifier_read(submit_waiting_notifier);
  3553. }
  3554. // Receive any new submissions
  3555. while (!list_empty(&submit_waiting)) {
  3556. struct work *work = list_entry(submit_waiting.next, struct work, list);
  3557. list_del(&work->list);
  3558. if ( (sws = begin_submission(work)) ) {
  3559. if (sws->ce)
  3560. curl_multi_add_handle(curlm, sws->ce->curl);
  3561. else if (sws->s) {
  3562. sws->next = write_sws;
  3563. write_sws = sws;
  3564. }
  3565. ++wip;
  3566. }
  3567. else {
  3568. --total_submitting;
  3569. free_work(work);
  3570. }
  3571. }
  3572. if (unlikely(shutting_down && !wip))
  3573. break;
  3574. mutex_unlock(&submitting_lock);
  3575. FD_ZERO(&rfds);
  3576. FD_ZERO(&wfds);
  3577. FD_ZERO(&efds);
  3578. tv_timeout.tv_sec = -1;
  3579. // Setup cURL with select
  3580. // Need to call perform to ensure the timeout gets updated
  3581. curl_multi_perform(curlm, &n);
  3582. curl_multi_fdset(curlm, &rfds, &wfds, &efds, &maxfd);
  3583. if (curlm_timeout_us >= 0)
  3584. {
  3585. timer_set_delay_from_now(&curlm_timer, curlm_timeout_us);
  3586. reduce_timeout_to(&tv_timeout, &curlm_timer);
  3587. }
  3588. // Setup waiting stratum submissions with select
  3589. for (sws = write_sws; sws; sws = sws->next)
  3590. {
  3591. struct pool *pool = sws->work->pool;
  3592. int fd = pool->sock;
  3593. if (fd == INVSOCK || (!pool->stratum_init) || !pool->stratum_notify)
  3594. continue;
  3595. FD_SET(fd, &wfds);
  3596. set_maxfd(&maxfd, fd);
  3597. }
  3598. // Setup "submit waiting" notifier with select
  3599. FD_SET(submit_waiting_notifier[0], &rfds);
  3600. set_maxfd(&maxfd, submit_waiting_notifier[0]);
  3601. // Wait for something interesting to happen :)
  3602. gettimeofday(&tv_now, NULL);
  3603. if (select(maxfd+1, &rfds, &wfds, &efds, select_timeout(&tv_timeout, &tv_now)) < 0) {
  3604. FD_ZERO(&rfds);
  3605. continue;
  3606. }
  3607. // Handle any stratum ready-to-write results
  3608. for (swsp = &write_sws; (sws = *swsp); ) {
  3609. struct work *work = sws->work;
  3610. struct pool *pool = work->pool;
  3611. int fd = pool->sock;
  3612. bool sessionid_match;
  3613. cg_rlock(&pool->data_lock);
  3614. // 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
  3615. // NOTE: Worst case scenario for a false positive: the pool rejects it as H-not-zero
  3616. sessionid_match = (!pool->nonce1) || !strcmp(work->nonce1, pool->nonce1);
  3617. cg_runlock(&pool->data_lock);
  3618. if (!sessionid_match)
  3619. {
  3620. applog(LOG_DEBUG, "No matching session id for resubmitting stratum share");
  3621. submit_discard_share2("disconnect", work);
  3622. ++tsreduce;
  3623. next_write_sws_del:
  3624. // Clear the fd from wfds, to avoid potentially blocking on other submissions to the same socket
  3625. FD_CLR(fd, &wfds);
  3626. // Delete sws for this submission, since we're done with it
  3627. *swsp = sws->next;
  3628. free_sws(sws);
  3629. --wip;
  3630. continue;
  3631. }
  3632. if (fd == INVSOCK || (!pool->stratum_init) || (!pool->stratum_notify) || !FD_ISSET(fd, &wfds)) {
  3633. next_write_sws:
  3634. // TODO: Check if stale, possibly discard etc
  3635. swsp = &sws->next;
  3636. continue;
  3637. }
  3638. char *s = sws->s;
  3639. struct stratum_share *sshare = calloc(sizeof(struct stratum_share), 1);
  3640. uint32_t nonce;
  3641. char *noncehex;
  3642. sshare->sshare_time = time(NULL);
  3643. sshare->work = copy_work(work);
  3644. nonce = *((uint32_t *)(work->data + 76));
  3645. noncehex = bin2hex((const unsigned char *)&nonce, 4);
  3646. mutex_lock(&sshare_lock);
  3647. /* Give the stratum share a unique id */
  3648. sshare->id = swork_id++;
  3649. HASH_ADD_INT(stratum_shares, id, sshare);
  3650. sprintf(s, "{\"params\": [\"%s\", \"%s\", \"%s\", \"%s\", \"%s\"], \"id\": %d, \"method\": \"mining.submit\"}",
  3651. pool->rpc_user, work->job_id, work->nonce2, work->ntime, noncehex, sshare->id);
  3652. mutex_unlock(&sshare_lock);
  3653. free(noncehex);
  3654. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->stratum_url, s);
  3655. if (likely(stratum_send(pool, s, strlen(s)))) {
  3656. if (pool_tclear(pool, &pool->submit_fail))
  3657. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  3658. applog(LOG_DEBUG, "Successfully submitted, adding to stratum_shares db");
  3659. goto next_write_sws_del;
  3660. } else if (!pool_tset(pool, &pool->submit_fail)) {
  3661. // Undo stuff
  3662. mutex_lock(&sshare_lock);
  3663. HASH_DEL(stratum_shares, sshare);
  3664. mutex_unlock(&sshare_lock);
  3665. free_work(sshare->work);
  3666. free(sshare);
  3667. applog(LOG_WARNING, "Pool %d stratum share submission failure", pool->pool_no);
  3668. total_ro++;
  3669. pool->remotefail_occasions++;
  3670. goto next_write_sws;
  3671. }
  3672. }
  3673. // Handle any cURL activities
  3674. curl_multi_perform(curlm, &n);
  3675. while( (cm = curl_multi_info_read(curlm, &n)) ) {
  3676. if (cm->msg == CURLMSG_DONE)
  3677. {
  3678. bool finished;
  3679. json_t *val = json_rpc_call_completed(cm->easy_handle, cm->data.result, false, NULL, &sws);
  3680. curl_multi_remove_handle(curlm, cm->easy_handle);
  3681. finished = submit_upstream_work_completed(sws->work, sws->resubmit, &sws->tv_submit, val);
  3682. if (!finished) {
  3683. if (retry_submission(sws))
  3684. curl_multi_add_handle(curlm, sws->ce->curl);
  3685. else
  3686. finished = true;
  3687. }
  3688. if (finished) {
  3689. --wip;
  3690. ++tsreduce;
  3691. struct pool *pool = sws->work->pool;
  3692. if (pool->sws_waiting_on_curl) {
  3693. pool->sws_waiting_on_curl->ce = sws->ce;
  3694. sws_has_ce(pool->sws_waiting_on_curl);
  3695. pool->sws_waiting_on_curl = pool->sws_waiting_on_curl->next;
  3696. curl_multi_add_handle(curlm, sws->ce->curl);
  3697. } else {
  3698. push_curl_entry(sws->ce, sws->work->pool);
  3699. }
  3700. free_sws(sws);
  3701. }
  3702. }
  3703. }
  3704. }
  3705. assert(!write_sws);
  3706. mutex_unlock(&submitting_lock);
  3707. curl_multi_cleanup(curlm);
  3708. applog(LOG_DEBUG, "submit_work thread exiting");
  3709. return NULL;
  3710. }
  3711. /* Find the pool that currently has the highest priority */
  3712. static struct pool *priority_pool(int choice)
  3713. {
  3714. struct pool *ret = NULL;
  3715. int i;
  3716. for (i = 0; i < total_pools; i++) {
  3717. struct pool *pool = pools[i];
  3718. if (pool->prio == choice) {
  3719. ret = pool;
  3720. break;
  3721. }
  3722. }
  3723. if (unlikely(!ret)) {
  3724. applog(LOG_ERR, "WTF No pool %d found!", choice);
  3725. return pools[choice];
  3726. }
  3727. return ret;
  3728. }
  3729. int prioritize_pools(char *param, int *pid)
  3730. {
  3731. char *ptr, *next;
  3732. int i, pr, prio = 0;
  3733. if (total_pools == 0) {
  3734. return MSG_NOPOOL;
  3735. }
  3736. if (param == NULL || *param == '\0') {
  3737. return MSG_MISPID;
  3738. }
  3739. bool pools_changed[total_pools];
  3740. int new_prio[total_pools];
  3741. for (i = 0; i < total_pools; ++i)
  3742. pools_changed[i] = false;
  3743. next = param;
  3744. while (next && *next) {
  3745. ptr = next;
  3746. next = strchr(ptr, ',');
  3747. if (next)
  3748. *(next++) = '\0';
  3749. i = atoi(ptr);
  3750. if (i < 0 || i >= total_pools) {
  3751. *pid = i;
  3752. return MSG_INVPID;
  3753. }
  3754. if (pools_changed[i]) {
  3755. *pid = i;
  3756. return MSG_DUPPID;
  3757. }
  3758. pools_changed[i] = true;
  3759. new_prio[i] = prio++;
  3760. }
  3761. // Only change them if no errors
  3762. for (i = 0; i < total_pools; i++) {
  3763. if (pools_changed[i])
  3764. pools[i]->prio = new_prio[i];
  3765. }
  3766. // In priority order, cycle through the unchanged pools and append them
  3767. for (pr = 0; pr < total_pools; pr++)
  3768. for (i = 0; i < total_pools; i++) {
  3769. if (!pools_changed[i] && pools[i]->prio == pr) {
  3770. pools[i]->prio = prio++;
  3771. pools_changed[i] = true;
  3772. break;
  3773. }
  3774. }
  3775. if (current_pool()->prio)
  3776. switch_pools(NULL);
  3777. return MSG_POOLPRIO;
  3778. }
  3779. void validate_pool_priorities(void)
  3780. {
  3781. // TODO: this should probably do some sort of logging
  3782. int i, j;
  3783. bool used[total_pools];
  3784. bool valid[total_pools];
  3785. for (i = 0; i < total_pools; i++)
  3786. used[i] = valid[i] = false;
  3787. for (i = 0; i < total_pools; i++) {
  3788. if (pools[i]->prio >=0 && pools[i]->prio < total_pools) {
  3789. if (!used[pools[i]->prio]) {
  3790. valid[i] = true;
  3791. used[pools[i]->prio] = true;
  3792. }
  3793. }
  3794. }
  3795. for (i = 0; i < total_pools; i++) {
  3796. if (!valid[i]) {
  3797. for (j = 0; j < total_pools; j++) {
  3798. if (!used[j]) {
  3799. applog(LOG_WARNING, "Pool %d priority changed from %d to %d", i, pools[i]->prio, j);
  3800. pools[i]->prio = j;
  3801. used[j] = true;
  3802. break;
  3803. }
  3804. }
  3805. }
  3806. }
  3807. }
  3808. static void clear_pool_work(struct pool *pool);
  3809. /* Specifies whether we can switch to this pool or not. */
  3810. static bool pool_unusable(struct pool *pool)
  3811. {
  3812. if (pool->idle)
  3813. return true;
  3814. if (pool->enabled != POOL_ENABLED)
  3815. return true;
  3816. return false;
  3817. }
  3818. void switch_pools(struct pool *selected)
  3819. {
  3820. struct pool *pool, *last_pool;
  3821. int i, pool_no, next_pool;
  3822. cg_wlock(&control_lock);
  3823. last_pool = currentpool;
  3824. pool_no = currentpool->pool_no;
  3825. /* Switch selected to pool number 0 and move the rest down */
  3826. if (selected) {
  3827. if (selected->prio != 0) {
  3828. for (i = 0; i < total_pools; i++) {
  3829. pool = pools[i];
  3830. if (pool->prio < selected->prio)
  3831. pool->prio++;
  3832. }
  3833. selected->prio = 0;
  3834. }
  3835. }
  3836. switch (pool_strategy) {
  3837. /* Both of these set to the master pool */
  3838. case POOL_BALANCE:
  3839. case POOL_FAILOVER:
  3840. case POOL_LOADBALANCE:
  3841. for (i = 0; i < total_pools; i++) {
  3842. pool = priority_pool(i);
  3843. if (pool_unusable(pool))
  3844. continue;
  3845. pool_no = pool->pool_no;
  3846. break;
  3847. }
  3848. break;
  3849. /* Both of these simply increment and cycle */
  3850. case POOL_ROUNDROBIN:
  3851. case POOL_ROTATE:
  3852. if (selected && !selected->idle) {
  3853. pool_no = selected->pool_no;
  3854. break;
  3855. }
  3856. next_pool = pool_no;
  3857. /* Select the next alive pool */
  3858. for (i = 1; i < total_pools; i++) {
  3859. next_pool++;
  3860. if (next_pool >= total_pools)
  3861. next_pool = 0;
  3862. pool = pools[next_pool];
  3863. if (pool_unusable(pool))
  3864. continue;
  3865. pool_no = next_pool;
  3866. break;
  3867. }
  3868. break;
  3869. default:
  3870. break;
  3871. }
  3872. currentpool = pools[pool_no];
  3873. pool = currentpool;
  3874. cg_wunlock(&control_lock);
  3875. /* Set the lagging flag to avoid pool not providing work fast enough
  3876. * messages in failover only mode since we have to get all fresh work
  3877. * as in restart_threads */
  3878. if (opt_fail_only)
  3879. pool_tset(pool, &pool->lagging);
  3880. if (pool != last_pool)
  3881. {
  3882. pool->block_id = 0;
  3883. if (pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  3884. applog(LOG_WARNING, "Switching to pool %d %s", pool->pool_no, pool->rpc_url);
  3885. if (pool->last_work_copy || pool->has_stratum || opt_fail_only)
  3886. clear_pool_work(last_pool);
  3887. }
  3888. }
  3889. mutex_lock(&lp_lock);
  3890. pthread_cond_broadcast(&lp_cond);
  3891. mutex_unlock(&lp_lock);
  3892. }
  3893. static void discard_work(struct work *work)
  3894. {
  3895. if (!work->clone && !work->rolls && !work->mined) {
  3896. if (work->pool)
  3897. work->pool->discarded_work++;
  3898. total_discarded++;
  3899. applog(LOG_DEBUG, "Discarded work");
  3900. } else
  3901. applog(LOG_DEBUG, "Discarded cloned or rolled work");
  3902. free_work(work);
  3903. }
  3904. static void wake_gws(void)
  3905. {
  3906. mutex_lock(stgd_lock);
  3907. pthread_cond_signal(&gws_cond);
  3908. mutex_unlock(stgd_lock);
  3909. }
  3910. static void discard_stale(void)
  3911. {
  3912. struct work *work, *tmp;
  3913. int stale = 0;
  3914. mutex_lock(stgd_lock);
  3915. HASH_ITER(hh, staged_work, work, tmp) {
  3916. if (stale_work(work, false)) {
  3917. HASH_DEL(staged_work, work);
  3918. discard_work(work);
  3919. stale++;
  3920. }
  3921. }
  3922. pthread_cond_signal(&gws_cond);
  3923. mutex_unlock(stgd_lock);
  3924. if (stale)
  3925. applog(LOG_DEBUG, "Discarded %d stales that didn't match current hash", stale);
  3926. }
  3927. bool stale_work_future(struct work *work, bool share, unsigned long ustime)
  3928. {
  3929. bool rv;
  3930. struct timeval tv, orig;
  3931. ldiv_t d;
  3932. d = ldiv(ustime, 1000000);
  3933. tv = (struct timeval){
  3934. .tv_sec = d.quot,
  3935. .tv_usec = d.rem,
  3936. };
  3937. orig = work->tv_staged;
  3938. timersub(&orig, &tv, &work->tv_staged);
  3939. rv = stale_work(work, share);
  3940. work->tv_staged = orig;
  3941. return rv;
  3942. }
  3943. static void restart_threads(void)
  3944. {
  3945. struct pool *cp = current_pool();
  3946. int i;
  3947. struct thr_info *thr;
  3948. /* Artificially set the lagging flag to avoid pool not providing work
  3949. * fast enough messages after every long poll */
  3950. pool_tset(cp, &cp->lagging);
  3951. /* Discard staged work that is now stale */
  3952. discard_stale();
  3953. rd_lock(&mining_thr_lock);
  3954. for (i = 0; i < mining_threads; i++)
  3955. {
  3956. thr = mining_thr[i];
  3957. thr->work_restart = true;
  3958. }
  3959. for (i = 0; i < mining_threads; i++)
  3960. {
  3961. thr = mining_thr[i];
  3962. notifier_wake(thr->work_restart_notifier);
  3963. }
  3964. rd_unlock(&mining_thr_lock);
  3965. }
  3966. static char *blkhashstr(unsigned char *hash)
  3967. {
  3968. unsigned char hash_swap[32];
  3969. swap256(hash_swap, hash);
  3970. swap32tole(hash_swap, hash_swap, 32 / 4);
  3971. return bin2hex(hash_swap, 32);
  3972. }
  3973. static void set_curblock(char *hexstr, unsigned char *hash)
  3974. {
  3975. unsigned char hash_swap[32];
  3976. current_block_id = ((uint32_t*)hash)[0];
  3977. strcpy(current_block, hexstr);
  3978. swap256(hash_swap, hash);
  3979. swap32tole(hash_swap, hash_swap, 32 / 4);
  3980. cg_wlock(&ch_lock);
  3981. gettimeofday(&block_timeval, NULL);
  3982. __update_block_title(hash_swap);
  3983. free(current_fullhash);
  3984. current_fullhash = bin2hex(hash_swap, 32);
  3985. get_timestamp(blocktime, &block_timeval);
  3986. applog(LOG_INFO, "New block: %s diff %s (%s)", current_hash, block_diff, net_hashrate);
  3987. cg_wunlock(&ch_lock);
  3988. }
  3989. /* Search to see if this string is from a block that has been seen before */
  3990. static bool block_exists(char *hexstr)
  3991. {
  3992. struct block *s;
  3993. rd_lock(&blk_lock);
  3994. HASH_FIND_STR(blocks, hexstr, s);
  3995. rd_unlock(&blk_lock);
  3996. if (s)
  3997. return true;
  3998. return false;
  3999. }
  4000. /* Tests if this work is from a block that has been seen before */
  4001. static inline bool from_existing_block(struct work *work)
  4002. {
  4003. char *hexstr = bin2hex(work->data + 8, 18);
  4004. bool ret;
  4005. ret = block_exists(hexstr);
  4006. free(hexstr);
  4007. return ret;
  4008. }
  4009. static int block_sort(struct block *blocka, struct block *blockb)
  4010. {
  4011. return blocka->block_no - blockb->block_no;
  4012. }
  4013. static void set_blockdiff(const struct work *work)
  4014. {
  4015. unsigned char target[32];
  4016. double diff;
  4017. uint64_t diff64;
  4018. real_block_target(target, work->data);
  4019. diff = target_diff(target);
  4020. diff64 = diff;
  4021. suffix_string(diff64, block_diff, 0);
  4022. hashrate_to_bufstr(net_hashrate, diff * 7158278, -1, H2B_SHORT);
  4023. if (unlikely(current_diff != diff))
  4024. applog(LOG_NOTICE, "Network difficulty changed to %s (%s)", block_diff, net_hashrate);
  4025. current_diff = diff;
  4026. }
  4027. static bool test_work_current(struct work *work)
  4028. {
  4029. bool ret = true;
  4030. char *hexstr;
  4031. if (work->mandatory)
  4032. return ret;
  4033. uint32_t block_id = ((uint32_t*)(work->data))[1];
  4034. /* Hack to work around dud work sneaking into test */
  4035. hexstr = bin2hex(work->data + 8, 18);
  4036. if (!strncmp(hexstr, "000000000000000000000000000000000000", 36))
  4037. goto out_free;
  4038. /* Search to see if this block exists yet and if not, consider it a
  4039. * new block and set the current block details to this one */
  4040. if (!block_exists(hexstr)) {
  4041. struct block *s = calloc(sizeof(struct block), 1);
  4042. int deleted_block = 0;
  4043. ret = false;
  4044. if (unlikely(!s))
  4045. quit (1, "test_work_current OOM");
  4046. strcpy(s->hash, hexstr);
  4047. s->block_no = new_blocks++;
  4048. wr_lock(&blk_lock);
  4049. /* Only keep the last hour's worth of blocks in memory since
  4050. * work from blocks before this is virtually impossible and we
  4051. * want to prevent memory usage from continually rising */
  4052. if (HASH_COUNT(blocks) > 6) {
  4053. struct block *oldblock;
  4054. HASH_SORT(blocks, block_sort);
  4055. oldblock = blocks;
  4056. deleted_block = oldblock->block_no;
  4057. HASH_DEL(blocks, oldblock);
  4058. free(oldblock);
  4059. }
  4060. HASH_ADD_STR(blocks, hash, s);
  4061. set_blockdiff(work);
  4062. wr_unlock(&blk_lock);
  4063. work->pool->block_id = block_id;
  4064. if (deleted_block)
  4065. applog(LOG_DEBUG, "Deleted block %d from database", deleted_block);
  4066. template_nonce = 0;
  4067. set_curblock(hexstr, &work->data[4]);
  4068. if (unlikely(new_blocks == 1))
  4069. goto out_free;
  4070. if (!work->stratum) {
  4071. if (work->longpoll) {
  4072. applog(LOG_NOTICE, "Longpoll from pool %d detected new block",
  4073. work->pool->pool_no);
  4074. } else if (have_longpoll)
  4075. applog(LOG_NOTICE, "New block detected on network before longpoll");
  4076. else
  4077. applog(LOG_NOTICE, "New block detected on network");
  4078. }
  4079. restart_threads();
  4080. } else {
  4081. bool restart = false;
  4082. struct pool *curpool = NULL;
  4083. if (unlikely(work->pool->block_id != block_id)) {
  4084. bool was_active = work->pool->block_id != 0;
  4085. work->pool->block_id = block_id;
  4086. if (!work->longpoll)
  4087. update_last_work(work);
  4088. if (was_active) { // Pool actively changed block
  4089. if (work->pool == (curpool = current_pool()))
  4090. restart = true;
  4091. if (block_id == current_block_id) {
  4092. // Caught up, only announce if this pool is the one in use
  4093. if (restart)
  4094. applog(LOG_NOTICE, "%s %d caught up to new block",
  4095. work->longpoll ? "Longpoll from pool" : "Pool",
  4096. work->pool->pool_no);
  4097. } else {
  4098. // Switched to a block we know, but not the latest... why?
  4099. // This might detect pools trying to double-spend or 51%,
  4100. // but let's not make any accusations until it's had time
  4101. // in the real world.
  4102. free(hexstr);
  4103. hexstr = blkhashstr(&work->data[4]);
  4104. applog(LOG_WARNING, "%s %d is issuing work for an old block: %s",
  4105. work->longpoll ? "Longpoll from pool" : "Pool",
  4106. work->pool->pool_no,
  4107. hexstr);
  4108. }
  4109. }
  4110. }
  4111. if (work->longpoll) {
  4112. ++work->pool->work_restart_id;
  4113. update_last_work(work);
  4114. if ((!restart) && work->pool == current_pool()) {
  4115. applog(
  4116. (opt_quiet_work_updates ? LOG_DEBUG : LOG_NOTICE),
  4117. "Longpoll from pool %d requested work update",
  4118. work->pool->pool_no);
  4119. restart = true;
  4120. }
  4121. }
  4122. if (restart)
  4123. restart_threads();
  4124. }
  4125. work->longpoll = false;
  4126. out_free:
  4127. free(hexstr);
  4128. return ret;
  4129. }
  4130. static int tv_sort(struct work *worka, struct work *workb)
  4131. {
  4132. return worka->tv_staged.tv_sec - workb->tv_staged.tv_sec;
  4133. }
  4134. static bool work_rollable(struct work *work)
  4135. {
  4136. return (!work->clone && work->rolltime);
  4137. }
  4138. static bool hash_push(struct work *work)
  4139. {
  4140. bool rc = true;
  4141. mutex_lock(stgd_lock);
  4142. if (work_rollable(work))
  4143. staged_rollable++;
  4144. if (likely(!getq->frozen)) {
  4145. HASH_ADD_INT(staged_work, id, work);
  4146. HASH_SORT(staged_work, tv_sort);
  4147. } else
  4148. rc = false;
  4149. pthread_cond_broadcast(&getq->cond);
  4150. mutex_unlock(stgd_lock);
  4151. return rc;
  4152. }
  4153. static void *stage_thread(void *userdata)
  4154. {
  4155. struct thr_info *mythr = userdata;
  4156. bool ok = true;
  4157. #ifndef HAVE_PTHREAD_CANCEL
  4158. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  4159. #endif
  4160. RenameThread("stage");
  4161. while (ok) {
  4162. struct work *work = NULL;
  4163. applog(LOG_DEBUG, "Popping work to stage thread");
  4164. work = tq_pop(mythr->q, NULL);
  4165. if (unlikely(!work)) {
  4166. applog(LOG_ERR, "Failed to tq_pop in stage_thread");
  4167. ok = false;
  4168. break;
  4169. }
  4170. work->work_restart_id = work->pool->work_restart_id;
  4171. test_work_current(work);
  4172. applog(LOG_DEBUG, "Pushing work to getwork queue (queued=%c)", work->queued?'Y':'N');
  4173. if (unlikely(!hash_push(work))) {
  4174. applog(LOG_WARNING, "Failed to hash_push in stage_thread");
  4175. continue;
  4176. }
  4177. }
  4178. tq_freeze(mythr->q);
  4179. return NULL;
  4180. }
  4181. static void stage_work(struct work *work)
  4182. {
  4183. applog(LOG_DEBUG, "Pushing work from pool %d to hash queue", work->pool->pool_no);
  4184. work->work_restart_id = work->pool->work_restart_id;
  4185. work->pool->last_work_time = time(NULL);
  4186. test_work_current(work);
  4187. hash_push(work);
  4188. }
  4189. #ifdef HAVE_CURSES
  4190. int curses_int(const char *query)
  4191. {
  4192. int ret;
  4193. char *cvar;
  4194. cvar = curses_input(query);
  4195. ret = atoi(cvar);
  4196. free(cvar);
  4197. return ret;
  4198. }
  4199. #endif
  4200. #ifdef HAVE_CURSES
  4201. static bool input_pool(bool live);
  4202. #endif
  4203. #ifdef HAVE_CURSES
  4204. static void display_pool_summary(struct pool *pool)
  4205. {
  4206. double efficiency = 0.0;
  4207. if (curses_active_locked()) {
  4208. wlog("Pool: %s\n", pool->rpc_url);
  4209. if (pool->solved)
  4210. wlog("SOLVED %d BLOCK%s!\n", pool->solved, pool->solved > 1 ? "S" : "");
  4211. wlog("%s own long-poll support\n", pool->lp_url ? "Has" : "Does not have");
  4212. wlog(" Queued work requests: %d\n", pool->getwork_requested);
  4213. wlog(" Share submissions: %d\n", pool->accepted + pool->rejected);
  4214. wlog(" Accepted shares: %d\n", pool->accepted);
  4215. wlog(" Rejected shares: %d\n", pool->rejected);
  4216. wlog(" Accepted difficulty shares: %1.f\n", pool->diff_accepted);
  4217. wlog(" Rejected difficulty shares: %1.f\n", pool->diff_rejected);
  4218. if (pool->accepted || pool->rejected)
  4219. wlog(" Reject ratio: %.1f%%\n", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  4220. uint64_t pool_bytes_xfer = pool->cgminer_pool_stats.net_bytes_received + pool->cgminer_pool_stats.net_bytes_sent;
  4221. efficiency = pool_bytes_xfer ? pool->diff_accepted * 2048. / pool_bytes_xfer : 0.0;
  4222. wlog(" Efficiency (accepted * difficulty / 2 KB): %.2f\n", efficiency);
  4223. wlog(" Discarded work due to new blocks: %d\n", pool->discarded_work);
  4224. wlog(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  4225. wlog(" Unable to get work from server occasions: %d\n", pool->getfail_occasions);
  4226. wlog(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  4227. unlock_curses();
  4228. }
  4229. }
  4230. #endif
  4231. /* We can't remove the memory used for this struct pool because there may
  4232. * still be work referencing it. We just remove it from the pools list */
  4233. void remove_pool(struct pool *pool)
  4234. {
  4235. int i, last_pool = total_pools - 1;
  4236. struct pool *other;
  4237. /* Boost priority of any lower prio than this one */
  4238. for (i = 0; i < total_pools; i++) {
  4239. other = pools[i];
  4240. if (other->prio > pool->prio)
  4241. other->prio--;
  4242. }
  4243. if (pool->pool_no < last_pool) {
  4244. /* Swap the last pool for this one */
  4245. (pools[last_pool])->pool_no = pool->pool_no;
  4246. pools[pool->pool_no] = pools[last_pool];
  4247. }
  4248. /* Give it an invalid number */
  4249. pool->pool_no = total_pools;
  4250. pool->removed = true;
  4251. pool->has_stratum = false;
  4252. total_pools--;
  4253. }
  4254. /* add a mutex if this needs to be thread safe in the future */
  4255. static struct JE {
  4256. char *buf;
  4257. struct JE *next;
  4258. } *jedata = NULL;
  4259. static void json_escape_free()
  4260. {
  4261. struct JE *jeptr = jedata;
  4262. struct JE *jenext;
  4263. jedata = NULL;
  4264. while (jeptr) {
  4265. jenext = jeptr->next;
  4266. free(jeptr->buf);
  4267. free(jeptr);
  4268. jeptr = jenext;
  4269. }
  4270. }
  4271. static char *json_escape(char *str)
  4272. {
  4273. struct JE *jeptr;
  4274. char *buf, *ptr;
  4275. /* 2x is the max, may as well just allocate that */
  4276. ptr = buf = malloc(strlen(str) * 2 + 1);
  4277. jeptr = malloc(sizeof(*jeptr));
  4278. jeptr->buf = buf;
  4279. jeptr->next = jedata;
  4280. jedata = jeptr;
  4281. while (*str) {
  4282. if (*str == '\\' || *str == '"')
  4283. *(ptr++) = '\\';
  4284. *(ptr++) = *(str++);
  4285. }
  4286. *ptr = '\0';
  4287. return buf;
  4288. }
  4289. void write_config(FILE *fcfg)
  4290. {
  4291. int i;
  4292. /* Write pool values */
  4293. fputs("{\n\"pools\" : [", fcfg);
  4294. for(i = 0; i < total_pools; i++) {
  4295. fprintf(fcfg, "%s\n\t{\n\t\t\"url\" : \"%s\",", i > 0 ? "," : "", json_escape(pools[i]->rpc_url));
  4296. if (pools[i]->rpc_proxy)
  4297. fprintf(fcfg, "\n\t\t\"pool-proxy\" : \"%s\",", json_escape(pools[i]->rpc_proxy));
  4298. fprintf(fcfg, "\n\t\t\"user\" : \"%s\",", json_escape(pools[i]->rpc_user));
  4299. fprintf(fcfg, "\n\t\t\"pass\" : \"%s\",", json_escape(pools[i]->rpc_pass));
  4300. fprintf(fcfg, "\n\t\t\"pool-priority\" : \"%d\"", pools[i]->prio);
  4301. if (pools[i]->force_rollntime)
  4302. fprintf(fcfg, ",\n\t\t\"force-rollntime\" : %d", pools[i]->force_rollntime);
  4303. fprintf(fcfg, "\n\t}");
  4304. }
  4305. fputs("\n]\n", fcfg);
  4306. fputs(",\n\"temp-cutoff\" : \"", fcfg);
  4307. for (i = 0; i < total_devices; ++i)
  4308. fprintf(fcfg, "%s%d", i > 0 ? "," : "", devices[i]->cutofftemp);
  4309. fputs("\",\n\"temp-target\" : \"", fcfg);
  4310. for (i = 0; i < total_devices; ++i)
  4311. fprintf(fcfg, "%s%d", i > 0 ? "," : "", devices[i]->targettemp);
  4312. fputs("\"", fcfg);
  4313. #ifdef HAVE_OPENCL
  4314. if (nDevs) {
  4315. /* Write GPU device values */
  4316. fputs(",\n\"intensity\" : \"", fcfg);
  4317. for(i = 0; i < nDevs; i++)
  4318. fprintf(fcfg, gpus[i].dynamic ? "%sd" : "%s%d", i > 0 ? "," : "", gpus[i].intensity);
  4319. fputs("\",\n\"vectors\" : \"", fcfg);
  4320. for(i = 0; i < nDevs; i++)
  4321. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  4322. gpus[i].vwidth);
  4323. fputs("\",\n\"worksize\" : \"", fcfg);
  4324. for(i = 0; i < nDevs; i++)
  4325. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  4326. (int)gpus[i].work_size);
  4327. fputs("\",\n\"kernel\" : \"", fcfg);
  4328. for(i = 0; i < nDevs; i++) {
  4329. fprintf(fcfg, "%s", i > 0 ? "," : "");
  4330. switch (gpus[i].kernel) {
  4331. case KL_NONE: // Shouldn't happen
  4332. break;
  4333. case KL_POCLBM:
  4334. fprintf(fcfg, "poclbm");
  4335. break;
  4336. case KL_PHATK:
  4337. fprintf(fcfg, "phatk");
  4338. break;
  4339. case KL_DIAKGCN:
  4340. fprintf(fcfg, "diakgcn");
  4341. break;
  4342. case KL_DIABLO:
  4343. fprintf(fcfg, "diablo");
  4344. break;
  4345. case KL_SCRYPT:
  4346. fprintf(fcfg, "scrypt");
  4347. break;
  4348. }
  4349. }
  4350. #ifdef USE_SCRYPT
  4351. fputs("\",\n\"lookup-gap\" : \"", fcfg);
  4352. for(i = 0; i < nDevs; i++)
  4353. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  4354. (int)gpus[i].opt_lg);
  4355. fputs("\",\n\"thread-concurrency\" : \"", fcfg);
  4356. for(i = 0; i < nDevs; i++)
  4357. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  4358. (int)gpus[i].opt_tc);
  4359. fputs("\",\n\"shaders\" : \"", fcfg);
  4360. for(i = 0; i < nDevs; i++)
  4361. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  4362. (int)gpus[i].shaders);
  4363. #endif
  4364. #ifdef HAVE_ADL
  4365. fputs("\",\n\"gpu-engine\" : \"", fcfg);
  4366. for(i = 0; i < nDevs; i++)
  4367. fprintf(fcfg, "%s%d-%d", i > 0 ? "," : "", gpus[i].min_engine, gpus[i].gpu_engine);
  4368. fputs("\",\n\"gpu-fan\" : \"", fcfg);
  4369. for(i = 0; i < nDevs; i++)
  4370. fprintf(fcfg, "%s%d-%d", i > 0 ? "," : "", gpus[i].min_fan, gpus[i].gpu_fan);
  4371. fputs("\",\n\"gpu-memclock\" : \"", fcfg);
  4372. for(i = 0; i < nDevs; i++)
  4373. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_memclock);
  4374. fputs("\",\n\"gpu-memdiff\" : \"", fcfg);
  4375. for(i = 0; i < nDevs; i++)
  4376. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_memdiff);
  4377. fputs("\",\n\"gpu-powertune\" : \"", fcfg);
  4378. for(i = 0; i < nDevs; i++)
  4379. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_powertune);
  4380. fputs("\",\n\"gpu-vddc\" : \"", fcfg);
  4381. for(i = 0; i < nDevs; i++)
  4382. fprintf(fcfg, "%s%1.3f", i > 0 ? "," : "", gpus[i].gpu_vddc);
  4383. fputs("\",\n\"temp-overheat\" : \"", fcfg);
  4384. for(i = 0; i < nDevs; i++)
  4385. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].adl.overtemp);
  4386. #endif
  4387. fputs("\"", fcfg);
  4388. }
  4389. #endif
  4390. #ifdef HAVE_ADL
  4391. if (opt_reorder)
  4392. fprintf(fcfg, ",\n\"gpu-reorder\" : true");
  4393. #endif
  4394. #ifdef WANT_CPUMINE
  4395. fprintf(fcfg, ",\n\"algo\" : \"%s\"", algo_names[opt_algo]);
  4396. #endif
  4397. /* Simple bool and int options */
  4398. struct opt_table *opt;
  4399. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  4400. char *p, *name = strdup(opt->names);
  4401. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  4402. if (p[1] != '-')
  4403. continue;
  4404. if (opt->type & OPT_NOARG &&
  4405. ((void *)opt->cb == (void *)opt_set_bool || (void *)opt->cb == (void *)opt_set_invbool) &&
  4406. (*(bool *)opt->u.arg == ((void *)opt->cb == (void *)opt_set_bool)))
  4407. fprintf(fcfg, ",\n\"%s\" : true", p+2);
  4408. if (opt->type & OPT_HASARG &&
  4409. ((void *)opt->cb_arg == (void *)set_int_0_to_9999 ||
  4410. (void *)opt->cb_arg == (void *)set_int_1_to_65535 ||
  4411. (void *)opt->cb_arg == (void *)set_int_0_to_10 ||
  4412. (void *)opt->cb_arg == (void *)set_int_1_to_10) &&
  4413. opt->desc != opt_hidden &&
  4414. 0 <= *(int *)opt->u.arg)
  4415. fprintf(fcfg, ",\n\"%s\" : \"%d\"", p+2, *(int *)opt->u.arg);
  4416. }
  4417. }
  4418. /* Special case options */
  4419. fprintf(fcfg, ",\n\"shares\" : \"%d\"", opt_shares);
  4420. if (pool_strategy == POOL_BALANCE)
  4421. fputs(",\n\"balance\" : true", fcfg);
  4422. if (pool_strategy == POOL_LOADBALANCE)
  4423. fputs(",\n\"load-balance\" : true", fcfg);
  4424. if (pool_strategy == POOL_ROUNDROBIN)
  4425. fputs(",\n\"round-robin\" : true", fcfg);
  4426. if (pool_strategy == POOL_ROTATE)
  4427. fprintf(fcfg, ",\n\"rotate\" : \"%d\"", opt_rotate_period);
  4428. #if defined(unix)
  4429. if (opt_stderr_cmd && *opt_stderr_cmd)
  4430. fprintf(fcfg, ",\n\"monitor\" : \"%s\"", json_escape(opt_stderr_cmd));
  4431. #endif // defined(unix)
  4432. if (opt_kernel_path && *opt_kernel_path) {
  4433. char *kpath = strdup(opt_kernel_path);
  4434. if (kpath[strlen(kpath)-1] == '/')
  4435. kpath[strlen(kpath)-1] = 0;
  4436. fprintf(fcfg, ",\n\"kernel-path\" : \"%s\"", json_escape(kpath));
  4437. }
  4438. if (schedstart.enable)
  4439. fprintf(fcfg, ",\n\"sched-time\" : \"%d:%d\"", schedstart.tm.tm_hour, schedstart.tm.tm_min);
  4440. if (schedstop.enable)
  4441. fprintf(fcfg, ",\n\"stop-time\" : \"%d:%d\"", schedstop.tm.tm_hour, schedstop.tm.tm_min);
  4442. if (opt_socks_proxy && *opt_socks_proxy)
  4443. fprintf(fcfg, ",\n\"socks-proxy\" : \"%s\"", json_escape(opt_socks_proxy));
  4444. #ifdef HAVE_OPENCL
  4445. for(i = 0; i < nDevs; i++)
  4446. if (gpus[i].deven == DEV_DISABLED)
  4447. break;
  4448. if (i < nDevs)
  4449. for (i = 0; i < nDevs; i++)
  4450. if (gpus[i].deven != DEV_DISABLED)
  4451. fprintf(fcfg, ",\n\"device\" : \"%d\"", i);
  4452. #endif
  4453. if (opt_api_allow)
  4454. fprintf(fcfg, ",\n\"api-allow\" : \"%s\"", json_escape(opt_api_allow));
  4455. if (strcmp(opt_api_description, PACKAGE_STRING) != 0)
  4456. fprintf(fcfg, ",\n\"api-description\" : \"%s\"", json_escape(opt_api_description));
  4457. if (opt_api_groups)
  4458. fprintf(fcfg, ",\n\"api-groups\" : \"%s\"", json_escape(opt_api_groups));
  4459. if (opt_icarus_options)
  4460. fprintf(fcfg, ",\n\"icarus-options\" : \"%s\"", json_escape(opt_icarus_options));
  4461. if (opt_icarus_timing)
  4462. fprintf(fcfg, ",\n\"icarus-timing\" : \"%s\"", json_escape(opt_icarus_timing));
  4463. fputs("\n}\n", fcfg);
  4464. json_escape_free();
  4465. }
  4466. void zero_bestshare(void)
  4467. {
  4468. int i;
  4469. best_diff = 0;
  4470. memset(best_share, 0, 8);
  4471. suffix_string(best_diff, best_share, 0);
  4472. for (i = 0; i < total_pools; i++) {
  4473. struct pool *pool = pools[i];
  4474. pool->best_diff = 0;
  4475. }
  4476. }
  4477. void zero_stats(void)
  4478. {
  4479. int i;
  4480. gettimeofday(&total_tv_start, NULL);
  4481. miner_started = total_tv_start;
  4482. total_mhashes_done = 0;
  4483. total_getworks = 0;
  4484. total_accepted = 0;
  4485. total_rejected = 0;
  4486. hw_errors = 0;
  4487. total_stale = 0;
  4488. total_discarded = 0;
  4489. total_bytes_xfer = 0;
  4490. new_blocks = 0;
  4491. local_work = 0;
  4492. total_go = 0;
  4493. total_ro = 0;
  4494. total_secs = 1.0;
  4495. total_diff1 = 0;
  4496. found_blocks = 0;
  4497. total_diff_accepted = 0;
  4498. total_diff_rejected = 0;
  4499. total_diff_stale = 0;
  4500. for (i = 0; i < total_pools; i++) {
  4501. struct pool *pool = pools[i];
  4502. pool->getwork_requested = 0;
  4503. pool->accepted = 0;
  4504. pool->rejected = 0;
  4505. pool->solved = 0;
  4506. pool->getwork_requested = 0;
  4507. pool->stale_shares = 0;
  4508. pool->discarded_work = 0;
  4509. pool->getfail_occasions = 0;
  4510. pool->remotefail_occasions = 0;
  4511. pool->last_share_time = 0;
  4512. pool->diff1 = 0;
  4513. pool->diff_accepted = 0;
  4514. pool->diff_rejected = 0;
  4515. pool->diff_stale = 0;
  4516. pool->last_share_diff = 0;
  4517. pool->cgminer_stats.getwork_calls = 0;
  4518. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  4519. pool->cgminer_stats.getwork_wait_max.tv_sec = 0;
  4520. pool->cgminer_stats.getwork_wait_max.tv_usec = 0;
  4521. pool->cgminer_pool_stats.getwork_calls = 0;
  4522. pool->cgminer_pool_stats.getwork_attempts = 0;
  4523. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  4524. pool->cgminer_pool_stats.getwork_wait_max.tv_sec = 0;
  4525. pool->cgminer_pool_stats.getwork_wait_max.tv_usec = 0;
  4526. pool->cgminer_pool_stats.min_diff = 0;
  4527. pool->cgminer_pool_stats.max_diff = 0;
  4528. pool->cgminer_pool_stats.min_diff_count = 0;
  4529. pool->cgminer_pool_stats.max_diff_count = 0;
  4530. pool->cgminer_pool_stats.times_sent = 0;
  4531. pool->cgminer_pool_stats.bytes_sent = 0;
  4532. pool->cgminer_pool_stats.net_bytes_sent = 0;
  4533. pool->cgminer_pool_stats.times_received = 0;
  4534. pool->cgminer_pool_stats.bytes_received = 0;
  4535. pool->cgminer_pool_stats.net_bytes_received = 0;
  4536. }
  4537. zero_bestshare();
  4538. for (i = 0; i < total_devices; ++i) {
  4539. struct cgpu_info *cgpu = get_devices(i);
  4540. mutex_lock(&hash_lock);
  4541. cgpu->total_mhashes = 0;
  4542. cgpu->accepted = 0;
  4543. cgpu->rejected = 0;
  4544. cgpu->hw_errors = 0;
  4545. cgpu->utility = 0.0;
  4546. cgpu->utility_diff1 = 0;
  4547. cgpu->last_share_pool_time = 0;
  4548. cgpu->diff1 = 0;
  4549. cgpu->diff_accepted = 0;
  4550. cgpu->diff_rejected = 0;
  4551. cgpu->last_share_diff = 0;
  4552. cgpu->thread_fail_init_count = 0;
  4553. cgpu->thread_zero_hash_count = 0;
  4554. cgpu->thread_fail_queue_count = 0;
  4555. cgpu->dev_sick_idle_60_count = 0;
  4556. cgpu->dev_dead_idle_600_count = 0;
  4557. cgpu->dev_nostart_count = 0;
  4558. cgpu->dev_over_heat_count = 0;
  4559. cgpu->dev_thermal_cutoff_count = 0;
  4560. cgpu->dev_comms_error_count = 0;
  4561. cgpu->dev_throttle_count = 0;
  4562. cgpu->cgminer_stats.getwork_calls = 0;
  4563. cgpu->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  4564. cgpu->cgminer_stats.getwork_wait_max.tv_sec = 0;
  4565. cgpu->cgminer_stats.getwork_wait_max.tv_usec = 0;
  4566. mutex_unlock(&hash_lock);
  4567. }
  4568. }
  4569. #ifdef HAVE_CURSES
  4570. static void display_pools(void)
  4571. {
  4572. struct pool *pool;
  4573. int selected, i, j;
  4574. char input;
  4575. opt_loginput = true;
  4576. immedok(logwin, true);
  4577. clear_logwin();
  4578. updated:
  4579. for (j = 0; j < total_pools; j++) {
  4580. for (i = 0; i < total_pools; i++) {
  4581. pool = pools[i];
  4582. if (pool->prio != j)
  4583. continue;
  4584. if (pool == current_pool())
  4585. wattron(logwin, A_BOLD);
  4586. if (pool->enabled != POOL_ENABLED)
  4587. wattron(logwin, A_DIM);
  4588. wlogprint("%d: ", pool->prio);
  4589. switch (pool->enabled) {
  4590. case POOL_ENABLED:
  4591. wlogprint("Enabled ");
  4592. break;
  4593. case POOL_DISABLED:
  4594. wlogprint("Disabled ");
  4595. break;
  4596. case POOL_REJECTING:
  4597. wlogprint("Rejectin ");
  4598. break;
  4599. }
  4600. if (pool->idle)
  4601. wlogprint("Dead ");
  4602. else
  4603. if (pool->has_stratum)
  4604. wlogprint("Strtm");
  4605. else
  4606. if (pool->lp_url && pool->proto != pool->lp_proto)
  4607. wlogprint("Mixed");
  4608. else
  4609. switch (pool->proto) {
  4610. case PLP_GETBLOCKTEMPLATE:
  4611. wlogprint(" GBT ");
  4612. break;
  4613. case PLP_GETWORK:
  4614. wlogprint("GWork");
  4615. break;
  4616. default:
  4617. wlogprint("Alive");
  4618. }
  4619. wlogprint(" Pool %d: %s User:%s\n",
  4620. pool->pool_no,
  4621. pool->rpc_url, pool->rpc_user);
  4622. wattroff(logwin, A_BOLD | A_DIM);
  4623. break; //for (i = 0; i < total_pools; i++)
  4624. }
  4625. }
  4626. retry:
  4627. wlogprint("\nCurrent pool management strategy: %s\n",
  4628. strategies[pool_strategy].s);
  4629. if (pool_strategy == POOL_ROTATE)
  4630. wlogprint("Set to rotate every %d minutes\n", opt_rotate_period);
  4631. wlogprint("[F]ailover only %s\n", opt_fail_only ? "enabled" : "disabled");
  4632. wlogprint("[A]dd pool [R]emove pool [D]isable pool [E]nable pool [P]rioritize pool\n");
  4633. wlogprint("[C]hange management strategy [S]witch pool [I]nformation\n");
  4634. wlogprint("Or press any other key to continue\n");
  4635. input = getch();
  4636. if (!strncasecmp(&input, "a", 1)) {
  4637. input_pool(true);
  4638. goto updated;
  4639. } else if (!strncasecmp(&input, "r", 1)) {
  4640. if (total_pools <= 1) {
  4641. wlogprint("Cannot remove last pool");
  4642. goto retry;
  4643. }
  4644. selected = curses_int("Select pool number");
  4645. if (selected < 0 || selected >= total_pools) {
  4646. wlogprint("Invalid selection\n");
  4647. goto retry;
  4648. }
  4649. pool = pools[selected];
  4650. if (pool == current_pool())
  4651. switch_pools(NULL);
  4652. if (pool == current_pool()) {
  4653. wlogprint("Unable to remove pool due to activity\n");
  4654. goto retry;
  4655. }
  4656. disable_pool(pool);
  4657. remove_pool(pool);
  4658. goto updated;
  4659. } else if (!strncasecmp(&input, "s", 1)) {
  4660. selected = curses_int("Select pool number");
  4661. if (selected < 0 || selected >= total_pools) {
  4662. wlogprint("Invalid selection\n");
  4663. goto retry;
  4664. }
  4665. pool = pools[selected];
  4666. enable_pool(pool);
  4667. switch_pools(pool);
  4668. goto updated;
  4669. } else if (!strncasecmp(&input, "d", 1)) {
  4670. if (enabled_pools <= 1) {
  4671. wlogprint("Cannot disable last pool");
  4672. goto retry;
  4673. }
  4674. selected = curses_int("Select pool number");
  4675. if (selected < 0 || selected >= total_pools) {
  4676. wlogprint("Invalid selection\n");
  4677. goto retry;
  4678. }
  4679. pool = pools[selected];
  4680. disable_pool(pool);
  4681. if (pool == current_pool())
  4682. switch_pools(NULL);
  4683. goto updated;
  4684. } else if (!strncasecmp(&input, "e", 1)) {
  4685. selected = curses_int("Select pool number");
  4686. if (selected < 0 || selected >= total_pools) {
  4687. wlogprint("Invalid selection\n");
  4688. goto retry;
  4689. }
  4690. pool = pools[selected];
  4691. enable_pool(pool);
  4692. if (pool->prio < current_pool()->prio)
  4693. switch_pools(pool);
  4694. goto updated;
  4695. } else if (!strncasecmp(&input, "c", 1)) {
  4696. for (i = 0; i <= TOP_STRATEGY; i++)
  4697. wlogprint("%d: %s\n", i, strategies[i].s);
  4698. selected = curses_int("Select strategy number type");
  4699. if (selected < 0 || selected > TOP_STRATEGY) {
  4700. wlogprint("Invalid selection\n");
  4701. goto retry;
  4702. }
  4703. if (selected == POOL_ROTATE) {
  4704. opt_rotate_period = curses_int("Select interval in minutes");
  4705. if (opt_rotate_period < 0 || opt_rotate_period > 9999) {
  4706. opt_rotate_period = 0;
  4707. wlogprint("Invalid selection\n");
  4708. goto retry;
  4709. }
  4710. }
  4711. pool_strategy = selected;
  4712. switch_pools(NULL);
  4713. goto updated;
  4714. } else if (!strncasecmp(&input, "i", 1)) {
  4715. selected = curses_int("Select pool number");
  4716. if (selected < 0 || selected >= total_pools) {
  4717. wlogprint("Invalid selection\n");
  4718. goto retry;
  4719. }
  4720. pool = pools[selected];
  4721. display_pool_summary(pool);
  4722. goto retry;
  4723. } else if (!strncasecmp(&input, "f", 1)) {
  4724. opt_fail_only ^= true;
  4725. goto updated;
  4726. } else if (!strncasecmp(&input, "p", 1)) {
  4727. char *prilist = curses_input("Enter new pool priority (comma separated list)");
  4728. int res = prioritize_pools(prilist, &i);
  4729. free(prilist);
  4730. switch (res) {
  4731. case MSG_NOPOOL:
  4732. wlogprint("No pools\n");
  4733. goto retry;
  4734. case MSG_MISPID:
  4735. wlogprint("Missing pool id parameter\n");
  4736. goto retry;
  4737. case MSG_INVPID:
  4738. wlogprint("Invalid pool id %d - range is 0 - %d\n", i, total_pools - 1);
  4739. goto retry;
  4740. case MSG_DUPPID:
  4741. wlogprint("Duplicate pool specified %d\n", i);
  4742. goto retry;
  4743. case MSG_POOLPRIO:
  4744. default:
  4745. goto updated;
  4746. }
  4747. } else
  4748. clear_logwin();
  4749. immedok(logwin, false);
  4750. opt_loginput = false;
  4751. }
  4752. static const char *summary_detail_level_str(void)
  4753. {
  4754. if (opt_compact)
  4755. return "compact";
  4756. if (opt_show_procs)
  4757. return "processors";
  4758. return "devices";
  4759. }
  4760. static void display_options(void)
  4761. {
  4762. int selected;
  4763. char input;
  4764. opt_loginput = true;
  4765. immedok(logwin, true);
  4766. clear_logwin();
  4767. retry:
  4768. wlogprint("[N]ormal [C]lear [S]ilent mode (disable all output)\n");
  4769. wlogprint("[D]ebug:%s\n[P]er-device:%s\n[Q]uiet:%s\n[V]erbose:%s\n"
  4770. "[R]PC debug:%s\n[W]orkTime details:%s\nsu[M]mary detail level:%s\n"
  4771. "[L]og interval:%d\n[Z]ero statistics\n",
  4772. opt_debug_console ? "on" : "off",
  4773. want_per_device_stats? "on" : "off",
  4774. opt_quiet ? "on" : "off",
  4775. opt_log_output ? "on" : "off",
  4776. opt_protocol ? "on" : "off",
  4777. opt_worktime ? "on" : "off",
  4778. summary_detail_level_str(),
  4779. opt_log_interval);
  4780. wlogprint("Select an option or any other key to return\n");
  4781. input = getch();
  4782. if (!strncasecmp(&input, "q", 1)) {
  4783. opt_quiet ^= true;
  4784. wlogprint("Quiet mode %s\n", opt_quiet ? "enabled" : "disabled");
  4785. goto retry;
  4786. } else if (!strncasecmp(&input, "v", 1)) {
  4787. opt_log_output ^= true;
  4788. if (opt_log_output)
  4789. opt_quiet = false;
  4790. wlogprint("Verbose mode %s\n", opt_log_output ? "enabled" : "disabled");
  4791. goto retry;
  4792. } else if (!strncasecmp(&input, "n", 1)) {
  4793. opt_log_output = false;
  4794. opt_debug_console = false;
  4795. opt_quiet = false;
  4796. opt_protocol = false;
  4797. opt_compact = false;
  4798. opt_show_procs = false;
  4799. devsummaryYOffset = 0;
  4800. want_per_device_stats = false;
  4801. wlogprint("Output mode reset to normal\n");
  4802. switch_compact();
  4803. goto retry;
  4804. } else if (!strncasecmp(&input, "d", 1)) {
  4805. opt_debug = true;
  4806. opt_debug_console ^= true;
  4807. opt_log_output = opt_debug_console;
  4808. if (opt_debug_console)
  4809. opt_quiet = false;
  4810. wlogprint("Debug mode %s\n", opt_debug_console ? "enabled" : "disabled");
  4811. goto retry;
  4812. } else if (!strncasecmp(&input, "m", 1)) {
  4813. if (opt_compact)
  4814. opt_compact = false;
  4815. else
  4816. if (!opt_show_procs)
  4817. opt_show_procs = true;
  4818. else
  4819. {
  4820. opt_compact = true;
  4821. opt_show_procs = false;
  4822. devsummaryYOffset = 0;
  4823. }
  4824. wlogprint("su[M]mary detail level changed to: %s\n", summary_detail_level_str());
  4825. switch_compact();
  4826. goto retry;
  4827. } else if (!strncasecmp(&input, "p", 1)) {
  4828. want_per_device_stats ^= true;
  4829. opt_log_output = want_per_device_stats;
  4830. wlogprint("Per-device stats %s\n", want_per_device_stats ? "enabled" : "disabled");
  4831. goto retry;
  4832. } else if (!strncasecmp(&input, "r", 1)) {
  4833. opt_protocol ^= true;
  4834. if (opt_protocol)
  4835. opt_quiet = false;
  4836. wlogprint("RPC protocol debugging %s\n", opt_protocol ? "enabled" : "disabled");
  4837. goto retry;
  4838. } else if (!strncasecmp(&input, "c", 1))
  4839. clear_logwin();
  4840. else if (!strncasecmp(&input, "l", 1)) {
  4841. selected = curses_int("Interval in seconds");
  4842. if (selected < 0 || selected > 9999) {
  4843. wlogprint("Invalid selection\n");
  4844. goto retry;
  4845. }
  4846. opt_log_interval = selected;
  4847. wlogprint("Log interval set to %d seconds\n", opt_log_interval);
  4848. goto retry;
  4849. } else if (!strncasecmp(&input, "s", 1)) {
  4850. opt_realquiet = true;
  4851. } else if (!strncasecmp(&input, "w", 1)) {
  4852. opt_worktime ^= true;
  4853. wlogprint("WorkTime details %s\n", opt_worktime ? "enabled" : "disabled");
  4854. goto retry;
  4855. } else if (!strncasecmp(&input, "z", 1)) {
  4856. zero_stats();
  4857. goto retry;
  4858. } else
  4859. clear_logwin();
  4860. immedok(logwin, false);
  4861. opt_loginput = false;
  4862. }
  4863. #endif
  4864. void default_save_file(char *filename)
  4865. {
  4866. #if defined(unix)
  4867. if (getenv("HOME") && *getenv("HOME")) {
  4868. strcpy(filename, getenv("HOME"));
  4869. strcat(filename, "/");
  4870. }
  4871. else
  4872. strcpy(filename, "");
  4873. strcat(filename, ".bfgminer/");
  4874. mkdir(filename, 0777);
  4875. #else
  4876. strcpy(filename, "");
  4877. #endif
  4878. strcat(filename, def_conf);
  4879. }
  4880. #ifdef HAVE_CURSES
  4881. static void set_options(void)
  4882. {
  4883. int selected;
  4884. char input;
  4885. opt_loginput = true;
  4886. immedok(logwin, true);
  4887. clear_logwin();
  4888. retry:
  4889. wlogprint("\n[L]ongpoll: %s\n", want_longpoll ? "On" : "Off");
  4890. wlogprint("[Q]ueue: %d\n[S]cantime: %d\n[E]xpiry: %d\n[R]etries: %d\n"
  4891. "[W]rite config file\n[B]FGMiner restart\n",
  4892. opt_queue, opt_scantime, opt_expiry, opt_retries);
  4893. wlogprint("Select an option or any other key to return\n");
  4894. input = getch();
  4895. if (!strncasecmp(&input, "q", 1)) {
  4896. selected = curses_int("Extra work items to queue");
  4897. if (selected < 0 || selected > 9999) {
  4898. wlogprint("Invalid selection\n");
  4899. goto retry;
  4900. }
  4901. opt_queue = selected;
  4902. goto retry;
  4903. } else if (!strncasecmp(&input, "l", 1)) {
  4904. if (want_longpoll)
  4905. stop_longpoll();
  4906. else
  4907. start_longpoll();
  4908. applog(LOG_WARNING, "Longpoll %s", want_longpoll ? "enabled" : "disabled");
  4909. goto retry;
  4910. } else if (!strncasecmp(&input, "s", 1)) {
  4911. selected = curses_int("Set scantime in seconds");
  4912. if (selected < 0 || selected > 9999) {
  4913. wlogprint("Invalid selection\n");
  4914. goto retry;
  4915. }
  4916. opt_scantime = selected;
  4917. goto retry;
  4918. } else if (!strncasecmp(&input, "e", 1)) {
  4919. selected = curses_int("Set expiry time in seconds");
  4920. if (selected < 0 || selected > 9999) {
  4921. wlogprint("Invalid selection\n");
  4922. goto retry;
  4923. }
  4924. opt_expiry = selected;
  4925. goto retry;
  4926. } else if (!strncasecmp(&input, "r", 1)) {
  4927. selected = curses_int("Retries before failing (-1 infinite)");
  4928. if (selected < -1 || selected > 9999) {
  4929. wlogprint("Invalid selection\n");
  4930. goto retry;
  4931. }
  4932. opt_retries = selected;
  4933. goto retry;
  4934. } else if (!strncasecmp(&input, "w", 1)) {
  4935. FILE *fcfg;
  4936. char *str, filename[PATH_MAX], prompt[PATH_MAX + 50];
  4937. default_save_file(filename);
  4938. sprintf(prompt, "Config filename to write (Enter for default) [%s]", filename);
  4939. str = curses_input(prompt);
  4940. if (strcmp(str, "-1")) {
  4941. struct stat statbuf;
  4942. strcpy(filename, str);
  4943. free(str);
  4944. if (!stat(filename, &statbuf)) {
  4945. wlogprint("File exists, overwrite?\n");
  4946. input = getch();
  4947. if (strncasecmp(&input, "y", 1))
  4948. goto retry;
  4949. }
  4950. }
  4951. else
  4952. free(str);
  4953. fcfg = fopen(filename, "w");
  4954. if (!fcfg) {
  4955. wlogprint("Cannot open or create file\n");
  4956. goto retry;
  4957. }
  4958. write_config(fcfg);
  4959. fclose(fcfg);
  4960. goto retry;
  4961. } else if (!strncasecmp(&input, "b", 1)) {
  4962. wlogprint("Are you sure?\n");
  4963. input = getch();
  4964. if (!strncasecmp(&input, "y", 1))
  4965. app_restart();
  4966. else
  4967. clear_logwin();
  4968. } else
  4969. clear_logwin();
  4970. immedok(logwin, false);
  4971. opt_loginput = false;
  4972. }
  4973. static void *input_thread(void __maybe_unused *userdata)
  4974. {
  4975. RenameThread("input");
  4976. if (!curses_active)
  4977. return NULL;
  4978. while (1) {
  4979. int input;
  4980. input = getch();
  4981. switch (input) {
  4982. case 'q': case 'Q':
  4983. kill_work();
  4984. return NULL;
  4985. case 'd': case 'D':
  4986. display_options();
  4987. break;
  4988. case 'p': case 'P':
  4989. display_pools();
  4990. break;
  4991. case 's': case 'S':
  4992. set_options();
  4993. break;
  4994. case 'g': case 'G':
  4995. if (have_opencl)
  4996. manage_gpu();
  4997. break;
  4998. #ifdef HAVE_CURSES
  4999. case KEY_DOWN:
  5000. if (devsummaryYOffset < -(total_lines + devcursor - statusy))
  5001. break;
  5002. devsummaryYOffset -= 2;
  5003. case KEY_UP:
  5004. if (devsummaryYOffset == 0)
  5005. break;
  5006. ++devsummaryYOffset;
  5007. if (curses_active_locked()) {
  5008. int i;
  5009. for (i = 0; i < mining_threads; i++)
  5010. curses_print_devstatus(i);
  5011. touchwin(statuswin);
  5012. wrefresh(statuswin);
  5013. unlock_curses();
  5014. }
  5015. break;
  5016. #endif
  5017. }
  5018. if (opt_realquiet) {
  5019. disable_curses();
  5020. break;
  5021. }
  5022. }
  5023. return NULL;
  5024. }
  5025. #endif
  5026. static void *api_thread(void *userdata)
  5027. {
  5028. struct thr_info *mythr = userdata;
  5029. pthread_detach(pthread_self());
  5030. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  5031. RenameThread("rpc");
  5032. api(api_thr_id);
  5033. mythr->has_pth = false;
  5034. return NULL;
  5035. }
  5036. void thread_reportin(struct thr_info *thr)
  5037. {
  5038. gettimeofday(&thr->last, NULL);
  5039. thr->cgpu->status = LIFE_WELL;
  5040. thr->getwork = 0;
  5041. thr->cgpu->device_last_well = time(NULL);
  5042. }
  5043. void thread_reportout(struct thr_info *thr)
  5044. {
  5045. thr->getwork = time(NULL);
  5046. }
  5047. static void hashmeter(int thr_id, struct timeval *diff,
  5048. uint64_t hashes_done)
  5049. {
  5050. struct timeval temp_tv_end, total_diff;
  5051. double secs;
  5052. double local_secs;
  5053. double utility;
  5054. static double local_mhashes_done = 0;
  5055. static double rolling = 0;
  5056. double local_mhashes = (double)hashes_done / 1000000.0;
  5057. bool showlog = false;
  5058. char cHr[h2bs_fmt_size[H2B_NOUNIT]], aHr[h2bs_fmt_size[H2B_NOUNIT]], uHr[h2bs_fmt_size[H2B_SPACED]];
  5059. struct thr_info *thr;
  5060. /* Update the last time this thread reported in */
  5061. if (thr_id >= 0) {
  5062. thr = get_thread(thr_id);
  5063. gettimeofday(&(thr->last), NULL);
  5064. thr->cgpu->device_last_well = time(NULL);
  5065. }
  5066. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  5067. /* So we can call hashmeter from a non worker thread */
  5068. if (thr_id >= 0) {
  5069. struct cgpu_info *cgpu = thr->cgpu;
  5070. int threadobj = cgpu->threads ?: 1;
  5071. double thread_rolling = 0.0;
  5072. int i;
  5073. applog(LOG_DEBUG, "[thread %d: %"PRIu64" hashes, %.1f khash/sec]",
  5074. thr_id, hashes_done, hashes_done / 1000 / secs);
  5075. /* Rolling average for each thread and each device */
  5076. decay_time(&thr->rolling, local_mhashes / secs);
  5077. for (i = 0; i < threadobj; i++)
  5078. thread_rolling += cgpu->thr[i]->rolling;
  5079. mutex_lock(&hash_lock);
  5080. decay_time(&cgpu->rolling, thread_rolling);
  5081. cgpu->total_mhashes += local_mhashes;
  5082. mutex_unlock(&hash_lock);
  5083. // If needed, output detailed, per-device stats
  5084. if (want_per_device_stats) {
  5085. struct timeval now;
  5086. struct timeval elapsed;
  5087. struct timeval *last_msg_tv = opt_show_procs ? &thr->cgpu->last_message_tv : &thr->cgpu->device->last_message_tv;
  5088. gettimeofday(&now, NULL);
  5089. timersub(&now, last_msg_tv, &elapsed);
  5090. if (opt_log_interval <= elapsed.tv_sec) {
  5091. struct cgpu_info *cgpu = thr->cgpu;
  5092. char logline[255];
  5093. *last_msg_tv = now;
  5094. get_statline(logline, cgpu);
  5095. if (!curses_active) {
  5096. printf("%s \r", logline);
  5097. fflush(stdout);
  5098. } else
  5099. applog(LOG_INFO, "%s", logline);
  5100. }
  5101. }
  5102. }
  5103. /* Totals are updated by all threads so can race without locking */
  5104. mutex_lock(&hash_lock);
  5105. gettimeofday(&temp_tv_end, NULL);
  5106. timersub(&temp_tv_end, &total_tv_end, &total_diff);
  5107. total_mhashes_done += local_mhashes;
  5108. local_mhashes_done += local_mhashes;
  5109. /* Only update with opt_log_interval */
  5110. if (total_diff.tv_sec < opt_log_interval)
  5111. goto out_unlock;
  5112. showlog = true;
  5113. gettimeofday(&total_tv_end, NULL);
  5114. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  5115. decay_time(&rolling, local_mhashes_done / local_secs);
  5116. global_hashrate = roundl(rolling) * 1000000;
  5117. timersub(&total_tv_end, &total_tv_start, &total_diff);
  5118. total_secs = (double)total_diff.tv_sec +
  5119. ((double)total_diff.tv_usec / 1000000.0);
  5120. utility = total_accepted / total_secs * 60;
  5121. ti_hashrate_bufstr(
  5122. (char*[]){cHr, aHr, uHr},
  5123. 1e6*rolling,
  5124. 1e6*total_mhashes_done / total_secs,
  5125. utility_to_hashrate(total_diff_accepted / (total_secs ?: 1) * 60),
  5126. H2B_SPACED);
  5127. sprintf(statusline, "%s%ds:%s avg:%s u:%s | A:%d R:%d S:%d HW:%d U:%.1f/m BS:%s",
  5128. want_per_device_stats ? "ALL " : "",
  5129. opt_log_interval,
  5130. cHr, aHr,
  5131. uHr,
  5132. total_accepted, total_rejected, total_stale,
  5133. hw_errors,
  5134. utility,
  5135. best_share);
  5136. local_mhashes_done = 0;
  5137. out_unlock:
  5138. mutex_unlock(&hash_lock);
  5139. if (showlog) {
  5140. if (!curses_active) {
  5141. printf("%s \r", statusline);
  5142. fflush(stdout);
  5143. } else
  5144. applog(LOG_INFO, "%s", statusline);
  5145. }
  5146. }
  5147. void hashmeter2(struct thr_info *thr)
  5148. {
  5149. struct timeval tv_now, tv_elapsed;
  5150. timerclear(&thr->tv_hashes_done);
  5151. gettimeofday(&tv_now, NULL);
  5152. timersub(&tv_now, &thr->tv_lastupdate, &tv_elapsed);
  5153. /* Update the hashmeter at most 5 times per second */
  5154. if (tv_elapsed.tv_sec > 0 || tv_elapsed.tv_usec > 200) {
  5155. hashmeter(thr->id, &tv_elapsed, thr->hashes_done);
  5156. thr->hashes_done = 0;
  5157. thr->tv_lastupdate = tv_now;
  5158. }
  5159. }
  5160. static void stratum_share_result(json_t *val, json_t *res_val, json_t *err_val,
  5161. struct stratum_share *sshare)
  5162. {
  5163. struct work *work = sshare->work;
  5164. share_result(val, res_val, err_val, work, false, "");
  5165. }
  5166. /* Parses stratum json responses and tries to find the id that the request
  5167. * matched to and treat it accordingly. */
  5168. bool parse_stratum_response(struct pool *pool, char *s)
  5169. {
  5170. json_t *val = NULL, *err_val, *res_val, *id_val;
  5171. struct stratum_share *sshare;
  5172. json_error_t err;
  5173. bool ret = false;
  5174. int id;
  5175. val = JSON_LOADS(s, &err);
  5176. if (!val) {
  5177. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  5178. goto out;
  5179. }
  5180. res_val = json_object_get(val, "result");
  5181. err_val = json_object_get(val, "error");
  5182. id_val = json_object_get(val, "id");
  5183. if (json_is_null(id_val) || !id_val) {
  5184. char *ss;
  5185. if (err_val)
  5186. ss = json_dumps(err_val, JSON_INDENT(3));
  5187. else
  5188. ss = strdup("(unknown reason)");
  5189. applog(LOG_INFO, "JSON-RPC non method decode failed: %s", ss);
  5190. free(ss);
  5191. goto out;
  5192. }
  5193. if (!json_is_integer(id_val)) {
  5194. if (json_is_string(id_val)
  5195. && !strncmp(json_string_value(id_val), "txlist", 6)
  5196. && !strcmp(json_string_value(id_val) + 6, pool->swork.job_id)
  5197. && json_is_array(res_val)) {
  5198. // Check that the transactions actually hash to the merkle links
  5199. {
  5200. unsigned maxtx = 1 << pool->swork.merkles;
  5201. unsigned mintx = maxtx >> 1;
  5202. --maxtx;
  5203. unsigned acttx = (unsigned)json_array_size(res_val);
  5204. if (acttx < mintx || acttx > maxtx) {
  5205. applog(LOG_WARNING, "Pool %u is sending mismatched block contents to us (%u is not %u-%u)",
  5206. pool->pool_no, acttx, mintx, maxtx);
  5207. goto fishy;
  5208. }
  5209. // TODO: Check hashes match actual merkle links
  5210. }
  5211. if (pool->swork.opaque) {
  5212. pool->swork.opaque = false;
  5213. applog(LOG_NOTICE, "Pool %u now providing block contents to us",
  5214. pool->pool_no);
  5215. }
  5216. pool->swork.transparency_time = (time_t)-1;
  5217. fishy:
  5218. ret = true;
  5219. }
  5220. goto out;
  5221. }
  5222. id = json_integer_value(id_val);
  5223. mutex_lock(&sshare_lock);
  5224. HASH_FIND_INT(stratum_shares, &id, sshare);
  5225. if (sshare)
  5226. HASH_DEL(stratum_shares, sshare);
  5227. mutex_unlock(&sshare_lock);
  5228. if (!sshare) {
  5229. if (json_is_true(res_val))
  5230. applog(LOG_NOTICE, "Accepted untracked stratum share from pool %d", pool->pool_no);
  5231. else
  5232. applog(LOG_NOTICE, "Rejected untracked stratum share from pool %d", pool->pool_no);
  5233. goto out;
  5234. }
  5235. else {
  5236. mutex_lock(&submitting_lock);
  5237. --total_submitting;
  5238. mutex_unlock(&submitting_lock);
  5239. }
  5240. stratum_share_result(val, res_val, err_val, sshare);
  5241. free_work(sshare->work);
  5242. free(sshare);
  5243. ret = true;
  5244. out:
  5245. if (val)
  5246. json_decref(val);
  5247. return ret;
  5248. }
  5249. static void shutdown_stratum(struct pool *pool)
  5250. {
  5251. // Shut down Stratum as if we never had it
  5252. pool->stratum_active = false;
  5253. pool->stratum_init = false;
  5254. pool->has_stratum = false;
  5255. shutdown(pool->sock, SHUT_RDWR);
  5256. free(pool->stratum_url);
  5257. if (pool->sockaddr_url == pool->stratum_url)
  5258. pool->sockaddr_url = NULL;
  5259. pool->stratum_url = NULL;
  5260. }
  5261. void clear_stratum_shares(struct pool *pool)
  5262. {
  5263. struct stratum_share *sshare, *tmpshare;
  5264. struct work *work;
  5265. double diff_cleared = 0;
  5266. int cleared = 0;
  5267. mutex_lock(&sshare_lock);
  5268. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  5269. if (sshare->work->pool == pool) {
  5270. HASH_DEL(stratum_shares, sshare);
  5271. work = sshare->work;
  5272. sharelog("disconnect", work);
  5273. diff_cleared += sshare->work->work_difficulty;
  5274. free_work(sshare->work);
  5275. free(sshare);
  5276. cleared++;
  5277. }
  5278. }
  5279. mutex_unlock(&sshare_lock);
  5280. if (cleared) {
  5281. applog(LOG_WARNING, "Lost %d shares due to stratum disconnect on pool %d", cleared, pool->pool_no);
  5282. mutex_lock(&stats_lock);
  5283. pool->stale_shares += cleared;
  5284. total_stale += cleared;
  5285. pool->diff_stale += diff_cleared;
  5286. total_diff_stale += diff_cleared;
  5287. mutex_unlock(&stats_lock);
  5288. mutex_lock(&submitting_lock);
  5289. total_submitting -= cleared;
  5290. mutex_unlock(&submitting_lock);
  5291. }
  5292. }
  5293. static void resubmit_stratum_shares(struct pool *pool)
  5294. {
  5295. struct stratum_share *sshare, *tmpshare;
  5296. struct work *work;
  5297. unsigned resubmitted = 0;
  5298. mutex_lock(&sshare_lock);
  5299. mutex_lock(&submitting_lock);
  5300. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  5301. if (sshare->work->pool != pool)
  5302. continue;
  5303. HASH_DEL(stratum_shares, sshare);
  5304. work = sshare->work;
  5305. list_add_tail(&work->list, &submit_waiting);
  5306. free(sshare);
  5307. ++resubmitted;
  5308. }
  5309. mutex_unlock(&submitting_lock);
  5310. mutex_unlock(&sshare_lock);
  5311. if (resubmitted) {
  5312. notifier_wake(submit_waiting_notifier);
  5313. applog(LOG_DEBUG, "Resubmitting %u shares due to stratum disconnect on pool %u", resubmitted, pool->pool_no);
  5314. }
  5315. }
  5316. static void clear_pool_work(struct pool *pool)
  5317. {
  5318. struct work *work, *tmp;
  5319. int cleared = 0;
  5320. mutex_lock(stgd_lock);
  5321. HASH_ITER(hh, staged_work, work, tmp) {
  5322. if (work->pool == pool) {
  5323. HASH_DEL(staged_work, work);
  5324. free_work(work);
  5325. cleared++;
  5326. }
  5327. }
  5328. mutex_unlock(stgd_lock);
  5329. }
  5330. static int cp_prio(void)
  5331. {
  5332. int prio;
  5333. cg_rlock(&control_lock);
  5334. prio = currentpool->prio;
  5335. cg_runlock(&control_lock);
  5336. return prio;
  5337. }
  5338. /* We only need to maintain a secondary pool connection when we need the
  5339. * capacity to get work from the backup pools while still on the primary */
  5340. static bool cnx_needed(struct pool *pool)
  5341. {
  5342. struct pool *cp;
  5343. /* Balance strategies need all pools online */
  5344. if (pool_strategy == POOL_BALANCE)
  5345. return true;
  5346. if (pool_strategy == POOL_LOADBALANCE)
  5347. return true;
  5348. /* Idle stratum pool needs something to kick it alive again */
  5349. if (pool->has_stratum && pool->idle)
  5350. return true;
  5351. /* Getwork pools without opt_fail_only need backup pools up to be able
  5352. * to leak shares */
  5353. cp = current_pool();
  5354. if (cp == pool)
  5355. return true;
  5356. if (!cp->has_stratum && (!opt_fail_only || !cp->hdr_path))
  5357. return true;
  5358. /* Keep the connection open to allow any stray shares to be submitted
  5359. * on switching pools for 2 minutes. */
  5360. if (difftime(time(NULL), pool->last_work_time) < 120)
  5361. return true;
  5362. /* If the pool has only just come to life and is higher priority than
  5363. * the current pool keep the connection open so we can fail back to
  5364. * it. */
  5365. if (pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  5366. return true;
  5367. if (pool_unworkable(cp))
  5368. return true;
  5369. return false;
  5370. }
  5371. static void wait_lpcurrent(struct pool *pool);
  5372. static void pool_resus(struct pool *pool);
  5373. static void gen_stratum_work(struct pool *pool, struct work *work);
  5374. static void stratum_resumed(struct pool *pool)
  5375. {
  5376. if (!pool->stratum_notify)
  5377. return;
  5378. if (pool_tclear(pool, &pool->idle)) {
  5379. applog(LOG_INFO, "Stratum connection to pool %d resumed", pool->pool_no);
  5380. pool_resus(pool);
  5381. }
  5382. }
  5383. static bool supports_resume(struct pool *pool)
  5384. {
  5385. bool ret;
  5386. cg_rlock(&pool->data_lock);
  5387. ret = (pool->sessionid != NULL);
  5388. cg_runlock(&pool->data_lock);
  5389. return ret;
  5390. }
  5391. /* One stratum thread per pool that has stratum waits on the socket checking
  5392. * for new messages and for the integrity of the socket connection. We reset
  5393. * the connection based on the integrity of the receive side only as the send
  5394. * side will eventually expire data it fails to send. */
  5395. static void *stratum_thread(void *userdata)
  5396. {
  5397. struct pool *pool = (struct pool *)userdata;
  5398. pthread_detach(pthread_self());
  5399. char threadname[20];
  5400. snprintf(threadname, 20, "stratum%u", pool->pool_no);
  5401. RenameThread(threadname);
  5402. srand(time(NULL) + (intptr_t)userdata);
  5403. while (42) {
  5404. struct timeval timeout;
  5405. int sel_ret;
  5406. fd_set rd;
  5407. char *s;
  5408. if (unlikely(!pool->has_stratum))
  5409. break;
  5410. /* Check to see whether we need to maintain this connection
  5411. * indefinitely or just bring it up when we switch to this
  5412. * pool */
  5413. if (!sock_full(pool) && !cnx_needed(pool)) {
  5414. suspend_stratum(pool);
  5415. clear_stratum_shares(pool);
  5416. clear_pool_work(pool);
  5417. wait_lpcurrent(pool);
  5418. if (!restart_stratum(pool)) {
  5419. pool_died(pool);
  5420. while (!restart_stratum(pool)) {
  5421. if (pool->removed)
  5422. goto out;
  5423. nmsleep(30000);
  5424. }
  5425. }
  5426. }
  5427. FD_ZERO(&rd);
  5428. FD_SET(pool->sock, &rd);
  5429. timeout.tv_sec = 120;
  5430. timeout.tv_usec = 0;
  5431. /* If we fail to receive any notify messages for 2 minutes we
  5432. * assume the connection has been dropped and treat this pool
  5433. * as dead */
  5434. if (!sock_full(pool) && (sel_ret = select(pool->sock + 1, &rd, NULL, NULL, &timeout)) < 1) {
  5435. applog(LOG_DEBUG, "Stratum select failed on pool %d with value %d", pool->pool_no, sel_ret);
  5436. s = NULL;
  5437. } else
  5438. s = recv_line(pool);
  5439. if (!s) {
  5440. if (!pool->has_stratum)
  5441. break;
  5442. applog(LOG_NOTICE, "Stratum connection to pool %d interrupted", pool->pool_no);
  5443. pool->getfail_occasions++;
  5444. total_go++;
  5445. pool->sock = INVSOCK;
  5446. /* If the socket to our stratum pool disconnects, all
  5447. * submissions need to be discarded or resent. */
  5448. if (!supports_resume(pool))
  5449. clear_stratum_shares(pool);
  5450. else
  5451. resubmit_stratum_shares(pool);
  5452. clear_pool_work(pool);
  5453. if (pool == current_pool())
  5454. restart_threads();
  5455. if (restart_stratum(pool))
  5456. continue;
  5457. shutdown_stratum(pool);
  5458. pool_died(pool);
  5459. break;
  5460. }
  5461. /* Check this pool hasn't died while being a backup pool and
  5462. * has not had its idle flag cleared */
  5463. stratum_resumed(pool);
  5464. if (!parse_method(pool, s) && !parse_stratum_response(pool, s))
  5465. applog(LOG_INFO, "Unknown stratum msg: %s", s);
  5466. free(s);
  5467. if (pool->swork.clean) {
  5468. struct work *work = make_work();
  5469. /* Generate a single work item to update the current
  5470. * block database */
  5471. pool->swork.clean = false;
  5472. gen_stratum_work(pool, work);
  5473. /* Try to extract block height from coinbase scriptSig */
  5474. char *hex_height = &pool->swork.coinbase1[8 /*version*/ + 2 /*txin count*/ + 72 /*prevout*/ + 2 /*scriptSig len*/ + 2 /*push opcode*/];
  5475. unsigned char cb_height_sz;
  5476. hex2bin(&cb_height_sz, &hex_height[-2], 1);
  5477. if (cb_height_sz == 3) {
  5478. // FIXME: The block number will overflow this by AD 2173
  5479. uint32_t block_id = ((uint32_t*)work->data)[1];
  5480. uint32_t height = 0;
  5481. hex2bin((unsigned char*)&height, hex_height, 3);
  5482. height = le32toh(height);
  5483. have_block_height(block_id, height);
  5484. }
  5485. ++pool->work_restart_id;
  5486. if (test_work_current(work)) {
  5487. /* Only accept a work update if this stratum
  5488. * connection is from the current pool */
  5489. if (pool == current_pool()) {
  5490. restart_threads();
  5491. applog(
  5492. (opt_quiet_work_updates ? LOG_DEBUG : LOG_NOTICE),
  5493. "Stratum from pool %d requested work update", pool->pool_no);
  5494. }
  5495. } else
  5496. applog(LOG_NOTICE, "Stratum from pool %d detected new block", pool->pool_no);
  5497. free_work(work);
  5498. }
  5499. if (pool->swork.transparency_time != (time_t)-1 && difftime(time(NULL), pool->swork.transparency_time) > 21.09375) {
  5500. // More than 4 timmills past since requested transactions
  5501. pool->swork.transparency_time = (time_t)-1;
  5502. pool->swork.opaque = true;
  5503. applog(LOG_WARNING, "Pool %u is hiding block contents from us",
  5504. pool->pool_no);
  5505. }
  5506. }
  5507. out:
  5508. return NULL;
  5509. }
  5510. static void init_stratum_thread(struct pool *pool)
  5511. {
  5512. if (unlikely(pthread_create(&pool->stratum_thread, NULL, stratum_thread, (void *)pool)))
  5513. quit(1, "Failed to create stratum thread");
  5514. }
  5515. static void *longpoll_thread(void *userdata);
  5516. static bool stratum_works(struct pool *pool)
  5517. {
  5518. applog(LOG_INFO, "Testing pool %d stratum %s", pool->pool_no, pool->stratum_url);
  5519. if (!extract_sockaddr(pool, pool->stratum_url))
  5520. return false;
  5521. if (!initiate_stratum(pool))
  5522. return false;
  5523. return true;
  5524. }
  5525. static bool pool_active(struct pool *pool, bool pinging)
  5526. {
  5527. struct timeval tv_getwork, tv_getwork_reply;
  5528. bool ret = false;
  5529. json_t *val;
  5530. CURL *curl;
  5531. int rolltime;
  5532. char *rpc_req;
  5533. struct work *work;
  5534. enum pool_protocol proto;
  5535. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  5536. /* This is the central point we activate stratum when we can */
  5537. curl = curl_easy_init();
  5538. if (unlikely(!curl)) {
  5539. applog(LOG_ERR, "CURL initialisation failed");
  5540. return false;
  5541. }
  5542. if (!(want_gbt || want_getwork))
  5543. goto nohttp;
  5544. work = make_work();
  5545. /* Probe for GBT support on first pass */
  5546. proto = want_gbt ? PLP_GETBLOCKTEMPLATE : PLP_GETWORK;
  5547. tryagain:
  5548. rpc_req = prepare_rpc_req_probe(work, proto, NULL);
  5549. work->pool = pool;
  5550. if (!rpc_req)
  5551. goto out;
  5552. pool->probed = false;
  5553. gettimeofday(&tv_getwork, NULL);
  5554. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  5555. true, false, &rolltime, pool, false);
  5556. gettimeofday(&tv_getwork_reply, NULL);
  5557. free(rpc_req);
  5558. /* Detect if a http getwork pool has an X-Stratum header at startup,
  5559. * and if so, switch to that in preference to getwork if it works */
  5560. if (pool->stratum_url && want_stratum && (pool->has_stratum || stratum_works(pool))) {
  5561. if (!pool->has_stratum) {
  5562. applog(LOG_NOTICE, "Switching pool %d %s to %s", pool->pool_no, pool->rpc_url, pool->stratum_url);
  5563. if (!pool->rpc_url)
  5564. pool->rpc_url = strdup(pool->stratum_url);
  5565. pool->has_stratum = true;
  5566. }
  5567. free_work(work);
  5568. if (val)
  5569. json_decref(val);
  5570. retry_stratum:
  5571. curl_easy_cleanup(curl);
  5572. /* We create the stratum thread for each pool just after
  5573. * successful authorisation. Once the init flag has been set
  5574. * we never unset it and the stratum thread is responsible for
  5575. * setting/unsetting the active flag */
  5576. bool init = pool_tset(pool, &pool->stratum_init);
  5577. if (!init) {
  5578. bool ret = initiate_stratum(pool) && auth_stratum(pool);
  5579. if (ret)
  5580. {
  5581. detect_algo = 2;
  5582. init_stratum_thread(pool);
  5583. }
  5584. else
  5585. pool_tclear(pool, &pool->stratum_init);
  5586. return ret;
  5587. }
  5588. return pool->stratum_active;
  5589. }
  5590. else if (pool->has_stratum)
  5591. shutdown_stratum(pool);
  5592. if (val) {
  5593. bool rc;
  5594. json_t *res;
  5595. res = json_object_get(val, "result");
  5596. if ((!json_is_object(res)) || (proto == PLP_GETBLOCKTEMPLATE && !json_object_get(res, "bits")))
  5597. goto badwork;
  5598. work->rolltime = rolltime;
  5599. rc = work_decode(pool, work, val);
  5600. if (rc) {
  5601. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  5602. pool->pool_no, pool->rpc_url);
  5603. work->pool = pool;
  5604. memcpy(&(work->tv_getwork), &tv_getwork, sizeof(struct timeval));
  5605. memcpy(&(work->tv_getwork_reply), &tv_getwork_reply, sizeof(struct timeval));
  5606. work->getwork_mode = GETWORK_MODE_TESTPOOL;
  5607. calc_diff(work, 0);
  5608. update_last_work(work);
  5609. applog(LOG_DEBUG, "Pushing pooltest work to base pool");
  5610. tq_push(control_thr[stage_thr_id].q, work);
  5611. total_getworks++;
  5612. pool->getwork_requested++;
  5613. ret = true;
  5614. gettimeofday(&pool->tv_idle, NULL);
  5615. } else {
  5616. badwork:
  5617. json_decref(val);
  5618. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher work from pool %u %s",
  5619. pool->pool_no, pool->rpc_url);
  5620. pool->proto = proto = pool_protocol_fallback(proto);
  5621. if (PLP_NONE != proto)
  5622. goto tryagain;
  5623. free_work(work);
  5624. goto out;
  5625. }
  5626. json_decref(val);
  5627. if (proto != pool->proto) {
  5628. pool->proto = proto;
  5629. applog(LOG_INFO, "Selected %s protocol for pool %u", pool_protocol_name(proto), pool->pool_no);
  5630. }
  5631. if (pool->lp_url)
  5632. goto out;
  5633. /* Decipher the longpoll URL, if any, and store it in ->lp_url */
  5634. const struct blktmpl_longpoll_req *lp;
  5635. if (work->tmpl && (lp = blktmpl_get_longpoll(work->tmpl))) {
  5636. // NOTE: work_decode takes care of lp id
  5637. pool->lp_url = lp->uri ? absolute_uri(lp->uri, pool->rpc_url) : pool->rpc_url;
  5638. if (!pool->lp_url)
  5639. {
  5640. ret = false;
  5641. goto out;
  5642. }
  5643. pool->lp_proto = PLP_GETBLOCKTEMPLATE;
  5644. }
  5645. else
  5646. if (pool->hdr_path && want_getwork) {
  5647. pool->lp_url = absolute_uri(pool->hdr_path, pool->rpc_url);
  5648. if (!pool->lp_url)
  5649. {
  5650. ret = false;
  5651. goto out;
  5652. }
  5653. pool->lp_proto = PLP_GETWORK;
  5654. } else
  5655. pool->lp_url = NULL;
  5656. if (want_longpoll && !pool->lp_started) {
  5657. pool->lp_started = true;
  5658. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  5659. quit(1, "Failed to create pool longpoll thread");
  5660. }
  5661. } else if (PLP_NONE != (proto = pool_protocol_fallback(proto))) {
  5662. pool->proto = proto;
  5663. goto tryagain;
  5664. } else {
  5665. free_work(work);
  5666. nohttp:
  5667. /* If we failed to parse a getwork, this could be a stratum
  5668. * url without the prefix stratum+tcp:// so let's check it */
  5669. if (extract_sockaddr(pool, pool->rpc_url) && initiate_stratum(pool)) {
  5670. pool->has_stratum = true;
  5671. goto retry_stratum;
  5672. }
  5673. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  5674. pool->pool_no, pool->rpc_url);
  5675. if (!pinging)
  5676. applog(LOG_WARNING, "Pool %u slow/down or URL or credentials invalid", pool->pool_no);
  5677. }
  5678. out:
  5679. curl_easy_cleanup(curl);
  5680. return ret;
  5681. }
  5682. static void pool_resus(struct pool *pool)
  5683. {
  5684. if (pool_strategy == POOL_FAILOVER && pool->prio < cp_prio()) {
  5685. applog(LOG_WARNING, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  5686. switch_pools(NULL);
  5687. } else
  5688. applog(LOG_INFO, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  5689. }
  5690. static struct work *hash_pop(void)
  5691. {
  5692. struct work *work = NULL, *tmp;
  5693. int hc;
  5694. retry:
  5695. mutex_lock(stgd_lock);
  5696. while (!getq->frozen && !HASH_COUNT(staged_work))
  5697. pthread_cond_wait(&getq->cond, stgd_lock);
  5698. hc = HASH_COUNT(staged_work);
  5699. /* Find clone work if possible, to allow masters to be reused */
  5700. if (hc > staged_rollable) {
  5701. HASH_ITER(hh, staged_work, work, tmp) {
  5702. if (!work_rollable(work))
  5703. break;
  5704. }
  5705. } else
  5706. work = staged_work;
  5707. if (can_roll(work) && should_roll(work))
  5708. {
  5709. // Instead of consuming it, force it to be cloned and grab the clone
  5710. mutex_unlock(stgd_lock);
  5711. clone_available();
  5712. goto retry;
  5713. }
  5714. HASH_DEL(staged_work, work);
  5715. if (work_rollable(work))
  5716. staged_rollable--;
  5717. /* Signal the getwork scheduler to look for more work */
  5718. pthread_cond_signal(&gws_cond);
  5719. /* Signal hash_pop again in case there are mutliple hash_pop waiters */
  5720. pthread_cond_signal(&getq->cond);
  5721. mutex_unlock(stgd_lock);
  5722. work->pool->last_work_time = time(NULL);
  5723. return work;
  5724. }
  5725. /* Clones work by rolling it if possible, and returning a clone instead of the
  5726. * original work item which gets staged again to possibly be rolled again in
  5727. * the future */
  5728. static struct work *clone_work(struct work *work)
  5729. {
  5730. int mrs = mining_threads + opt_queue - total_staged();
  5731. struct work *work_clone;
  5732. bool cloned;
  5733. if (mrs < 1)
  5734. return work;
  5735. cloned = false;
  5736. work_clone = make_clone(work);
  5737. while (mrs-- > 0 && can_roll(work) && should_roll(work)) {
  5738. applog(LOG_DEBUG, "Pushing rolled converted work to stage thread");
  5739. stage_work(work_clone);
  5740. roll_work(work);
  5741. work_clone = make_clone(work);
  5742. /* Roll it again to prevent duplicates should this be used
  5743. * directly later on */
  5744. roll_work(work);
  5745. cloned = true;
  5746. }
  5747. if (cloned) {
  5748. stage_work(work);
  5749. return work_clone;
  5750. }
  5751. free_work(work_clone);
  5752. return work;
  5753. }
  5754. void gen_hash(unsigned char *data, unsigned char *hash, int len)
  5755. {
  5756. unsigned char hash1[32];
  5757. sha2(data, len, hash1);
  5758. sha2(hash1, 32, hash);
  5759. }
  5760. /* Diff 1 is a 256 bit unsigned integer of
  5761. * 0x00000000ffff0000000000000000000000000000000000000000000000000000
  5762. * so we use a big endian 64 bit unsigned integer centred on the 5th byte to
  5763. * cover a huge range of difficulty targets, though not all 256 bits' worth */
  5764. static void bdiff_target_leadzero(unsigned char *target, double diff)
  5765. {
  5766. uint64_t *data64, h64;
  5767. double d64;
  5768. d64 = diffone;
  5769. d64 /= diff;
  5770. d64 = ceil(d64);
  5771. h64 = d64;
  5772. memset(target, 0, 32);
  5773. if (d64 < 18446744073709551616.0) {
  5774. unsigned char *rtarget = target;
  5775. memset(rtarget, 0, 32);
  5776. if (opt_scrypt)
  5777. data64 = (uint64_t *)(rtarget + 2);
  5778. else
  5779. data64 = (uint64_t *)(rtarget + 4);
  5780. *data64 = htobe64(h64);
  5781. } else {
  5782. /* Support for the classic all FFs just-below-1 diff */
  5783. if (opt_scrypt)
  5784. memset(&target[2], 0xff, 30);
  5785. else
  5786. memset(&target[4], 0xff, 28);
  5787. }
  5788. }
  5789. static inline
  5790. void set_work_target(struct work *work, double diff)
  5791. {
  5792. unsigned char rtarget[32];
  5793. bdiff_target_leadzero(rtarget, diff);
  5794. swab256(work->target, rtarget);
  5795. if (opt_debug) {
  5796. char *htarget = bin2hex(rtarget, 32);
  5797. applog(LOG_DEBUG, "Generated target %s", htarget);
  5798. free(htarget);
  5799. }
  5800. }
  5801. /* Generates stratum based work based on the most recent notify information
  5802. * from the pool. This will keep generating work while a pool is down so we use
  5803. * other means to detect when the pool has died in stratum_thread */
  5804. static void gen_stratum_work(struct pool *pool, struct work *work)
  5805. {
  5806. unsigned char *coinbase, merkle_root[32], merkle_sha[64];
  5807. char *header, *merkle_hash;
  5808. uint32_t *data32, *swap32;
  5809. size_t alloc_len;
  5810. int i;
  5811. clean_work(work);
  5812. /* Use intermediate lock to update the one pool variable */
  5813. cg_ilock(&pool->data_lock);
  5814. /* Generate coinbase */
  5815. work->nonce2 = bin2hex((const unsigned char *)&pool->nonce2, pool->n2size);
  5816. pool->nonce2++;
  5817. /* Downgrade to a read lock to read off the pool variables */
  5818. cg_dlock(&pool->data_lock);
  5819. alloc_len = pool->swork.cb_len;
  5820. align_len(&alloc_len);
  5821. coinbase = calloc(alloc_len, 1);
  5822. if (unlikely(!coinbase))
  5823. quit(1, "Failed to calloc coinbase in gen_stratum_work");
  5824. hex2bin(coinbase, pool->swork.coinbase1, pool->swork.cb1_len);
  5825. hex2bin(coinbase + pool->swork.cb1_len, pool->nonce1, pool->n1_len);
  5826. hex2bin(coinbase + pool->swork.cb1_len + pool->n1_len, work->nonce2, pool->n2size);
  5827. hex2bin(coinbase + pool->swork.cb1_len + pool->n1_len + pool->n2size, pool->swork.coinbase2, pool->swork.cb2_len);
  5828. /* Generate merkle root */
  5829. gen_hash(coinbase, merkle_root, pool->swork.cb_len);
  5830. free(coinbase);
  5831. memcpy(merkle_sha, merkle_root, 32);
  5832. for (i = 0; i < pool->swork.merkles; i++) {
  5833. unsigned char merkle_bin[32];
  5834. hex2bin(merkle_bin, pool->swork.merkle[i], 32);
  5835. memcpy(merkle_sha + 32, merkle_bin, 32);
  5836. gen_hash(merkle_sha, merkle_root, 64);
  5837. memcpy(merkle_sha, merkle_root, 32);
  5838. }
  5839. data32 = (uint32_t *)merkle_sha;
  5840. swap32 = (uint32_t *)merkle_root;
  5841. for (i = 0; i < 32 / 4; i++)
  5842. swap32[i] = swab32(data32[i]);
  5843. merkle_hash = bin2hex((const unsigned char *)merkle_root, 32);
  5844. header = calloc(pool->swork.header_len, 1);
  5845. if (unlikely(!header))
  5846. quit(1, "Failed to calloc header in gen_stratum_work");
  5847. sprintf(header, "%s%s%s%s%s%s%s",
  5848. pool->swork.bbversion,
  5849. pool->swork.prev_hash,
  5850. merkle_hash,
  5851. pool->swork.ntime,
  5852. pool->swork.nbit,
  5853. "00000000", /* nonce */
  5854. workpadding);
  5855. /* Store the stratum work diff to check it still matches the pool's
  5856. * stratum diff when submitting shares */
  5857. work->sdiff = pool->swork.diff;
  5858. /* Copy parameters required for share submission */
  5859. work->job_id = strdup(pool->swork.job_id);
  5860. work->nonce1 = strdup(pool->nonce1);
  5861. work->ntime = strdup(pool->swork.ntime);
  5862. cg_runlock(&pool->data_lock);
  5863. applog(LOG_DEBUG, "Generated stratum merkle %s", merkle_hash);
  5864. applog(LOG_DEBUG, "Generated stratum header %s", header);
  5865. applog(LOG_DEBUG, "Work job_id %s nonce2 %s ntime %s", work->job_id, work->nonce2, work->ntime);
  5866. free(merkle_hash);
  5867. /* Convert hex data to binary data for work */
  5868. if (unlikely(!hex2bin(work->data, header, 128)))
  5869. quit(1, "Failed to convert header to data in gen_stratum_work");
  5870. free(header);
  5871. calc_midstate(work);
  5872. set_work_target(work, work->sdiff);
  5873. local_work++;
  5874. work->pool = pool;
  5875. work->stratum = true;
  5876. work->blk.nonce = 0;
  5877. work->id = total_work++;
  5878. work->longpoll = false;
  5879. work->getwork_mode = GETWORK_MODE_STRATUM;
  5880. work->work_restart_id = work->pool->work_restart_id;
  5881. calc_diff(work, 0);
  5882. gettimeofday(&work->tv_staged, NULL);
  5883. }
  5884. void request_work(struct thr_info *thr)
  5885. {
  5886. struct cgpu_info *cgpu = thr->cgpu;
  5887. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  5888. /* Tell the watchdog thread this thread is waiting on getwork and
  5889. * should not be restarted */
  5890. thread_reportout(thr);
  5891. // HACK: Since get_work still blocks, reportout all processors dependent on this thread
  5892. for (struct cgpu_info *proc = thr->cgpu->next_proc; proc; proc = proc->next_proc)
  5893. {
  5894. if (proc->threads)
  5895. break;
  5896. thread_reportout(proc->thr[0]);
  5897. }
  5898. gettimeofday(&dev_stats->_get_start, NULL);
  5899. }
  5900. // FIXME: Make this non-blocking (and remove HACK above)
  5901. struct work *get_work(struct thr_info *thr)
  5902. {
  5903. const int thr_id = thr->id;
  5904. struct cgpu_info *cgpu = thr->cgpu;
  5905. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  5906. struct cgminer_stats *pool_stats;
  5907. struct timeval tv_get;
  5908. struct work *work = NULL;
  5909. applog(LOG_DEBUG, "%"PRIpreprv": Popping work from get queue to get work", cgpu->proc_repr);
  5910. while (!work) {
  5911. work = hash_pop();
  5912. if (stale_work(work, false)) {
  5913. discard_work(work);
  5914. work = NULL;
  5915. wake_gws();
  5916. }
  5917. }
  5918. applog(LOG_DEBUG, "%"PRIpreprv": Got work from get queue to get work for thread %d", cgpu->proc_repr, thr_id);
  5919. work->thr_id = thr_id;
  5920. thread_reportin(thr);
  5921. // HACK: Since get_work still blocks, reportin all processors dependent on this thread
  5922. for (struct cgpu_info *proc = thr->cgpu->next_proc; proc; proc = proc->next_proc)
  5923. {
  5924. if (proc->threads)
  5925. break;
  5926. thread_reportin(proc->thr[0]);
  5927. }
  5928. work->mined = true;
  5929. work->blk.nonce = 0;
  5930. gettimeofday(&tv_get, NULL);
  5931. timersub(&tv_get, &dev_stats->_get_start, &tv_get);
  5932. timeradd(&tv_get, &dev_stats->getwork_wait, &dev_stats->getwork_wait);
  5933. if (timercmp(&tv_get, &dev_stats->getwork_wait_max, >))
  5934. dev_stats->getwork_wait_max = tv_get;
  5935. if (timercmp(&tv_get, &dev_stats->getwork_wait_min, <))
  5936. dev_stats->getwork_wait_min = tv_get;
  5937. ++dev_stats->getwork_calls;
  5938. pool_stats = &(work->pool->cgminer_stats);
  5939. timeradd(&tv_get, &pool_stats->getwork_wait, &pool_stats->getwork_wait);
  5940. if (timercmp(&tv_get, &pool_stats->getwork_wait_max, >))
  5941. pool_stats->getwork_wait_max = tv_get;
  5942. if (timercmp(&tv_get, &pool_stats->getwork_wait_min, <))
  5943. pool_stats->getwork_wait_min = tv_get;
  5944. ++pool_stats->getwork_calls;
  5945. return work;
  5946. }
  5947. static
  5948. void _submit_work_async(struct work *work)
  5949. {
  5950. applog(LOG_DEBUG, "Pushing submit work to work thread");
  5951. mutex_lock(&submitting_lock);
  5952. ++total_submitting;
  5953. list_add_tail(&work->list, &submit_waiting);
  5954. mutex_unlock(&submitting_lock);
  5955. notifier_wake(submit_waiting_notifier);
  5956. }
  5957. void submit_work_async(struct work *work_in, struct timeval *tv_work_found)
  5958. {
  5959. struct work *work = copy_work(work_in);
  5960. if (tv_work_found)
  5961. memcpy(&(work->tv_work_found), tv_work_found, sizeof(struct timeval));
  5962. _submit_work_async(work);
  5963. }
  5964. enum test_nonce2_result hashtest2(struct work *work, bool checktarget)
  5965. {
  5966. uint32_t *hash2_32 = (uint32_t *)&work->hash[0];
  5967. hash_data(work->hash, work->data);
  5968. if (hash2_32[7] != 0)
  5969. return TNR_BAD;
  5970. if (!checktarget)
  5971. return TNR_GOOD;
  5972. if (!hash_target_check_v(work->hash, work->target))
  5973. return TNR_HIGH;
  5974. return TNR_GOOD;
  5975. }
  5976. enum test_nonce2_result _test_nonce2(struct work *work, uint32_t nonce, bool checktarget)
  5977. {
  5978. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  5979. *work_nonce = htole32(nonce);
  5980. #ifdef USE_SCRYPT
  5981. if (opt_scrypt) {
  5982. if (!scrypt_test(work->data, work->target, nonce))
  5983. return TNR_BAD;
  5984. return TNR_GOOD;
  5985. }
  5986. #endif
  5987. return hashtest2(work, checktarget);
  5988. }
  5989. void submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  5990. {
  5991. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  5992. uint32_t bak_nonce = *work_nonce;
  5993. struct timeval tv_work_found;
  5994. enum test_nonce2_result res;
  5995. gettimeofday(&tv_work_found, NULL);
  5996. *work_nonce = htole32(nonce);
  5997. mutex_lock(&stats_lock);
  5998. total_diff1++;
  5999. thr->cgpu->diff1++;
  6000. work->pool->diff1++;
  6001. mutex_unlock(&stats_lock);
  6002. /* Do one last check before attempting to submit the work */
  6003. /* Side effect: sets work->data for us */
  6004. res = test_nonce2(work, nonce);
  6005. if (unlikely(res == TNR_BAD))
  6006. {
  6007. struct cgpu_info *cgpu = thr->cgpu;
  6008. applog(LOG_WARNING, "%"PRIpreprv": invalid nonce - HW error",
  6009. cgpu->proc_repr);
  6010. mutex_lock(&stats_lock);
  6011. ++hw_errors;
  6012. ++thr->cgpu->hw_errors;
  6013. mutex_unlock(&stats_lock);
  6014. if (thr->cgpu->drv->hw_error)
  6015. thr->cgpu->drv->hw_error(thr);
  6016. goto out;
  6017. }
  6018. mutex_lock(&stats_lock);
  6019. thr->cgpu->last_device_valid_work = time(NULL);
  6020. mutex_unlock(&stats_lock);
  6021. if (res == TNR_HIGH)
  6022. {
  6023. // Share above target, normal
  6024. /* Check the diff of the share, even if it didn't reach the
  6025. * target, just to set the best share value if it's higher. */
  6026. share_diff(work);
  6027. goto out;
  6028. }
  6029. submit_work_async(work, &tv_work_found);
  6030. out:
  6031. *work_nonce = bak_nonce;
  6032. }
  6033. bool abandon_work(struct work *work, struct timeval *wdiff, uint64_t hashes)
  6034. {
  6035. if (wdiff->tv_sec > opt_scantime ||
  6036. work->blk.nonce >= MAXTHREADS - hashes ||
  6037. hashes >= 0xfffffffe ||
  6038. stale_work(work, false))
  6039. return true;
  6040. return false;
  6041. }
  6042. static
  6043. void __thr_being_msg(struct thr_info *thr, const char *being)
  6044. {
  6045. struct cgpu_info *proc = thr->cgpu;
  6046. if (proc->threads > 1)
  6047. applog(LOG_WARNING, "%"PRIpreprv" (thread %d) being %s", proc->proc_repr, thr->id, being);
  6048. else
  6049. applog(LOG_WARNING, "%"PRIpreprv" being %s", proc->proc_repr, being);
  6050. }
  6051. void mt_disable_start(struct thr_info *mythr)
  6052. {
  6053. hashmeter2(mythr);
  6054. mythr->prev_work = mythr->work;
  6055. mythr->work = NULL;
  6056. mythr->_job_transition_in_progress = false;
  6057. __thr_being_msg(mythr, "disabled");
  6058. mythr->rolling = mythr->cgpu->rolling = 0;
  6059. thread_reportout(mythr);
  6060. }
  6061. /* Create a hashtable of work items for devices with a queue. The device
  6062. * driver must have a custom queue_full function or it will default to true
  6063. * and put only one work item in the queue. Work items should not be removed
  6064. * from this hashtable until they are no longer in use anywhere. Once a work
  6065. * item is physically queued on the device itself, the work->queued flag
  6066. * should be set under cgpu->qlock write lock to prevent it being dereferenced
  6067. * while still in use. */
  6068. static void fill_queue(struct thr_info *mythr, struct cgpu_info *cgpu, struct device_drv *drv, const int thr_id)
  6069. {
  6070. thread_reportout(mythr);
  6071. do {
  6072. struct work *work;
  6073. wr_lock(&cgpu->qlock);
  6074. if (HASH_COUNT(cgpu->queued_work) == cgpu->queued_count) {
  6075. work = get_work(mythr);
  6076. //work->device_diff = MIN(drv->max_diff, work->work_difficulty);
  6077. HASH_ADD_INT(cgpu->queued_work, id, work);
  6078. }
  6079. wr_unlock(&cgpu->qlock);
  6080. /* The queue_full function should be used by the driver to
  6081. * actually place work items on the physical device if it
  6082. * does have a queue. */
  6083. } while (drv->queue_full && !drv->queue_full(cgpu));
  6084. }
  6085. /* This function is for retrieving one work item from the queued hashtable of
  6086. * available work items that are not yet physically on a device (which is
  6087. * flagged with the work->queued bool). Code using this function must be able
  6088. * to handle NULL as a return which implies there is no work available. */
  6089. struct work *get_queued(struct cgpu_info *cgpu)
  6090. {
  6091. struct work *work, *tmp, *ret = NULL;
  6092. wr_lock(&cgpu->qlock);
  6093. HASH_ITER(hh, cgpu->queued_work, work, tmp) {
  6094. if (!work->queued) {
  6095. work->queued = true;
  6096. cgpu->queued_count++;
  6097. ret = work;
  6098. break;
  6099. }
  6100. }
  6101. wr_unlock(&cgpu->qlock);
  6102. return ret;
  6103. }
  6104. /* This function is for finding an already queued work item in the
  6105. * given que hashtable. Code using this function must be able
  6106. * to handle NULL as a return which implies there is no matching work.
  6107. * The calling function must lock access to the que if it is required.
  6108. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  6109. struct work *__find_work_bymidstate(struct work *que, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  6110. {
  6111. struct work *work, *tmp, *ret = NULL;
  6112. HASH_ITER(hh, que, work, tmp) {
  6113. if (work->queued &&
  6114. memcmp(work->midstate, midstate, midstatelen) == 0 &&
  6115. memcmp(work->data + offset, data, datalen) == 0) {
  6116. ret = work;
  6117. break;
  6118. }
  6119. }
  6120. return ret;
  6121. }
  6122. /* This function is for finding an already queued work item in the
  6123. * device's queued_work hashtable. Code using this function must be able
  6124. * to handle NULL as a return which implies there is no matching work.
  6125. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  6126. struct work *find_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  6127. {
  6128. struct work *ret;
  6129. rd_lock(&cgpu->qlock);
  6130. ret = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  6131. rd_unlock(&cgpu->qlock);
  6132. return ret;
  6133. }
  6134. /* This function should be used by queued device drivers when they're sure
  6135. * the work struct is no longer in use. */
  6136. void work_completed(struct cgpu_info *cgpu, struct work *work)
  6137. {
  6138. wr_lock(&cgpu->qlock);
  6139. if (work->queued)
  6140. cgpu->queued_count--;
  6141. HASH_DEL(cgpu->queued_work, work);
  6142. wr_unlock(&cgpu->qlock);
  6143. free_work(work);
  6144. }
  6145. static void flush_queue(struct cgpu_info *cgpu)
  6146. {
  6147. struct work *work, *tmp;
  6148. int discarded = 0;
  6149. wr_lock(&cgpu->qlock);
  6150. HASH_ITER(hh, cgpu->queued_work, work, tmp) {
  6151. /* Can only discard the work items if they're not physically
  6152. * queued on the device. */
  6153. if (!work->queued) {
  6154. HASH_DEL(cgpu->queued_work, work);
  6155. discard_work(work);
  6156. discarded++;
  6157. }
  6158. }
  6159. wr_unlock(&cgpu->qlock);
  6160. if (discarded)
  6161. applog(LOG_DEBUG, "Discarded %d queued work items", discarded);
  6162. }
  6163. /* This version of hash work is for devices that are fast enough to always
  6164. * perform a full nonce range and need a queue to maintain the device busy.
  6165. * Work creation and destruction is not done from within this function
  6166. * directly. */
  6167. void hash_queued_work(struct thr_info *mythr)
  6168. {
  6169. const long cycle = opt_log_interval / 5 ? : 1;
  6170. struct timeval tv_start = {0, 0}, tv_end;
  6171. struct cgpu_info *cgpu = mythr->cgpu;
  6172. struct device_drv *drv = cgpu->drv;
  6173. const int thr_id = mythr->id;
  6174. int64_t hashes_done = 0;
  6175. while (42) {
  6176. struct timeval diff;
  6177. int64_t hashes;
  6178. mythr->work_restart = false;
  6179. fill_queue(mythr, cgpu, drv, thr_id);
  6180. thread_reportin(mythr);
  6181. hashes = drv->scanwork(mythr);
  6182. if (unlikely(hashes == -1 )) {
  6183. applog(LOG_ERR, "%s %d failure, disabling!", drv->name, cgpu->device_id);
  6184. cgpu->deven = DEV_DISABLED;
  6185. dev_error(cgpu, REASON_THREAD_ZERO_HASH);
  6186. mt_disable(mythr);
  6187. }
  6188. hashes_done += hashes;
  6189. gettimeofday(&tv_end, NULL);
  6190. timersub(&tv_end, &tv_start, &diff);
  6191. if (diff.tv_sec >= cycle) {
  6192. hashmeter(thr_id, &diff, hashes_done);
  6193. hashes_done = 0;
  6194. memcpy(&tv_start, &tv_end, sizeof(struct timeval));
  6195. }
  6196. if (unlikely(mythr->work_restart)) {
  6197. flush_queue(cgpu);
  6198. if (drv->flush_work)
  6199. drv->flush_work(cgpu);
  6200. }
  6201. if (unlikely(mythr->pause || cgpu->deven != DEV_ENABLED))
  6202. mt_disable(mythr);
  6203. }
  6204. }
  6205. void mt_disable_finish(struct thr_info *mythr)
  6206. {
  6207. struct device_drv *drv = mythr->cgpu->drv;
  6208. thread_reportin(mythr);
  6209. __thr_being_msg(mythr, "re-enabled");
  6210. if (drv->thread_enable)
  6211. drv->thread_enable(mythr);
  6212. }
  6213. void mt_disable(struct thr_info *mythr)
  6214. {
  6215. mt_disable_start(mythr);
  6216. applog(LOG_DEBUG, "Waiting for wakeup notification in miner thread");
  6217. do {
  6218. notifier_read(mythr->notifier);
  6219. } while (mythr->pause);
  6220. mt_disable_finish(mythr);
  6221. }
  6222. enum {
  6223. STAT_SLEEP_INTERVAL = 1,
  6224. STAT_CTR_INTERVAL = 10000000,
  6225. FAILURE_INTERVAL = 30,
  6226. };
  6227. /* Stage another work item from the work returned in a longpoll */
  6228. 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)
  6229. {
  6230. bool rc;
  6231. work->rolltime = rolltime;
  6232. rc = work_decode(pool, work, val);
  6233. if (unlikely(!rc)) {
  6234. applog(LOG_ERR, "Could not convert longpoll data to work");
  6235. free_work(work);
  6236. return;
  6237. }
  6238. total_getworks++;
  6239. pool->getwork_requested++;
  6240. work->pool = pool;
  6241. memcpy(&(work->tv_getwork), tv_lp, sizeof(struct timeval));
  6242. memcpy(&(work->tv_getwork_reply), tv_lp_reply, sizeof(struct timeval));
  6243. calc_diff(work, 0);
  6244. if (pool->enabled == POOL_REJECTING)
  6245. work->mandatory = true;
  6246. work->longpoll = true;
  6247. work->getwork_mode = GETWORK_MODE_LP;
  6248. update_last_work(work);
  6249. /* We'll be checking this work item twice, but we already know it's
  6250. * from a new block so explicitly force the new block detection now
  6251. * rather than waiting for it to hit the stage thread. This also
  6252. * allows testwork to know whether LP discovered the block or not. */
  6253. test_work_current(work);
  6254. /* Don't use backup LPs as work if we have failover-only enabled. Use
  6255. * the longpoll work from a pool that has been rejecting shares as a
  6256. * way to detect when the pool has recovered.
  6257. */
  6258. if (pool != current_pool() && opt_fail_only && pool->enabled != POOL_REJECTING) {
  6259. free_work(work);
  6260. return;
  6261. }
  6262. work = clone_work(work);
  6263. applog(LOG_DEBUG, "Pushing converted work to stage thread");
  6264. stage_work(work);
  6265. applog(LOG_DEBUG, "Converted longpoll data to work");
  6266. }
  6267. /* If we want longpoll, enable it for the chosen default pool, or, if
  6268. * the pool does not support longpoll, find the first one that does
  6269. * and use its longpoll support */
  6270. static struct pool *select_longpoll_pool(struct pool *cp)
  6271. {
  6272. int i;
  6273. if (cp->lp_url)
  6274. return cp;
  6275. for (i = 0; i < total_pools; i++) {
  6276. struct pool *pool = pools[i];
  6277. if (pool->has_stratum || pool->lp_url)
  6278. return pool;
  6279. }
  6280. return NULL;
  6281. }
  6282. /* This will make the longpoll thread wait till it's the current pool, or it
  6283. * has been flagged as rejecting, before attempting to open any connections.
  6284. */
  6285. static void wait_lpcurrent(struct pool *pool)
  6286. {
  6287. if (cnx_needed(pool))
  6288. return;
  6289. while (pool != current_pool() && pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  6290. mutex_lock(&lp_lock);
  6291. pthread_cond_wait(&lp_cond, &lp_lock);
  6292. mutex_unlock(&lp_lock);
  6293. }
  6294. }
  6295. static curl_socket_t save_curl_socket(void *vpool, __maybe_unused curlsocktype purpose, struct curl_sockaddr *addr) {
  6296. struct pool *pool = vpool;
  6297. curl_socket_t sock = socket(addr->family, addr->socktype, addr->protocol);
  6298. pool->lp_socket = sock;
  6299. return sock;
  6300. }
  6301. static void *longpoll_thread(void *userdata)
  6302. {
  6303. struct pool *cp = (struct pool *)userdata;
  6304. /* This *pool is the source of the actual longpoll, not the pool we've
  6305. * tied it to */
  6306. struct timeval start, reply, end;
  6307. struct pool *pool = NULL;
  6308. char threadname[20];
  6309. CURL *curl = NULL;
  6310. int failures = 0;
  6311. char *lp_url;
  6312. int rolltime;
  6313. #ifndef HAVE_PTHREAD_CANCEL
  6314. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  6315. #endif
  6316. snprintf(threadname, 20, "longpoll%u", cp->pool_no);
  6317. RenameThread(threadname);
  6318. curl = curl_easy_init();
  6319. if (unlikely(!curl)) {
  6320. applog(LOG_ERR, "CURL initialisation failed");
  6321. return NULL;
  6322. }
  6323. retry_pool:
  6324. pool = select_longpoll_pool(cp);
  6325. if (!pool) {
  6326. applog(LOG_WARNING, "No suitable long-poll found for %s", cp->rpc_url);
  6327. while (!pool) {
  6328. nmsleep(60000);
  6329. pool = select_longpoll_pool(cp);
  6330. }
  6331. }
  6332. if (pool->has_stratum) {
  6333. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  6334. cp->rpc_url, pool->rpc_url);
  6335. goto out;
  6336. }
  6337. /* Any longpoll from any pool is enough for this to be true */
  6338. have_longpoll = true;
  6339. wait_lpcurrent(cp);
  6340. {
  6341. lp_url = pool->lp_url;
  6342. if (cp == pool)
  6343. applog(LOG_WARNING, "Long-polling activated for %s (%s)", lp_url, pool_protocol_name(pool->lp_proto));
  6344. else
  6345. applog(LOG_WARNING, "Long-polling activated for %s via %s (%s)", cp->rpc_url, lp_url, pool_protocol_name(pool->lp_proto));
  6346. }
  6347. while (42) {
  6348. json_t *val, *soval;
  6349. struct work *work = make_work();
  6350. char *lpreq;
  6351. lpreq = prepare_rpc_req(work, pool->lp_proto, pool->lp_id);
  6352. work->pool = pool;
  6353. if (!lpreq)
  6354. {
  6355. free_work(work);
  6356. goto lpfail;
  6357. }
  6358. wait_lpcurrent(cp);
  6359. gettimeofday(&start, NULL);
  6360. /* Longpoll connections can be persistent for a very long time
  6361. * and any number of issues could have come up in the meantime
  6362. * so always establish a fresh connection instead of relying on
  6363. * a persistent one. */
  6364. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  6365. curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, save_curl_socket);
  6366. curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, pool);
  6367. val = json_rpc_call(curl, lp_url, pool->rpc_userpass,
  6368. lpreq, false, true, &rolltime, pool, false);
  6369. pool->lp_socket = CURL_SOCKET_BAD;
  6370. gettimeofday(&reply, NULL);
  6371. free(lpreq);
  6372. if (likely(val)) {
  6373. soval = json_object_get(json_object_get(val, "result"), "submitold");
  6374. if (soval)
  6375. pool->submit_old = json_is_true(soval);
  6376. else
  6377. pool->submit_old = false;
  6378. convert_to_work(val, rolltime, pool, work, &start, &reply);
  6379. failures = 0;
  6380. json_decref(val);
  6381. } else {
  6382. /* Some pools regularly drop the longpoll request so
  6383. * only see this as longpoll failure if it happens
  6384. * immediately and just restart it the rest of the
  6385. * time. */
  6386. gettimeofday(&end, NULL);
  6387. free_work(work);
  6388. if (end.tv_sec - start.tv_sec > 30)
  6389. continue;
  6390. if (failures == 1)
  6391. applog(LOG_WARNING, "longpoll failed for %s, retrying every 30s", lp_url);
  6392. lpfail:
  6393. nmsleep(30000);
  6394. }
  6395. if (pool != cp) {
  6396. pool = select_longpoll_pool(cp);
  6397. if (pool->has_stratum) {
  6398. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  6399. cp->rpc_url, pool->rpc_url);
  6400. break;
  6401. }
  6402. if (unlikely(!pool))
  6403. goto retry_pool;
  6404. }
  6405. if (unlikely(pool->removed))
  6406. break;
  6407. }
  6408. out:
  6409. curl_easy_cleanup(curl);
  6410. return NULL;
  6411. }
  6412. static void stop_longpoll(void)
  6413. {
  6414. int i;
  6415. want_longpoll = false;
  6416. for (i = 0; i < total_pools; ++i)
  6417. {
  6418. struct pool *pool = pools[i];
  6419. if (unlikely(!pool->lp_started))
  6420. continue;
  6421. pool->lp_started = false;
  6422. pthread_cancel(pool->longpoll_thread);
  6423. }
  6424. have_longpoll = false;
  6425. }
  6426. static void start_longpoll(void)
  6427. {
  6428. int i;
  6429. want_longpoll = true;
  6430. for (i = 0; i < total_pools; ++i)
  6431. {
  6432. struct pool *pool = pools[i];
  6433. if (unlikely(pool->removed || pool->lp_started || !pool->lp_url))
  6434. continue;
  6435. pool->lp_started = true;
  6436. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  6437. quit(1, "Failed to create pool longpoll thread");
  6438. }
  6439. }
  6440. void reinit_device(struct cgpu_info *cgpu)
  6441. {
  6442. if (cgpu->drv->reinit_device)
  6443. cgpu->drv->reinit_device(cgpu);
  6444. }
  6445. static struct timeval rotate_tv;
  6446. /* We reap curls if they are unused for over a minute */
  6447. static void reap_curl(struct pool *pool)
  6448. {
  6449. struct curl_ent *ent, *iter;
  6450. struct timeval now;
  6451. int reaped = 0;
  6452. gettimeofday(&now, NULL);
  6453. mutex_lock(&pool->pool_lock);
  6454. list_for_each_entry_safe(ent, iter, &pool->curlring, node) {
  6455. if (pool->curls < 2)
  6456. break;
  6457. if (now.tv_sec - ent->tv.tv_sec > 300) {
  6458. reaped++;
  6459. pool->curls--;
  6460. list_del(&ent->node);
  6461. curl_easy_cleanup(ent->curl);
  6462. free(ent);
  6463. }
  6464. }
  6465. mutex_unlock(&pool->pool_lock);
  6466. if (reaped)
  6467. applog(LOG_DEBUG, "Reaped %d curl%s from pool %d", reaped, reaped > 1 ? "s" : "", pool->pool_no);
  6468. }
  6469. static void *watchpool_thread(void __maybe_unused *userdata)
  6470. {
  6471. int intervals = 0;
  6472. #ifndef HAVE_PTHREAD_CANCEL
  6473. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  6474. #endif
  6475. RenameThread("watchpool");
  6476. while (42) {
  6477. struct timeval now;
  6478. int i;
  6479. if (++intervals > 20)
  6480. intervals = 0;
  6481. gettimeofday(&now, NULL);
  6482. for (i = 0; i < total_pools; i++) {
  6483. struct pool *pool = pools[i];
  6484. if (!opt_benchmark)
  6485. reap_curl(pool);
  6486. /* Get a rolling utility per pool over 10 mins */
  6487. if (intervals > 19) {
  6488. int shares = pool->diff1 - pool->last_shares;
  6489. pool->last_shares = pool->diff1;
  6490. pool->utility = (pool->utility + (double)shares * 0.63) / 1.63;
  6491. pool->shares = pool->utility;
  6492. }
  6493. if (pool->enabled == POOL_DISABLED)
  6494. continue;
  6495. /* Don't start testing any pools if the test threads
  6496. * from startup are still doing their first attempt. */
  6497. if (unlikely(pool->testing)) {
  6498. pthread_join(pool->test_thread, NULL);
  6499. pool->testing = false;
  6500. }
  6501. /* Test pool is idle once every minute */
  6502. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 30) {
  6503. gettimeofday(&pool->tv_idle, NULL);
  6504. if (pool_active(pool, true) && pool_tclear(pool, &pool->idle))
  6505. pool_resus(pool);
  6506. }
  6507. }
  6508. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  6509. gettimeofday(&rotate_tv, NULL);
  6510. switch_pools(NULL);
  6511. }
  6512. nmsleep(30000);
  6513. }
  6514. return NULL;
  6515. }
  6516. void mt_enable(struct thr_info *thr)
  6517. {
  6518. applog(LOG_DEBUG, "Waking up thread %d", thr->id);
  6519. notifier_wake(thr->notifier);
  6520. }
  6521. void proc_enable(struct cgpu_info *cgpu)
  6522. {
  6523. int j;
  6524. cgpu->deven = DEV_ENABLED;
  6525. for (j = cgpu->threads ?: 1; j--; )
  6526. mt_enable(cgpu->thr[j]);
  6527. }
  6528. #define device_recovered(cgpu) proc_enable(cgpu)
  6529. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  6530. * the screen at regular intervals, and restarts threads if they appear to have
  6531. * died. */
  6532. #define WATCHDOG_INTERVAL 2
  6533. #define WATCHDOG_SICK_TIME 60
  6534. #define WATCHDOG_DEAD_TIME 600
  6535. #define WATCHDOG_SICK_COUNT (WATCHDOG_SICK_TIME/WATCHDOG_INTERVAL)
  6536. #define WATCHDOG_DEAD_COUNT (WATCHDOG_DEAD_TIME/WATCHDOG_INTERVAL)
  6537. static void *watchdog_thread(void __maybe_unused *userdata)
  6538. {
  6539. const unsigned int interval = WATCHDOG_INTERVAL;
  6540. struct timeval zero_tv;
  6541. #ifndef HAVE_PTHREAD_CANCEL
  6542. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  6543. #endif
  6544. RenameThread("watchdog");
  6545. memset(&zero_tv, 0, sizeof(struct timeval));
  6546. gettimeofday(&rotate_tv, NULL);
  6547. while (1) {
  6548. int i;
  6549. struct timeval now;
  6550. sleep(interval);
  6551. discard_stale();
  6552. hashmeter(-1, &zero_tv, 0);
  6553. #ifdef HAVE_CURSES
  6554. if (curses_active_locked()) {
  6555. change_logwinsize();
  6556. curses_print_status();
  6557. for (i = 0; i < mining_threads; i++)
  6558. curses_print_devstatus(i);
  6559. touchwin(statuswin);
  6560. wrefresh(statuswin);
  6561. touchwin(logwin);
  6562. wrefresh(logwin);
  6563. unlock_curses();
  6564. }
  6565. #endif
  6566. gettimeofday(&now, NULL);
  6567. if (!sched_paused && !should_run()) {
  6568. applog(LOG_WARNING, "Pausing execution as per stop time %02d:%02d scheduled",
  6569. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  6570. if (!schedstart.enable) {
  6571. quit(0, "Terminating execution as planned");
  6572. break;
  6573. }
  6574. applog(LOG_WARNING, "Will restart execution as scheduled at %02d:%02d",
  6575. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  6576. sched_paused = true;
  6577. rd_lock(&mining_thr_lock);
  6578. for (i = 0; i < mining_threads; i++)
  6579. mining_thr[i]->pause = true;
  6580. rd_unlock(&mining_thr_lock);
  6581. } else if (sched_paused && should_run()) {
  6582. applog(LOG_WARNING, "Restarting execution as per start time %02d:%02d scheduled",
  6583. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  6584. if (schedstop.enable)
  6585. applog(LOG_WARNING, "Will pause execution as scheduled at %02d:%02d",
  6586. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  6587. sched_paused = false;
  6588. for (i = 0; i < mining_threads; i++) {
  6589. struct thr_info *thr;
  6590. thr = get_thread(i);
  6591. thr->pause = false;
  6592. }
  6593. for (i = 0; i < total_devices; ++i)
  6594. {
  6595. struct cgpu_info *cgpu = get_devices(i);
  6596. /* Don't touch disabled devices */
  6597. if (cgpu->deven == DEV_DISABLED)
  6598. continue;
  6599. proc_enable(cgpu);
  6600. }
  6601. }
  6602. for (i = 0; i < total_devices; ++i) {
  6603. struct cgpu_info *cgpu = get_devices(i);
  6604. struct thr_info *thr = cgpu->thr[0];
  6605. enum dev_enable *denable;
  6606. char *dev_str = cgpu->proc_repr;
  6607. int gpu;
  6608. if (cgpu->drv->get_stats)
  6609. cgpu->drv->get_stats(cgpu);
  6610. gpu = cgpu->device_id;
  6611. denable = &cgpu->deven;
  6612. #ifdef HAVE_ADL
  6613. if (adl_active && cgpu->has_adl)
  6614. gpu_autotune(gpu, denable);
  6615. if (opt_debug && cgpu->has_adl) {
  6616. int engineclock = 0, memclock = 0, activity = 0, fanspeed = 0, fanpercent = 0, powertune = 0;
  6617. float temp = 0, vddc = 0;
  6618. if (gpu_stats(gpu, &temp, &engineclock, &memclock, &vddc, &activity, &fanspeed, &fanpercent, &powertune))
  6619. applog(LOG_DEBUG, "%.1f C F: %d%%(%dRPM) E: %dMHz M: %dMHz V: %.3fV A: %d%% P: %d%%",
  6620. temp, fanpercent, fanspeed, engineclock, memclock, vddc, activity, powertune);
  6621. }
  6622. #endif
  6623. /* Thread is disabled */
  6624. if (*denable == DEV_DISABLED)
  6625. continue;
  6626. else
  6627. if (*denable == DEV_RECOVER_ERR) {
  6628. if (opt_restart && difftime(time(NULL), cgpu->device_last_not_well) > cgpu->reinit_backoff) {
  6629. applog(LOG_NOTICE, "Attempting to reinitialize %s",
  6630. dev_str);
  6631. if (cgpu->reinit_backoff < 300)
  6632. cgpu->reinit_backoff *= 2;
  6633. device_recovered(cgpu);
  6634. }
  6635. continue;
  6636. }
  6637. else
  6638. if (*denable == DEV_RECOVER) {
  6639. if (opt_restart && cgpu->temp < cgpu->targettemp) {
  6640. applog(LOG_NOTICE, "%s recovered to temperature below target, re-enabling",
  6641. dev_str);
  6642. device_recovered(cgpu);
  6643. }
  6644. cgpu->device_last_not_well = time(NULL);
  6645. cgpu->device_not_well_reason = REASON_DEV_THERMAL_CUTOFF;
  6646. continue;
  6647. }
  6648. else
  6649. if (cgpu->temp > cgpu->cutofftemp)
  6650. {
  6651. applog(LOG_WARNING, "%s hit thermal cutoff limit, disabling!",
  6652. dev_str);
  6653. *denable = DEV_RECOVER;
  6654. dev_error(cgpu, REASON_DEV_THERMAL_CUTOFF);
  6655. }
  6656. if (thr->getwork) {
  6657. if (cgpu->status == LIFE_WELL && thr->getwork < now.tv_sec - opt_log_interval) {
  6658. int thrid;
  6659. bool cgpu_idle = true;
  6660. thr->rolling = 0;
  6661. for (thrid = 0; thrid < cgpu->threads; ++thrid)
  6662. if (!cgpu->thr[thrid]->getwork)
  6663. cgpu_idle = false;
  6664. if (cgpu_idle) {
  6665. cgpu->rolling = 0;
  6666. cgpu->status = LIFE_WAIT;
  6667. }
  6668. }
  6669. continue;
  6670. }
  6671. else if (cgpu->status == LIFE_WAIT)
  6672. cgpu->status = LIFE_WELL;
  6673. #ifdef WANT_CPUMINE
  6674. if (!strcmp(cgpu->drv->dname, "cpu"))
  6675. continue;
  6676. #endif
  6677. if (cgpu->status != LIFE_WELL && (now.tv_sec - thr->last.tv_sec < WATCHDOG_SICK_TIME)) {
  6678. if (cgpu->status != LIFE_INIT)
  6679. applog(LOG_ERR, "%s: Recovered, declaring WELL!", dev_str);
  6680. cgpu->status = LIFE_WELL;
  6681. cgpu->device_last_well = time(NULL);
  6682. } else if (cgpu->status == LIFE_WELL && (now.tv_sec - thr->last.tv_sec > WATCHDOG_SICK_TIME)) {
  6683. thr->rolling = cgpu->rolling = 0;
  6684. cgpu->status = LIFE_SICK;
  6685. applog(LOG_ERR, "%s: Idle for more than 60 seconds, declaring SICK!", dev_str);
  6686. gettimeofday(&thr->sick, NULL);
  6687. dev_error(cgpu, REASON_DEV_SICK_IDLE_60);
  6688. #ifdef HAVE_ADL
  6689. if (adl_active && cgpu->has_adl && gpu_activity(gpu) > 50) {
  6690. applog(LOG_ERR, "GPU still showing activity suggesting a hard hang.");
  6691. applog(LOG_ERR, "Will not attempt to auto-restart it.");
  6692. } else
  6693. #endif
  6694. if (opt_restart) {
  6695. applog(LOG_ERR, "%s: Attempting to restart", dev_str);
  6696. reinit_device(cgpu);
  6697. }
  6698. } else if (cgpu->status == LIFE_SICK && (now.tv_sec - thr->last.tv_sec > WATCHDOG_DEAD_TIME)) {
  6699. cgpu->status = LIFE_DEAD;
  6700. applog(LOG_ERR, "%s: Not responded for more than 10 minutes, declaring DEAD!", dev_str);
  6701. gettimeofday(&thr->sick, NULL);
  6702. dev_error(cgpu, REASON_DEV_DEAD_IDLE_600);
  6703. } else if (now.tv_sec - thr->sick.tv_sec > 60 &&
  6704. (cgpu->status == LIFE_SICK || cgpu->status == LIFE_DEAD)) {
  6705. /* Attempt to restart a GPU that's sick or dead once every minute */
  6706. gettimeofday(&thr->sick, NULL);
  6707. #ifdef HAVE_ADL
  6708. if (adl_active && cgpu->has_adl && gpu_activity(gpu) > 50) {
  6709. /* Again do not attempt to restart a device that may have hard hung */
  6710. } else
  6711. #endif
  6712. if (opt_restart)
  6713. reinit_device(cgpu);
  6714. }
  6715. }
  6716. }
  6717. return NULL;
  6718. }
  6719. static void log_print_status(struct cgpu_info *cgpu)
  6720. {
  6721. char logline[255];
  6722. get_statline(logline, cgpu);
  6723. applog(LOG_WARNING, "%s", logline);
  6724. }
  6725. void print_summary(void)
  6726. {
  6727. struct timeval diff;
  6728. int hours, mins, secs, i;
  6729. double utility, efficiency = 0.0;
  6730. timersub(&total_tv_end, &total_tv_start, &diff);
  6731. hours = diff.tv_sec / 3600;
  6732. mins = (diff.tv_sec % 3600) / 60;
  6733. secs = diff.tv_sec % 60;
  6734. utility = total_accepted / total_secs * 60;
  6735. efficiency = total_bytes_xfer ? total_diff_accepted * 2048. / total_bytes_xfer : 0.0;
  6736. applog(LOG_WARNING, "\nSummary of runtime statistics:\n");
  6737. applog(LOG_WARNING, "Started at %s", datestamp);
  6738. if (total_pools == 1)
  6739. applog(LOG_WARNING, "Pool: %s", pools[0]->rpc_url);
  6740. #ifdef WANT_CPUMINE
  6741. if (opt_n_threads)
  6742. applog(LOG_WARNING, "CPU hasher algorithm used: %s", algo_names[opt_algo]);
  6743. #endif
  6744. applog(LOG_WARNING, "Runtime: %d hrs : %d mins : %d secs", hours, mins, secs);
  6745. applog(LOG_WARNING, "Average hashrate: %.1f Megahash/s", total_mhashes_done / total_secs);
  6746. applog(LOG_WARNING, "Solved blocks: %d", found_blocks);
  6747. applog(LOG_WARNING, "Best share difficulty: %s", best_share);
  6748. applog(LOG_WARNING, "Share submissions: %d", total_accepted + total_rejected);
  6749. applog(LOG_WARNING, "Accepted shares: %d", total_accepted);
  6750. applog(LOG_WARNING, "Rejected shares: %d", total_rejected);
  6751. applog(LOG_WARNING, "Accepted difficulty shares: %1.f", total_diff_accepted);
  6752. applog(LOG_WARNING, "Rejected difficulty shares: %1.f", total_diff_rejected);
  6753. if (total_accepted || total_rejected)
  6754. applog(LOG_WARNING, "Reject ratio: %.1f%%", (double)(total_rejected * 100) / (double)(total_accepted + total_rejected));
  6755. applog(LOG_WARNING, "Hardware errors: %d", hw_errors);
  6756. applog(LOG_WARNING, "Efficiency (accepted shares * difficulty / 2 KB): %.2f", efficiency);
  6757. applog(LOG_WARNING, "Utility (accepted shares / min): %.2f/min\n", utility);
  6758. applog(LOG_WARNING, "Stale submissions discarded due to new blocks: %d", total_stale);
  6759. applog(LOG_WARNING, "Unable to get work from server occasions: %d", total_go);
  6760. applog(LOG_WARNING, "Work items generated locally: %d", local_work);
  6761. applog(LOG_WARNING, "Submitting work remotely delay occasions: %d", total_ro);
  6762. applog(LOG_WARNING, "New blocks detected on network: %d\n", new_blocks);
  6763. if (total_pools > 1) {
  6764. for (i = 0; i < total_pools; i++) {
  6765. struct pool *pool = pools[i];
  6766. applog(LOG_WARNING, "Pool: %s", pool->rpc_url);
  6767. if (pool->solved)
  6768. applog(LOG_WARNING, "SOLVED %d BLOCK%s!", pool->solved, pool->solved > 1 ? "S" : "");
  6769. applog(LOG_WARNING, " Share submissions: %d", pool->accepted + pool->rejected);
  6770. applog(LOG_WARNING, " Accepted shares: %d", pool->accepted);
  6771. applog(LOG_WARNING, " Rejected shares: %d", pool->rejected);
  6772. applog(LOG_WARNING, " Accepted difficulty shares: %1.f", pool->diff_accepted);
  6773. applog(LOG_WARNING, " Rejected difficulty shares: %1.f", pool->diff_rejected);
  6774. if (pool->accepted || pool->rejected)
  6775. applog(LOG_WARNING, " Reject ratio: %.1f%%", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  6776. uint64_t pool_bytes_xfer = pool->cgminer_pool_stats.net_bytes_received + pool->cgminer_pool_stats.net_bytes_sent;
  6777. efficiency = pool_bytes_xfer ? pool->diff_accepted * 2048. / pool_bytes_xfer : 0.0;
  6778. applog(LOG_WARNING, " Efficiency (accepted * difficulty / 2 KB): %.2f", efficiency);
  6779. applog(LOG_WARNING, " Stale submissions discarded due to new blocks: %d", pool->stale_shares);
  6780. applog(LOG_WARNING, " Unable to get work from server occasions: %d", pool->getfail_occasions);
  6781. applog(LOG_WARNING, " Submitting work remotely delay occasions: %d\n", pool->remotefail_occasions);
  6782. }
  6783. }
  6784. applog(LOG_WARNING, "Summary of per device statistics:\n");
  6785. for (i = 0; i < total_devices; ++i) {
  6786. struct cgpu_info *cgpu = get_devices(i);
  6787. if ((!cgpu->proc_id) && cgpu->next_proc)
  6788. {
  6789. // Device summary line
  6790. opt_show_procs = false;
  6791. log_print_status(cgpu);
  6792. opt_show_procs = true;
  6793. }
  6794. log_print_status(cgpu);
  6795. }
  6796. if (opt_shares)
  6797. applog(LOG_WARNING, "Mined %d accepted shares of %d requested\n", total_accepted, opt_shares);
  6798. fflush(stdout);
  6799. fflush(stderr);
  6800. if (opt_shares > total_accepted)
  6801. applog(LOG_WARNING, "WARNING - Mined only %d shares of %d requested.", total_accepted, opt_shares);
  6802. }
  6803. static void clean_up(void)
  6804. {
  6805. #ifdef HAVE_OPENCL
  6806. clear_adl(nDevs);
  6807. #endif
  6808. #ifdef HAVE_LIBUSB
  6809. libusb_exit(NULL);
  6810. #endif
  6811. gettimeofday(&total_tv_end, NULL);
  6812. #ifdef HAVE_CURSES
  6813. disable_curses();
  6814. #endif
  6815. if (!opt_realquiet && successful_connect)
  6816. print_summary();
  6817. if (opt_n_threads)
  6818. free(cpus);
  6819. curl_global_cleanup();
  6820. }
  6821. void quit(int status, const char *format, ...)
  6822. {
  6823. va_list ap;
  6824. clean_up();
  6825. if (format) {
  6826. va_start(ap, format);
  6827. vfprintf(stderr, format, ap);
  6828. va_end(ap);
  6829. }
  6830. fprintf(stderr, "\n");
  6831. fflush(stderr);
  6832. if (status) {
  6833. const char *ev = getenv("__BFGMINER_SEGFAULT_ERRQUIT");
  6834. if (unlikely(ev && ev[0] && ev[0] != '0')) {
  6835. const char **p = NULL;
  6836. // NOTE debugger can bypass with: p = &p
  6837. *p = format; // Segfault, hopefully dumping core
  6838. }
  6839. }
  6840. #if defined(unix)
  6841. if (forkpid > 0) {
  6842. kill(forkpid, SIGTERM);
  6843. forkpid = 0;
  6844. }
  6845. #endif
  6846. exit(status);
  6847. }
  6848. #ifdef HAVE_CURSES
  6849. char *curses_input(const char *query)
  6850. {
  6851. char *input;
  6852. echo();
  6853. input = malloc(255);
  6854. if (!input)
  6855. quit(1, "Failed to malloc input");
  6856. leaveok(logwin, false);
  6857. wlogprint("%s:\n", query);
  6858. wgetnstr(logwin, input, 255);
  6859. if (!strlen(input))
  6860. strcpy(input, "-1");
  6861. leaveok(logwin, true);
  6862. noecho();
  6863. return input;
  6864. }
  6865. #endif
  6866. static bool pools_active = false;
  6867. static void *test_pool_thread(void *arg)
  6868. {
  6869. struct pool *pool = (struct pool *)arg;
  6870. if (pool_active(pool, false)) {
  6871. pool_tset(pool, &pool->lagging);
  6872. pool_tclear(pool, &pool->idle);
  6873. cg_wlock(&control_lock);
  6874. if (!pools_active) {
  6875. currentpool = pool;
  6876. if (pool->pool_no != 0)
  6877. applog(LOG_NOTICE, "Switching to pool %d %s - first alive pool", pool->pool_no, pool->rpc_url);
  6878. pools_active = true;
  6879. }
  6880. cg_wunlock(&control_lock);
  6881. pool_resus(pool);
  6882. } else
  6883. pool_died(pool);
  6884. return NULL;
  6885. }
  6886. /* Always returns true that the pool details were added unless we are not
  6887. * live, implying this is the only pool being added, so if no pools are
  6888. * active it returns false. */
  6889. bool add_pool_details(struct pool *pool, bool live, char *url, char *user, char *pass)
  6890. {
  6891. pool->rpc_url = url;
  6892. pool->rpc_user = user;
  6893. pool->rpc_pass = pass;
  6894. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  6895. if (!pool->rpc_userpass)
  6896. quit(1, "Failed to malloc userpass");
  6897. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  6898. pool->testing = true;
  6899. pool->idle = true;
  6900. enable_pool(pool);
  6901. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  6902. if (!live) {
  6903. pthread_join(pool->test_thread, NULL);
  6904. pool->testing = false;
  6905. return pools_active;
  6906. }
  6907. return true;
  6908. }
  6909. #ifdef HAVE_CURSES
  6910. static bool input_pool(bool live)
  6911. {
  6912. char *url = NULL, *user = NULL, *pass = NULL;
  6913. struct pool *pool;
  6914. bool ret = false;
  6915. immedok(logwin, true);
  6916. wlogprint("Input server details.\n");
  6917. url = curses_input("URL");
  6918. if (!url)
  6919. goto out;
  6920. user = curses_input("Username");
  6921. if (!user)
  6922. goto out;
  6923. pass = curses_input("Password");
  6924. if (!pass)
  6925. goto out;
  6926. pool = add_pool();
  6927. if (!detect_stratum(pool, url) && strncmp(url, "http://", 7) &&
  6928. strncmp(url, "https://", 8)) {
  6929. char *httpinput;
  6930. httpinput = malloc(256);
  6931. if (!httpinput)
  6932. quit(1, "Failed to malloc httpinput");
  6933. strcpy(httpinput, "http://");
  6934. strncat(httpinput, url, 248);
  6935. free(url);
  6936. url = httpinput;
  6937. }
  6938. ret = add_pool_details(pool, live, url, user, pass);
  6939. out:
  6940. immedok(logwin, false);
  6941. if (!ret) {
  6942. if (url)
  6943. free(url);
  6944. if (user)
  6945. free(user);
  6946. if (pass)
  6947. free(pass);
  6948. }
  6949. return ret;
  6950. }
  6951. #endif
  6952. #if defined(unix)
  6953. static void fork_monitor()
  6954. {
  6955. // Make a pipe: [readFD, writeFD]
  6956. int pfd[2];
  6957. int r = pipe(pfd);
  6958. if (r < 0) {
  6959. perror("pipe - failed to create pipe for --monitor");
  6960. exit(1);
  6961. }
  6962. // Make stderr write end of pipe
  6963. fflush(stderr);
  6964. r = dup2(pfd[1], 2);
  6965. if (r < 0) {
  6966. perror("dup2 - failed to alias stderr to write end of pipe for --monitor");
  6967. exit(1);
  6968. }
  6969. r = close(pfd[1]);
  6970. if (r < 0) {
  6971. perror("close - failed to close write end of pipe for --monitor");
  6972. exit(1);
  6973. }
  6974. // Don't allow a dying monitor to kill the main process
  6975. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  6976. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  6977. if (SIG_ERR == sr0 || SIG_ERR == sr1) {
  6978. perror("signal - failed to edit signal mask for --monitor");
  6979. exit(1);
  6980. }
  6981. // Fork a child process
  6982. forkpid = fork();
  6983. if (forkpid < 0) {
  6984. perror("fork - failed to fork child process for --monitor");
  6985. exit(1);
  6986. }
  6987. // Child: launch monitor command
  6988. if (0 == forkpid) {
  6989. // Make stdin read end of pipe
  6990. r = dup2(pfd[0], 0);
  6991. if (r < 0) {
  6992. perror("dup2 - in child, failed to alias read end of pipe to stdin for --monitor");
  6993. exit(1);
  6994. }
  6995. close(pfd[0]);
  6996. if (r < 0) {
  6997. perror("close - in child, failed to close read end of pipe for --monitor");
  6998. exit(1);
  6999. }
  7000. // Launch user specified command
  7001. execl("/bin/bash", "/bin/bash", "-c", opt_stderr_cmd, (char*)NULL);
  7002. perror("execl - in child failed to exec user specified command for --monitor");
  7003. exit(1);
  7004. }
  7005. // Parent: clean up unused fds and bail
  7006. r = close(pfd[0]);
  7007. if (r < 0) {
  7008. perror("close - failed to close read end of pipe for --monitor");
  7009. exit(1);
  7010. }
  7011. }
  7012. #endif // defined(unix)
  7013. #ifdef HAVE_CURSES
  7014. void enable_curses(void) {
  7015. int x;
  7016. __maybe_unused int y;
  7017. lock_curses();
  7018. if (curses_active) {
  7019. unlock_curses();
  7020. return;
  7021. }
  7022. mainwin = initscr();
  7023. keypad(mainwin, true);
  7024. getmaxyx(mainwin, y, x);
  7025. statuswin = newwin(logstart, x, 0, 0);
  7026. leaveok(statuswin, true);
  7027. // For whatever reason, PDCurses crashes if the logwin is initialized to height y-logcursor
  7028. // We resize the window later anyway, so just start it off at 1 :)
  7029. logwin = newwin(1, 0, logcursor, 0);
  7030. idlok(logwin, true);
  7031. scrollok(logwin, true);
  7032. leaveok(logwin, true);
  7033. cbreak();
  7034. noecho();
  7035. curses_active = true;
  7036. statusy = logstart;
  7037. unlock_curses();
  7038. }
  7039. #endif
  7040. /* TODO: fix need a dummy CPU device_drv even if no support for CPU mining */
  7041. #ifndef WANT_CPUMINE
  7042. struct device_drv cpu_drv;
  7043. struct device_drv cpu_drv = {
  7044. .name = "CPU",
  7045. };
  7046. #endif
  7047. #ifdef USE_BITFORCE
  7048. extern struct device_drv bitforce_drv;
  7049. #endif
  7050. #ifdef USE_ICARUS
  7051. extern struct device_drv cairnsmore_drv;
  7052. extern struct device_drv icarus_drv;
  7053. #endif
  7054. #ifdef USE_AVALON
  7055. extern struct device_drv avalon_drv;
  7056. #endif
  7057. #ifdef USE_MODMINER
  7058. extern struct device_drv modminer_drv;
  7059. #endif
  7060. #ifdef USE_X6500
  7061. extern struct device_drv x6500_api;
  7062. #endif
  7063. #ifdef USE_ZTEX
  7064. extern struct device_drv ztex_drv;
  7065. #endif
  7066. static int cgminer_id_count = 0;
  7067. static int device_line_id_count;
  7068. void register_device(struct cgpu_info *cgpu)
  7069. {
  7070. cgpu->deven = DEV_ENABLED;
  7071. wr_lock(&devices_lock);
  7072. devices[cgpu->cgminer_id = cgminer_id_count++] = cgpu;
  7073. wr_unlock(&devices_lock);
  7074. if (!cgpu->proc_id)
  7075. cgpu->device_line_id = device_line_id_count++;
  7076. mining_threads += cgpu->threads ?: 1;
  7077. #ifdef HAVE_CURSES
  7078. adj_width(mining_threads, &dev_width);
  7079. #endif
  7080. #ifdef HAVE_OPENCL
  7081. if (cgpu->drv == &opencl_api) {
  7082. gpu_threads += cgpu->threads;
  7083. }
  7084. #endif
  7085. rwlock_init(&cgpu->qlock);
  7086. cgpu->queued_work = NULL;
  7087. }
  7088. struct _cgpu_devid_counter {
  7089. char name[4];
  7090. int lastid;
  7091. UT_hash_handle hh;
  7092. };
  7093. void renumber_cgpu(struct cgpu_info *cgpu)
  7094. {
  7095. static struct _cgpu_devid_counter *devids = NULL;
  7096. struct _cgpu_devid_counter *d;
  7097. HASH_FIND_STR(devids, cgpu->drv->name, d);
  7098. if (d)
  7099. cgpu->device_id = ++d->lastid;
  7100. else {
  7101. d = malloc(sizeof(*d));
  7102. memcpy(d->name, cgpu->drv->name, sizeof(d->name));
  7103. cgpu->device_id = d->lastid = 0;
  7104. HASH_ADD_STR(devids, name, d);
  7105. }
  7106. }
  7107. static bool my_blkmaker_sha256_callback(void *digest, const void *buffer, size_t length)
  7108. {
  7109. sha2(buffer, length, digest);
  7110. return true;
  7111. }
  7112. #ifndef HAVE_PTHREAD_CANCEL
  7113. extern void setup_pthread_cancel_workaround();
  7114. extern struct sigaction pcwm_orig_term_handler;
  7115. #endif
  7116. static void probe_pools(void)
  7117. {
  7118. int i;
  7119. for (i = 0; i < total_pools; i++) {
  7120. struct pool *pool = pools[i];
  7121. pool->testing = true;
  7122. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  7123. }
  7124. }
  7125. static void raise_fd_limits(void)
  7126. {
  7127. #ifdef HAVE_SETRLIMIT
  7128. struct rlimit fdlimit;
  7129. unsigned long old_soft_limit;
  7130. if (getrlimit(RLIMIT_NOFILE, &fdlimit))
  7131. applogr(, LOG_DEBUG, "setrlimit: Failed to getrlimit(RLIMIT_NOFILE)");
  7132. if (fdlimit.rlim_cur == RLIM_INFINITY)
  7133. applogr(, LOG_DEBUG, "setrlimit: Soft fd limit already infinite");
  7134. if (fdlimit.rlim_cur == fdlimit.rlim_max)
  7135. applogr(, LOG_DEBUG, "setrlimit: Soft fd limit already identical to hard limit (%lu)", (unsigned long)fdlimit.rlim_max);
  7136. old_soft_limit = fdlimit.rlim_cur;
  7137. fdlimit.rlim_cur = fdlimit.rlim_max;
  7138. if (setrlimit(RLIMIT_NOFILE, &fdlimit))
  7139. 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);
  7140. applog(LOG_DEBUG, "setrlimit: Increased soft fd limit from %lu to hard limit of %lu", old_soft_limit, (unsigned long)fdlimit.rlim_max);
  7141. #else
  7142. applog(LOG_DEBUG, "setrlimit: Not supported by platform");
  7143. #endif
  7144. }
  7145. int main(int argc, char *argv[])
  7146. {
  7147. struct sigaction handler;
  7148. struct thr_info *thr;
  7149. struct block *block;
  7150. unsigned int k;
  7151. int i, j;
  7152. char *s;
  7153. blkmk_sha256_impl = my_blkmaker_sha256_callback;
  7154. #ifndef HAVE_PTHREAD_CANCEL
  7155. setup_pthread_cancel_workaround();
  7156. #endif
  7157. /* This dangerous functions tramples random dynamically allocated
  7158. * variables so do it before anything at all */
  7159. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  7160. quit(1, "Failed to curl_global_init");
  7161. initial_args = malloc(sizeof(char *) * (argc + 1));
  7162. for (i = 0; i < argc; i++)
  7163. initial_args[i] = strdup(argv[i]);
  7164. initial_args[argc] = NULL;
  7165. #ifdef HAVE_LIBUSB
  7166. int err = libusb_init(NULL);
  7167. if (err) {
  7168. fprintf(stderr, "libusb_init() failed err %d", err);
  7169. fflush(stderr);
  7170. quit(1, "libusb_init() failed");
  7171. }
  7172. #endif
  7173. mutex_init(&hash_lock);
  7174. mutex_init(&console_lock);
  7175. cglock_init(&control_lock);
  7176. mutex_init(&stats_lock);
  7177. mutex_init(&sharelog_lock);
  7178. cglock_init(&ch_lock);
  7179. mutex_init(&sshare_lock);
  7180. rwlock_init(&blk_lock);
  7181. rwlock_init(&netacc_lock);
  7182. rwlock_init(&mining_thr_lock);
  7183. rwlock_init(&devices_lock);
  7184. mutex_init(&lp_lock);
  7185. if (unlikely(pthread_cond_init(&lp_cond, NULL)))
  7186. quit(1, "Failed to pthread_cond_init lp_cond");
  7187. if (unlikely(pthread_cond_init(&gws_cond, NULL)))
  7188. quit(1, "Failed to pthread_cond_init gws_cond");
  7189. notifier_init(submit_waiting_notifier);
  7190. sprintf(packagename, "%s %s", PACKAGE, VERSION);
  7191. #ifdef WANT_CPUMINE
  7192. init_max_name_len();
  7193. #endif
  7194. handler.sa_handler = &sighandler;
  7195. handler.sa_flags = 0;
  7196. sigemptyset(&handler.sa_mask);
  7197. #ifdef HAVE_PTHREAD_CANCEL
  7198. sigaction(SIGTERM, &handler, &termhandler);
  7199. #else
  7200. // Need to let pthread_cancel emulation handle SIGTERM first
  7201. termhandler = pcwm_orig_term_handler;
  7202. pcwm_orig_term_handler = handler;
  7203. #endif
  7204. sigaction(SIGINT, &handler, &inthandler);
  7205. #ifndef WIN32
  7206. signal(SIGPIPE, SIG_IGN);
  7207. #endif
  7208. opt_kernel_path = alloca(PATH_MAX);
  7209. strcpy(opt_kernel_path, CGMINER_PREFIX);
  7210. cgminer_path = alloca(PATH_MAX);
  7211. s = strdup(argv[0]);
  7212. strcpy(cgminer_path, dirname(s));
  7213. free(s);
  7214. strcat(cgminer_path, "/");
  7215. #ifdef WANT_CPUMINE
  7216. // Hack to make cgminer silent when called recursively on WIN32
  7217. int skip_to_bench = 0;
  7218. #if defined(WIN32)
  7219. char buf[32];
  7220. if (GetEnvironmentVariable("BFGMINER_BENCH_ALGO", buf, 16))
  7221. skip_to_bench = 1;
  7222. if (GetEnvironmentVariable("CGMINER_BENCH_ALGO", buf, 16))
  7223. skip_to_bench = 1;
  7224. #endif // defined(WIN32)
  7225. #endif
  7226. devcursor = 8;
  7227. logstart = devcursor + 1;
  7228. logcursor = logstart + 1;
  7229. block = calloc(sizeof(struct block), 1);
  7230. if (unlikely(!block))
  7231. quit (1, "main OOM");
  7232. for (i = 0; i < 36; i++)
  7233. strcat(block->hash, "0");
  7234. HASH_ADD_STR(blocks, hash, block);
  7235. strcpy(current_block, block->hash);
  7236. INIT_LIST_HEAD(&scan_devices);
  7237. mutex_init(&submitting_lock);
  7238. INIT_LIST_HEAD(&submit_waiting);
  7239. #ifdef HAVE_OPENCL
  7240. memset(gpus, 0, sizeof(gpus));
  7241. for (i = 0; i < MAX_GPUDEVICES; i++)
  7242. gpus[i].dynamic = true;
  7243. #endif
  7244. schedstart.tm.tm_sec = 1;
  7245. schedstop .tm.tm_sec = 1;
  7246. /* parse command line */
  7247. opt_register_table(opt_config_table,
  7248. "Options for both config file and command line");
  7249. opt_register_table(opt_cmdline_table,
  7250. "Options for command line only");
  7251. opt_parse(&argc, argv, applog_and_exit);
  7252. if (argc != 1)
  7253. quit(1, "Unexpected extra commandline arguments");
  7254. if (!config_loaded)
  7255. load_default_config();
  7256. #ifndef HAVE_PTHREAD_CANCEL
  7257. // Can't do this any earlier, or config isn't loaded
  7258. applog(LOG_DEBUG, "pthread_cancel workaround in use");
  7259. #endif
  7260. raise_fd_limits();
  7261. if (opt_benchmark) {
  7262. struct pool *pool;
  7263. want_longpoll = false;
  7264. pool = add_pool();
  7265. pool->rpc_url = malloc(255);
  7266. strcpy(pool->rpc_url, "Benchmark");
  7267. pool->rpc_user = pool->rpc_url;
  7268. pool->rpc_pass = pool->rpc_url;
  7269. enable_pool(pool);
  7270. pool->idle = false;
  7271. successful_connect = true;
  7272. }
  7273. #ifdef USE_X6500
  7274. ft232r_scan();
  7275. #endif
  7276. #ifdef HAVE_CURSES
  7277. if (opt_realquiet || devices_enabled == -1)
  7278. use_curses = false;
  7279. if (use_curses)
  7280. enable_curses();
  7281. #endif
  7282. applog(LOG_WARNING, "Started %s", packagename);
  7283. if (cnfbuf) {
  7284. applog(LOG_NOTICE, "Loaded configuration file %s", cnfbuf);
  7285. switch (fileconf_load) {
  7286. case 0:
  7287. applog(LOG_WARNING, "Fatal JSON error in configuration file.");
  7288. applog(LOG_WARNING, "Configuration file could not be used.");
  7289. break;
  7290. case -1:
  7291. applog(LOG_WARNING, "Error in configuration file, partially loaded.");
  7292. if (use_curses)
  7293. applog(LOG_WARNING, "Start BFGMiner with -T to see what failed to load.");
  7294. break;
  7295. default:
  7296. break;
  7297. }
  7298. free(cnfbuf);
  7299. cnfbuf = NULL;
  7300. }
  7301. strcat(opt_kernel_path, "/");
  7302. if (want_per_device_stats)
  7303. opt_log_output = true;
  7304. #ifdef WANT_CPUMINE
  7305. #ifdef USE_SCRYPT
  7306. if (opt_scrypt)
  7307. set_scrypt_algo(&opt_algo);
  7308. else
  7309. #endif
  7310. if (0 <= opt_bench_algo) {
  7311. double rate = bench_algo_stage3(opt_bench_algo);
  7312. if (!skip_to_bench)
  7313. printf("%.5f (%s)\n", rate, algo_names[opt_bench_algo]);
  7314. else {
  7315. // Write result to shared memory for parent
  7316. #if defined(WIN32)
  7317. char unique_name[64];
  7318. if (GetEnvironmentVariable("BFGMINER_SHARED_MEM", unique_name, 32) || GetEnvironmentVariable("CGMINER_SHARED_MEM", unique_name, 32)) {
  7319. HANDLE map_handle = CreateFileMapping(
  7320. INVALID_HANDLE_VALUE, // use paging file
  7321. NULL, // default security attributes
  7322. PAGE_READWRITE, // read/write access
  7323. 0, // size: high 32-bits
  7324. 4096, // size: low 32-bits
  7325. unique_name // name of map object
  7326. );
  7327. if (NULL != map_handle) {
  7328. void *shared_mem = MapViewOfFile(
  7329. map_handle, // object to map view of
  7330. FILE_MAP_WRITE, // read/write access
  7331. 0, // high offset: map from
  7332. 0, // low offset: beginning
  7333. 0 // default: map entire file
  7334. );
  7335. if (NULL != shared_mem)
  7336. CopyMemory(shared_mem, &rate, sizeof(rate));
  7337. (void)UnmapViewOfFile(shared_mem);
  7338. }
  7339. (void)CloseHandle(map_handle);
  7340. }
  7341. #endif
  7342. }
  7343. exit(0);
  7344. }
  7345. #endif
  7346. #ifdef HAVE_OPENCL
  7347. if (!opt_nogpu)
  7348. opencl_api.drv_detect();
  7349. gpu_threads = 0;
  7350. #endif
  7351. #ifdef USE_ICARUS
  7352. if (!opt_scrypt)
  7353. {
  7354. cairnsmore_drv.drv_detect();
  7355. icarus_drv.drv_detect();
  7356. }
  7357. #endif
  7358. #ifdef USE_AVALON
  7359. if (!opt_scrypt)
  7360. avalon_drv.drv_detect();
  7361. #endif
  7362. #ifdef USE_BITFORCE
  7363. if (!opt_scrypt)
  7364. bitforce_drv.drv_detect();
  7365. #endif
  7366. #ifdef USE_MODMINER
  7367. if (!opt_scrypt)
  7368. modminer_drv.drv_detect();
  7369. #endif
  7370. #ifdef USE_X6500
  7371. if (!opt_scrypt)
  7372. x6500_api.drv_detect();
  7373. #endif
  7374. #ifdef USE_ZTEX
  7375. if (!opt_scrypt)
  7376. ztex_drv.drv_detect();
  7377. #endif
  7378. #ifdef WANT_CPUMINE
  7379. cpu_drv.drv_detect();
  7380. #endif
  7381. #ifdef USE_X6500
  7382. ft232r_scan_free();
  7383. #endif
  7384. for (i = 0; i < total_devices; ++i)
  7385. if (!devices[i]->devtype)
  7386. devices[i]->devtype = "PGA";
  7387. if (devices_enabled == -1) {
  7388. applog(LOG_ERR, "Devices detected:");
  7389. for (i = 0; i < total_devices; ++i) {
  7390. struct cgpu_info *cgpu = devices[i];
  7391. if (cgpu->name)
  7392. applog(LOG_ERR, " %2d. %"PRIprepr": %s (driver: %s)", i, cgpu->proc_repr, cgpu->name, cgpu->drv->dname);
  7393. else
  7394. applog(LOG_ERR, " %2d. %"PRIprepr" (driver: %s)", i, cgpu->proc_repr, cgpu->drv->dname);
  7395. }
  7396. quit(0, "%d devices listed", total_devices);
  7397. }
  7398. mining_threads = 0;
  7399. if (devices_enabled) {
  7400. for (i = 0; i < (int)(sizeof(devices_enabled) * 8) - 1; ++i) {
  7401. if (devices_enabled & (1 << i)) {
  7402. if (i >= total_devices)
  7403. quit (1, "Command line options set a device that doesn't exist");
  7404. register_device(devices[i]);
  7405. } else if (i < total_devices) {
  7406. if (opt_removedisabled) {
  7407. if (devices[i]->drv == &cpu_drv)
  7408. --opt_n_threads;
  7409. } else {
  7410. register_device(devices[i]);
  7411. }
  7412. devices[i]->deven = DEV_DISABLED;
  7413. }
  7414. }
  7415. total_devices = cgminer_id_count;
  7416. } else {
  7417. for (i = 0; i < total_devices; ++i)
  7418. register_device(devices[i]);
  7419. }
  7420. #ifdef USE_USBUTILS
  7421. if (!total_devices) {
  7422. applog(LOG_WARNING, "No devices detected!");
  7423. applog(LOG_WARNING, "Waiting for USB hotplug devices or press q to quit");
  7424. }
  7425. #else
  7426. if (!total_devices)
  7427. quit(1, "All devices disabled, cannot mine!");
  7428. #endif
  7429. load_temp_config();
  7430. for (i = 0; i < total_devices; ++i)
  7431. devices[i]->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  7432. #ifdef HAVE_CURSES
  7433. change_summarywinsize();
  7434. #endif
  7435. if (!total_pools) {
  7436. applog(LOG_WARNING, "Need to specify at least one pool server.");
  7437. #ifdef HAVE_CURSES
  7438. if (!use_curses || !input_pool(false))
  7439. #endif
  7440. quit(1, "Pool setup failed");
  7441. }
  7442. for (i = 0; i < total_pools; i++) {
  7443. struct pool *pool = pools[i];
  7444. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  7445. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  7446. if (!pool->rpc_url)
  7447. quit(1, "No URI supplied for pool %u", i);
  7448. if (!pool->rpc_userpass) {
  7449. if (!pool->rpc_user || !pool->rpc_pass)
  7450. quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  7451. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  7452. if (!pool->rpc_userpass)
  7453. quit(1, "Failed to malloc userpass");
  7454. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  7455. }
  7456. }
  7457. /* Set the currentpool to pool with priority 0 */
  7458. validate_pool_priorities();
  7459. for (i = 0; i < total_pools; i++) {
  7460. struct pool *pool = pools[i];
  7461. if (!pool->prio)
  7462. currentpool = pool;
  7463. }
  7464. #ifdef HAVE_SYSLOG_H
  7465. if (use_syslog)
  7466. openlog(PACKAGE, LOG_PID, LOG_USER);
  7467. #endif
  7468. #if defined(unix)
  7469. if (opt_stderr_cmd)
  7470. fork_monitor();
  7471. #endif // defined(unix)
  7472. mining_thr = calloc(mining_threads, sizeof(thr));
  7473. if (!mining_thr)
  7474. quit(1, "Failed to calloc mining_thr");
  7475. for (i = 0; i < mining_threads; i++) {
  7476. mining_thr[i] = calloc(1, sizeof(*thr));
  7477. if (!mining_thr[i])
  7478. quit(1, "Failed to calloc mining_thr[%d]", i);
  7479. }
  7480. total_control_threads = 7;
  7481. control_thr = calloc(total_control_threads, sizeof(*thr));
  7482. if (!control_thr)
  7483. quit(1, "Failed to calloc control_thr");
  7484. gwsched_thr_id = 0;
  7485. stage_thr_id = 1;
  7486. thr = &control_thr[stage_thr_id];
  7487. thr->q = tq_new();
  7488. if (!thr->q)
  7489. quit(1, "Failed to tq_new");
  7490. /* start stage thread */
  7491. if (thr_info_create(thr, NULL, stage_thread, thr))
  7492. quit(1, "stage thread create failed");
  7493. pthread_detach(thr->pth);
  7494. /* Create a unique get work queue */
  7495. getq = tq_new();
  7496. if (!getq)
  7497. quit(1, "Failed to create getq");
  7498. /* We use the getq mutex as the staged lock */
  7499. stgd_lock = &getq->mutex;
  7500. if (opt_benchmark)
  7501. goto begin_bench;
  7502. for (i = 0; i < total_pools; i++) {
  7503. struct pool *pool = pools[i];
  7504. enable_pool(pool);
  7505. pool->idle = true;
  7506. }
  7507. applog(LOG_NOTICE, "Probing for an alive pool");
  7508. do {
  7509. int slept = 0;
  7510. /* Look for at least one active pool before starting */
  7511. probe_pools();
  7512. do {
  7513. sleep(1);
  7514. slept++;
  7515. } while (!pools_active && slept < 60);
  7516. if (!pools_active) {
  7517. applog(LOG_ERR, "No servers were found that could be used to get work from.");
  7518. applog(LOG_ERR, "Please check the details from the list below of the servers you have input");
  7519. applog(LOG_ERR, "Most likely you have input the wrong URL, forgotten to add a port, or have not set up workers");
  7520. for (i = 0; i < total_pools; i++) {
  7521. struct pool *pool;
  7522. pool = pools[i];
  7523. applog(LOG_WARNING, "Pool: %d URL: %s User: %s Password: %s",
  7524. i, pool->rpc_url, pool->rpc_user, pool->rpc_pass);
  7525. }
  7526. #ifdef HAVE_CURSES
  7527. if (use_curses) {
  7528. halfdelay(150);
  7529. applog(LOG_ERR, "Press any key to exit, or BFGMiner will try again in 15s.");
  7530. if (getch() != ERR)
  7531. quit(0, "No servers could be used! Exiting.");
  7532. cbreak();
  7533. } else
  7534. #endif
  7535. quit(0, "No servers could be used! Exiting.");
  7536. }
  7537. } while (!pools_active);
  7538. #ifdef USE_SCRYPT
  7539. if (detect_algo == 1 && !opt_scrypt) {
  7540. applog(LOG_NOTICE, "Detected scrypt algorithm");
  7541. opt_scrypt = true;
  7542. }
  7543. #endif
  7544. detect_algo = 0;
  7545. begin_bench:
  7546. total_mhashes_done = 0;
  7547. for (i = 0; i < total_devices; i++) {
  7548. struct cgpu_info *cgpu = devices[i];
  7549. cgpu->rolling = cgpu->total_mhashes = 0;
  7550. }
  7551. gettimeofday(&total_tv_start, NULL);
  7552. gettimeofday(&total_tv_end, NULL);
  7553. miner_started = total_tv_start;
  7554. if (schedstart.tm.tm_sec)
  7555. localtime_r(&miner_started.tv_sec, &schedstart.tm);
  7556. if (schedstop.tm.tm_sec)
  7557. localtime_r(&miner_started.tv_sec, &schedstop .tm);
  7558. get_datestamp(datestamp, &total_tv_start);
  7559. // Initialise processors and threads
  7560. k = 0;
  7561. for (i = 0; i < total_devices; ++i) {
  7562. struct cgpu_info *cgpu = devices[i];
  7563. struct device_drv *api = cgpu->drv;
  7564. int threadobj = cgpu->threads;
  7565. if (!threadobj)
  7566. // Create a fake thread object to handle hashmeter etc
  7567. threadobj = 1;
  7568. cgpu->thr = calloc(threadobj + 1, sizeof(*cgpu->thr));
  7569. cgpu->thr[threadobj] = NULL;
  7570. cgpu->status = LIFE_INIT;
  7571. cgpu->max_hashes = 0;
  7572. // Setup thread structs before starting any of the threads, in case they try to interact
  7573. for (j = 0; j < threadobj; ++j, ++k) {
  7574. thr = get_thread(k);
  7575. thr->id = k;
  7576. thr->cgpu = cgpu;
  7577. thr->device_thread = j;
  7578. thr->work_restart_notifier[1] = INVSOCK;
  7579. thr->mutex_request[1] = INVSOCK;
  7580. thr->_job_transition_in_progress = true;
  7581. timerclear(&thr->tv_morework);
  7582. thr->_last_sbr_state = true;
  7583. thr->scanhash_working = true;
  7584. thr->hashes_done = 0;
  7585. timerclear(&thr->tv_hashes_done);
  7586. gettimeofday(&thr->tv_lastupdate, NULL);
  7587. thr->tv_poll.tv_sec = -1;
  7588. thr->_max_nonce = api->can_limit_work ? api->can_limit_work(thr) : 0xffffffff;
  7589. cgpu->thr[j] = thr;
  7590. }
  7591. }
  7592. // Start threads
  7593. for (i = 0; i < total_devices; ++i) {
  7594. struct cgpu_info *cgpu = devices[i];
  7595. if (!cgpu->threads)
  7596. memcpy(&cgpu->thr[0]->notifier, &cgpu->device->thr[0]->notifier, sizeof(cgpu->thr[0]->notifier));
  7597. for (j = 0; j < cgpu->threads; ++j) {
  7598. thr = cgpu->thr[j];
  7599. notifier_init(thr->notifier);
  7600. /* Enable threads for devices set not to mine but disable
  7601. * their queue in case we wish to enable them later */
  7602. if (cgpu->drv->thread_prepare && !cgpu->drv->thread_prepare(thr))
  7603. continue;
  7604. thread_reportout(thr);
  7605. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  7606. quit(1, "thread %d create failed", thr->id);
  7607. }
  7608. if (cgpu->deven == DEV_ENABLED)
  7609. proc_enable(cgpu);
  7610. }
  7611. #ifdef HAVE_OPENCL
  7612. applog(LOG_INFO, "%d gpu miner threads started", gpu_threads);
  7613. for (i = 0; i < nDevs; i++)
  7614. pause_dynamic_threads(i);
  7615. #endif
  7616. #ifdef WANT_CPUMINE
  7617. applog(LOG_INFO, "%d cpu miner threads started, "
  7618. "using SHA256 '%s' algorithm.",
  7619. opt_n_threads,
  7620. algo_names[opt_algo]);
  7621. #endif
  7622. gettimeofday(&total_tv_start, NULL);
  7623. gettimeofday(&total_tv_end, NULL);
  7624. {
  7625. pthread_t submit_thread;
  7626. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, NULL)))
  7627. quit(1, "submit_work thread create failed");
  7628. }
  7629. watchpool_thr_id = 2;
  7630. thr = &control_thr[watchpool_thr_id];
  7631. /* start watchpool thread */
  7632. if (thr_info_create(thr, NULL, watchpool_thread, NULL))
  7633. quit(1, "watchpool thread create failed");
  7634. pthread_detach(thr->pth);
  7635. watchdog_thr_id = 3;
  7636. thr = &control_thr[watchdog_thr_id];
  7637. /* start watchdog thread */
  7638. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  7639. quit(1, "watchdog thread create failed");
  7640. pthread_detach(thr->pth);
  7641. #ifdef HAVE_OPENCL
  7642. /* Create reinit gpu thread */
  7643. gpur_thr_id = 4;
  7644. thr = &control_thr[gpur_thr_id];
  7645. thr->q = tq_new();
  7646. if (!thr->q)
  7647. quit(1, "tq_new failed for gpur_thr_id");
  7648. if (thr_info_create(thr, NULL, reinit_gpu, thr))
  7649. quit(1, "reinit_gpu thread create failed");
  7650. #endif
  7651. /* Create API socket thread */
  7652. api_thr_id = 5;
  7653. thr = &control_thr[api_thr_id];
  7654. if (thr_info_create(thr, NULL, api_thread, thr))
  7655. quit(1, "API thread create failed");
  7656. #ifdef HAVE_CURSES
  7657. /* Create curses input thread for keyboard input. Create this last so
  7658. * that we know all threads are created since this can call kill_work
  7659. * to try and shut down ll previous threads. */
  7660. input_thr_id = 6;
  7661. thr = &control_thr[input_thr_id];
  7662. if (thr_info_create(thr, NULL, input_thread, thr))
  7663. quit(1, "input thread create failed");
  7664. pthread_detach(thr->pth);
  7665. #endif
  7666. /* Just to be sure */
  7667. if (total_control_threads != 7)
  7668. quit(1, "incorrect total_control_threads (%d) should be 7", total_control_threads);
  7669. /* Once everything is set up, main() becomes the getwork scheduler */
  7670. while (42) {
  7671. int ts, max_staged = opt_queue;
  7672. struct pool *pool, *cp;
  7673. bool lagging = false;
  7674. struct curl_ent *ce;
  7675. struct work *work;
  7676. cp = current_pool();
  7677. /* If the primary pool is a getwork pool and cannot roll work,
  7678. * try to stage one extra work per mining thread */
  7679. if (!cp->has_stratum && cp->proto != PLP_GETBLOCKTEMPLATE && !staged_rollable)
  7680. max_staged += mining_threads;
  7681. mutex_lock(stgd_lock);
  7682. ts = __total_staged();
  7683. if (!cp->has_stratum && cp->proto != PLP_GETBLOCKTEMPLATE && !ts && !opt_fail_only)
  7684. lagging = true;
  7685. /* Wait until hash_pop tells us we need to create more work */
  7686. if (ts > max_staged) {
  7687. pthread_cond_wait(&gws_cond, stgd_lock);
  7688. ts = __total_staged();
  7689. }
  7690. mutex_unlock(stgd_lock);
  7691. if (ts > max_staged)
  7692. continue;
  7693. work = make_work();
  7694. if (lagging && !pool_tset(cp, &cp->lagging)) {
  7695. applog(LOG_WARNING, "Pool %d not providing work fast enough", cp->pool_no);
  7696. cp->getfail_occasions++;
  7697. total_go++;
  7698. }
  7699. pool = select_pool(lagging);
  7700. retry:
  7701. if (pool->has_stratum) {
  7702. while (!pool->stratum_active || !pool->stratum_notify) {
  7703. struct pool *altpool = select_pool(true);
  7704. if (altpool == pool && pool->has_stratum)
  7705. nmsleep(5000);
  7706. pool = altpool;
  7707. goto retry;
  7708. }
  7709. gen_stratum_work(pool, work);
  7710. applog(LOG_DEBUG, "Generated stratum work");
  7711. stage_work(work);
  7712. continue;
  7713. }
  7714. if (pool->last_work_copy) {
  7715. mutex_lock(&pool->last_work_lock);
  7716. struct work *last_work = pool->last_work_copy;
  7717. if (!last_work)
  7718. {}
  7719. else
  7720. if (can_roll(last_work) && should_roll(last_work)) {
  7721. free_work(work);
  7722. work = make_clone(pool->last_work_copy);
  7723. mutex_unlock(&pool->last_work_lock);
  7724. roll_work(work);
  7725. 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)));
  7726. stage_work(work);
  7727. continue;
  7728. } else if (last_work->tmpl && pool->proto == PLP_GETBLOCKTEMPLATE && blkmk_work_left(last_work->tmpl) > (unsigned long)mining_threads) {
  7729. // Don't free last_work_copy, since it is used to detect upstream provides plenty of work per template
  7730. } else {
  7731. free_work(last_work);
  7732. pool->last_work_copy = NULL;
  7733. }
  7734. mutex_unlock(&pool->last_work_lock);
  7735. }
  7736. if (clone_available()) {
  7737. applog(LOG_DEBUG, "Cloned getwork work");
  7738. free_work(work);
  7739. continue;
  7740. }
  7741. if (opt_benchmark) {
  7742. get_benchmark_work(work);
  7743. applog(LOG_DEBUG, "Generated benchmark work");
  7744. stage_work(work);
  7745. continue;
  7746. }
  7747. work->pool = pool;
  7748. ce = pop_curl_entry3(pool, 2);
  7749. /* obtain new work from bitcoin via JSON-RPC */
  7750. if (!get_upstream_work(work, ce->curl)) {
  7751. struct pool *next_pool;
  7752. /* Make sure the pool just hasn't stopped serving
  7753. * requests but is up as we'll keep hammering it */
  7754. push_curl_entry(ce, pool);
  7755. ++pool->seq_getfails;
  7756. pool_died(pool);
  7757. next_pool = select_pool(!opt_fail_only);
  7758. if (pool == next_pool) {
  7759. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, retrying in 5s", pool->pool_no);
  7760. nmsleep(5000);
  7761. } else {
  7762. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, failover activated", pool->pool_no);
  7763. pool = next_pool;
  7764. }
  7765. goto retry;
  7766. }
  7767. if (ts >= max_staged)
  7768. pool_tclear(pool, &pool->lagging);
  7769. if (pool_tclear(pool, &pool->idle))
  7770. pool_resus(pool);
  7771. applog(LOG_DEBUG, "Generated getwork work");
  7772. stage_work(work);
  7773. push_curl_entry(ce, pool);
  7774. }
  7775. return 0;
  7776. }