miner.c 255 KB

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