miner.c 239 KB

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