miner.c 179 KB

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