miner.c 277 KB

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