miner.c 163 KB

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