miner.c 280 KB

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