miner.c 235 KB

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