miner.c 179 KB

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