miner.c 217 KB

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