miner.c 220 KB

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