miner.c 227 KB

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