miner.c 183 KB

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