miner.c 160 KB

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