miner.c 160 KB

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