miner.c 233 KB

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