miner.c 181 KB

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