miner.c 199 KB

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