miner.c 162 KB

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