miner.c 161 KB

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