miner.c 278 KB

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