miner.c 180 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998
  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->status == LIFE_WAIT)
  1738. wprintw(statuswin, "WAIT ");
  1739. else if (cgpu->deven == DEV_DISABLED)
  1740. wprintw(statuswin, "OFF ");
  1741. else if (cgpu->deven == DEV_RECOVER)
  1742. wprintw(statuswin, "REST ");
  1743. else
  1744. wprintw(statuswin, "%s", cHr);
  1745. adj_width(cgpu->accepted, &awidth);
  1746. adj_width(cgpu->rejected, &rwidth);
  1747. adj_width(cgpu->hw_errors, &hwwidth);
  1748. adj_width(cgpu->utility, &uwidth);
  1749. wprintw(statuswin, "/%s/%s | A:%*d R:%*d HW:%*d U:%*.2f/m",
  1750. aHr,
  1751. uHr,
  1752. awidth, cgpu->accepted,
  1753. rwidth, cgpu->rejected,
  1754. hwwidth, cgpu->hw_errors,
  1755. uwidth + 3, cgpu->utility);
  1756. if (cgpu->api->get_statline) {
  1757. logline[0] = '\0';
  1758. cgpu->api->get_statline(logline, cgpu);
  1759. wprintw(statuswin, "%s", logline);
  1760. }
  1761. wclrtoeol(statuswin);
  1762. }
  1763. #endif
  1764. static void print_status(int thr_id)
  1765. {
  1766. if (!curses_active)
  1767. text_print_status(thr_id);
  1768. }
  1769. #ifdef HAVE_CURSES
  1770. /* Check for window resize. Called with curses mutex locked */
  1771. static inline bool change_logwinsize(void)
  1772. {
  1773. int x, y, logx, logy;
  1774. bool ret = false;
  1775. getmaxyx(mainwin, y, x);
  1776. if (x < 80 || y < 25)
  1777. return ret;
  1778. if (y > statusy + 2 && statusy < logstart) {
  1779. if (y - 2 < logstart)
  1780. statusy = y - 2;
  1781. else
  1782. statusy = logstart;
  1783. logcursor = statusy + 1;
  1784. mvwin(logwin, logcursor, 0);
  1785. wresize(statuswin, statusy, x);
  1786. ret = true;
  1787. }
  1788. y -= logcursor;
  1789. getmaxyx(logwin, logy, logx);
  1790. /* Detect screen size change */
  1791. if (x != logx || y != logy) {
  1792. wresize(logwin, y, x);
  1793. ret = true;
  1794. }
  1795. return ret;
  1796. }
  1797. static void check_winsizes(void)
  1798. {
  1799. if (!use_curses)
  1800. return;
  1801. if (curses_active_locked()) {
  1802. int y, x;
  1803. x = getmaxx(statuswin);
  1804. if (logstart > LINES - 2)
  1805. statusy = LINES - 2;
  1806. else
  1807. statusy = logstart;
  1808. logcursor = statusy + 1;
  1809. wresize(statuswin, statusy, x);
  1810. getmaxyx(mainwin, y, x);
  1811. y -= logcursor;
  1812. wresize(logwin, y, x);
  1813. mvwin(logwin, logcursor, 0);
  1814. unlock_curses();
  1815. }
  1816. }
  1817. /* For mandatory printing when mutex is already locked */
  1818. void wlog(const char *f, ...)
  1819. {
  1820. va_list ap;
  1821. va_start(ap, f);
  1822. vw_printw(logwin, f, ap);
  1823. va_end(ap);
  1824. }
  1825. /* Mandatory printing */
  1826. void wlogprint(const char *f, ...)
  1827. {
  1828. va_list ap;
  1829. if (curses_active_locked()) {
  1830. va_start(ap, f);
  1831. vw_printw(logwin, f, ap);
  1832. va_end(ap);
  1833. unlock_curses();
  1834. }
  1835. }
  1836. #endif
  1837. #ifdef HAVE_CURSES
  1838. bool log_curses_only(int prio, const char *f, va_list ap)
  1839. {
  1840. bool high_prio;
  1841. high_prio = (prio == LOG_WARNING || prio == LOG_ERR);
  1842. if (curses_active_locked()) {
  1843. if (!opt_loginput || high_prio) {
  1844. vw_printw(logwin, f, ap);
  1845. if (high_prio) {
  1846. touchwin(logwin);
  1847. wrefresh(logwin);
  1848. }
  1849. }
  1850. unlock_curses();
  1851. return true;
  1852. }
  1853. return false;
  1854. }
  1855. void clear_logwin(void)
  1856. {
  1857. if (curses_active_locked()) {
  1858. wclear(logwin);
  1859. unlock_curses();
  1860. }
  1861. }
  1862. #endif
  1863. /* regenerate the full work->hash value and also return true if it's a block */
  1864. bool regeneratehash(const struct work *work)
  1865. {
  1866. uint32_t *data32 = (uint32_t *)(work->data);
  1867. unsigned char swap[128];
  1868. uint32_t *swap32 = (uint32_t *)swap;
  1869. unsigned char hash1[32];
  1870. uint32_t *hash32 = (uint32_t *)(work->hash);
  1871. uint32_t difficulty = 0;
  1872. uint32_t diffbytes = 0;
  1873. uint32_t diffvalue = 0;
  1874. uint32_t diffcmp[8];
  1875. int diffshift = 0;
  1876. int i;
  1877. swap32yes(swap32, data32, 80 / 4);
  1878. sha2(swap, 80, hash1, false);
  1879. sha2(hash1, 32, (unsigned char *)(work->hash), false);
  1880. difficulty = be32toh(*((uint32_t *)(work->data + 72)));
  1881. diffbytes = ((difficulty >> 24) & 0xff) - 3;
  1882. diffvalue = difficulty & 0x00ffffff;
  1883. diffshift = (diffbytes % 4) * 8;
  1884. if (diffshift == 0) {
  1885. diffshift = 32;
  1886. diffbytes--;
  1887. }
  1888. memset(diffcmp, 0, 32);
  1889. diffcmp[(diffbytes >> 2) + 1] = diffvalue >> (32 - diffshift);
  1890. diffcmp[diffbytes >> 2] = diffvalue << diffshift;
  1891. for (i = 7; i >= 0; i--) {
  1892. uint32_t hash32i = be32toh(hash32[i]);
  1893. if (hash32i > diffcmp[i])
  1894. return false;
  1895. if (hash32i < diffcmp[i])
  1896. return true;
  1897. }
  1898. // https://en.bitcoin.it/wiki/Block says: "numerically below"
  1899. // https://en.bitcoin.it/wiki/Target says: "lower than or equal to"
  1900. // code in bitcoind 0.3.24 main.cpp CheckWork() says: if (hash > hashTarget) return false;
  1901. return true;
  1902. }
  1903. static void enable_pool(struct pool *pool)
  1904. {
  1905. if (pool->enabled != POOL_ENABLED) {
  1906. enabled_pools++;
  1907. pool->enabled = POOL_ENABLED;
  1908. }
  1909. }
  1910. static void disable_pool(struct pool *pool)
  1911. {
  1912. if (pool->enabled == POOL_ENABLED)
  1913. enabled_pools--;
  1914. pool->enabled = POOL_DISABLED;
  1915. }
  1916. static void reject_pool(struct pool *pool)
  1917. {
  1918. if (pool->enabled == POOL_ENABLED)
  1919. enabled_pools--;
  1920. pool->enabled = POOL_REJECTING;
  1921. }
  1922. static bool submit_upstream_work(const struct work *work, CURL *curl, bool resubmit)
  1923. {
  1924. char *hexstr = NULL;
  1925. json_t *val, *res;
  1926. char *s, *sd;
  1927. bool rc = false;
  1928. int thr_id = work->thr_id;
  1929. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  1930. struct pool *pool = work->pool;
  1931. int rolltime;
  1932. uint32_t *hash32;
  1933. struct timeval tv_submit, tv_submit_reply;
  1934. char hashshow[64+1] = "";
  1935. char worktime[200] = "";
  1936. if (work->tmpl) {
  1937. unsigned char data[76];
  1938. swap32yes(data, work->data, 76);
  1939. json_t *req = blkmk_submit_jansson(work->tmpl, data, work->dataid, *((uint32_t*)&work->data[76]));
  1940. s = json_dumps(req, 0);
  1941. sd = bin2hex(data, 80);
  1942. } else {
  1943. s = malloc(345);
  1944. sd = malloc(345);
  1945. /* build hex string */
  1946. hexstr = bin2hex(work->data, sizeof(work->data));
  1947. if (unlikely(!hexstr)) {
  1948. applog(LOG_ERR, "submit_upstream_work OOM");
  1949. goto out_nofree;
  1950. }
  1951. /* build JSON-RPC request */
  1952. sprintf(s,
  1953. "{\"method\": \"getwork\", \"params\": [ \"%s\" ], \"id\":1}\r\n",
  1954. hexstr);
  1955. sprintf(sd,
  1956. "{\"method\": \"getwork\", \"params\": [ \"%s\" ], \"id\":1}",
  1957. hexstr);
  1958. }
  1959. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->rpc_url, sd);
  1960. gettimeofday(&tv_submit, NULL);
  1961. /* issue JSON-RPC request */
  1962. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, s, false, false, &rolltime, pool, true);
  1963. free(s);
  1964. free(sd);
  1965. gettimeofday(&tv_submit_reply, NULL);
  1966. if (unlikely(!val)) {
  1967. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  1968. if (!pool_tset(pool, &pool->submit_fail)) {
  1969. total_ro++;
  1970. pool->remotefail_occasions++;
  1971. applog(LOG_WARNING, "Pool %d communication failure, caching submissions", pool->pool_no);
  1972. }
  1973. goto out;
  1974. } else if (pool_tclear(pool, &pool->submit_fail))
  1975. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  1976. res = json_object_get(val, "result");
  1977. if (!QUIET) {
  1978. hash32 = (uint32_t *)(work->hash);
  1979. if (opt_scrypt)
  1980. sprintf(hashshow, "%08lx.%08lx", (unsigned long)(hash32[7]), (unsigned long)(hash32[6]));
  1981. else {
  1982. int intdiff = round(work->work_difficulty);
  1983. sprintf(hashshow, "%08lx Diff %d%s", (unsigned long)(hash32[6]), intdiff,
  1984. work->block? " BLOCK!" : "");
  1985. }
  1986. if (opt_worktime) {
  1987. char workclone[20];
  1988. struct tm *tm, tm_getwork, tm_submit_reply;
  1989. double getwork_time = tdiff((struct timeval *)&(work->tv_getwork_reply),
  1990. (struct timeval *)&(work->tv_getwork));
  1991. double getwork_to_work = tdiff((struct timeval *)&(work->tv_work_start),
  1992. (struct timeval *)&(work->tv_getwork_reply));
  1993. double work_time = tdiff((struct timeval *)&(work->tv_work_found),
  1994. (struct timeval *)&(work->tv_work_start));
  1995. double work_to_submit = tdiff(&tv_submit,
  1996. (struct timeval *)&(work->tv_work_found));
  1997. double submit_time = tdiff(&tv_submit_reply, &tv_submit);
  1998. int diffplaces = 3;
  1999. tm = localtime(&(work->tv_getwork.tv_sec));
  2000. memcpy(&tm_getwork, tm, sizeof(struct tm));
  2001. tm = localtime(&(tv_submit_reply.tv_sec));
  2002. memcpy(&tm_submit_reply, tm, sizeof(struct tm));
  2003. if (work->clone) {
  2004. sprintf(workclone, "C:%1.3f",
  2005. tdiff((struct timeval *)&(work->tv_cloned),
  2006. (struct timeval *)&(work->tv_getwork_reply)));
  2007. }
  2008. else
  2009. strcpy(workclone, "O");
  2010. if (work->work_difficulty < 1)
  2011. diffplaces = 6;
  2012. 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",
  2013. (unsigned long)swab32(*(uint32_t *)&(work->data[opt_scrypt ? 32 : 28])),
  2014. (unsigned long)swab32(*(uint32_t *)&(work->data[opt_scrypt ? 28 : 24])),
  2015. work->getwork_mode, diffplaces, work->work_difficulty,
  2016. tm_getwork.tm_hour, tm_getwork.tm_min,
  2017. tm_getwork.tm_sec, getwork_time, workclone,
  2018. getwork_to_work, work_time, work_to_submit, submit_time,
  2019. tm_submit_reply.tm_hour, tm_submit_reply.tm_min,
  2020. tm_submit_reply.tm_sec);
  2021. }
  2022. }
  2023. /* Theoretically threads could race when modifying accepted and
  2024. * rejected values but the chance of two submits completing at the
  2025. * same time is zero so there is no point adding extra locking */
  2026. if (json_is_null(res) || json_is_true(res)) {
  2027. cgpu->accepted++;
  2028. cgpu->accepted_weighed += work->work_difficulty;
  2029. total_accepted++;
  2030. total_accepted_weighed += work->work_difficulty;
  2031. pool->accepted++;
  2032. cgpu->diff_accepted += work->work_difficulty;
  2033. total_diff_accepted += work->work_difficulty;
  2034. pool->diff_accepted += work->work_difficulty;
  2035. pool->seq_rejects = 0;
  2036. cgpu->last_share_pool = pool->pool_no;
  2037. cgpu->last_share_pool_time = time(NULL);
  2038. cgpu->last_share_diff = work->work_difficulty;
  2039. pool->last_share_time = cgpu->last_share_pool_time;
  2040. pool->last_share_diff = work->work_difficulty;
  2041. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  2042. if (!QUIET) {
  2043. if (total_pools > 1)
  2044. applog(LOG_NOTICE, "Accepted %s %s %d pool %d %s%s",
  2045. hashshow, cgpu->api->name, cgpu->device_id, work->pool->pool_no, resubmit ? "(resubmit)" : "", worktime);
  2046. else
  2047. applog(LOG_NOTICE, "Accepted %s %s %d %s%s",
  2048. hashshow, cgpu->api->name, cgpu->device_id, resubmit ? "(resubmit)" : "", worktime);
  2049. }
  2050. sharelog("accept", work);
  2051. if (opt_shares && total_accepted >= opt_shares) {
  2052. applog(LOG_WARNING, "Successfully mined %d accepted shares as requested and exiting.", opt_shares);
  2053. kill_work();
  2054. goto out;
  2055. }
  2056. /* Detect if a pool that has been temporarily disabled for
  2057. * continually rejecting shares has started accepting shares.
  2058. * This will only happen with the work returned from a
  2059. * longpoll */
  2060. if (unlikely(pool->enabled == POOL_REJECTING)) {
  2061. applog(LOG_WARNING, "Rejecting pool %d now accepting shares, re-enabling!", pool->pool_no);
  2062. enable_pool(pool);
  2063. switch_pools(NULL);
  2064. }
  2065. } else {
  2066. cgpu->rejected++;
  2067. total_rejected++;
  2068. pool->rejected++;
  2069. cgpu->diff_rejected += work->work_difficulty;
  2070. total_diff_rejected += work->work_difficulty;
  2071. pool->diff_rejected += work->work_difficulty;
  2072. pool->seq_rejects++;
  2073. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  2074. if (!QUIET) {
  2075. char where[17];
  2076. char disposition[36] = "reject";
  2077. char reason[32];
  2078. if (total_pools > 1)
  2079. sprintf(where, "pool %d", work->pool->pool_no);
  2080. else
  2081. strcpy(where, "");
  2082. if (!json_is_string(res))
  2083. res = json_object_get(val, "reject-reason");
  2084. if (res) {
  2085. const char *reasontmp = json_string_value(res);
  2086. size_t reasonLen = strlen(reasontmp);
  2087. if (reasonLen > 28)
  2088. reasonLen = 28;
  2089. reason[0] = ' '; reason[1] = '(';
  2090. memcpy(2 + reason, reasontmp, reasonLen);
  2091. reason[reasonLen + 2] = ')'; reason[reasonLen + 3] = '\0';
  2092. memcpy(disposition + 7, reasontmp, reasonLen);
  2093. disposition[6] = ':'; disposition[reasonLen + 7] = '\0';
  2094. } else
  2095. strcpy(reason, "");
  2096. applog(LOG_NOTICE, "Rejected %s %s %d %s%s %s%s",
  2097. hashshow, cgpu->api->name, cgpu->device_id, where, reason, resubmit ? "(resubmit)" : "", worktime);
  2098. sharelog(disposition, work);
  2099. }
  2100. /* Once we have more than a nominal amount of sequential rejects,
  2101. * at least 10 and more than 3 mins at the current utility,
  2102. * disable the pool because some pool error is likely to have
  2103. * ensued. Do not do this if we know the share just happened to
  2104. * be stale due to networking delays.
  2105. */
  2106. if (pool->seq_rejects > 10 && !work->stale && opt_disable_pool && enabled_pools > 1) {
  2107. double utility = total_accepted / total_secs * 60;
  2108. if (pool->seq_rejects > utility * 3) {
  2109. applog(LOG_WARNING, "Pool %d rejected %d sequential shares, disabling!",
  2110. pool->pool_no, pool->seq_rejects);
  2111. reject_pool(pool);
  2112. if (pool == current_pool())
  2113. switch_pools(NULL);
  2114. pool->seq_rejects = 0;
  2115. }
  2116. }
  2117. }
  2118. cgpu->utility = cgpu->accepted / total_secs * 60;
  2119. cgpu->utility_diff1 = cgpu->accepted_weighed / total_secs * 60;
  2120. if (!opt_realquiet)
  2121. print_status(thr_id);
  2122. if (!want_per_device_stats) {
  2123. char logline[255];
  2124. get_statline(logline, cgpu);
  2125. applog(LOG_INFO, "%s", logline);
  2126. }
  2127. json_decref(val);
  2128. rc = true;
  2129. out:
  2130. free(hexstr);
  2131. out_nofree:
  2132. return rc;
  2133. }
  2134. static const char *getwork_rpc_req =
  2135. "{\"method\": \"getwork\", \"params\": [], \"id\":0}\r\n";
  2136. /* In balanced mode, the amount of diff1 solutions per pool is monitored as a
  2137. * rolling average per 10 minutes and if pools start getting more, it biases
  2138. * away from them to distribute work evenly. The share count is reset to the
  2139. * rolling average every 10 minutes to not send all work to one pool after it
  2140. * has been disabled/out for an extended period. */
  2141. static struct pool *select_balanced(struct pool *cp)
  2142. {
  2143. int i, lowest = cp->shares;
  2144. struct pool *ret = cp;
  2145. for (i = 0; i < total_pools; i++) {
  2146. struct pool *pool = pools[i];
  2147. if (pool->idle || pool->enabled != POOL_ENABLED)
  2148. continue;
  2149. if (pool->shares < lowest) {
  2150. lowest = pool->shares;
  2151. ret = pool;
  2152. }
  2153. }
  2154. ret->shares++;
  2155. return ret;
  2156. }
  2157. /* Select any active pool in a rotating fashion when loadbalance is chosen */
  2158. static inline struct pool *select_pool(bool lagging)
  2159. {
  2160. static int rotating_pool = 0;
  2161. struct pool *pool, *cp;
  2162. cp = current_pool();
  2163. if (pool_strategy == POOL_BALANCE)
  2164. return select_balanced(cp);
  2165. if (pool_strategy != POOL_LOADBALANCE && (!lagging || opt_fail_only))
  2166. pool = cp;
  2167. else
  2168. pool = NULL;
  2169. while (!pool) {
  2170. if (++rotating_pool >= total_pools)
  2171. rotating_pool = 0;
  2172. pool = pools[rotating_pool];
  2173. if ((!pool->idle && pool->enabled == POOL_ENABLED) || pool == cp)
  2174. break;
  2175. pool = NULL;
  2176. }
  2177. return pool;
  2178. }
  2179. static double DIFFEXACTONE = 26959946667150639794667015087019630673637144422540572481103610249216.0;
  2180. /*
  2181. * Calculate the work share difficulty
  2182. */
  2183. static void calc_diff(struct work *work)
  2184. {
  2185. struct cgminer_pool_stats *pool_stats = &(work->pool->cgminer_pool_stats);
  2186. double targ;
  2187. int i;
  2188. targ = 0;
  2189. for (i = 31; i >= 0; i--) {
  2190. targ *= 256;
  2191. targ += work->target[i];
  2192. }
  2193. work->work_difficulty = DIFFEXACTONE / (targ ? : DIFFEXACTONE);
  2194. pool_stats->last_diff = work->work_difficulty;
  2195. if (work->work_difficulty == pool_stats->min_diff)
  2196. pool_stats->min_diff_count++;
  2197. else if (work->work_difficulty < pool_stats->min_diff || pool_stats->min_diff == 0) {
  2198. pool_stats->min_diff = work->work_difficulty;
  2199. pool_stats->min_diff_count = 1;
  2200. }
  2201. if (work->work_difficulty == pool_stats->max_diff)
  2202. pool_stats->max_diff_count++;
  2203. else if (work->work_difficulty > pool_stats->max_diff) {
  2204. pool_stats->max_diff = work->work_difficulty;
  2205. pool_stats->max_diff_count = 1;
  2206. }
  2207. }
  2208. static void get_benchmark_work(struct work *work)
  2209. {
  2210. // Use a random work block pulled from a pool
  2211. static uint8_t bench_block[] = { CGMINER_BENCHMARK_BLOCK };
  2212. size_t bench_size = sizeof(work);
  2213. size_t work_size = sizeof(bench_block);
  2214. size_t min_size = (work_size < bench_size ? work_size : bench_size);
  2215. memset(work, 0, sizeof(work));
  2216. memcpy(work, &bench_block, min_size);
  2217. work->mandatory = true;
  2218. work->pool = pools[0];
  2219. gettimeofday(&(work->tv_getwork), NULL);
  2220. memcpy(&(work->tv_getwork_reply), &(work->tv_getwork), sizeof(struct timeval));
  2221. work->getwork_mode = GETWORK_MODE_BENCHMARK;
  2222. calc_diff(work);
  2223. }
  2224. static char *prepare_rpc_req(struct work *work, enum pool_protocol proto, const char *lpid)
  2225. {
  2226. char *rpc_req;
  2227. switch (proto) {
  2228. case PLP_GETWORK:
  2229. work->tmpl = NULL;
  2230. return strdup(getwork_rpc_req);
  2231. case PLP_GETBLOCKTEMPLATE:
  2232. work->tmpl_refcount = malloc(sizeof(*work->tmpl_refcount));
  2233. if (!work->tmpl_refcount)
  2234. return NULL;
  2235. work->tmpl = blktmpl_create();
  2236. if (!work->tmpl)
  2237. goto gbtfail2;
  2238. *work->tmpl_refcount = 1;
  2239. gbt_capabilities_t caps = blktmpl_addcaps(work->tmpl);
  2240. if (!caps)
  2241. goto gbtfail;
  2242. caps |= GBT_LONGPOLL;
  2243. json_t *req = blktmpl_request_jansson(caps, lpid);
  2244. if (!req)
  2245. goto gbtfail;
  2246. rpc_req = json_dumps(req, 0);
  2247. if (!rpc_req)
  2248. goto gbtfail;
  2249. json_decref(req);
  2250. return rpc_req;
  2251. default:
  2252. return NULL;
  2253. }
  2254. return NULL;
  2255. gbtfail:
  2256. blktmpl_free(work->tmpl);
  2257. work->tmpl = NULL;
  2258. gbtfail2:
  2259. free(work->tmpl_refcount);
  2260. work->tmpl_refcount = NULL;
  2261. return NULL;
  2262. }
  2263. static const char *pool_protocol_name(enum pool_protocol proto)
  2264. {
  2265. switch (proto) {
  2266. case PLP_GETBLOCKTEMPLATE:
  2267. return "getblocktemplate";
  2268. case PLP_GETWORK:
  2269. return "getwork";
  2270. default:
  2271. return "UNKNOWN";
  2272. }
  2273. }
  2274. static enum pool_protocol pool_protocol_fallback(enum pool_protocol proto)
  2275. {
  2276. switch (proto) {
  2277. case PLP_GETBLOCKTEMPLATE:
  2278. return PLP_GETWORK;
  2279. default:
  2280. return PLP_NONE;
  2281. }
  2282. }
  2283. static bool get_upstream_work(struct work *work, CURL *curl)
  2284. {
  2285. struct pool *pool = work->pool;
  2286. struct cgminer_pool_stats *pool_stats = &(pool->cgminer_pool_stats);
  2287. struct timeval tv_elapsed;
  2288. json_t *val = NULL;
  2289. bool rc = false;
  2290. char *url;
  2291. enum pool_protocol proto;
  2292. char *rpc_req;
  2293. tryagain:
  2294. rpc_req = prepare_rpc_req(work, pool->proto, NULL);
  2295. if (!rpc_req)
  2296. return false;
  2297. applog(LOG_DEBUG, "DBG: sending %s get RPC call: %s", pool->rpc_url, rpc_req);
  2298. url = pool->rpc_url;
  2299. gettimeofday(&(work->tv_getwork), NULL);
  2300. val = json_rpc_call(curl, url, pool->rpc_userpass, rpc_req, false,
  2301. false, &work->rolltime, pool, false);
  2302. pool_stats->getwork_attempts++;
  2303. free(rpc_req);
  2304. if (likely(val)) {
  2305. rc = work_decode(json_object_get(val, "result"), work);
  2306. if (unlikely(!rc))
  2307. applog(LOG_DEBUG, "Failed to decode work in get_upstream_work");
  2308. } else if (PLP_NONE != (proto = pool_protocol_fallback(pool->proto))) {
  2309. applog(LOG_WARNING, "Pool %u failed getblocktemplate request; falling back to getwork protocol", pool->pool_no);
  2310. pool->proto = proto;
  2311. goto tryagain;
  2312. } else
  2313. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  2314. gettimeofday(&(work->tv_getwork_reply), NULL);
  2315. timersub(&(work->tv_getwork_reply), &(work->tv_getwork), &tv_elapsed);
  2316. pool_stats->getwork_wait_rolling += ((double)tv_elapsed.tv_sec + ((double)tv_elapsed.tv_usec / 1000000)) * 0.63;
  2317. pool_stats->getwork_wait_rolling /= 1.63;
  2318. timeradd(&tv_elapsed, &(pool_stats->getwork_wait), &(pool_stats->getwork_wait));
  2319. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_max), >)) {
  2320. pool_stats->getwork_wait_max.tv_sec = tv_elapsed.tv_sec;
  2321. pool_stats->getwork_wait_max.tv_usec = tv_elapsed.tv_usec;
  2322. }
  2323. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_min), <)) {
  2324. pool_stats->getwork_wait_min.tv_sec = tv_elapsed.tv_sec;
  2325. pool_stats->getwork_wait_min.tv_usec = tv_elapsed.tv_usec;
  2326. }
  2327. pool_stats->getwork_calls++;
  2328. work->pool = pool;
  2329. work->longpoll = false;
  2330. work->getwork_mode = GETWORK_MODE_POOL;
  2331. calc_diff(work);
  2332. total_getworks++;
  2333. pool->getwork_requested++;
  2334. if (likely(val))
  2335. json_decref(val);
  2336. return rc;
  2337. }
  2338. static struct work *make_work(void)
  2339. {
  2340. struct work *work = calloc(1, sizeof(struct work));
  2341. if (unlikely(!work))
  2342. quit(1, "Failed to calloc work in make_work");
  2343. mutex_lock(&control_lock);
  2344. work->id = total_work++;
  2345. mutex_unlock(&control_lock);
  2346. return work;
  2347. }
  2348. static void free_work(struct work *work)
  2349. {
  2350. if (work->tmpl) {
  2351. struct pool *pool = work->pool;
  2352. mutex_lock(&pool->pool_lock);
  2353. bool free_tmpl = !--*work->tmpl_refcount;
  2354. mutex_unlock(&pool->pool_lock);
  2355. if (free_tmpl) {
  2356. blktmpl_free(work->tmpl);
  2357. free(work->tmpl_refcount);
  2358. }
  2359. }
  2360. free(work);
  2361. }
  2362. static void workio_cmd_free(struct workio_cmd *wc)
  2363. {
  2364. if (!wc)
  2365. return;
  2366. switch (wc->cmd) {
  2367. case WC_SUBMIT_WORK:
  2368. free_work(wc->work);
  2369. break;
  2370. default: /* do nothing */
  2371. break;
  2372. }
  2373. memset(wc, 0, sizeof(*wc)); /* poison */
  2374. free(wc);
  2375. }
  2376. #ifdef HAVE_CURSES
  2377. static void disable_curses(void)
  2378. {
  2379. if (curses_active_locked()) {
  2380. curses_active = false;
  2381. leaveok(logwin, false);
  2382. leaveok(statuswin, false);
  2383. leaveok(mainwin, false);
  2384. nocbreak();
  2385. echo();
  2386. delwin(logwin);
  2387. delwin(statuswin);
  2388. delwin(mainwin);
  2389. endwin();
  2390. #ifdef WIN32
  2391. // Move the cursor to after curses output.
  2392. HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
  2393. CONSOLE_SCREEN_BUFFER_INFO csbi;
  2394. COORD coord;
  2395. if (GetConsoleScreenBufferInfo(hout, &csbi)) {
  2396. coord.X = 0;
  2397. coord.Y = csbi.dwSize.Y - 1;
  2398. SetConsoleCursorPosition(hout, coord);
  2399. }
  2400. #endif
  2401. unlock_curses();
  2402. }
  2403. }
  2404. #endif
  2405. static void print_summary(void);
  2406. static void __kill_work(void)
  2407. {
  2408. struct thr_info *thr;
  2409. int i;
  2410. if (!successful_connect)
  2411. return;
  2412. applog(LOG_INFO, "Received kill message");
  2413. applog(LOG_DEBUG, "Killing off watchpool thread");
  2414. /* Kill the watchpool thread */
  2415. thr = &thr_info[watchpool_thr_id];
  2416. thr_info_cancel(thr);
  2417. applog(LOG_DEBUG, "Killing off watchdog thread");
  2418. /* Kill the watchdog thread */
  2419. thr = &thr_info[watchdog_thr_id];
  2420. thr_info_cancel(thr);
  2421. applog(LOG_DEBUG, "Stopping mining threads");
  2422. /* Stop the mining threads*/
  2423. for (i = 0; i < mining_threads; i++) {
  2424. thr = &thr_info[i];
  2425. thr_info_freeze(thr);
  2426. thr->pause = true;
  2427. }
  2428. sleep(1);
  2429. applog(LOG_DEBUG, "Killing off mining threads");
  2430. /* Kill the mining threads*/
  2431. for (i = 0; i < mining_threads; i++) {
  2432. thr = &thr_info[i];
  2433. thr_info_cancel(thr);
  2434. }
  2435. applog(LOG_DEBUG, "Killing off stage thread");
  2436. /* Stop the others */
  2437. thr = &thr_info[stage_thr_id];
  2438. thr_info_cancel(thr);
  2439. applog(LOG_DEBUG, "Killing off API thread");
  2440. thr = &thr_info[api_thr_id];
  2441. thr_info_cancel(thr);
  2442. }
  2443. /* This should be the common exit path */
  2444. void kill_work(void)
  2445. {
  2446. __kill_work();
  2447. quit(0, "Shutdown signal received.");
  2448. }
  2449. static
  2450. #ifdef WIN32
  2451. const
  2452. #endif
  2453. char **initial_args;
  2454. static void clean_up(void);
  2455. void app_restart(void)
  2456. {
  2457. applog(LOG_WARNING, "Attempting to restart %s", packagename);
  2458. __kill_work();
  2459. clean_up();
  2460. #if defined(unix)
  2461. if (forkpid > 0) {
  2462. kill(forkpid, SIGTERM);
  2463. forkpid = 0;
  2464. }
  2465. #endif
  2466. execv(initial_args[0], initial_args);
  2467. applog(LOG_WARNING, "Failed to restart application");
  2468. }
  2469. static void sighandler(int __maybe_unused sig)
  2470. {
  2471. /* Restore signal handlers so we can still quit if kill_work fails */
  2472. sigaction(SIGTERM, &termhandler, NULL);
  2473. sigaction(SIGINT, &inthandler, NULL);
  2474. kill_work();
  2475. }
  2476. static void start_longpoll(void);
  2477. static void stop_longpoll(void);
  2478. /* Called with pool_lock held. Recruit an extra curl if none are available for
  2479. * this pool. */
  2480. static void recruit_curl(struct pool *pool)
  2481. {
  2482. struct curl_ent *ce = calloc(sizeof(struct curl_ent), 1);
  2483. ce->curl = curl_easy_init();
  2484. if (unlikely(!ce || !ce->curl))
  2485. quit(1, "Failed to init in recruit_curl");
  2486. list_add(&ce->node, &pool->curlring);
  2487. pool->curls++;
  2488. applog(LOG_DEBUG, "Recruited curl %d for pool %d", pool->curls, pool->pool_no);
  2489. }
  2490. /* Grab an available curl if there is one. If not, then recruit extra curls
  2491. * unless we are in a submit_fail situation, or we have opt_delaynet enabled
  2492. * and there are already 5 curls in circulation. Limit total number to the
  2493. * number of mining threads per pool as well to prevent blasting a pool during
  2494. * network delays/outages. */
  2495. static struct curl_ent *pop_curl_entry(struct pool *pool)
  2496. {
  2497. int curl_limit = opt_delaynet ? 5 : (mining_threads + opt_queue) * 2;
  2498. struct curl_ent *ce;
  2499. mutex_lock(&pool->pool_lock);
  2500. retry:
  2501. if (!pool->curls)
  2502. recruit_curl(pool);
  2503. else if (list_empty(&pool->curlring)) {
  2504. if (pool->curls >= curl_limit) {
  2505. pthread_cond_wait(&pool->cr_cond, &pool->pool_lock);
  2506. goto retry;
  2507. } else
  2508. recruit_curl(pool);
  2509. }
  2510. ce = list_entry(pool->curlring.next, struct curl_ent, node);
  2511. list_del(&ce->node);
  2512. mutex_unlock(&pool->pool_lock);
  2513. return ce;
  2514. }
  2515. static void push_curl_entry(struct curl_ent *ce, struct pool *pool)
  2516. {
  2517. mutex_lock(&pool->pool_lock);
  2518. if (!ce || !ce->curl)
  2519. quit(1, "Attempted to add NULL in push_curl_entry");
  2520. list_add_tail(&ce->node, &pool->curlring);
  2521. gettimeofday(&ce->tv, NULL);
  2522. pthread_cond_signal(&pool->cr_cond);
  2523. mutex_unlock(&pool->pool_lock);
  2524. }
  2525. /* This is overkill, but at least we'll know accurately how much work is
  2526. * queued to prevent ever being left without work */
  2527. static void inc_queued(struct pool *pool)
  2528. {
  2529. mutex_lock(&qd_lock);
  2530. total_queued++;
  2531. pool->queued++;
  2532. mutex_unlock(&qd_lock);
  2533. }
  2534. static void dec_queued(struct pool *pool)
  2535. {
  2536. mutex_lock(&qd_lock);
  2537. total_queued--;
  2538. pool->queued--;
  2539. mutex_unlock(&qd_lock);
  2540. }
  2541. static int __global_queued(void)
  2542. {
  2543. return total_queued;
  2544. }
  2545. static int global_queued(void)
  2546. {
  2547. int ret;
  2548. mutex_lock(&qd_lock);
  2549. ret = __global_queued();
  2550. mutex_unlock(&qd_lock);
  2551. return ret;
  2552. }
  2553. static bool stale_work(struct work *work, bool share);
  2554. static inline bool should_roll(struct work *work)
  2555. {
  2556. struct timeval now;
  2557. time_t expiry;
  2558. if (work->pool != current_pool() && pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE)
  2559. return false;
  2560. if (work->rolltime > opt_scantime)
  2561. expiry = work->rolltime;
  2562. else
  2563. expiry = opt_scantime;
  2564. expiry = expiry * 2 / 3;
  2565. /* We shouldn't roll if we're unlikely to get one shares' duration
  2566. * work out of doing so */
  2567. gettimeofday(&now, NULL);
  2568. if (now.tv_sec - work->tv_staged.tv_sec > expiry)
  2569. return false;
  2570. return true;
  2571. }
  2572. /* Limit rolls to 7000 to not beyond 2 hours in the future where bitcoind will
  2573. * reject blocks as invalid. */
  2574. static inline bool can_roll(struct work *work)
  2575. {
  2576. if (!(work->pool && !work->clone))
  2577. return false;
  2578. if (work->tmpl) {
  2579. if (stale_work(work, false))
  2580. return false;
  2581. return blkmk_work_left(work->tmpl);
  2582. }
  2583. return (work->rolltime &&
  2584. work->rolls < 7000 && !stale_work(work, false));
  2585. }
  2586. static void roll_work(struct work *work)
  2587. {
  2588. if (work->tmpl) {
  2589. if (blkmk_get_data(work->tmpl, work->data, 80, time(NULL), NULL, &work->dataid) < 76)
  2590. applog(LOG_ERR, "Failed to get next data from template; spinning wheels!");
  2591. swap32yes(work->data, work->data, 80 / 4);
  2592. calc_midstate(work);
  2593. applog(LOG_DEBUG, "Successfully rolled extranonce to dataid %u", work->dataid);
  2594. } else {
  2595. uint32_t *work_ntime;
  2596. uint32_t ntime;
  2597. work_ntime = (uint32_t *)(work->data + 68);
  2598. ntime = be32toh(*work_ntime);
  2599. ntime++;
  2600. *work_ntime = htobe32(ntime);
  2601. applog(LOG_DEBUG, "Successfully rolled time header in work");
  2602. }
  2603. local_work++;
  2604. work->rolls++;
  2605. work->blk.nonce = 0;
  2606. /* This is now a different work item so it needs a different ID for the
  2607. * hashtable */
  2608. work->id = total_work++;
  2609. }
  2610. static void workcpy(struct work *dest, const struct work *work)
  2611. {
  2612. memcpy(dest, work, sizeof(*dest));
  2613. if (work->tmpl) {
  2614. struct pool *pool = work->pool;
  2615. mutex_lock(&pool->pool_lock);
  2616. ++*work->tmpl_refcount;
  2617. mutex_unlock(&pool->pool_lock);
  2618. }
  2619. }
  2620. static struct work *make_clone(struct work *work)
  2621. {
  2622. struct work *work_clone = make_work();
  2623. workcpy(work_clone, work);
  2624. work_clone->clone = true;
  2625. gettimeofday((struct timeval *)&(work_clone->tv_cloned), NULL);
  2626. work_clone->longpoll = false;
  2627. work_clone->mandatory = false;
  2628. /* Make cloned work appear slightly older to bias towards keeping the
  2629. * master work item which can be further rolled */
  2630. work_clone->tv_staged.tv_sec -= 1;
  2631. return work_clone;
  2632. }
  2633. static bool stage_work(struct work *work);
  2634. static bool clone_available(void)
  2635. {
  2636. struct work *work, *tmp;
  2637. bool cloned = false;
  2638. if (!staged_rollable)
  2639. goto out;
  2640. mutex_lock(stgd_lock);
  2641. HASH_ITER(hh, staged_work, work, tmp) {
  2642. if (can_roll(work) && should_roll(work)) {
  2643. struct work *work_clone;
  2644. roll_work(work);
  2645. work_clone = make_clone(work);
  2646. roll_work(work);
  2647. applog(LOG_DEBUG, "Pushing cloned available work to stage thread");
  2648. if (unlikely(!stage_work(work_clone))) {
  2649. free(work_clone);
  2650. break;
  2651. }
  2652. cloned = true;
  2653. break;
  2654. }
  2655. }
  2656. mutex_unlock(stgd_lock);
  2657. out:
  2658. return cloned;
  2659. }
  2660. static bool queue_request(void);
  2661. static void pool_died(struct pool *pool)
  2662. {
  2663. if (!pool_tset(pool, &pool->idle)) {
  2664. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  2665. gettimeofday(&pool->tv_idle, NULL);
  2666. switch_pools(NULL);
  2667. }
  2668. }
  2669. static void *get_work_thread(void *userdata)
  2670. {
  2671. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  2672. struct pool *pool = current_pool();
  2673. struct work *ret_work= NULL;
  2674. struct curl_ent *ce = NULL;
  2675. pthread_detach(pthread_self());
  2676. rename_thr("bfg-get_work");
  2677. applog(LOG_DEBUG, "Creating extra get work thread");
  2678. pool = wc->pool;
  2679. if (clone_available()) {
  2680. applog(LOG_DEBUG, "dec_queued from get_work_thread due to clone available\n");
  2681. dec_queued(pool);
  2682. goto out;
  2683. }
  2684. ret_work = make_work();
  2685. ret_work->thr = NULL;
  2686. if (opt_benchmark) {
  2687. get_benchmark_work(ret_work);
  2688. ret_work->queued = true;
  2689. } else {
  2690. ret_work->pool = wc->pool;
  2691. if (!ce)
  2692. ce = pop_curl_entry(pool);
  2693. /* obtain new work from bitcoin via JSON-RPC */
  2694. if (!get_upstream_work(ret_work, ce->curl)) {
  2695. applog(LOG_DEBUG, "json_rpc_call failed on get work, retrying");
  2696. dec_queued(pool);
  2697. /* Make sure the pool just hasn't stopped serving
  2698. * requests but is up as we'll keep hammering it */
  2699. if (++pool->seq_getfails > mining_threads + opt_queue)
  2700. pool_died(pool);
  2701. queue_request();
  2702. free_work(ret_work);
  2703. goto out;
  2704. }
  2705. pool->seq_getfails = 0;
  2706. ret_work->queued = true;
  2707. }
  2708. applog(LOG_DEBUG, "Pushing work to requesting thread");
  2709. /* send work to requesting thread */
  2710. if (unlikely(!tq_push(thr_info[stage_thr_id].q, ret_work))) {
  2711. applog(LOG_ERR, "Failed to tq_push work in workio_get_work");
  2712. kill_work();
  2713. free_work(ret_work);
  2714. dec_queued(pool);
  2715. }
  2716. out:
  2717. workio_cmd_free(wc);
  2718. if (ce)
  2719. push_curl_entry(ce, pool);
  2720. return NULL;
  2721. }
  2722. /* As per the submit work system, we try to reuse the existing curl handles,
  2723. * but start recruiting extra connections if we start accumulating queued
  2724. * requests */
  2725. static bool workio_get_work(struct workio_cmd *wc)
  2726. {
  2727. pthread_t get_thread;
  2728. if (unlikely(pthread_create(&get_thread, NULL, get_work_thread, (void *)wc))) {
  2729. applog(LOG_ERR, "Failed to create get_work_thread");
  2730. return false;
  2731. }
  2732. return true;
  2733. }
  2734. static bool stale_work(struct work *work, bool share)
  2735. {
  2736. struct timeval now;
  2737. time_t work_expiry;
  2738. struct pool *pool;
  2739. uint32_t block_id;
  2740. int getwork_delay;
  2741. block_id = ((uint32_t*)work->data)[1];
  2742. pool = work->pool;
  2743. /* Technically the rolltime should be correct but some pools
  2744. * advertise a broken expire= that is lower than a meaningful
  2745. * scantime */
  2746. if (work->rolltime > opt_scantime)
  2747. work_expiry = work->rolltime;
  2748. else
  2749. work_expiry = opt_expiry;
  2750. if (share) {
  2751. /* If the share isn't on this pool's latest block, it's stale */
  2752. if (pool->block_id != block_id)
  2753. {
  2754. applog(LOG_DEBUG, "Share stale due to block mismatch (%08lx != %08lx)", (long)block_id, (long)pool->block_id);
  2755. return true;
  2756. }
  2757. /* If the pool doesn't want old shares, then any found in work before
  2758. * the most recent longpoll is stale */
  2759. if ((!pool->submit_old) && work->work_restart_id != pool->work_restart_id)
  2760. {
  2761. applog(LOG_DEBUG, "Share stale due to work restart (%02x != %02x)", work->work_restart_id, pool->work_restart_id);
  2762. return true;
  2763. }
  2764. } else {
  2765. /* If this work isn't for the latest Bitcoin block, it's stale */
  2766. /* But only care about the current pool if failover-only */
  2767. if (block_id != ((enabled_pools <= 1 || opt_fail_only) ? pool->block_id : current_block_id))
  2768. {
  2769. applog(LOG_DEBUG, "Work stale due to block mismatch (%08lx != %d ? %08lx : %08lx)", (long)block_id, (int)opt_fail_only, (long)pool->block_id, (long)current_block_id);
  2770. return true;
  2771. }
  2772. /* If the pool has asked us to restart since this work, it's stale */
  2773. if (work->work_restart_id != pool->work_restart_id)
  2774. {
  2775. applog(LOG_DEBUG, "Work stale due to work restart (%02x != %02x)", work->work_restart_id, pool->work_restart_id);
  2776. return true;
  2777. }
  2778. /* Factor in the average getwork delay of this pool, rounding it up to
  2779. * the nearest second */
  2780. getwork_delay = pool->cgminer_pool_stats.getwork_wait_rolling * 5 + 1;
  2781. work_expiry -= getwork_delay;
  2782. if (unlikely(work_expiry < 5))
  2783. work_expiry = 5;
  2784. }
  2785. gettimeofday(&now, NULL);
  2786. if ((now.tv_sec - work->tv_staged.tv_sec) >= work_expiry) {
  2787. applog(LOG_DEBUG, "%s stale due to expiry (%d - %d >= %d)", share?"Share":"Work", now.tv_sec, work->tv_staged.tv_sec, work_expiry);
  2788. return true;
  2789. }
  2790. /* If the user only wants strict failover, any work from a pool other than
  2791. * the current one is always considered stale */
  2792. if (opt_fail_only && !share && pool != current_pool() && !work->mandatory &&
  2793. pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  2794. applog(LOG_DEBUG, "Work stale due to fail only pool mismatch (pool %u vs %u)", pool->pool_no, current_pool()->pool_no);
  2795. return true;
  2796. }
  2797. return false;
  2798. }
  2799. static void check_solve(struct work *work)
  2800. {
  2801. work->block = regeneratehash(work);
  2802. if (unlikely(work->block)) {
  2803. work->pool->solved++;
  2804. found_blocks++;
  2805. work->mandatory = true;
  2806. applog(LOG_NOTICE, "Found block for pool %d!", work->pool->pool_no);
  2807. }
  2808. }
  2809. static void submit_discard_share(struct work *work)
  2810. {
  2811. sharelog("discard", work);
  2812. ++total_stale;
  2813. ++(work->pool->stale_shares);
  2814. total_diff_stale += work->work_difficulty;
  2815. work->pool->diff_stale += work->work_difficulty;
  2816. }
  2817. static void *submit_work_thread(void *userdata)
  2818. {
  2819. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  2820. struct work *work;
  2821. struct pool *pool;
  2822. bool resubmit;
  2823. struct curl_ent *ce;
  2824. int failures;
  2825. time_t staleexpire;
  2826. pthread_detach(pthread_self());
  2827. rename_thr("bfg-submit_work");
  2828. applog(LOG_DEBUG, "Creating extra submit work thread");
  2829. next_submit:
  2830. work = wc->work;
  2831. pool = work->pool;
  2832. resubmit = false;
  2833. failures = 0;
  2834. check_solve(work);
  2835. if (stale_work(work, true)) {
  2836. work->stale = true;
  2837. if (unlikely(!list_empty(&submit_waiting))) {
  2838. applog(LOG_WARNING, "Stale share detected while queued submissions are waiting, discarding");
  2839. submit_discard_share(work);
  2840. goto out;
  2841. }
  2842. if (opt_submit_stale)
  2843. applog(LOG_NOTICE, "Stale share detected, submitting as user requested");
  2844. else if (pool->submit_old)
  2845. applog(LOG_NOTICE, "Stale share detected, submitting as pool requested");
  2846. else {
  2847. applog(LOG_NOTICE, "Stale share detected, discarding");
  2848. submit_discard_share(work);
  2849. goto out;
  2850. }
  2851. staleexpire = time(NULL) + 300;
  2852. }
  2853. ce = pop_curl_entry(pool);
  2854. /* submit solution to bitcoin via JSON-RPC */
  2855. while (!submit_upstream_work(work, ce->curl, resubmit)) {
  2856. resubmit = true;
  2857. if ((!work->stale) && stale_work(work, true)) {
  2858. work->stale = true;
  2859. if (opt_submit_stale)
  2860. applog(LOG_NOTICE, "Share become stale during submission failure, will retry as user requested");
  2861. else if (pool->submit_old)
  2862. applog(LOG_NOTICE, "Share become stale during submission failure, will retry as pool requested");
  2863. else {
  2864. applog(LOG_NOTICE, "Share become stale during submission failure, discarding");
  2865. submit_discard_share(work);
  2866. break;
  2867. }
  2868. staleexpire = time(NULL) + 300;
  2869. }
  2870. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  2871. applog(LOG_ERR, "Failed %d retries, discarding", opt_retries);
  2872. submit_discard_share(work);
  2873. break;
  2874. }
  2875. else if (work->stale) {
  2876. if (unlikely(!list_empty(&submit_waiting))) {
  2877. applog(LOG_WARNING, "Stale share failed to submit while queued submissions are waiting, discarding");
  2878. submit_discard_share(work);
  2879. break;
  2880. } else if (unlikely(opt_retries < 0 && staleexpire <= time(NULL))) {
  2881. applog(LOG_NOTICE, "Stale share failed to submit for 5 minutes, discarding");
  2882. submit_discard_share(work);
  2883. break;
  2884. }
  2885. }
  2886. /* pause, then restart work-request loop */
  2887. applog(LOG_INFO, "json_rpc_call failed on submit_work, retrying");
  2888. }
  2889. push_curl_entry(ce, pool);
  2890. out:
  2891. workio_cmd_free(wc);
  2892. mutex_lock(&submitting_lock);
  2893. if (!list_empty(&submit_waiting)) {
  2894. applog(LOG_DEBUG, "submit_work continuing with queued submission");
  2895. wc = list_entry(submit_waiting.next, struct workio_cmd, list);
  2896. list_del(&wc->list);
  2897. mutex_unlock(&submitting_lock);
  2898. goto next_submit;
  2899. }
  2900. --submitting;
  2901. mutex_unlock(&submitting_lock);
  2902. return NULL;
  2903. }
  2904. /* We try to reuse curl handles as much as possible, but if there is already
  2905. * work queued to be submitted, we start generating extra handles to submit
  2906. * the shares to avoid ever increasing backlogs. This allows us to scale to
  2907. * any size hardware */
  2908. static bool workio_submit_work(struct workio_cmd *wc)
  2909. {
  2910. pthread_t submit_thread;
  2911. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, (void *)wc))) {
  2912. applog(LOG_ERR, "Failed to create submit_work_thread");
  2913. return false;
  2914. }
  2915. return true;
  2916. }
  2917. /* Find the pool that currently has the highest priority */
  2918. static struct pool *priority_pool(int choice)
  2919. {
  2920. struct pool *ret = NULL;
  2921. int i;
  2922. for (i = 0; i < total_pools; i++) {
  2923. struct pool *pool = pools[i];
  2924. if (pool->prio == choice) {
  2925. ret = pool;
  2926. break;
  2927. }
  2928. }
  2929. if (unlikely(!ret)) {
  2930. applog(LOG_ERR, "WTF No pool %d found!", choice);
  2931. return pools[choice];
  2932. }
  2933. return ret;
  2934. }
  2935. void switch_pools(struct pool *selected)
  2936. {
  2937. struct pool *pool, *last_pool;
  2938. int i, pool_no, next_pool;
  2939. mutex_lock(&control_lock);
  2940. last_pool = currentpool;
  2941. pool_no = currentpool->pool_no;
  2942. /* Switch selected to pool number 0 and move the rest down */
  2943. if (selected) {
  2944. if (selected->prio != 0) {
  2945. for (i = 0; i < total_pools; i++) {
  2946. pool = pools[i];
  2947. if (pool->prio < selected->prio)
  2948. pool->prio++;
  2949. }
  2950. selected->prio = 0;
  2951. }
  2952. }
  2953. switch (pool_strategy) {
  2954. /* Both of these set to the master pool */
  2955. case POOL_BALANCE:
  2956. case POOL_FAILOVER:
  2957. case POOL_LOADBALANCE:
  2958. for (i = 0; i < total_pools; i++) {
  2959. pool = priority_pool(i);
  2960. if (!pool->idle && pool->enabled == POOL_ENABLED) {
  2961. pool_no = pool->pool_no;
  2962. break;
  2963. }
  2964. }
  2965. break;
  2966. /* Both of these simply increment and cycle */
  2967. case POOL_ROUNDROBIN:
  2968. case POOL_ROTATE:
  2969. if (selected && !selected->idle) {
  2970. pool_no = selected->pool_no;
  2971. break;
  2972. }
  2973. next_pool = pool_no;
  2974. /* Select the next alive pool */
  2975. for (i = 1; i < total_pools; i++) {
  2976. next_pool++;
  2977. if (next_pool >= total_pools)
  2978. next_pool = 0;
  2979. pool = pools[next_pool];
  2980. if (!pool->idle && pool->enabled == POOL_ENABLED) {
  2981. pool_no = next_pool;
  2982. break;
  2983. }
  2984. }
  2985. break;
  2986. default:
  2987. break;
  2988. }
  2989. currentpool = pools[pool_no];
  2990. pool = currentpool;
  2991. pool->block_id = 0;
  2992. mutex_unlock(&control_lock);
  2993. /* Set the lagging flag to avoid pool not providing work fast enough
  2994. * messages in failover only mode since we have to get all fresh work
  2995. * as in restart_threads */
  2996. if (opt_fail_only)
  2997. pool_tset(pool, &pool->lagging);
  2998. if (pool != last_pool)
  2999. applog(LOG_WARNING, "Switching to %s", pool->rpc_url);
  3000. mutex_lock(&lp_lock);
  3001. pthread_cond_broadcast(&lp_cond);
  3002. mutex_unlock(&lp_lock);
  3003. }
  3004. static void discard_work(struct work *work)
  3005. {
  3006. if (!work->clone && !work->rolls && !work->mined) {
  3007. if (work->pool)
  3008. work->pool->discarded_work++;
  3009. total_discarded++;
  3010. applog(LOG_DEBUG, "Discarded work");
  3011. } else
  3012. applog(LOG_DEBUG, "Discarded cloned or rolled work");
  3013. free_work(work);
  3014. }
  3015. static void discard_stale(void)
  3016. {
  3017. struct work *work, *tmp;
  3018. int stale = 0;
  3019. mutex_lock(stgd_lock);
  3020. HASH_ITER(hh, staged_work, work, tmp) {
  3021. if (stale_work(work, false)) {
  3022. HASH_DEL(staged_work, work);
  3023. work->pool->staged--;
  3024. discard_work(work);
  3025. stale++;
  3026. }
  3027. }
  3028. mutex_unlock(stgd_lock);
  3029. if (stale) {
  3030. applog(LOG_DEBUG, "Discarded %d stales that didn't match current hash", stale);
  3031. while (stale-- > 0)
  3032. queue_request();
  3033. }
  3034. }
  3035. void ms_to_abstime(unsigned int mstime, struct timespec *abstime)
  3036. {
  3037. struct timeval now, then, tdiff;
  3038. tdiff.tv_sec = mstime / 1000;
  3039. tdiff.tv_usec = mstime * 1000 - (tdiff.tv_sec * 1000000);
  3040. gettimeofday(&now, NULL);
  3041. timeradd(&now, &tdiff, &then);
  3042. abstime->tv_sec = then.tv_sec;
  3043. abstime->tv_nsec = then.tv_usec * 1000;
  3044. }
  3045. /* A generic wait function for threads that poll that will wait a specified
  3046. * time tdiff waiting on the pthread conditional that is broadcast when a
  3047. * work restart is required. Returns the value of pthread_cond_timedwait
  3048. * which is zero if the condition was met or ETIMEDOUT if not.
  3049. */
  3050. int restart_wait(unsigned int mstime)
  3051. {
  3052. struct timespec abstime;
  3053. int rc;
  3054. ms_to_abstime(mstime, &abstime);
  3055. mutex_lock(&restart_lock);
  3056. rc = pthread_cond_timedwait(&restart_cond, &restart_lock, &abstime);
  3057. mutex_unlock(&restart_lock);
  3058. return rc;
  3059. }
  3060. /* A generic wait function for threads that poll that will wait a specified
  3061. * time waiting on a share to become stale. Returns positive if the share
  3062. * became stale or zero if the timer expired first. If checkend is true, will
  3063. * immediatley return negative if the share is guaranteed to become stale
  3064. * before the timer expires.
  3065. */
  3066. int stale_wait(unsigned int mstime, struct work*work, bool checkend)
  3067. {
  3068. struct timespec abstime;
  3069. int rc;
  3070. if (checkend) {
  3071. struct timeval tv, orig;
  3072. ldiv_t d;
  3073. d = ldiv(mstime, 1000);
  3074. tv.tv_sec = d.quot;
  3075. tv.tv_usec = d.rem * 1000;
  3076. orig = work->tv_staged;
  3077. timersub(&orig, &tv, &work->tv_staged);
  3078. rc = stale_work(work, true);
  3079. work->tv_staged = orig;
  3080. if (rc)
  3081. return -1;
  3082. }
  3083. ms_to_abstime(mstime, &abstime);
  3084. rc = -1;
  3085. while (1) {
  3086. mutex_lock(&restart_lock);
  3087. if (stale_work(work, true)) {
  3088. rc = 1;
  3089. } else if (pthread_cond_timedwait(&restart_cond, &restart_lock, &abstime)) {
  3090. rc = 0;
  3091. }
  3092. mutex_unlock(&restart_lock);
  3093. if (rc != -1)
  3094. return rc;
  3095. }
  3096. }
  3097. static void restart_threads(void)
  3098. {
  3099. struct pool *cp = current_pool();
  3100. int i, fd;
  3101. struct thr_info *thr;
  3102. /* Artificially set the lagging flag to avoid pool not providing work
  3103. * fast enough messages after every long poll */
  3104. pool_tset(cp, &cp->lagging);
  3105. /* Discard staged work that is now stale */
  3106. discard_stale();
  3107. for (i = 0; i < mining_threads; i++)
  3108. {
  3109. thr = &thr_info[i];
  3110. fd = thr->_work_restart_fd_w;
  3111. thr->work_restart = true;
  3112. if (fd != -1)
  3113. write(fd, "\0", 1);
  3114. }
  3115. mutex_lock(&restart_lock);
  3116. pthread_cond_broadcast(&restart_cond);
  3117. mutex_unlock(&restart_lock);
  3118. }
  3119. static char *blkhashstr(unsigned char *hash)
  3120. {
  3121. unsigned char hash_swap[32];
  3122. swap256(hash_swap, hash);
  3123. swap32tole(hash_swap, hash_swap, 32 / 4);
  3124. return bin2hex(hash_swap, 32);
  3125. }
  3126. static void set_curblock(char *hexstr, unsigned char *hash)
  3127. {
  3128. unsigned char hash_swap[32];
  3129. char *old_hash;
  3130. current_block_id = ((uint32_t*)hash)[0];
  3131. strcpy(current_block, hexstr);
  3132. swap256(hash_swap, hash);
  3133. swap32tole(hash_swap, hash_swap, 32 / 4);
  3134. /* Don't free current_hash directly to avoid dereferencing when read
  3135. * elsewhere - and update block_timeval inside the same lock */
  3136. mutex_lock(&ch_lock);
  3137. gettimeofday(&block_timeval, NULL);
  3138. old_hash = current_hash;
  3139. current_hash = bin2hex(hash_swap + 4, 16);
  3140. free(old_hash);
  3141. old_hash = current_fullhash;
  3142. current_fullhash = bin2hex(hash_swap, 32);
  3143. free(old_hash);
  3144. mutex_unlock(&ch_lock);
  3145. get_timestamp(blocktime, &block_timeval);
  3146. if (unlikely(!current_hash))
  3147. quit (1, "set_curblock OOM");
  3148. applog(LOG_INFO, "New block: %s...", current_hash);
  3149. }
  3150. /* Search to see if this string is from a block that has been seen before */
  3151. static bool block_exists(char *hexstr)
  3152. {
  3153. struct block *s;
  3154. rd_lock(&blk_lock);
  3155. HASH_FIND_STR(blocks, hexstr, s);
  3156. rd_unlock(&blk_lock);
  3157. if (s)
  3158. return true;
  3159. return false;
  3160. }
  3161. /* Tests if this work is from a block that has been seen before */
  3162. static inline bool from_existing_block(struct work *work)
  3163. {
  3164. char *hexstr = bin2hex(work->data, 18);
  3165. bool ret;
  3166. if (unlikely(!hexstr)) {
  3167. applog(LOG_ERR, "from_existing_block OOM");
  3168. return true;
  3169. }
  3170. ret = block_exists(hexstr);
  3171. free(hexstr);
  3172. return ret;
  3173. }
  3174. static int block_sort(struct block *blocka, struct block *blockb)
  3175. {
  3176. return blocka->block_no - blockb->block_no;
  3177. }
  3178. static void test_work_current(struct work *work)
  3179. {
  3180. char *hexstr;
  3181. if (work->mandatory)
  3182. return;
  3183. uint32_t block_id = ((uint32_t*)(work->data))[1];
  3184. hexstr = bin2hex(&work->data[4], 18);
  3185. if (unlikely(!hexstr)) {
  3186. applog(LOG_ERR, "stage_thread OOM");
  3187. return;
  3188. }
  3189. /* Search to see if this block exists yet and if not, consider it a
  3190. * new block and set the current block details to this one */
  3191. if (!block_exists(hexstr)) {
  3192. struct block *s = calloc(sizeof(struct block), 1);
  3193. int deleted_block = 0;
  3194. if (unlikely(!s))
  3195. quit (1, "test_work_current OOM");
  3196. strcpy(s->hash, hexstr);
  3197. s->block_no = new_blocks++;
  3198. wr_lock(&blk_lock);
  3199. /* Only keep the last hour's worth of blocks in memory since
  3200. * work from blocks before this is virtually impossible and we
  3201. * want to prevent memory usage from continually rising */
  3202. if (HASH_COUNT(blocks) > 6) {
  3203. struct block *oldblock;
  3204. HASH_SORT(blocks, block_sort);
  3205. oldblock = blocks;
  3206. deleted_block = oldblock->block_no;
  3207. HASH_DEL(blocks, oldblock);
  3208. free(oldblock);
  3209. }
  3210. HASH_ADD_STR(blocks, hash, s);
  3211. wr_unlock(&blk_lock);
  3212. work->pool->block_id = block_id;
  3213. if (deleted_block)
  3214. applog(LOG_DEBUG, "Deleted block %d from database", deleted_block);
  3215. set_curblock(hexstr, &work->data[4]);
  3216. if (unlikely(new_blocks == 1))
  3217. goto out_free;
  3218. if (work->longpoll) {
  3219. applog(LOG_NOTICE, "LONGPOLL from pool %d detected new block",
  3220. work->pool->pool_no);
  3221. work->longpoll = false;
  3222. } else if (have_longpoll)
  3223. applog(LOG_NOTICE, "New block detected on network before longpoll");
  3224. else
  3225. applog(LOG_NOTICE, "New block detected on network");
  3226. restart_threads();
  3227. } else {
  3228. bool restart = false;
  3229. struct pool *curpool = NULL;
  3230. if (unlikely(work->pool->block_id != block_id)) {
  3231. bool was_active = work->pool->block_id != 0;
  3232. work->pool->block_id = block_id;
  3233. if (was_active) { // Pool actively changed block
  3234. if (work->pool == (curpool = current_pool()))
  3235. restart = true;
  3236. if (block_id == current_block_id) {
  3237. // Caught up, only announce if this pool is the one in use
  3238. if (restart)
  3239. applog(LOG_NOTICE, "%s %d caught up to new block",
  3240. work->longpoll ? "LONGPOLL from pool" : "Pool",
  3241. work->pool->pool_no);
  3242. } else {
  3243. // Switched to a block we know, but not the latest... why?
  3244. // This might detect pools trying to double-spend or 51%,
  3245. // but let's not make any accusations until it's had time
  3246. // in the real world.
  3247. free(hexstr);
  3248. hexstr = blkhashstr(&work->data[4]);
  3249. applog(LOG_WARNING, "%s %d is issuing work for an old block: %s",
  3250. work->longpoll ? "LONGPOLL from pool" : "Pool",
  3251. work->pool->pool_no,
  3252. hexstr);
  3253. }
  3254. }
  3255. }
  3256. if (work->longpoll) {
  3257. work->longpoll = false;
  3258. ++work->pool->work_restart_id;
  3259. if ((!restart) && work->pool == current_pool()) {
  3260. applog(LOG_NOTICE, "LONGPOLL from pool %d requested work restart",
  3261. work->pool->pool_no);
  3262. restart = true;
  3263. }
  3264. }
  3265. if (restart)
  3266. restart_threads();
  3267. }
  3268. out_free:
  3269. free(hexstr);
  3270. }
  3271. static int tv_sort(struct work *worka, struct work *workb)
  3272. {
  3273. return worka->tv_staged.tv_sec - workb->tv_staged.tv_sec;
  3274. }
  3275. static bool work_rollable(struct work *work)
  3276. {
  3277. return (!work->clone && work->rolltime);
  3278. }
  3279. static bool hash_push(struct work *work)
  3280. {
  3281. bool rc = true;
  3282. mutex_lock(stgd_lock);
  3283. if (work_rollable(work))
  3284. staged_rollable++;
  3285. if (likely(!getq->frozen)) {
  3286. HASH_ADD_INT(staged_work, id, work);
  3287. HASH_SORT(staged_work, tv_sort);
  3288. } else
  3289. rc = false;
  3290. pthread_cond_signal(&getq->cond);
  3291. mutex_unlock(stgd_lock);
  3292. work->pool->staged++;
  3293. if (work->queued) {
  3294. work->queued = false;
  3295. applog(LOG_DEBUG, "dec_queued in hash_push\n");
  3296. dec_queued(work->pool);
  3297. }
  3298. return rc;
  3299. }
  3300. static void *stage_thread(void *userdata)
  3301. {
  3302. struct thr_info *mythr = userdata;
  3303. bool ok = true;
  3304. rename_thr("bfg-stage");
  3305. while (ok) {
  3306. struct work *work = NULL;
  3307. applog(LOG_DEBUG, "Popping work to stage thread");
  3308. work = tq_pop(mythr->q, NULL);
  3309. if (unlikely(!work)) {
  3310. applog(LOG_ERR, "Failed to tq_pop in stage_thread");
  3311. ok = false;
  3312. break;
  3313. }
  3314. work->work_restart_id = work->pool->work_restart_id;
  3315. test_work_current(work);
  3316. applog(LOG_DEBUG, "Pushing work to getwork queue (queued=%c)", work->queued?'Y':'N');
  3317. if (unlikely(!hash_push(work))) {
  3318. applog(LOG_WARNING, "Failed to hash_push in stage_thread");
  3319. continue;
  3320. }
  3321. }
  3322. tq_freeze(mythr->q);
  3323. return NULL;
  3324. }
  3325. static bool stage_work(struct work *work)
  3326. {
  3327. applog(LOG_DEBUG, "Pushing work to stage thread");
  3328. if (unlikely(!tq_push(thr_info[stage_thr_id].q, work))) {
  3329. applog(LOG_ERR, "Could not tq_push work in stage_work");
  3330. return false;
  3331. }
  3332. return true;
  3333. }
  3334. #ifdef HAVE_CURSES
  3335. int curses_int(const char *query)
  3336. {
  3337. int ret;
  3338. char *cvar;
  3339. cvar = curses_input(query);
  3340. ret = atoi(cvar);
  3341. free(cvar);
  3342. return ret;
  3343. }
  3344. #endif
  3345. #ifdef HAVE_CURSES
  3346. static bool input_pool(bool live);
  3347. #endif
  3348. #ifdef HAVE_CURSES
  3349. static void display_pool_summary(struct pool *pool)
  3350. {
  3351. double efficiency = 0.0;
  3352. if (curses_active_locked()) {
  3353. wlog("Pool: %s\n", pool->rpc_url);
  3354. if (pool->solved)
  3355. wlog("SOLVED %d BLOCK%s!\n", pool->solved, pool->solved > 1 ? "S" : "");
  3356. wlog("%s own long-poll support\n", pool->lp_url ? "Has" : "Does not have");
  3357. wlog(" Queued work requests: %d\n", pool->getwork_requested);
  3358. wlog(" Share submissions: %d\n", pool->accepted + pool->rejected);
  3359. wlog(" Accepted shares: %d\n", pool->accepted);
  3360. wlog(" Rejected shares: %d\n", pool->rejected);
  3361. wlog(" Accepted difficulty shares: %1.f\n", pool->diff_accepted);
  3362. wlog(" Rejected difficulty shares: %1.f\n", pool->diff_rejected);
  3363. if (pool->accepted || pool->rejected)
  3364. wlog(" Reject ratio: %.1f%%\n", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  3365. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  3366. wlog(" Efficiency (accepted / queued): %.0f%%\n", efficiency);
  3367. wlog(" Discarded work due to new blocks: %d\n", pool->discarded_work);
  3368. wlog(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  3369. wlog(" Unable to get work from server occasions: %d\n", pool->getfail_occasions);
  3370. wlog(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  3371. unlock_curses();
  3372. }
  3373. }
  3374. #endif
  3375. /* We can't remove the memory used for this struct pool because there may
  3376. * still be work referencing it. We just remove it from the pools list */
  3377. void remove_pool(struct pool *pool)
  3378. {
  3379. int i, last_pool = total_pools - 1;
  3380. struct pool *other;
  3381. /* Boost priority of any lower prio than this one */
  3382. for (i = 0; i < total_pools; i++) {
  3383. other = pools[i];
  3384. if (other->prio > pool->prio)
  3385. other->prio--;
  3386. }
  3387. if (pool->pool_no < last_pool) {
  3388. /* Swap the last pool for this one */
  3389. (pools[last_pool])->pool_no = pool->pool_no;
  3390. pools[pool->pool_no] = pools[last_pool];
  3391. }
  3392. /* Give it an invalid number */
  3393. pool->pool_no = total_pools;
  3394. pool->removed = true;
  3395. total_pools--;
  3396. }
  3397. /* add a mutex if this needs to be thread safe in the future */
  3398. static struct JE {
  3399. char *buf;
  3400. struct JE *next;
  3401. } *jedata = NULL;
  3402. static void json_escape_free()
  3403. {
  3404. struct JE *jeptr = jedata;
  3405. struct JE *jenext;
  3406. jedata = NULL;
  3407. while (jeptr) {
  3408. jenext = jeptr->next;
  3409. free(jeptr->buf);
  3410. free(jeptr);
  3411. jeptr = jenext;
  3412. }
  3413. }
  3414. static char *json_escape(char *str)
  3415. {
  3416. struct JE *jeptr;
  3417. char *buf, *ptr;
  3418. /* 2x is the max, may as well just allocate that */
  3419. ptr = buf = malloc(strlen(str) * 2 + 1);
  3420. jeptr = malloc(sizeof(*jeptr));
  3421. jeptr->buf = buf;
  3422. jeptr->next = jedata;
  3423. jedata = jeptr;
  3424. while (*str) {
  3425. if (*str == '\\' || *str == '"')
  3426. *(ptr++) = '\\';
  3427. *(ptr++) = *(str++);
  3428. }
  3429. *ptr = '\0';
  3430. return buf;
  3431. }
  3432. void write_config(FILE *fcfg)
  3433. {
  3434. int i;
  3435. /* Write pool values */
  3436. fputs("{\n\"pools\" : [", fcfg);
  3437. for(i = 0; i < total_pools; i++) {
  3438. fprintf(fcfg, "%s\n\t{\n\t\t\"url\" : \"%s\",", i > 0 ? "," : "", json_escape(pools[i]->rpc_url));
  3439. if (pools[i]->rpc_proxy)
  3440. fprintf(fcfg, "\n\t\t\"pool-proxy\" : \"%s\",", json_escape(pools[i]->rpc_proxy));
  3441. fprintf(fcfg, "\n\t\t\"user\" : \"%s\",", json_escape(pools[i]->rpc_user));
  3442. fprintf(fcfg, "\n\t\t\"pass\" : \"%s\"\n\t}", json_escape(pools[i]->rpc_pass));
  3443. }
  3444. fputs("\n]\n", fcfg);
  3445. #ifdef HAVE_OPENCL
  3446. if (nDevs) {
  3447. /* Write GPU device values */
  3448. fputs(",\n\"intensity\" : \"", fcfg);
  3449. for(i = 0; i < nDevs; i++)
  3450. fprintf(fcfg, gpus[i].dynamic ? "%sd" : "%s%d", i > 0 ? "," : "", gpus[i].intensity);
  3451. fputs("\",\n\"vectors\" : \"", fcfg);
  3452. for(i = 0; i < nDevs; i++)
  3453. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  3454. gpus[i].vwidth);
  3455. fputs("\",\n\"worksize\" : \"", fcfg);
  3456. for(i = 0; i < nDevs; i++)
  3457. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  3458. (int)gpus[i].work_size);
  3459. fputs("\",\n\"kernel\" : \"", fcfg);
  3460. for(i = 0; i < nDevs; i++) {
  3461. fprintf(fcfg, "%s", i > 0 ? "," : "");
  3462. switch (gpus[i].kernel) {
  3463. case KL_NONE: // Shouldn't happen
  3464. break;
  3465. case KL_POCLBM:
  3466. fprintf(fcfg, "poclbm");
  3467. break;
  3468. case KL_PHATK:
  3469. fprintf(fcfg, "phatk");
  3470. break;
  3471. case KL_DIAKGCN:
  3472. fprintf(fcfg, "diakgcn");
  3473. break;
  3474. case KL_DIABLO:
  3475. fprintf(fcfg, "diablo");
  3476. break;
  3477. case KL_SCRYPT:
  3478. fprintf(fcfg, "scrypt");
  3479. break;
  3480. }
  3481. }
  3482. #ifdef USE_SCRYPT
  3483. fputs("\",\n\"lookup-gap\" : \"", fcfg);
  3484. for(i = 0; i < nDevs; i++)
  3485. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  3486. (int)gpus[i].opt_lg);
  3487. fputs("\",\n\"thread-concurrency\" : \"", fcfg);
  3488. for(i = 0; i < nDevs; i++)
  3489. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  3490. (int)gpus[i].opt_tc);
  3491. fputs("\",\n\"shaders\" : \"", fcfg);
  3492. for(i = 0; i < nDevs; i++)
  3493. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  3494. (int)gpus[i].shaders);
  3495. #endif
  3496. #ifdef HAVE_ADL
  3497. fputs("\",\n\"gpu-engine\" : \"", fcfg);
  3498. for(i = 0; i < nDevs; i++)
  3499. fprintf(fcfg, "%s%d-%d", i > 0 ? "," : "", gpus[i].min_engine, gpus[i].gpu_engine);
  3500. fputs("\",\n\"gpu-fan\" : \"", fcfg);
  3501. for(i = 0; i < nDevs; i++)
  3502. fprintf(fcfg, "%s%d-%d", i > 0 ? "," : "", gpus[i].min_fan, gpus[i].gpu_fan);
  3503. fputs("\",\n\"gpu-memclock\" : \"", fcfg);
  3504. for(i = 0; i < nDevs; i++)
  3505. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_memclock);
  3506. fputs("\",\n\"gpu-memdiff\" : \"", fcfg);
  3507. for(i = 0; i < nDevs; i++)
  3508. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_memdiff);
  3509. fputs("\",\n\"gpu-powertune\" : \"", fcfg);
  3510. for(i = 0; i < nDevs; i++)
  3511. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_powertune);
  3512. fputs("\",\n\"gpu-vddc\" : \"", fcfg);
  3513. for(i = 0; i < nDevs; i++)
  3514. fprintf(fcfg, "%s%1.3f", i > 0 ? "," : "", gpus[i].gpu_vddc);
  3515. fputs("\",\n\"temp-cutoff\" : \"", fcfg);
  3516. for(i = 0; i < nDevs; i++)
  3517. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].cutofftemp);
  3518. fputs("\",\n\"temp-overheat\" : \"", fcfg);
  3519. for(i = 0; i < nDevs; i++)
  3520. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].adl.overtemp);
  3521. fputs("\",\n\"temp-target\" : \"", fcfg);
  3522. for(i = 0; i < nDevs; i++)
  3523. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].targettemp);
  3524. #endif
  3525. fputs("\"", fcfg);
  3526. }
  3527. #endif
  3528. #ifdef HAVE_ADL
  3529. if (opt_reorder)
  3530. fprintf(fcfg, ",\n\"gpu-reorder\" : true");
  3531. #endif
  3532. #ifdef WANT_CPUMINE
  3533. fprintf(fcfg, ",\n\"algo\" : \"%s\"", algo_names[opt_algo]);
  3534. #endif
  3535. /* Simple bool and int options */
  3536. struct opt_table *opt;
  3537. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  3538. char *p, *name = strdup(opt->names);
  3539. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  3540. if (p[1] != '-')
  3541. continue;
  3542. if (opt->type & OPT_NOARG &&
  3543. ((void *)opt->cb == (void *)opt_set_bool || (void *)opt->cb == (void *)opt_set_invbool) &&
  3544. (*(bool *)opt->u.arg == ((void *)opt->cb == (void *)opt_set_bool)))
  3545. fprintf(fcfg, ",\n\"%s\" : true", p+2);
  3546. if (opt->type & OPT_HASARG &&
  3547. ((void *)opt->cb_arg == (void *)set_int_0_to_9999 ||
  3548. (void *)opt->cb_arg == (void *)set_int_1_to_65535 ||
  3549. (void *)opt->cb_arg == (void *)set_int_0_to_10 ||
  3550. (void *)opt->cb_arg == (void *)set_int_1_to_10) &&
  3551. opt->desc != opt_hidden &&
  3552. 0 <= *(int *)opt->u.arg)
  3553. fprintf(fcfg, ",\n\"%s\" : \"%d\"", p+2, *(int *)opt->u.arg);
  3554. }
  3555. }
  3556. /* Special case options */
  3557. fprintf(fcfg, ",\n\"shares\" : \"%d\"", opt_shares);
  3558. if (pool_strategy == POOL_BALANCE)
  3559. fputs(",\n\"balance\" : true", fcfg);
  3560. if (pool_strategy == POOL_LOADBALANCE)
  3561. fputs(",\n\"load-balance\" : true", fcfg);
  3562. if (pool_strategy == POOL_ROUNDROBIN)
  3563. fputs(",\n\"round-robin\" : true", fcfg);
  3564. if (pool_strategy == POOL_ROTATE)
  3565. fprintf(fcfg, ",\n\"rotate\" : \"%d\"", opt_rotate_period);
  3566. #if defined(unix)
  3567. if (opt_stderr_cmd && *opt_stderr_cmd)
  3568. fprintf(fcfg, ",\n\"monitor\" : \"%s\"", json_escape(opt_stderr_cmd));
  3569. #endif // defined(unix)
  3570. if (opt_kernel_path && *opt_kernel_path) {
  3571. char *kpath = strdup(opt_kernel_path);
  3572. if (kpath[strlen(kpath)-1] == '/')
  3573. kpath[strlen(kpath)-1] = 0;
  3574. fprintf(fcfg, ",\n\"kernel-path\" : \"%s\"", json_escape(kpath));
  3575. }
  3576. if (schedstart.enable)
  3577. fprintf(fcfg, ",\n\"sched-time\" : \"%d:%d\"", schedstart.tm.tm_hour, schedstart.tm.tm_min);
  3578. if (schedstop.enable)
  3579. fprintf(fcfg, ",\n\"stop-time\" : \"%d:%d\"", schedstop.tm.tm_hour, schedstop.tm.tm_min);
  3580. if (opt_socks_proxy && *opt_socks_proxy)
  3581. fprintf(fcfg, ",\n\"socks-proxy\" : \"%s\"", json_escape(opt_socks_proxy));
  3582. #ifdef HAVE_OPENCL
  3583. for(i = 0; i < nDevs; i++)
  3584. if (gpus[i].deven == DEV_DISABLED)
  3585. break;
  3586. if (i < nDevs)
  3587. for (i = 0; i < nDevs; i++)
  3588. if (gpus[i].deven != DEV_DISABLED)
  3589. fprintf(fcfg, ",\n\"device\" : \"%d\"", i);
  3590. #endif
  3591. if (opt_api_allow)
  3592. fprintf(fcfg, ",\n\"api-allow\" : \"%s\"", json_escape(opt_api_allow));
  3593. if (strcmp(opt_api_description, PACKAGE_STRING) != 0)
  3594. fprintf(fcfg, ",\n\"api-description\" : \"%s\"", json_escape(opt_api_description));
  3595. if (opt_api_groups)
  3596. fprintf(fcfg, ",\n\"api-groups\" : \"%s\"", json_escape(opt_api_groups));
  3597. if (opt_icarus_options)
  3598. fprintf(fcfg, ",\n\"icarus-options\" : \"%s\"", json_escape(opt_icarus_options));
  3599. if (opt_icarus_timing)
  3600. fprintf(fcfg, ",\n\"icarus-timing\" : \"%s\"", json_escape(opt_icarus_timing));
  3601. fputs("\n}\n", fcfg);
  3602. json_escape_free();
  3603. }
  3604. #ifdef HAVE_CURSES
  3605. static void display_pools(void)
  3606. {
  3607. struct pool *pool;
  3608. int selected, i;
  3609. char input;
  3610. opt_loginput = true;
  3611. immedok(logwin, true);
  3612. clear_logwin();
  3613. updated:
  3614. for (i = 0; i < total_pools; i++) {
  3615. pool = pools[i];
  3616. if (pool == current_pool())
  3617. wattron(logwin, A_BOLD);
  3618. if (pool->enabled != POOL_ENABLED)
  3619. wattron(logwin, A_DIM);
  3620. wlogprint("%d: ", pool->pool_no);
  3621. switch (pool->enabled) {
  3622. case POOL_ENABLED:
  3623. wlogprint("Enabled ");
  3624. break;
  3625. case POOL_DISABLED:
  3626. wlogprint("Disabled ");
  3627. break;
  3628. case POOL_REJECTING:
  3629. wlogprint("Rejectin ");
  3630. break;
  3631. }
  3632. if (pool->idle)
  3633. wlogprint("Dead ");
  3634. else
  3635. if (pool->lp_url && pool->proto != pool->lp_proto)
  3636. wlogprint("Mixed");
  3637. else
  3638. switch (pool->proto) {
  3639. case PLP_GETBLOCKTEMPLATE:
  3640. wlogprint(" GBT ");
  3641. break;
  3642. case PLP_GETWORK:
  3643. wlogprint("GWork");
  3644. break;
  3645. default:
  3646. wlogprint("Alive");
  3647. }
  3648. wlogprint(" Priority %d: %s User:%s\n",
  3649. pool->prio,
  3650. pool->rpc_url, pool->rpc_user);
  3651. wattroff(logwin, A_BOLD | A_DIM);
  3652. }
  3653. retry:
  3654. wlogprint("\nCurrent pool management strategy: %s\n",
  3655. strategies[pool_strategy]);
  3656. if (pool_strategy == POOL_ROTATE)
  3657. wlogprint("Set to rotate every %d minutes\n", opt_rotate_period);
  3658. wlogprint("[F]ailover only %s\n", opt_fail_only ? "enabled" : "disabled");
  3659. wlogprint("[A]dd pool [R]emove pool [D]isable pool [E]nable pool\n");
  3660. wlogprint("[C]hange management strategy [S]witch pool [I]nformation\n");
  3661. wlogprint("Or press any other key to continue\n");
  3662. input = getch();
  3663. if (!strncasecmp(&input, "a", 1)) {
  3664. input_pool(true);
  3665. goto updated;
  3666. } else if (!strncasecmp(&input, "r", 1)) {
  3667. if (total_pools <= 1) {
  3668. wlogprint("Cannot remove last pool");
  3669. goto retry;
  3670. }
  3671. selected = curses_int("Select pool number");
  3672. if (selected < 0 || selected >= total_pools) {
  3673. wlogprint("Invalid selection\n");
  3674. goto retry;
  3675. }
  3676. pool = pools[selected];
  3677. if (pool == current_pool())
  3678. switch_pools(NULL);
  3679. if (pool == current_pool()) {
  3680. wlogprint("Unable to remove pool due to activity\n");
  3681. goto retry;
  3682. }
  3683. disable_pool(pool);
  3684. remove_pool(pool);
  3685. goto updated;
  3686. } else if (!strncasecmp(&input, "s", 1)) {
  3687. selected = curses_int("Select pool number");
  3688. if (selected < 0 || selected >= total_pools) {
  3689. wlogprint("Invalid selection\n");
  3690. goto retry;
  3691. }
  3692. pool = pools[selected];
  3693. enable_pool(pool);
  3694. switch_pools(pool);
  3695. goto updated;
  3696. } else if (!strncasecmp(&input, "d", 1)) {
  3697. if (enabled_pools <= 1) {
  3698. wlogprint("Cannot disable last pool");
  3699. goto retry;
  3700. }
  3701. selected = curses_int("Select pool number");
  3702. if (selected < 0 || selected >= total_pools) {
  3703. wlogprint("Invalid selection\n");
  3704. goto retry;
  3705. }
  3706. pool = pools[selected];
  3707. disable_pool(pool);
  3708. if (pool == current_pool())
  3709. switch_pools(NULL);
  3710. goto updated;
  3711. } else if (!strncasecmp(&input, "e", 1)) {
  3712. selected = curses_int("Select pool number");
  3713. if (selected < 0 || selected >= total_pools) {
  3714. wlogprint("Invalid selection\n");
  3715. goto retry;
  3716. }
  3717. pool = pools[selected];
  3718. enable_pool(pool);
  3719. if (pool->prio < current_pool()->prio)
  3720. switch_pools(pool);
  3721. goto updated;
  3722. } else if (!strncasecmp(&input, "c", 1)) {
  3723. for (i = 0; i <= TOP_STRATEGY; i++)
  3724. wlogprint("%d: %s\n", i, strategies[i]);
  3725. selected = curses_int("Select strategy number type");
  3726. if (selected < 0 || selected > TOP_STRATEGY) {
  3727. wlogprint("Invalid selection\n");
  3728. goto retry;
  3729. }
  3730. if (selected == POOL_ROTATE) {
  3731. opt_rotate_period = curses_int("Select interval in minutes");
  3732. if (opt_rotate_period < 0 || opt_rotate_period > 9999) {
  3733. opt_rotate_period = 0;
  3734. wlogprint("Invalid selection\n");
  3735. goto retry;
  3736. }
  3737. }
  3738. pool_strategy = selected;
  3739. switch_pools(NULL);
  3740. goto updated;
  3741. } else if (!strncasecmp(&input, "i", 1)) {
  3742. selected = curses_int("Select pool number");
  3743. if (selected < 0 || selected >= total_pools) {
  3744. wlogprint("Invalid selection\n");
  3745. goto retry;
  3746. }
  3747. pool = pools[selected];
  3748. display_pool_summary(pool);
  3749. goto retry;
  3750. } else if (!strncasecmp(&input, "f", 1)) {
  3751. opt_fail_only ^= true;
  3752. goto updated;
  3753. } else
  3754. clear_logwin();
  3755. immedok(logwin, false);
  3756. opt_loginput = false;
  3757. }
  3758. static void display_options(void)
  3759. {
  3760. int selected;
  3761. char input;
  3762. opt_loginput = true;
  3763. immedok(logwin, true);
  3764. clear_logwin();
  3765. retry:
  3766. wlogprint("[N]ormal [C]lear [S]ilent mode (disable all output)\n");
  3767. 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",
  3768. opt_debug_console ? "on" : "off",
  3769. want_per_device_stats? "on" : "off",
  3770. opt_quiet ? "on" : "off",
  3771. opt_log_output ? "on" : "off",
  3772. opt_protocol ? "on" : "off",
  3773. opt_worktime ? "on" : "off",
  3774. opt_log_interval);
  3775. wlogprint("Select an option or any other key to return\n");
  3776. input = getch();
  3777. if (!strncasecmp(&input, "q", 1)) {
  3778. opt_quiet ^= true;
  3779. wlogprint("Quiet mode %s\n", opt_quiet ? "enabled" : "disabled");
  3780. goto retry;
  3781. } else if (!strncasecmp(&input, "v", 1)) {
  3782. opt_log_output ^= true;
  3783. if (opt_log_output)
  3784. opt_quiet = false;
  3785. wlogprint("Verbose mode %s\n", opt_log_output ? "enabled" : "disabled");
  3786. goto retry;
  3787. } else if (!strncasecmp(&input, "n", 1)) {
  3788. opt_log_output = false;
  3789. opt_debug_console = false;
  3790. opt_quiet = false;
  3791. opt_protocol = false;
  3792. want_per_device_stats = false;
  3793. wlogprint("Output mode reset to normal\n");
  3794. goto retry;
  3795. } else if (!strncasecmp(&input, "d", 1)) {
  3796. opt_debug = true;
  3797. opt_debug_console ^= true;
  3798. opt_log_output = opt_debug_console;
  3799. if (opt_debug_console)
  3800. opt_quiet = false;
  3801. wlogprint("Debug mode %s\n", opt_debug_console ? "enabled" : "disabled");
  3802. goto retry;
  3803. } else if (!strncasecmp(&input, "p", 1)) {
  3804. want_per_device_stats ^= true;
  3805. opt_log_output = want_per_device_stats;
  3806. wlogprint("Per-device stats %s\n", want_per_device_stats ? "enabled" : "disabled");
  3807. goto retry;
  3808. } else if (!strncasecmp(&input, "r", 1)) {
  3809. opt_protocol ^= true;
  3810. if (opt_protocol)
  3811. opt_quiet = false;
  3812. wlogprint("RPC protocol debugging %s\n", opt_protocol ? "enabled" : "disabled");
  3813. goto retry;
  3814. } else if (!strncasecmp(&input, "c", 1))
  3815. clear_logwin();
  3816. else if (!strncasecmp(&input, "l", 1)) {
  3817. selected = curses_int("Interval in seconds");
  3818. if (selected < 0 || selected > 9999) {
  3819. wlogprint("Invalid selection\n");
  3820. goto retry;
  3821. }
  3822. opt_log_interval = selected;
  3823. wlogprint("Log interval set to %d seconds\n", opt_log_interval);
  3824. goto retry;
  3825. } else if (!strncasecmp(&input, "s", 1)) {
  3826. opt_realquiet = true;
  3827. } else if (!strncasecmp(&input, "w", 1)) {
  3828. opt_worktime ^= true;
  3829. wlogprint("WorkTime details %s\n", opt_worktime ? "enabled" : "disabled");
  3830. goto retry;
  3831. } else
  3832. clear_logwin();
  3833. immedok(logwin, false);
  3834. opt_loginput = false;
  3835. }
  3836. #endif
  3837. void default_save_file(char *filename)
  3838. {
  3839. #if defined(unix)
  3840. if (getenv("HOME") && *getenv("HOME")) {
  3841. strcpy(filename, getenv("HOME"));
  3842. strcat(filename, "/");
  3843. }
  3844. else
  3845. strcpy(filename, "");
  3846. strcat(filename, ".bfgminer/");
  3847. mkdir(filename, 0777);
  3848. #else
  3849. strcpy(filename, "");
  3850. #endif
  3851. strcat(filename, def_conf);
  3852. }
  3853. #ifdef HAVE_CURSES
  3854. static void set_options(void)
  3855. {
  3856. int selected;
  3857. char input;
  3858. opt_loginput = true;
  3859. immedok(logwin, true);
  3860. clear_logwin();
  3861. retry:
  3862. wlogprint("\n[L]ongpoll: %s\n", want_longpoll ? "On" : "Off");
  3863. wlogprint("[Q]ueue: %d\n[S]cantime: %d\n[E]xpiry: %d\n[R]etries: %d\n"
  3864. "[W]rite config file\n[B]FGMiner restart\n",
  3865. opt_queue, opt_scantime, opt_expiry, opt_retries);
  3866. wlogprint("Select an option or any other key to return\n");
  3867. input = getch();
  3868. if (!strncasecmp(&input, "q", 1)) {
  3869. selected = curses_int("Extra work items to queue");
  3870. if (selected < 0 || selected > 9999) {
  3871. wlogprint("Invalid selection\n");
  3872. goto retry;
  3873. }
  3874. opt_queue = selected;
  3875. goto retry;
  3876. } else if (!strncasecmp(&input, "l", 1)) {
  3877. if (want_longpoll)
  3878. stop_longpoll();
  3879. else
  3880. start_longpoll();
  3881. applog(LOG_WARNING, "Longpoll %s", want_longpoll ? "enabled" : "disabled");
  3882. goto retry;
  3883. } else if (!strncasecmp(&input, "s", 1)) {
  3884. selected = curses_int("Set scantime in seconds");
  3885. if (selected < 0 || selected > 9999) {
  3886. wlogprint("Invalid selection\n");
  3887. goto retry;
  3888. }
  3889. opt_scantime = selected;
  3890. goto retry;
  3891. } else if (!strncasecmp(&input, "e", 1)) {
  3892. selected = curses_int("Set expiry time in seconds");
  3893. if (selected < 0 || selected > 9999) {
  3894. wlogprint("Invalid selection\n");
  3895. goto retry;
  3896. }
  3897. opt_expiry = selected;
  3898. goto retry;
  3899. } else if (!strncasecmp(&input, "r", 1)) {
  3900. selected = curses_int("Retries before failing (-1 infinite)");
  3901. if (selected < -1 || selected > 9999) {
  3902. wlogprint("Invalid selection\n");
  3903. goto retry;
  3904. }
  3905. opt_retries = selected;
  3906. goto retry;
  3907. } else if (!strncasecmp(&input, "w", 1)) {
  3908. FILE *fcfg;
  3909. char *str, filename[PATH_MAX], prompt[PATH_MAX + 50];
  3910. default_save_file(filename);
  3911. sprintf(prompt, "Config filename to write (Enter for default) [%s]", filename);
  3912. str = curses_input(prompt);
  3913. if (strcmp(str, "-1")) {
  3914. struct stat statbuf;
  3915. strcpy(filename, str);
  3916. if (!stat(filename, &statbuf)) {
  3917. wlogprint("File exists, overwrite?\n");
  3918. input = getch();
  3919. if (strncasecmp(&input, "y", 1))
  3920. goto retry;
  3921. }
  3922. }
  3923. fcfg = fopen(filename, "w");
  3924. if (!fcfg) {
  3925. wlogprint("Cannot open or create file\n");
  3926. goto retry;
  3927. }
  3928. write_config(fcfg);
  3929. fclose(fcfg);
  3930. goto retry;
  3931. } else if (!strncasecmp(&input, "b", 1)) {
  3932. wlogprint("Are you sure?\n");
  3933. input = getch();
  3934. if (!strncasecmp(&input, "y", 1))
  3935. app_restart();
  3936. else
  3937. clear_logwin();
  3938. } else
  3939. clear_logwin();
  3940. immedok(logwin, false);
  3941. opt_loginput = false;
  3942. }
  3943. static void *input_thread(void __maybe_unused *userdata)
  3944. {
  3945. rename_thr("bfg-input");
  3946. if (!curses_active)
  3947. return NULL;
  3948. while (1) {
  3949. int input;
  3950. input = getch();
  3951. switch (input) {
  3952. case 'q': case 'Q':
  3953. kill_work();
  3954. return NULL;
  3955. case 'd': case 'D':
  3956. display_options();
  3957. break;
  3958. case 'p': case 'P':
  3959. display_pools();
  3960. break;
  3961. case 's': case 'S':
  3962. set_options();
  3963. break;
  3964. case 'g': case 'G':
  3965. if (have_opencl)
  3966. manage_gpu();
  3967. break;
  3968. #ifdef HAVE_CURSES
  3969. case KEY_DOWN:
  3970. if (devsummaryYOffset < -(total_devices + devcursor - statusy))
  3971. break;
  3972. devsummaryYOffset -= 2;
  3973. case KEY_UP:
  3974. if (devsummaryYOffset == 0)
  3975. break;
  3976. ++devsummaryYOffset;
  3977. if (curses_active_locked()) {
  3978. int i;
  3979. for (i = 0; i < mining_threads; i++)
  3980. curses_print_devstatus(i);
  3981. touchwin(statuswin);
  3982. wrefresh(statuswin);
  3983. unlock_curses();
  3984. }
  3985. break;
  3986. #endif
  3987. }
  3988. if (opt_realquiet) {
  3989. disable_curses();
  3990. break;
  3991. }
  3992. }
  3993. return NULL;
  3994. }
  3995. #endif
  3996. /* This thread should not be shut down unless a problem occurs */
  3997. static void *workio_thread(void *userdata)
  3998. {
  3999. struct thr_info *mythr = userdata;
  4000. bool ok = true;
  4001. rename_thr("bfg-workio");
  4002. while (ok) {
  4003. struct workio_cmd *wc;
  4004. applog(LOG_DEBUG, "Popping work to work thread");
  4005. /* wait for workio_cmd sent to us, on our queue */
  4006. wc = tq_pop(mythr->q, NULL);
  4007. if (unlikely(!wc)) {
  4008. applog(LOG_ERR, "Failed to tq_pop in workio_thread");
  4009. ok = false;
  4010. break;
  4011. }
  4012. /* process workio_cmd */
  4013. switch (wc->cmd) {
  4014. case WC_GET_WORK:
  4015. ok = workio_get_work(wc);
  4016. break;
  4017. case WC_SUBMIT_WORK:
  4018. {
  4019. mutex_lock(&submitting_lock);
  4020. if (submitting >= opt_submit_threads) {
  4021. if (list_empty(&submit_waiting))
  4022. applog(LOG_WARNING, "workio_thread queuing submissions (see --submit-threads)");
  4023. else
  4024. applog(LOG_DEBUG, "workio_thread queuing submission");
  4025. list_add_tail(&wc->list, &submit_waiting);
  4026. mutex_unlock(&submitting_lock);
  4027. break;
  4028. }
  4029. ++submitting;
  4030. mutex_unlock(&submitting_lock);
  4031. ok = workio_submit_work(wc);
  4032. break;
  4033. }
  4034. default:
  4035. ok = false;
  4036. break;
  4037. }
  4038. }
  4039. tq_freeze(mythr->q);
  4040. return NULL;
  4041. }
  4042. static void *api_thread(void *userdata)
  4043. {
  4044. struct thr_info *mythr = userdata;
  4045. pthread_detach(pthread_self());
  4046. rename_thr("bfg-rpc");
  4047. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  4048. api(api_thr_id);
  4049. PTH(mythr) = 0L;
  4050. return NULL;
  4051. }
  4052. void thread_reportin(struct thr_info *thr)
  4053. {
  4054. gettimeofday(&thr->last, NULL);
  4055. thr->cgpu->status = LIFE_WELL;
  4056. thr->getwork = 0;
  4057. thr->cgpu->device_last_well = time(NULL);
  4058. }
  4059. static inline void thread_reportout(struct thr_info *thr)
  4060. {
  4061. thr->getwork = time(NULL);
  4062. }
  4063. static void hashmeter(int thr_id, struct timeval *diff,
  4064. unsigned long long hashes_done)
  4065. {
  4066. struct timeval temp_tv_end, total_diff;
  4067. double secs;
  4068. double local_secs;
  4069. double utility, efficiency = 0.0;
  4070. static double local_mhashes_done = 0;
  4071. static double rolling = 0;
  4072. double local_mhashes = (double)hashes_done / 1000000.0;
  4073. bool showlog = false;
  4074. char cHr[h2bs_fmt_size[H2B_NOUNIT]], aHr[h2bs_fmt_size[H2B_NOUNIT]], uHr[h2bs_fmt_size[H2B_SPACED]];
  4075. /* Update the last time this thread reported in */
  4076. if (thr_id >= 0) {
  4077. gettimeofday(&thr_info[thr_id].last, NULL);
  4078. thr_info[thr_id].cgpu->device_last_well = time(NULL);
  4079. }
  4080. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  4081. /* So we can call hashmeter from a non worker thread */
  4082. if (thr_id >= 0) {
  4083. struct thr_info *thr = &thr_info[thr_id];
  4084. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  4085. double thread_rolling = 0.0;
  4086. int i;
  4087. applog(LOG_DEBUG, "[thread %d: %llu hashes, %.1f khash/sec]",
  4088. thr_id, hashes_done, hashes_done / 1000 / secs);
  4089. /* Rolling average for each thread and each device */
  4090. decay_time(&thr->rolling, local_mhashes / secs);
  4091. for (i = 0; i < cgpu->threads; i++)
  4092. thread_rolling += cgpu->thr[i]->rolling;
  4093. mutex_lock(&hash_lock);
  4094. decay_time(&cgpu->rolling, thread_rolling);
  4095. cgpu->total_mhashes += local_mhashes;
  4096. mutex_unlock(&hash_lock);
  4097. // If needed, output detailed, per-device stats
  4098. if (want_per_device_stats) {
  4099. struct timeval now;
  4100. struct timeval elapsed;
  4101. gettimeofday(&now, NULL);
  4102. timersub(&now, &thr->cgpu->last_message_tv, &elapsed);
  4103. if (opt_log_interval <= elapsed.tv_sec) {
  4104. struct cgpu_info *cgpu = thr->cgpu;
  4105. char logline[255];
  4106. cgpu->last_message_tv = now;
  4107. get_statline(logline, cgpu);
  4108. if (!curses_active) {
  4109. printf("%s \r", logline);
  4110. fflush(stdout);
  4111. } else
  4112. applog(LOG_INFO, "%s", logline);
  4113. }
  4114. }
  4115. }
  4116. /* Totals are updated by all threads so can race without locking */
  4117. mutex_lock(&hash_lock);
  4118. gettimeofday(&temp_tv_end, NULL);
  4119. timersub(&temp_tv_end, &total_tv_end, &total_diff);
  4120. total_mhashes_done += local_mhashes;
  4121. local_mhashes_done += local_mhashes;
  4122. if (total_diff.tv_sec < opt_log_interval)
  4123. /* Only update the total every opt_log_interval seconds */
  4124. goto out_unlock;
  4125. showlog = true;
  4126. gettimeofday(&total_tv_end, NULL);
  4127. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  4128. decay_time(&rolling, local_mhashes_done / local_secs);
  4129. global_hashrate = roundl(rolling) * 1000000;
  4130. timersub(&total_tv_end, &total_tv_start, &total_diff);
  4131. total_secs = (double)total_diff.tv_sec +
  4132. ((double)total_diff.tv_usec / 1000000.0);
  4133. utility = total_accepted / total_secs * 60;
  4134. efficiency = total_getworks ? total_accepted * 100.0 / total_getworks : 0.0;
  4135. ti_hashrate_bufstr(
  4136. (char*[]){cHr, aHr, uHr},
  4137. 1e6*rolling,
  4138. 1e6*total_mhashes_done / total_secs,
  4139. utility_to_hashrate(total_accepted_weighed / (total_secs ?: 1) * 60),
  4140. H2B_SPACED);
  4141. sprintf(statusline, "%s%ds:%s avg:%s u:%s | A:%d R:%d HW:%d E:%.0f%% U:%.1f/m",
  4142. want_per_device_stats ? "ALL " : "",
  4143. opt_log_interval,
  4144. cHr, aHr,
  4145. uHr,
  4146. total_accepted, total_rejected, hw_errors, efficiency, utility);
  4147. local_mhashes_done = 0;
  4148. out_unlock:
  4149. mutex_unlock(&hash_lock);
  4150. if (showlog) {
  4151. if (!curses_active) {
  4152. printf("%s \r", statusline);
  4153. fflush(stdout);
  4154. } else
  4155. applog(LOG_INFO, "%s", statusline);
  4156. }
  4157. }
  4158. static void *longpoll_thread(void *userdata);
  4159. // NOTE: This assumes reference URI is a root
  4160. static char *absolute_uri(char *uri, const char *ref)
  4161. {
  4162. if (strstr(uri, "://"))
  4163. return strdup(uri);
  4164. char *copy_start, *abs;
  4165. bool need_slash = false;
  4166. copy_start = (uri[0] == '/') ? &uri[1] : uri;
  4167. if (ref[strlen(ref) - 1] != '/')
  4168. need_slash = true;
  4169. abs = malloc(strlen(ref) + strlen(copy_start) + 2);
  4170. if (!abs) {
  4171. applog(LOG_ERR, "Malloc failure in absolute_uri");
  4172. return NULL;
  4173. }
  4174. sprintf(abs, "%s%s%s", ref, need_slash ? "/" : "", copy_start);
  4175. return abs;
  4176. }
  4177. static bool pool_active(struct pool *pool, bool pinging)
  4178. {
  4179. struct timeval tv_getwork, tv_getwork_reply;
  4180. bool ret = false;
  4181. json_t *val;
  4182. CURL *curl;
  4183. int rolltime;
  4184. char *rpc_req;
  4185. struct work *work;
  4186. enum pool_protocol proto;
  4187. curl = curl_easy_init();
  4188. if (unlikely(!curl)) {
  4189. applog(LOG_ERR, "CURL initialisation failed");
  4190. return false;
  4191. }
  4192. work = make_work();
  4193. work->pool = pool;
  4194. proto = want_gbt ? PLP_GETBLOCKTEMPLATE : PLP_GETWORK;
  4195. tryagain:
  4196. rpc_req = prepare_rpc_req(work, proto, NULL);
  4197. if (!rpc_req)
  4198. return false;
  4199. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  4200. pool->probed = false;
  4201. gettimeofday(&tv_getwork, NULL);
  4202. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  4203. true, false, &rolltime, pool, false);
  4204. gettimeofday(&tv_getwork_reply, NULL);
  4205. if (val) {
  4206. bool rc;
  4207. json_t *res;
  4208. res = json_object_get(val, "result");
  4209. if ((!json_is_object(res)) || (proto == PLP_GETBLOCKTEMPLATE && !json_object_get(res, "bits")))
  4210. goto badwork;
  4211. rc = work_decode(res, work);
  4212. if (rc) {
  4213. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  4214. pool->pool_no, pool->rpc_url);
  4215. work->pool = pool;
  4216. work->rolltime = rolltime;
  4217. memcpy(&(work->tv_getwork), &tv_getwork, sizeof(struct timeval));
  4218. memcpy(&(work->tv_getwork_reply), &tv_getwork_reply, sizeof(struct timeval));
  4219. work->getwork_mode = GETWORK_MODE_TESTPOOL;
  4220. calc_diff(work);
  4221. applog(LOG_DEBUG, "Pushing pooltest work to base pool");
  4222. tq_push(thr_info[stage_thr_id].q, work);
  4223. total_getworks++;
  4224. pool->getwork_requested++;
  4225. ret = true;
  4226. gettimeofday(&pool->tv_idle, NULL);
  4227. } else {
  4228. badwork:
  4229. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher work from pool %u %s",
  4230. pool->pool_no, pool->rpc_url);
  4231. if (PLP_NONE != (proto = pool_protocol_fallback(proto)))
  4232. goto tryagain;
  4233. free_work(work);
  4234. goto out;
  4235. }
  4236. json_decref(val);
  4237. if (proto != pool->proto) {
  4238. pool->proto = proto;
  4239. applog(LOG_INFO, "Selected %s protocol for pool %u", pool_protocol_name(proto), pool->pool_no);
  4240. }
  4241. if (pool->lp_url)
  4242. goto out;
  4243. /* Decipher the longpoll URL, if any, and store it in ->lp_url */
  4244. const struct blktmpl_longpoll_req *lp;
  4245. if (work->tmpl && (lp = blktmpl_get_longpoll(work->tmpl))) {
  4246. // NOTE: work_decode takes care of lp id
  4247. pool->lp_url = lp->uri ? absolute_uri(lp->uri, pool->rpc_url) : pool->rpc_url;
  4248. if (!pool->lp_url)
  4249. return false;
  4250. pool->lp_proto = PLP_GETBLOCKTEMPLATE;
  4251. }
  4252. else
  4253. if (pool->hdr_path) {
  4254. pool->lp_url = absolute_uri(pool->hdr_path, pool->rpc_url);
  4255. if (!pool->lp_url)
  4256. return false;
  4257. pool->lp_proto = PLP_GETWORK;
  4258. } else
  4259. pool->lp_url = NULL;
  4260. if (want_longpoll && !pool->lp_started) {
  4261. pool->lp_started = true;
  4262. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  4263. quit(1, "Failed to create pool longpoll thread");
  4264. }
  4265. } else if (PLP_NONE != (proto = pool_protocol_fallback(proto))) {
  4266. goto tryagain;
  4267. } else {
  4268. free_work(work);
  4269. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  4270. pool->pool_no, pool->rpc_url);
  4271. if (!pinging)
  4272. applog(LOG_WARNING, "Pool %u slow/down or URL or credentials invalid", pool->pool_no);
  4273. }
  4274. out:
  4275. curl_easy_cleanup(curl);
  4276. return ret;
  4277. }
  4278. static inline int cp_prio(void)
  4279. {
  4280. int prio;
  4281. mutex_lock(&control_lock);
  4282. prio = currentpool->prio;
  4283. mutex_unlock(&control_lock);
  4284. return prio;
  4285. }
  4286. static void pool_resus(struct pool *pool)
  4287. {
  4288. applog(LOG_WARNING, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  4289. if (pool->prio < cp_prio() && pool_strategy == POOL_FAILOVER)
  4290. switch_pools(NULL);
  4291. }
  4292. static bool queue_request(void)
  4293. {
  4294. int ts, tq, maxq = opt_queue + mining_threads;
  4295. struct pool *pool, *cp;
  4296. struct workio_cmd *wc;
  4297. bool lagging;
  4298. ts = total_staged();
  4299. tq = global_queued();
  4300. if (ts && ts + tq >= maxq)
  4301. return true;
  4302. cp = current_pool();
  4303. lagging = !opt_fail_only && cp->lagging && !ts && cp->queued >= maxq;
  4304. if (!lagging && cp->staged + cp->queued >= maxq)
  4305. return true;
  4306. pool = select_pool(lagging);
  4307. if (pool->staged + pool->queued >= maxq)
  4308. return true;
  4309. /* fill out work request message */
  4310. wc = calloc(1, sizeof(*wc));
  4311. if (unlikely(!wc)) {
  4312. applog(LOG_ERR, "Failed to calloc wc in queue_request");
  4313. return false;
  4314. }
  4315. wc->cmd = WC_GET_WORK;
  4316. wc->pool = pool;
  4317. applog(LOG_DEBUG, "Queueing getwork request to work thread");
  4318. /* send work request to workio thread */
  4319. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  4320. applog(LOG_ERR, "Failed to tq_push in queue_request");
  4321. workio_cmd_free(wc);
  4322. return false;
  4323. }
  4324. inc_queued(pool);
  4325. return true;
  4326. }
  4327. static struct work *hash_pop(const struct timespec *abstime)
  4328. {
  4329. struct work *work = NULL, *tmp;
  4330. int rc = 0, hc;
  4331. mutex_lock(stgd_lock);
  4332. while (!getq->frozen && !HASH_COUNT(staged_work) && !rc)
  4333. rc = pthread_cond_timedwait(&getq->cond, stgd_lock, abstime);
  4334. hc = HASH_COUNT(staged_work);
  4335. if (likely(hc)) {
  4336. /* Find clone work if possible, to allow masters to be reused */
  4337. if (hc > staged_rollable) {
  4338. HASH_ITER(hh, staged_work, work, tmp) {
  4339. if (!work_rollable(work))
  4340. break;
  4341. }
  4342. } else
  4343. work = staged_work;
  4344. HASH_DEL(staged_work, work);
  4345. work->pool->staged--;
  4346. if (work_rollable(work))
  4347. staged_rollable--;
  4348. }
  4349. mutex_unlock(stgd_lock);
  4350. queue_request();
  4351. return work;
  4352. }
  4353. static bool reuse_work(struct work *work)
  4354. {
  4355. if (can_roll(work) && should_roll(work)) {
  4356. roll_work(work);
  4357. return true;
  4358. }
  4359. return false;
  4360. }
  4361. /* Clones work by rolling it if possible, and returning a clone instead of the
  4362. * original work item which gets staged again to possibly be rolled again in
  4363. * the future */
  4364. static struct work *clone_work(struct work *work)
  4365. {
  4366. int mrs = mining_threads + opt_queue - total_staged();
  4367. struct work *work_clone;
  4368. bool cloned;
  4369. if (mrs < 1)
  4370. return work;
  4371. cloned = false;
  4372. work_clone = make_clone(work);
  4373. while (mrs-- > 0 && can_roll(work) && should_roll(work)) {
  4374. applog(LOG_DEBUG, "Pushing rolled converted work to stage thread");
  4375. if (unlikely(!stage_work(work_clone))) {
  4376. cloned = false;
  4377. break;
  4378. }
  4379. roll_work(work);
  4380. work_clone = make_clone(work);
  4381. /* Roll it again to prevent duplicates should this be used
  4382. * directly later on */
  4383. roll_work(work);
  4384. cloned = true;
  4385. }
  4386. if (cloned) {
  4387. stage_work(work);
  4388. return work_clone;
  4389. }
  4390. free_work(work_clone);
  4391. return work;
  4392. }
  4393. static void get_work(struct work *work, struct thr_info *thr, const int thr_id)
  4394. {
  4395. struct timespec abstime = {0, 0};
  4396. struct work *work_heap;
  4397. struct timeval now;
  4398. struct pool *pool;
  4399. /* Tell the watchdog thread this thread is waiting on getwork and
  4400. * should not be restarted */
  4401. thread_reportout(thr);
  4402. if (opt_benchmark) {
  4403. get_benchmark_work(work);
  4404. goto out;
  4405. }
  4406. retry:
  4407. pool = current_pool();
  4408. if (reuse_work(work))
  4409. goto out;
  4410. if (!pool->lagging && !total_staged() && global_queued() >= mining_threads + opt_queue) {
  4411. struct cgpu_info *cgpu = thr->cgpu;
  4412. bool stalled = true;
  4413. int i;
  4414. /* Check to see if all the threads on the device that called
  4415. * get_work are waiting on work and only consider the pool
  4416. * lagging if true */
  4417. for (i = 0; i < cgpu->threads; i++) {
  4418. if (!cgpu->thr[i]->getwork) {
  4419. stalled = false;
  4420. break;
  4421. }
  4422. }
  4423. if (stalled && !pool_tset(pool, &pool->lagging)) {
  4424. applog(LOG_WARNING, "Pool %d not providing work fast enough", pool->pool_no);
  4425. pool->getfail_occasions++;
  4426. total_go++;
  4427. }
  4428. }
  4429. gettimeofday(&now, NULL);
  4430. abstime.tv_sec = now.tv_sec + 60;
  4431. applog(LOG_DEBUG, "Popping work from get queue to get work");
  4432. keepwaiting:
  4433. /* wait for 1st response, or get cached response */
  4434. work_heap = hash_pop(&abstime);
  4435. if (unlikely(!work_heap)) {
  4436. /* Attempt to switch pools if this one times out */
  4437. pool_died(pool);
  4438. if (pool == current_pool())
  4439. goto keepwaiting;
  4440. goto retry;
  4441. }
  4442. if (stale_work(work_heap, false)) {
  4443. discard_work(work_heap);
  4444. goto retry;
  4445. }
  4446. pool = work_heap->pool;
  4447. /* If we make it here we have succeeded in getting fresh work */
  4448. if (!work_heap->mined) {
  4449. /* Only clear the lagging flag if we are staging them at a
  4450. * rate faster then we're using them */
  4451. if (pool->lagging && total_staged())
  4452. pool_tclear(pool, &pool->lagging);
  4453. if (pool_tclear(pool, &pool->idle))
  4454. pool_resus(pool);
  4455. }
  4456. memcpy(work, work_heap, sizeof(struct work));
  4457. free(work_heap);
  4458. out:
  4459. work->thr_id = thr_id;
  4460. thread_reportin(thr);
  4461. work->mined = true;
  4462. }
  4463. bool submit_work_sync(struct thr_info *thr, const struct work *work_in, struct timeval *tv_work_found)
  4464. {
  4465. struct workio_cmd *wc;
  4466. /* fill out work request message */
  4467. wc = calloc(1, sizeof(*wc));
  4468. if (unlikely(!wc)) {
  4469. applog(LOG_ERR, "Failed to calloc wc in submit_work_sync");
  4470. return false;
  4471. }
  4472. wc->work = make_work();
  4473. wc->cmd = WC_SUBMIT_WORK;
  4474. wc->thr = thr;
  4475. workcpy(wc->work, work_in);
  4476. if (tv_work_found)
  4477. memcpy(&(wc->work->tv_work_found), tv_work_found, sizeof(struct timeval));
  4478. applog(LOG_DEBUG, "Pushing submit work to work thread");
  4479. /* send solution to workio thread */
  4480. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  4481. applog(LOG_ERR, "Failed to tq_push work in submit_work_sync");
  4482. goto err_out;
  4483. }
  4484. return true;
  4485. err_out:
  4486. workio_cmd_free(wc);
  4487. return false;
  4488. }
  4489. enum test_nonce2_result hashtest2(const struct work *work, bool checktarget)
  4490. {
  4491. uint32_t *data32 = (uint32_t *)(work->data);
  4492. unsigned char swap[128];
  4493. uint32_t *swap32 = (uint32_t *)swap;
  4494. unsigned char hash1[32];
  4495. unsigned char hash2[32];
  4496. uint32_t *hash2_32 = (uint32_t *)hash2;
  4497. swap32yes(swap32, data32, 80 / 4);
  4498. sha2(swap, 80, hash1, false);
  4499. sha2(hash1, 32, hash2, false);
  4500. if (hash2_32[7] != 0)
  4501. return TNR_BAD;
  4502. if (!checktarget)
  4503. return TNR_GOOD;
  4504. swap32yes(hash2_32, hash2_32, 32 / 4);
  4505. memcpy((void*)work->hash, hash2, 32);
  4506. if (!fulltest(work->hash, work->target))
  4507. return TNR_HIGH;
  4508. return TNR_GOOD;
  4509. }
  4510. enum test_nonce2_result _test_nonce2(struct work *work, uint32_t nonce, bool checktarget)
  4511. {
  4512. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  4513. *work_nonce = nonce;
  4514. #ifdef USE_SCRYPT
  4515. if (opt_scrypt) {
  4516. if (!scrypt_test(work->data, work->target, nonce))
  4517. return TNR_BAD;
  4518. return TNR_GOOD;
  4519. }
  4520. #endif
  4521. return hashtest2(work, checktarget);
  4522. }
  4523. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  4524. {
  4525. struct timeval tv_work_found;
  4526. gettimeofday(&tv_work_found, NULL);
  4527. total_diff1++;
  4528. thr->cgpu->diff1++;
  4529. work->pool->diff1++;
  4530. /* Do one last check before attempting to submit the work */
  4531. /* Side effect: sets work->data for us */
  4532. switch (test_nonce2(work, nonce)) {
  4533. case TNR_BAD:
  4534. {
  4535. struct cgpu_info *cgpu = thr->cgpu;
  4536. applog(LOG_WARNING, "%s %u: invalid nonce - HW error",
  4537. cgpu->api->name, cgpu->device_id);
  4538. ++hw_errors;
  4539. ++thr->cgpu->hw_errors;
  4540. return false;
  4541. }
  4542. case TNR_HIGH:
  4543. // Share above target, normal
  4544. return true;
  4545. case TNR_GOOD:
  4546. break;
  4547. }
  4548. return submit_work_sync(thr, work, &tv_work_found);
  4549. }
  4550. static inline bool abandon_work(struct work *work, struct timeval *wdiff, uint64_t hashes)
  4551. {
  4552. if (wdiff->tv_sec > opt_scantime ||
  4553. work->blk.nonce >= MAXTHREADS - hashes ||
  4554. hashes >= 0xfffffffe ||
  4555. stale_work(work, false))
  4556. return true;
  4557. return false;
  4558. }
  4559. static void mt_disable(struct thr_info *mythr, const int thr_id,
  4560. const struct device_api *api)
  4561. {
  4562. applog(LOG_WARNING, "Thread %d being disabled", thr_id);
  4563. mythr->rolling = mythr->cgpu->rolling = 0;
  4564. applog(LOG_DEBUG, "Popping wakeup ping in miner thread");
  4565. thread_reportout(mythr);
  4566. do {
  4567. tq_pop(mythr->q, NULL); /* Ignore ping that's popped */
  4568. } while (mythr->pause);
  4569. thread_reportin(mythr);
  4570. applog(LOG_WARNING, "Thread %d being re-enabled", thr_id);
  4571. if (api->thread_enable)
  4572. api->thread_enable(mythr);
  4573. }
  4574. void *miner_thread(void *userdata)
  4575. {
  4576. struct thr_info *mythr = userdata;
  4577. const int thr_id = mythr->id;
  4578. struct cgpu_info *cgpu = mythr->cgpu;
  4579. const struct device_api *api = cgpu->api;
  4580. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  4581. struct cgminer_stats *pool_stats;
  4582. struct timeval getwork_start;
  4583. {
  4584. char thrname[16];
  4585. sprintf(thrname, "bfg-miner-%s%d", api->name, cgpu->device_id);
  4586. rename_thr(thrname);
  4587. }
  4588. /* Try to cycle approximately 5 times before each log update */
  4589. const long cycle = opt_log_interval / 5 ? : 1;
  4590. struct timeval tv_start, tv_end, tv_workstart, tv_lastupdate;
  4591. struct timeval diff, sdiff, wdiff = {0, 0};
  4592. uint32_t max_nonce = api->can_limit_work ? api->can_limit_work(mythr) : 0xffffffff;
  4593. int64_t hashes_done = 0;
  4594. int64_t hashes;
  4595. struct work *work = make_work();
  4596. const bool primary = (!mythr->device_thread) || mythr->primary_thread;
  4597. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  4598. gettimeofday(&getwork_start, NULL);
  4599. if (api->thread_init && !api->thread_init(mythr)) {
  4600. cgpu->device_last_not_well = time(NULL);
  4601. cgpu->device_not_well_reason = REASON_THREAD_FAIL_INIT;
  4602. cgpu->thread_fail_init_count++;
  4603. goto out;
  4604. }
  4605. thread_reportout(mythr);
  4606. applog(LOG_DEBUG, "Popping ping in miner thread");
  4607. tq_pop(mythr->q, NULL); /* Wait for a ping to start */
  4608. sdiff.tv_sec = sdiff.tv_usec = 0;
  4609. gettimeofday(&tv_lastupdate, NULL);
  4610. while (1) {
  4611. mythr->work_restart = false;
  4612. if (api->free_work && likely(work->pool))
  4613. api->free_work(mythr, work);
  4614. get_work(work, mythr, thr_id);
  4615. cgpu->new_work = true;
  4616. gettimeofday(&tv_workstart, NULL);
  4617. work->blk.nonce = 0;
  4618. cgpu->max_hashes = 0;
  4619. if (api->prepare_work && !api->prepare_work(mythr, work)) {
  4620. applog(LOG_ERR, "work prepare failed, exiting "
  4621. "mining thread %d", thr_id);
  4622. break;
  4623. }
  4624. do {
  4625. gettimeofday(&tv_start, NULL);
  4626. timersub(&tv_start, &getwork_start, &getwork_start);
  4627. timeradd(&getwork_start,
  4628. &(dev_stats->getwork_wait),
  4629. &(dev_stats->getwork_wait));
  4630. if (timercmp(&getwork_start, &(dev_stats->getwork_wait_max), >)) {
  4631. dev_stats->getwork_wait_max.tv_sec = getwork_start.tv_sec;
  4632. dev_stats->getwork_wait_max.tv_usec = getwork_start.tv_usec;
  4633. }
  4634. if (timercmp(&getwork_start, &(dev_stats->getwork_wait_min), <)) {
  4635. dev_stats->getwork_wait_min.tv_sec = getwork_start.tv_sec;
  4636. dev_stats->getwork_wait_min.tv_usec = getwork_start.tv_usec;
  4637. }
  4638. dev_stats->getwork_calls++;
  4639. pool_stats = &(work->pool->cgminer_stats);
  4640. timeradd(&getwork_start,
  4641. &(pool_stats->getwork_wait),
  4642. &(pool_stats->getwork_wait));
  4643. if (timercmp(&getwork_start, &(pool_stats->getwork_wait_max), >)) {
  4644. pool_stats->getwork_wait_max.tv_sec = getwork_start.tv_sec;
  4645. pool_stats->getwork_wait_max.tv_usec = getwork_start.tv_usec;
  4646. }
  4647. if (timercmp(&getwork_start, &(pool_stats->getwork_wait_min), <)) {
  4648. pool_stats->getwork_wait_min.tv_sec = getwork_start.tv_sec;
  4649. pool_stats->getwork_wait_min.tv_usec = getwork_start.tv_usec;
  4650. }
  4651. pool_stats->getwork_calls++;
  4652. gettimeofday(&(work->tv_work_start), NULL);
  4653. thread_reportin(mythr);
  4654. hashes = api->scanhash(mythr, work, work->blk.nonce + max_nonce);
  4655. thread_reportin(mythr);
  4656. gettimeofday(&getwork_start, NULL);
  4657. if (unlikely(hashes == -1)) {
  4658. applog(LOG_ERR, "%s %d failure, disabling!", api->name, cgpu->device_id);
  4659. cgpu->deven = DEV_DISABLED;
  4660. cgpu->device_last_not_well = time(NULL);
  4661. cgpu->device_not_well_reason = REASON_THREAD_ZERO_HASH;
  4662. cgpu->thread_zero_hash_count++;
  4663. mt_disable(mythr, thr_id, api);
  4664. }
  4665. hashes_done += hashes;
  4666. if (hashes > cgpu->max_hashes)
  4667. cgpu->max_hashes = hashes;
  4668. gettimeofday(&tv_end, NULL);
  4669. timersub(&tv_end, &tv_start, &diff);
  4670. sdiff.tv_sec += diff.tv_sec;
  4671. sdiff.tv_usec += diff.tv_usec;
  4672. if (sdiff.tv_usec > 1000000) {
  4673. ++sdiff.tv_sec;
  4674. sdiff.tv_usec -= 1000000;
  4675. }
  4676. timersub(&tv_end, &tv_workstart, &wdiff);
  4677. if (unlikely((long)sdiff.tv_sec < cycle)) {
  4678. int mult;
  4679. if (likely(!api->can_limit_work || max_nonce == 0xffffffff))
  4680. continue;
  4681. mult = 1000000 / ((sdiff.tv_usec + 0x400) / 0x400) + 0x10;
  4682. mult *= cycle;
  4683. if (max_nonce > (0xffffffff * 0x400) / mult)
  4684. max_nonce = 0xffffffff;
  4685. else
  4686. max_nonce = (max_nonce * mult) / 0x400;
  4687. } else if (unlikely(sdiff.tv_sec > cycle) && api->can_limit_work)
  4688. max_nonce = max_nonce * cycle / sdiff.tv_sec;
  4689. else if (unlikely(sdiff.tv_usec > 100000) && api->can_limit_work)
  4690. max_nonce = max_nonce * 0x400 / (((cycle * 1000000) + sdiff.tv_usec) / (cycle * 1000000 / 0x400));
  4691. timersub(&tv_end, &tv_lastupdate, &diff);
  4692. if (diff.tv_sec >= opt_log_interval) {
  4693. hashmeter(thr_id, &diff, hashes_done);
  4694. hashes_done = 0;
  4695. tv_lastupdate = tv_end;
  4696. }
  4697. if (unlikely(mythr->work_restart)) {
  4698. /* Apart from device_thread 0, we stagger the
  4699. * starting of every next thread to try and get
  4700. * all devices busy before worrying about
  4701. * getting work for their extra threads */
  4702. if (!primary) {
  4703. struct timespec rgtp;
  4704. rgtp.tv_sec = 0;
  4705. rgtp.tv_nsec = 250 * mythr->device_thread * 1000000;
  4706. nanosleep(&rgtp, NULL);
  4707. }
  4708. break;
  4709. }
  4710. if (unlikely(mythr->pause || cgpu->deven != DEV_ENABLED))
  4711. mt_disable(mythr, thr_id, api);
  4712. sdiff.tv_sec = sdiff.tv_usec = 0;
  4713. } while (!abandon_work(work, &wdiff, cgpu->max_hashes));
  4714. }
  4715. out:
  4716. if (api->thread_shutdown)
  4717. api->thread_shutdown(mythr);
  4718. thread_reportin(mythr);
  4719. applog(LOG_ERR, "Thread %d failure, exiting", thr_id);
  4720. tq_freeze(mythr->q);
  4721. return NULL;
  4722. }
  4723. enum {
  4724. STAT_SLEEP_INTERVAL = 1,
  4725. STAT_CTR_INTERVAL = 10000000,
  4726. FAILURE_INTERVAL = 30,
  4727. };
  4728. /* Stage another work item from the work returned in a longpoll */
  4729. 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)
  4730. {
  4731. bool rc;
  4732. rc = work_decode(json_object_get(val, "result"), work);
  4733. if (unlikely(!rc)) {
  4734. applog(LOG_ERR, "Could not convert longpoll data to work");
  4735. free_work(work);
  4736. return;
  4737. }
  4738. work->pool = pool;
  4739. work->rolltime = rolltime;
  4740. work->longpoll = true;
  4741. memcpy(&(work->tv_getwork), tv_lp, sizeof(struct timeval));
  4742. memcpy(&(work->tv_getwork_reply), tv_lp_reply, sizeof(struct timeval));
  4743. work->getwork_mode = GETWORK_MODE_LP;
  4744. calc_diff(work);
  4745. if (pool->enabled == POOL_REJECTING)
  4746. work->mandatory = true;
  4747. /* We'll be checking this work item twice, but we already know it's
  4748. * from a new block so explicitly force the new block detection now
  4749. * rather than waiting for it to hit the stage thread. This also
  4750. * allows testwork to know whether LP discovered the block or not. */
  4751. test_work_current(work);
  4752. /* Don't use backup LPs as work if we have failover-only enabled. Use
  4753. * the longpoll work from a pool that has been rejecting shares as a
  4754. * way to detect when the pool has recovered.
  4755. */
  4756. if (pool != current_pool() && opt_fail_only && pool->enabled != POOL_REJECTING) {
  4757. free_work(work);
  4758. return;
  4759. }
  4760. work = clone_work(work);
  4761. applog(LOG_DEBUG, "Pushing converted work to stage thread");
  4762. if (unlikely(!stage_work(work)))
  4763. free_work(work);
  4764. else
  4765. applog(LOG_DEBUG, "Converted longpoll data to work");
  4766. }
  4767. /* If we want longpoll, enable it for the chosen default pool, or, if
  4768. * the pool does not support longpoll, find the first one that does
  4769. * and use its longpoll support */
  4770. static struct pool *select_longpoll_pool(struct pool *cp)
  4771. {
  4772. int i;
  4773. if (cp->lp_url)
  4774. return cp;
  4775. for (i = 0; i < total_pools; i++) {
  4776. struct pool *pool = pools[i];
  4777. if (pool->lp_url)
  4778. return pool;
  4779. }
  4780. return NULL;
  4781. }
  4782. /* This will make the longpoll thread wait till it's the current pool, or it
  4783. * has been flagged as rejecting, before attempting to open any connections.
  4784. */
  4785. static void wait_lpcurrent(struct pool *pool)
  4786. {
  4787. if (pool->enabled == POOL_REJECTING || pool_strategy == POOL_LOADBALANCE || pool_strategy == POOL_BALANCE)
  4788. return;
  4789. while (pool != current_pool() && pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  4790. mutex_lock(&lp_lock);
  4791. pthread_cond_wait(&lp_cond, &lp_lock);
  4792. mutex_unlock(&lp_lock);
  4793. }
  4794. }
  4795. static curl_socket_t save_curl_socket(void *vpool, __maybe_unused curlsocktype purpose, struct curl_sockaddr *addr) {
  4796. struct pool *pool = vpool;
  4797. curl_socket_t sock = socket(addr->family, addr->socktype, addr->protocol);
  4798. pool->lp_socket = sock;
  4799. return sock;
  4800. }
  4801. static void *longpoll_thread(void *userdata)
  4802. {
  4803. struct pool *cp = (struct pool *)userdata;
  4804. /* This *pool is the source of the actual longpoll, not the pool we've
  4805. * tied it to */
  4806. struct pool *pool = NULL;
  4807. struct timeval start, reply, end;
  4808. CURL *curl = NULL;
  4809. int failures = 0;
  4810. int rolltime;
  4811. rename_thr("bfg-longpoll");
  4812. curl = curl_easy_init();
  4813. if (unlikely(!curl)) {
  4814. applog(LOG_ERR, "CURL initialisation failed");
  4815. goto out;
  4816. }
  4817. retry_pool:
  4818. pool = select_longpoll_pool(cp);
  4819. if (!pool) {
  4820. applog(LOG_WARNING, "No suitable long-poll found for pool %s", cp->rpc_url);
  4821. while (!pool) {
  4822. sleep(60);
  4823. pool = select_longpoll_pool(cp);
  4824. }
  4825. }
  4826. /* Any longpoll from any pool is enough for this to be true */
  4827. have_longpoll = true;
  4828. wait_lpcurrent(cp);
  4829. if (cp == pool)
  4830. applog(LOG_WARNING, "Long-polling activated via %s (%s)", pool->lp_url, pool_protocol_name(pool->lp_proto));
  4831. else
  4832. applog(LOG_WARNING, "Long-polling activated for pool %s via %s (%s)", cp->rpc_url, pool->lp_url, pool_protocol_name(pool->lp_proto));
  4833. while (42) {
  4834. json_t *val, *soval;
  4835. struct work *work = make_work();
  4836. work->pool = pool;
  4837. const char *rpc_req;
  4838. rpc_req = prepare_rpc_req(work, pool->lp_proto, pool->lp_id);
  4839. if (!rpc_req)
  4840. goto lpfail;
  4841. wait_lpcurrent(cp);
  4842. gettimeofday(&start, NULL);
  4843. /* Longpoll connections can be persistent for a very long time
  4844. * and any number of issues could have come up in the meantime
  4845. * so always establish a fresh connection instead of relying on
  4846. * a persistent one. */
  4847. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  4848. curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, save_curl_socket);
  4849. curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, pool);
  4850. val = json_rpc_call(curl, pool->lp_url, pool->rpc_userpass, rpc_req,
  4851. false, true, &rolltime, pool, false);
  4852. pool->lp_socket = CURL_SOCKET_BAD;
  4853. gettimeofday(&reply, NULL);
  4854. if (likely(val)) {
  4855. soval = json_object_get(json_object_get(val, "result"), "submitold");
  4856. if (soval)
  4857. pool->submit_old = json_is_true(soval);
  4858. else
  4859. pool->submit_old = false;
  4860. convert_to_work(val, rolltime, pool, work, &start, &reply);
  4861. failures = 0;
  4862. json_decref(val);
  4863. } else {
  4864. /* Some pools regularly drop the longpoll request so
  4865. * only see this as longpoll failure if it happens
  4866. * immediately and just restart it the rest of the
  4867. * time. */
  4868. gettimeofday(&end, NULL);
  4869. free_work(work);
  4870. if (end.tv_sec - start.tv_sec > 30)
  4871. continue;
  4872. if (failures == 1)
  4873. applog(LOG_WARNING, "longpoll failed for %s, retrying every 30s", pool->lp_url);
  4874. lpfail:
  4875. sleep(30);
  4876. }
  4877. if (pool != cp) {
  4878. pool = select_longpoll_pool(cp);
  4879. if (unlikely(!pool))
  4880. goto retry_pool;
  4881. }
  4882. if (unlikely(pool->removed))
  4883. break;
  4884. }
  4885. out:
  4886. if (curl)
  4887. curl_easy_cleanup(curl);
  4888. return NULL;
  4889. }
  4890. static void stop_longpoll(void)
  4891. {
  4892. int i;
  4893. want_longpoll = false;
  4894. for (i = 0; i < total_pools; ++i)
  4895. {
  4896. struct pool *pool = pools[i];
  4897. if (unlikely(!pool->lp_started))
  4898. continue;
  4899. pool->lp_started = false;
  4900. pthread_cancel(pool->longpoll_thread);
  4901. }
  4902. have_longpoll = false;
  4903. }
  4904. static void start_longpoll(void)
  4905. {
  4906. int i;
  4907. want_longpoll = true;
  4908. for (i = 0; i < total_pools; ++i)
  4909. {
  4910. struct pool *pool = pools[i];
  4911. if (unlikely(pool->removed || pool->lp_started || !pool->lp_url))
  4912. continue;
  4913. pool->lp_started = true;
  4914. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  4915. quit(1, "Failed to create pool longpoll thread");
  4916. }
  4917. }
  4918. void reinit_device(struct cgpu_info *cgpu)
  4919. {
  4920. if (cgpu->api->reinit_device)
  4921. cgpu->api->reinit_device(cgpu);
  4922. }
  4923. static struct timeval rotate_tv;
  4924. /* We reap curls if they are unused for over a minute */
  4925. static void reap_curl(struct pool *pool)
  4926. {
  4927. struct curl_ent *ent, *iter;
  4928. struct timeval now;
  4929. int reaped = 0;
  4930. gettimeofday(&now, NULL);
  4931. mutex_lock(&pool->pool_lock);
  4932. list_for_each_entry_safe(ent, iter, &pool->curlring, node) {
  4933. if (pool->curls < 2)
  4934. break;
  4935. if (now.tv_sec - ent->tv.tv_sec > 300) {
  4936. reaped++;
  4937. pool->curls--;
  4938. list_del(&ent->node);
  4939. curl_easy_cleanup(ent->curl);
  4940. free(ent);
  4941. }
  4942. }
  4943. mutex_unlock(&pool->pool_lock);
  4944. if (reaped)
  4945. applog(LOG_DEBUG, "Reaped %d curl%s from pool %d", reaped, reaped > 1 ? "s" : "", pool->pool_no);
  4946. }
  4947. static void *watchpool_thread(void __maybe_unused *userdata)
  4948. {
  4949. int intervals = 0;
  4950. rename_thr("bfg-watchpool");
  4951. while (42) {
  4952. struct timeval now;
  4953. int i;
  4954. if (++intervals > 20)
  4955. intervals = 0;
  4956. gettimeofday(&now, NULL);
  4957. for (i = 0; i < total_pools; i++) {
  4958. struct pool *pool = pools[i];
  4959. if (!opt_benchmark)
  4960. reap_curl(pool);
  4961. if (pool->enabled == POOL_DISABLED)
  4962. continue;
  4963. /* Test pool is idle once every minute */
  4964. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 60) {
  4965. gettimeofday(&pool->tv_idle, NULL);
  4966. if (pool_active(pool, true) && pool_tclear(pool, &pool->idle))
  4967. pool_resus(pool);
  4968. }
  4969. /* Get a rolling utility per pool over 10 mins */
  4970. if (intervals > 19) {
  4971. int shares = pool->diff1 - pool->last_shares;
  4972. pool->last_shares = pool->diff1;
  4973. pool->utility = (pool->utility + (double)shares * 0.63) / 1.63;
  4974. pool->shares = pool->utility;
  4975. }
  4976. }
  4977. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  4978. gettimeofday(&rotate_tv, NULL);
  4979. switch_pools(NULL);
  4980. }
  4981. sleep(30);
  4982. }
  4983. return NULL;
  4984. }
  4985. void device_recovered(struct cgpu_info *cgpu)
  4986. {
  4987. struct thr_info *thr;
  4988. int j;
  4989. cgpu->deven = DEV_ENABLED;
  4990. for (j = 0; j < cgpu->threads; ++j) {
  4991. thr = cgpu->thr[j];
  4992. applog(LOG_DEBUG, "Pushing ping to thread %d", thr->id);
  4993. tq_push(thr->q, &ping);
  4994. }
  4995. }
  4996. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  4997. * the screen at regular intervals, and restarts threads if they appear to have
  4998. * died. */
  4999. #define WATCHDOG_INTERVAL 3
  5000. #define WATCHDOG_SICK_TIME 60
  5001. #define WATCHDOG_DEAD_TIME 600
  5002. #define WATCHDOG_SICK_COUNT (WATCHDOG_SICK_TIME/WATCHDOG_INTERVAL)
  5003. #define WATCHDOG_DEAD_COUNT (WATCHDOG_DEAD_TIME/WATCHDOG_INTERVAL)
  5004. static void *watchdog_thread(void __maybe_unused *userdata)
  5005. {
  5006. const unsigned int interval = WATCHDOG_INTERVAL;
  5007. struct timeval zero_tv;
  5008. rename_thr("bfg-watchdog");
  5009. memset(&zero_tv, 0, sizeof(struct timeval));
  5010. gettimeofday(&rotate_tv, NULL);
  5011. while (1) {
  5012. int i;
  5013. struct timeval now;
  5014. sleep(interval);
  5015. discard_stale();
  5016. hashmeter(-1, &zero_tv, 0);
  5017. #ifdef HAVE_CURSES
  5018. if (curses_active_locked()) {
  5019. change_logwinsize();
  5020. curses_print_status();
  5021. for (i = 0; i < mining_threads; i++)
  5022. curses_print_devstatus(i);
  5023. touchwin(statuswin);
  5024. wrefresh(statuswin);
  5025. touchwin(logwin);
  5026. wrefresh(logwin);
  5027. unlock_curses();
  5028. }
  5029. #endif
  5030. gettimeofday(&now, NULL);
  5031. if (!sched_paused && !should_run()) {
  5032. applog(LOG_WARNING, "Pausing execution as per stop time %02d:%02d scheduled",
  5033. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  5034. if (!schedstart.enable) {
  5035. quit(0, "Terminating execution as planned");
  5036. break;
  5037. }
  5038. applog(LOG_WARNING, "Will restart execution as scheduled at %02d:%02d",
  5039. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  5040. sched_paused = true;
  5041. for (i = 0; i < mining_threads; i++) {
  5042. struct thr_info *thr;
  5043. thr = &thr_info[i];
  5044. thr->pause = true;
  5045. }
  5046. } else if (sched_paused && should_run()) {
  5047. applog(LOG_WARNING, "Restarting execution as per start time %02d:%02d scheduled",
  5048. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  5049. if (schedstop.enable)
  5050. applog(LOG_WARNING, "Will pause execution as scheduled at %02d:%02d",
  5051. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  5052. sched_paused = false;
  5053. for (i = 0; i < mining_threads; i++) {
  5054. struct thr_info *thr;
  5055. thr = &thr_info[i];
  5056. /* Don't touch disabled devices */
  5057. if (thr->cgpu->deven == DEV_DISABLED)
  5058. continue;
  5059. thr->pause = false;
  5060. tq_push(thr->q, &ping);
  5061. }
  5062. }
  5063. for (i = 0; i < total_devices; ++i) {
  5064. struct cgpu_info *cgpu = devices[i];
  5065. struct thr_info *thr = cgpu->thr[0];
  5066. enum dev_enable *denable;
  5067. char dev_str[8];
  5068. int gpu;
  5069. if (cgpu->api->get_stats)
  5070. cgpu->api->get_stats(cgpu);
  5071. gpu = cgpu->device_id;
  5072. denable = &cgpu->deven;
  5073. sprintf(dev_str, "%s%d", cgpu->api->name, gpu);
  5074. #ifdef HAVE_ADL
  5075. if (adl_active && cgpu->has_adl)
  5076. gpu_autotune(gpu, denable);
  5077. if (opt_debug && cgpu->has_adl) {
  5078. int engineclock = 0, memclock = 0, activity = 0, fanspeed = 0, fanpercent = 0, powertune = 0;
  5079. float temp = 0, vddc = 0;
  5080. if (gpu_stats(gpu, &temp, &engineclock, &memclock, &vddc, &activity, &fanspeed, &fanpercent, &powertune))
  5081. applog(LOG_DEBUG, "%.1f C F: %d%%(%dRPM) E: %dMHz M: %dMhz V: %.3fV A: %d%% P: %d%%",
  5082. temp, fanpercent, fanspeed, engineclock, memclock, vddc, activity, powertune);
  5083. }
  5084. #endif
  5085. /* Thread is disabled */
  5086. if (*denable == DEV_DISABLED)
  5087. continue;
  5088. else
  5089. if (*denable == DEV_RECOVER) {
  5090. if (opt_restart && cgpu->temp < cgpu->targettemp) {
  5091. applog(LOG_NOTICE, "%s %u recovered to temperature below target, re-enabling",
  5092. cgpu->api->name, cgpu->device_id);
  5093. device_recovered(cgpu);
  5094. }
  5095. cgpu->device_last_not_well = time(NULL);
  5096. cgpu->device_not_well_reason = REASON_DEV_THERMAL_CUTOFF;
  5097. continue;
  5098. }
  5099. else
  5100. if (cgpu->temp > cgpu->cutofftemp)
  5101. {
  5102. applog(LOG_WARNING, "%s %u hit thermal cutoff limit, disabling!",
  5103. cgpu->api->name, cgpu->device_id);
  5104. *denable = DEV_RECOVER;
  5105. cgpu->device_last_not_well = time(NULL);
  5106. cgpu->device_not_well_reason = REASON_DEV_THERMAL_CUTOFF;
  5107. ++cgpu->dev_thermal_cutoff_count;
  5108. }
  5109. if (thr->getwork) {
  5110. if (cgpu->status == LIFE_WELL && thr->getwork < now.tv_sec - opt_log_interval) {
  5111. int thrid;
  5112. bool cgpu_idle = true;
  5113. thr->rolling = 0;
  5114. for (thrid = 0; thrid < cgpu->threads; ++thrid)
  5115. if (!cgpu->thr[thrid]->getwork)
  5116. cgpu_idle = false;
  5117. if (cgpu_idle) {
  5118. cgpu->rolling = 0;
  5119. cgpu->status = LIFE_WAIT;
  5120. }
  5121. }
  5122. continue;
  5123. }
  5124. else if (cgpu->status == LIFE_WAIT)
  5125. cgpu->status = LIFE_WELL;
  5126. #ifdef WANT_CPUMINE
  5127. if (!strcmp(cgpu->api->dname, "cpu"))
  5128. continue;
  5129. #endif
  5130. if (cgpu->status != LIFE_WELL && (now.tv_sec - thr->last.tv_sec < WATCHDOG_SICK_TIME)) {
  5131. if (cgpu->status != LIFE_INIT)
  5132. applog(LOG_ERR, "%s: Recovered, declaring WELL!", dev_str);
  5133. cgpu->status = LIFE_WELL;
  5134. cgpu->device_last_well = time(NULL);
  5135. } else if (cgpu->status == LIFE_WELL && (now.tv_sec - thr->last.tv_sec > WATCHDOG_SICK_TIME)) {
  5136. thr->rolling = cgpu->rolling = 0;
  5137. cgpu->status = LIFE_SICK;
  5138. applog(LOG_ERR, "%s: Idle for more than 60 seconds, declaring SICK!", dev_str);
  5139. gettimeofday(&thr->sick, NULL);
  5140. cgpu->device_last_not_well = time(NULL);
  5141. cgpu->device_not_well_reason = REASON_DEV_SICK_IDLE_60;
  5142. cgpu->dev_sick_idle_60_count++;
  5143. #ifdef HAVE_ADL
  5144. if (adl_active && cgpu->has_adl && gpu_activity(gpu) > 50) {
  5145. applog(LOG_ERR, "GPU still showing activity suggesting a hard hang.");
  5146. applog(LOG_ERR, "Will not attempt to auto-restart it.");
  5147. } else
  5148. #endif
  5149. if (opt_restart) {
  5150. applog(LOG_ERR, "%s: Attempting to restart", dev_str);
  5151. reinit_device(cgpu);
  5152. }
  5153. } else if (cgpu->status == LIFE_SICK && (now.tv_sec - thr->last.tv_sec > WATCHDOG_DEAD_TIME)) {
  5154. cgpu->status = LIFE_DEAD;
  5155. applog(LOG_ERR, "%s: Not responded for more than 10 minutes, declaring DEAD!", dev_str);
  5156. gettimeofday(&thr->sick, NULL);
  5157. cgpu->device_last_not_well = time(NULL);
  5158. cgpu->device_not_well_reason = REASON_DEV_DEAD_IDLE_600;
  5159. cgpu->dev_dead_idle_600_count++;
  5160. } else if (now.tv_sec - thr->sick.tv_sec > 60 &&
  5161. (cgpu->status == LIFE_SICK || cgpu->status == LIFE_DEAD)) {
  5162. /* Attempt to restart a GPU that's sick or dead once every minute */
  5163. gettimeofday(&thr->sick, NULL);
  5164. #ifdef HAVE_ADL
  5165. if (adl_active && cgpu->has_adl && gpu_activity(gpu) > 50) {
  5166. /* Again do not attempt to restart a device that may have hard hung */
  5167. } else
  5168. #endif
  5169. if (opt_restart)
  5170. reinit_device(cgpu);
  5171. }
  5172. }
  5173. }
  5174. return NULL;
  5175. }
  5176. static void log_print_status(struct cgpu_info *cgpu)
  5177. {
  5178. char logline[255];
  5179. get_statline(logline, cgpu);
  5180. applog(LOG_WARNING, "%s", logline);
  5181. }
  5182. static void print_summary(void)
  5183. {
  5184. struct timeval diff;
  5185. int hours, mins, secs, i;
  5186. double utility, efficiency = 0.0, work_util;
  5187. timersub(&total_tv_end, &total_tv_start, &diff);
  5188. hours = diff.tv_sec / 3600;
  5189. mins = (diff.tv_sec % 3600) / 60;
  5190. secs = diff.tv_sec % 60;
  5191. utility = total_accepted / total_secs * 60;
  5192. efficiency = total_getworks ? total_accepted * 100.0 / total_getworks : 0.0;
  5193. work_util = total_diff1 / total_secs * 60;
  5194. applog(LOG_WARNING, "\nSummary of runtime statistics:\n");
  5195. applog(LOG_WARNING, "Started at %s", datestamp);
  5196. if (total_pools == 1)
  5197. applog(LOG_WARNING, "Pool: %s", pools[0]->rpc_url);
  5198. #ifdef WANT_CPUMINE
  5199. if (opt_n_threads)
  5200. applog(LOG_WARNING, "CPU hasher algorithm used: %s", algo_names[opt_algo]);
  5201. #endif
  5202. applog(LOG_WARNING, "Runtime: %d hrs : %d mins : %d secs", hours, mins, secs);
  5203. applog(LOG_WARNING, "Average hashrate: %.1f Megahash/s", total_mhashes_done / total_secs);
  5204. applog(LOG_WARNING, "Solved blocks: %d", found_blocks);
  5205. applog(LOG_WARNING, "Queued work requests: %d", total_getworks);
  5206. applog(LOG_WARNING, "Share submissions: %d", total_accepted + total_rejected);
  5207. applog(LOG_WARNING, "Accepted shares: %d", total_accepted);
  5208. applog(LOG_WARNING, "Rejected shares: %d", total_rejected);
  5209. applog(LOG_WARNING, "Accepted difficulty shares: %1.f", total_diff_accepted);
  5210. applog(LOG_WARNING, "Rejected difficulty shares: %1.f", total_diff_rejected);
  5211. if (total_accepted || total_rejected)
  5212. applog(LOG_WARNING, "Reject ratio: %.1f%%", (double)(total_rejected * 100) / (double)(total_accepted + total_rejected));
  5213. applog(LOG_WARNING, "Hardware errors: %d", hw_errors);
  5214. applog(LOG_WARNING, "Efficiency (accepted / queued): %.0f%%", efficiency);
  5215. applog(LOG_WARNING, "Utility (accepted shares / min): %.2f/min\n", utility);
  5216. applog(LOG_WARNING, "Discarded work due to new blocks: %d", total_discarded);
  5217. applog(LOG_WARNING, "Stale submissions discarded due to new blocks: %d", total_stale);
  5218. applog(LOG_WARNING, "Unable to get work from server occasions: %d", total_go);
  5219. applog(LOG_WARNING, "Work items generated locally: %d", local_work);
  5220. applog(LOG_WARNING, "Submitting work remotely delay occasions: %d", total_ro);
  5221. applog(LOG_WARNING, "New blocks detected on network: %d\n", new_blocks);
  5222. if (total_pools > 1) {
  5223. for (i = 0; i < total_pools; i++) {
  5224. struct pool *pool = pools[i];
  5225. applog(LOG_WARNING, "Pool: %s", pool->rpc_url);
  5226. if (pool->solved)
  5227. applog(LOG_WARNING, "SOLVED %d BLOCK%s!", pool->solved, pool->solved > 1 ? "S" : "");
  5228. applog(LOG_WARNING, " Queued work requests: %d", pool->getwork_requested);
  5229. applog(LOG_WARNING, " Share submissions: %d", pool->accepted + pool->rejected);
  5230. applog(LOG_WARNING, " Accepted shares: %d", pool->accepted);
  5231. applog(LOG_WARNING, " Rejected shares: %d", pool->rejected);
  5232. applog(LOG_WARNING, " Accepted difficulty shares: %1.f", pool->diff_accepted);
  5233. applog(LOG_WARNING, " Rejected difficulty shares: %1.f", pool->diff_rejected);
  5234. if (pool->accepted || pool->rejected)
  5235. applog(LOG_WARNING, " Reject ratio: %.1f%%", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  5236. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  5237. applog(LOG_WARNING, " Efficiency (accepted / queued): %.0f%%", efficiency);
  5238. applog(LOG_WARNING, " Discarded work due to new blocks: %d", pool->discarded_work);
  5239. applog(LOG_WARNING, " Stale submissions discarded due to new blocks: %d", pool->stale_shares);
  5240. applog(LOG_WARNING, " Unable to get work from server occasions: %d", pool->getfail_occasions);
  5241. applog(LOG_WARNING, " Submitting work remotely delay occasions: %d\n", pool->remotefail_occasions);
  5242. }
  5243. }
  5244. applog(LOG_WARNING, "Summary of per device statistics:\n");
  5245. for (i = 0; i < total_devices; ++i)
  5246. log_print_status(devices[i]);
  5247. if (opt_shares)
  5248. applog(LOG_WARNING, "Mined %d accepted shares of %d requested\n", total_accepted, opt_shares);
  5249. fflush(stdout);
  5250. fflush(stderr);
  5251. if (opt_shares > total_accepted)
  5252. applog(LOG_WARNING, "WARNING - Mined only %d shares of %d requested.", total_accepted, opt_shares);
  5253. }
  5254. static void clean_up(void)
  5255. {
  5256. #ifdef HAVE_OPENCL
  5257. clear_adl(nDevs);
  5258. opencl_dynamic_cleanup();
  5259. #endif
  5260. #ifdef HAVE_LIBUSB
  5261. libusb_exit(NULL);
  5262. #endif
  5263. gettimeofday(&total_tv_end, NULL);
  5264. #ifdef HAVE_CURSES
  5265. disable_curses();
  5266. #endif
  5267. if (!opt_realquiet && successful_connect)
  5268. print_summary();
  5269. if (opt_n_threads)
  5270. free(cpus);
  5271. curl_global_cleanup();
  5272. }
  5273. void quit(int status, const char *format, ...)
  5274. {
  5275. va_list ap;
  5276. clean_up();
  5277. if (format) {
  5278. va_start(ap, format);
  5279. vfprintf(stderr, format, ap);
  5280. va_end(ap);
  5281. }
  5282. fprintf(stderr, "\n");
  5283. fflush(stderr);
  5284. if (status) {
  5285. const char *ev = getenv("__BFGMINER_SEGFAULT_ERRQUIT");
  5286. if (unlikely(ev && ev[0] && ev[0] != '0')) {
  5287. const char **p = NULL;
  5288. // NOTE debugger can bypass with: p = &p
  5289. *p = format; // Segfault, hopefully dumping core
  5290. }
  5291. }
  5292. #if defined(unix)
  5293. if (forkpid > 0) {
  5294. kill(forkpid, SIGTERM);
  5295. forkpid = 0;
  5296. }
  5297. #endif
  5298. exit(status);
  5299. }
  5300. #ifdef HAVE_CURSES
  5301. char *curses_input(const char *query)
  5302. {
  5303. char *input;
  5304. echo();
  5305. input = malloc(255);
  5306. if (!input)
  5307. quit(1, "Failed to malloc input");
  5308. leaveok(logwin, false);
  5309. wlogprint("%s:\n", query);
  5310. wgetnstr(logwin, input, 255);
  5311. if (!strlen(input))
  5312. strcpy(input, "-1");
  5313. leaveok(logwin, true);
  5314. noecho();
  5315. return input;
  5316. }
  5317. #endif
  5318. void add_pool_details5(bool live, char *url, char *user, char *pass, char *proxy)
  5319. {
  5320. struct pool *pool;
  5321. pool = add_pool();
  5322. pool->rpc_url = url;
  5323. pool->rpc_user = user;
  5324. pool->rpc_pass = pass;
  5325. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  5326. if (!pool->rpc_userpass)
  5327. quit(1, "Failed to malloc userpass");
  5328. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  5329. pool->rpc_proxy = proxy;
  5330. /* Test the pool is not idle if we're live running, otherwise
  5331. * it will be tested separately */
  5332. enable_pool(pool);
  5333. if (live && !pool_active(pool, false))
  5334. pool->idle = true;
  5335. }
  5336. void add_pool_details(bool live, char *url, char *user, char *pass)
  5337. {
  5338. add_pool_details5(live, url, user, pass, NULL);
  5339. }
  5340. #ifdef HAVE_CURSES
  5341. static bool input_pool(bool live)
  5342. {
  5343. char *url = NULL, *user = NULL, *pass = NULL;
  5344. bool ret = false;
  5345. immedok(logwin, true);
  5346. wlogprint("Input server details.\n");
  5347. url = curses_input("URL");
  5348. if (!url)
  5349. goto out;
  5350. if (strncmp(url, "http://", 7) &&
  5351. strncmp(url, "https://", 8)) {
  5352. char *httpinput;
  5353. httpinput = malloc(255);
  5354. if (!httpinput)
  5355. quit(1, "Failed to malloc httpinput");
  5356. strcpy(httpinput, "http://");
  5357. strncat(httpinput, url, 248);
  5358. free(url);
  5359. url = httpinput;
  5360. }
  5361. user = curses_input("Username");
  5362. if (!user)
  5363. goto out;
  5364. pass = curses_input("Password");
  5365. if (!pass)
  5366. goto out;
  5367. add_pool_details(live, url, user, pass);
  5368. ret = true;
  5369. out:
  5370. immedok(logwin, false);
  5371. if (!ret) {
  5372. if (url)
  5373. free(url);
  5374. if (user)
  5375. free(user);
  5376. if (pass)
  5377. free(pass);
  5378. }
  5379. return ret;
  5380. }
  5381. #endif
  5382. #if defined(unix)
  5383. static void fork_monitor()
  5384. {
  5385. // Make a pipe: [readFD, writeFD]
  5386. int pfd[2];
  5387. int r = pipe(pfd);
  5388. if (r < 0) {
  5389. perror("pipe - failed to create pipe for --monitor");
  5390. exit(1);
  5391. }
  5392. // Make stderr write end of pipe
  5393. fflush(stderr);
  5394. r = dup2(pfd[1], 2);
  5395. if (r < 0) {
  5396. perror("dup2 - failed to alias stderr to write end of pipe for --monitor");
  5397. exit(1);
  5398. }
  5399. r = close(pfd[1]);
  5400. if (r < 0) {
  5401. perror("close - failed to close write end of pipe for --monitor");
  5402. exit(1);
  5403. }
  5404. // Don't allow a dying monitor to kill the main process
  5405. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  5406. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  5407. if (SIG_ERR == sr0 || SIG_ERR == sr1) {
  5408. perror("signal - failed to edit signal mask for --monitor");
  5409. exit(1);
  5410. }
  5411. // Fork a child process
  5412. forkpid = fork();
  5413. if (forkpid < 0) {
  5414. perror("fork - failed to fork child process for --monitor");
  5415. exit(1);
  5416. }
  5417. // Child: launch monitor command
  5418. if (0 == forkpid) {
  5419. // Make stdin read end of pipe
  5420. r = dup2(pfd[0], 0);
  5421. if (r < 0) {
  5422. perror("dup2 - in child, failed to alias read end of pipe to stdin for --monitor");
  5423. exit(1);
  5424. }
  5425. close(pfd[0]);
  5426. if (r < 0) {
  5427. perror("close - in child, failed to close read end of pipe for --monitor");
  5428. exit(1);
  5429. }
  5430. // Launch user specified command
  5431. execl("/bin/bash", "/bin/bash", "-c", opt_stderr_cmd, (char*)NULL);
  5432. perror("execl - in child failed to exec user specified command for --monitor");
  5433. exit(1);
  5434. }
  5435. // Parent: clean up unused fds and bail
  5436. r = close(pfd[0]);
  5437. if (r < 0) {
  5438. perror("close - failed to close read end of pipe for --monitor");
  5439. exit(1);
  5440. }
  5441. }
  5442. #endif // defined(unix)
  5443. #ifdef HAVE_CURSES
  5444. void enable_curses(void) {
  5445. int x,y;
  5446. lock_curses();
  5447. if (curses_active) {
  5448. unlock_curses();
  5449. return;
  5450. }
  5451. mainwin = initscr();
  5452. keypad(mainwin, true);
  5453. getmaxyx(mainwin, y, x);
  5454. statuswin = newwin(logstart, x, 0, 0);
  5455. leaveok(statuswin, true);
  5456. // For whatever reason, PDCurses crashes if the logwin is initialized to height y-logcursor
  5457. // We resize the window later anyway, so just start it off at 1 :)
  5458. logwin = newwin(1, 0, logcursor, 0);
  5459. idlok(logwin, true);
  5460. scrollok(logwin, true);
  5461. leaveok(logwin, true);
  5462. cbreak();
  5463. noecho();
  5464. curses_active = true;
  5465. statusy = logstart;
  5466. unlock_curses();
  5467. }
  5468. #endif
  5469. /* TODO: fix need a dummy CPU device_api even if no support for CPU mining */
  5470. #ifndef WANT_CPUMINE
  5471. struct device_api cpu_api;
  5472. struct device_api cpu_api = {
  5473. .name = "CPU",
  5474. };
  5475. #endif
  5476. #ifdef USE_BITFORCE
  5477. extern struct device_api bitforce_api;
  5478. #endif
  5479. #ifdef USE_ICARUS
  5480. extern struct device_api cairnsmore_api;
  5481. extern struct device_api icarus_api;
  5482. #endif
  5483. #ifdef USE_MODMINER
  5484. extern struct device_api modminer_api;
  5485. #endif
  5486. #ifdef USE_ZTEX
  5487. extern struct device_api ztex_api;
  5488. #endif
  5489. static int cgminer_id_count = 0;
  5490. void register_device(struct cgpu_info *cgpu)
  5491. {
  5492. cgpu->deven = DEV_ENABLED;
  5493. devices[cgpu->cgminer_id = cgminer_id_count++] = cgpu;
  5494. mining_threads += cgpu->threads;
  5495. #ifdef HAVE_CURSES
  5496. adj_width(mining_threads, &dev_width);
  5497. #endif
  5498. #ifdef HAVE_OPENCL
  5499. if (cgpu->api == &opencl_api) {
  5500. gpu_threads += cgpu->threads;
  5501. }
  5502. #endif
  5503. }
  5504. struct _cgpu_devid_counter {
  5505. char name[4];
  5506. int lastid;
  5507. UT_hash_handle hh;
  5508. };
  5509. void renumber_cgpu(struct cgpu_info *cgpu)
  5510. {
  5511. static struct _cgpu_devid_counter *devids = NULL;
  5512. struct _cgpu_devid_counter *d;
  5513. HASH_FIND_STR(devids, cgpu->api->name, d);
  5514. if (d)
  5515. cgpu->device_id = ++d->lastid;
  5516. else {
  5517. d = malloc(sizeof(*d));
  5518. memcpy(d->name, cgpu->api->name, sizeof(d->name));
  5519. cgpu->device_id = d->lastid = 0;
  5520. HASH_ADD_STR(devids, name, d);
  5521. }
  5522. }
  5523. bool add_cgpu(struct cgpu_info*cgpu)
  5524. {
  5525. renumber_cgpu(cgpu);
  5526. devices = realloc(devices, sizeof(struct cgpu_info *) * (total_devices + 2));
  5527. devices[total_devices++] = cgpu;
  5528. return true;
  5529. }
  5530. static bool my_blkmaker_sha256_callback(void *digest, const void *buffer, size_t length)
  5531. {
  5532. sha2(buffer, length, digest, false);
  5533. return true;
  5534. }
  5535. int main(int argc, char *argv[])
  5536. {
  5537. struct block *block, *tmpblock;
  5538. struct work *work, *tmpwork;
  5539. bool pools_active = false;
  5540. struct sigaction handler;
  5541. struct thr_info *thr;
  5542. char *s;
  5543. unsigned int k;
  5544. int i, j;
  5545. blkmk_sha256_impl = my_blkmaker_sha256_callback;
  5546. /* This dangerous functions tramples random dynamically allocated
  5547. * variables so do it before anything at all */
  5548. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  5549. quit(1, "Failed to curl_global_init");
  5550. initial_args = malloc(sizeof(char *) * (argc + 1));
  5551. for (i = 0; i < argc; i++)
  5552. initial_args[i] = strdup(argv[i]);
  5553. initial_args[argc] = NULL;
  5554. #ifdef HAVE_LIBUSB
  5555. libusb_init(NULL);
  5556. #endif
  5557. mutex_init(&hash_lock);
  5558. mutex_init(&qd_lock);
  5559. mutex_init(&console_lock);
  5560. mutex_init(&control_lock);
  5561. mutex_init(&sharelog_lock);
  5562. mutex_init(&ch_lock);
  5563. rwlock_init(&blk_lock);
  5564. rwlock_init(&netacc_lock);
  5565. mutex_init(&lp_lock);
  5566. if (unlikely(pthread_cond_init(&lp_cond, NULL)))
  5567. quit(1, "Failed to pthread_cond_init lp_cond");
  5568. mutex_init(&restart_lock);
  5569. if (unlikely(pthread_cond_init(&restart_cond, NULL)))
  5570. quit(1, "Failed to pthread_cond_init restart_cond");
  5571. sprintf(packagename, "%s %s", PACKAGE, VERSION);
  5572. #ifdef WANT_CPUMINE
  5573. init_max_name_len();
  5574. #endif
  5575. handler.sa_handler = &sighandler;
  5576. handler.sa_flags = 0;
  5577. sigemptyset(&handler.sa_mask);
  5578. sigaction(SIGTERM, &handler, &termhandler);
  5579. sigaction(SIGINT, &handler, &inthandler);
  5580. opt_kernel_path = alloca(PATH_MAX);
  5581. strcpy(opt_kernel_path, CGMINER_PREFIX);
  5582. cgminer_path = alloca(PATH_MAX);
  5583. s = strdup(argv[0]);
  5584. strcpy(cgminer_path, dirname(s));
  5585. free(s);
  5586. strcat(cgminer_path, "/");
  5587. #ifdef WANT_CPUMINE
  5588. // Hack to make cgminer silent when called recursively on WIN32
  5589. int skip_to_bench = 0;
  5590. #if defined(WIN32)
  5591. char buf[32];
  5592. if (GetEnvironmentVariable("BFGMINER_BENCH_ALGO", buf, 16))
  5593. skip_to_bench = 1;
  5594. if (GetEnvironmentVariable("CGMINER_BENCH_ALGO", buf, 16))
  5595. skip_to_bench = 1;
  5596. #endif // defined(WIN32)
  5597. #endif
  5598. devcursor = 8;
  5599. logstart = devcursor + 1;
  5600. logcursor = logstart + 1;
  5601. block = calloc(sizeof(struct block), 1);
  5602. if (unlikely(!block))
  5603. quit (1, "main OOM");
  5604. for (i = 0; i < 36; i++)
  5605. strcat(block->hash, "0");
  5606. HASH_ADD_STR(blocks, hash, block);
  5607. strcpy(current_block, block->hash);
  5608. INIT_LIST_HEAD(&scan_devices);
  5609. mutex_init(&submitting_lock);
  5610. INIT_LIST_HEAD(&submit_waiting);
  5611. #ifdef HAVE_OPENCL
  5612. memset(gpus, 0, sizeof(gpus));
  5613. for (i = 0; i < MAX_GPUDEVICES; i++)
  5614. gpus[i].dynamic = true;
  5615. #endif
  5616. schedstart.tm.tm_sec = 1;
  5617. schedstop .tm.tm_sec = 1;
  5618. /* parse command line */
  5619. opt_register_table(opt_config_table,
  5620. "Options for both config file and command line");
  5621. opt_register_table(opt_cmdline_table,
  5622. "Options for command line only");
  5623. opt_parse(&argc, argv, applog_and_exit);
  5624. if (argc != 1)
  5625. quit(1, "Unexpected extra commandline arguments");
  5626. if (!config_loaded)
  5627. load_default_config();
  5628. if (opt_benchmark) {
  5629. struct pool *pool;
  5630. want_longpoll = false;
  5631. pool = add_pool();
  5632. pool->rpc_url = malloc(255);
  5633. strcpy(pool->rpc_url, "Benchmark");
  5634. pool->rpc_user = pool->rpc_url;
  5635. pool->rpc_pass = pool->rpc_url;
  5636. enable_pool(pool);
  5637. pool->idle = false;
  5638. successful_connect = true;
  5639. }
  5640. #ifdef HAVE_CURSES
  5641. if (opt_realquiet || devices_enabled == -1)
  5642. use_curses = false;
  5643. if (use_curses)
  5644. enable_curses();
  5645. #endif
  5646. applog(LOG_WARNING, "Started %s", packagename);
  5647. if (cnfbuf) {
  5648. applog(LOG_NOTICE, "Loaded configuration file %s", cnfbuf);
  5649. switch (fileconf_load) {
  5650. case 0:
  5651. applog(LOG_WARNING, "Fatal JSON error in configuration file.");
  5652. applog(LOG_WARNING, "Configuration file could not be used.");
  5653. break;
  5654. case -1:
  5655. applog(LOG_WARNING, "Error in configuration file, partially loaded.");
  5656. if (use_curses)
  5657. applog(LOG_WARNING, "Start BFGMiner with -T to see what failed to load.");
  5658. break;
  5659. default:
  5660. break;
  5661. }
  5662. free(cnfbuf);
  5663. cnfbuf = NULL;
  5664. }
  5665. strcat(opt_kernel_path, "/");
  5666. if (want_per_device_stats)
  5667. opt_log_output = true;
  5668. #ifdef WANT_CPUMINE
  5669. #ifdef USE_SCRYPT
  5670. if (opt_scrypt)
  5671. set_scrypt_algo(&opt_algo);
  5672. else
  5673. #endif
  5674. if (0 <= opt_bench_algo) {
  5675. double rate = bench_algo_stage3(opt_bench_algo);
  5676. if (!skip_to_bench)
  5677. printf("%.5f (%s)\n", rate, algo_names[opt_bench_algo]);
  5678. else {
  5679. // Write result to shared memory for parent
  5680. #if defined(WIN32)
  5681. char unique_name[64];
  5682. if (GetEnvironmentVariable("BFGMINER_SHARED_MEM", unique_name, 32) || GetEnvironmentVariable("CGMINER_SHARED_MEM", unique_name, 32)) {
  5683. HANDLE map_handle = CreateFileMapping(
  5684. INVALID_HANDLE_VALUE, // use paging file
  5685. NULL, // default security attributes
  5686. PAGE_READWRITE, // read/write access
  5687. 0, // size: high 32-bits
  5688. 4096, // size: low 32-bits
  5689. unique_name // name of map object
  5690. );
  5691. if (NULL != map_handle) {
  5692. void *shared_mem = MapViewOfFile(
  5693. map_handle, // object to map view of
  5694. FILE_MAP_WRITE, // read/write access
  5695. 0, // high offset: map from
  5696. 0, // low offset: beginning
  5697. 0 // default: map entire file
  5698. );
  5699. if (NULL != shared_mem)
  5700. CopyMemory(shared_mem, &rate, sizeof(rate));
  5701. (void)UnmapViewOfFile(shared_mem);
  5702. }
  5703. (void)CloseHandle(map_handle);
  5704. }
  5705. #endif
  5706. }
  5707. exit(0);
  5708. }
  5709. #endif
  5710. #ifdef HAVE_OPENCL
  5711. if (!opt_nogpu)
  5712. opencl_api.api_detect();
  5713. gpu_threads = 0;
  5714. #endif
  5715. #ifdef USE_ICARUS
  5716. if (!opt_scrypt)
  5717. {
  5718. cairnsmore_api.api_detect();
  5719. icarus_api.api_detect();
  5720. }
  5721. #endif
  5722. #ifdef USE_BITFORCE
  5723. if (!opt_scrypt)
  5724. bitforce_api.api_detect();
  5725. #endif
  5726. #ifdef USE_MODMINER
  5727. if (!opt_scrypt)
  5728. modminer_api.api_detect();
  5729. #endif
  5730. #ifdef USE_ZTEX
  5731. if (!opt_scrypt)
  5732. ztex_api.api_detect();
  5733. #endif
  5734. #ifdef WANT_CPUMINE
  5735. cpu_api.api_detect();
  5736. #endif
  5737. for (i = 0; i < total_devices; ++i)
  5738. if (!devices[i]->devtype)
  5739. devices[i]->devtype = "PGA";
  5740. if (devices_enabled == -1) {
  5741. applog(LOG_ERR, "Devices detected:");
  5742. for (i = 0; i < total_devices; ++i) {
  5743. struct cgpu_info *cgpu = devices[i];
  5744. if (cgpu->name)
  5745. applog(LOG_ERR, " %2d. %s %d: %s (driver: %s)", i, cgpu->api->name, cgpu->device_id, cgpu->name, cgpu->api->dname);
  5746. else
  5747. applog(LOG_ERR, " %2d. %s %d (driver: %s)", i, cgpu->api->name, cgpu->device_id, cgpu->api->dname);
  5748. }
  5749. quit(0, "%d devices listed", total_devices);
  5750. }
  5751. mining_threads = 0;
  5752. if (devices_enabled) {
  5753. for (i = 0; i < (int)(sizeof(devices_enabled) * 8) - 1; ++i) {
  5754. if (devices_enabled & (1 << i)) {
  5755. if (i >= total_devices)
  5756. quit (1, "Command line options set a device that doesn't exist");
  5757. register_device(devices[i]);
  5758. } else if (i < total_devices) {
  5759. if (opt_removedisabled) {
  5760. if (devices[i]->api == &cpu_api)
  5761. --opt_n_threads;
  5762. } else {
  5763. register_device(devices[i]);
  5764. }
  5765. devices[i]->deven = DEV_DISABLED;
  5766. }
  5767. }
  5768. total_devices = cgminer_id_count;
  5769. } else {
  5770. for (i = 0; i < total_devices; ++i)
  5771. register_device(devices[i]);
  5772. }
  5773. if (!total_devices)
  5774. quit(1, "All devices disabled, cannot mine!");
  5775. load_temp_config();
  5776. for (i = 0; i < total_devices; ++i)
  5777. devices[i]->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  5778. logstart += total_devices;
  5779. logcursor = logstart + 1;
  5780. #ifdef HAVE_CURSES
  5781. check_winsizes();
  5782. #endif
  5783. if (!total_pools) {
  5784. applog(LOG_WARNING, "Need to specify at least one pool server.");
  5785. #ifdef HAVE_CURSES
  5786. if (!use_curses || !input_pool(false))
  5787. #endif
  5788. quit(1, "Pool setup failed");
  5789. }
  5790. for (i = 0; i < total_pools; i++) {
  5791. struct pool *pool = pools[i];
  5792. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  5793. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  5794. if (!pool->rpc_userpass) {
  5795. if (!pool->rpc_user || !pool->rpc_pass)
  5796. quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  5797. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  5798. if (!pool->rpc_userpass)
  5799. quit(1, "Failed to malloc userpass");
  5800. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  5801. } else {
  5802. pool->rpc_user = malloc(strlen(pool->rpc_userpass) + 1);
  5803. if (!pool->rpc_user)
  5804. quit(1, "Failed to malloc user");
  5805. strcpy(pool->rpc_user, pool->rpc_userpass);
  5806. pool->rpc_user = strtok(pool->rpc_user, ":");
  5807. if (!pool->rpc_user)
  5808. quit(1, "Failed to find colon delimiter in userpass");
  5809. }
  5810. }
  5811. /* Set the currentpool to pool 0 */
  5812. currentpool = pools[0];
  5813. #ifdef HAVE_SYSLOG_H
  5814. if (use_syslog)
  5815. openlog(PACKAGE, LOG_PID, LOG_USER);
  5816. #endif
  5817. #if defined(unix)
  5818. if (opt_stderr_cmd)
  5819. fork_monitor();
  5820. #endif // defined(unix)
  5821. total_threads = mining_threads + 7;
  5822. thr_info = calloc(total_threads, sizeof(*thr));
  5823. if (!thr_info)
  5824. quit(1, "Failed to calloc thr_info");
  5825. /* init workio thread info */
  5826. work_thr_id = mining_threads;
  5827. thr = &thr_info[work_thr_id];
  5828. thr->id = work_thr_id;
  5829. thr->q = tq_new();
  5830. if (!thr->q)
  5831. quit(1, "Failed to tq_new");
  5832. /* start work I/O thread */
  5833. if (thr_info_create(thr, NULL, workio_thread, thr))
  5834. quit(1, "workio thread create failed");
  5835. stage_thr_id = mining_threads + 1;
  5836. thr = &thr_info[stage_thr_id];
  5837. thr->q = tq_new();
  5838. if (!thr->q)
  5839. quit(1, "Failed to tq_new");
  5840. /* start stage thread */
  5841. if (thr_info_create(thr, NULL, stage_thread, thr))
  5842. quit(1, "stage thread create failed");
  5843. pthread_detach(thr->pth);
  5844. /* Create a unique get work queue */
  5845. getq = tq_new();
  5846. if (!getq)
  5847. quit(1, "Failed to create getq");
  5848. /* We use the getq mutex as the staged lock */
  5849. stgd_lock = &getq->mutex;
  5850. if (opt_benchmark)
  5851. goto begin_bench;
  5852. for (i = 0; i < total_pools; i++) {
  5853. struct pool *pool = pools[i];
  5854. enable_pool(pool);
  5855. pool->idle = true;
  5856. }
  5857. applog(LOG_NOTICE, "Probing for an alive pool");
  5858. do {
  5859. /* Look for at least one active pool before starting */
  5860. for (i = 0; i < total_pools; i++) {
  5861. struct pool *pool = pools[i];
  5862. if (pool_active(pool, false)) {
  5863. if (!currentpool)
  5864. currentpool = pool;
  5865. applog(LOG_INFO, "Pool %d %s active", pool->pool_no, pool->rpc_url);
  5866. pools_active = true;
  5867. break;
  5868. } else {
  5869. if (pool == currentpool)
  5870. currentpool = NULL;
  5871. applog(LOG_WARNING, "Unable to get work from pool %d %s", pool->pool_no, pool->rpc_url);
  5872. }
  5873. }
  5874. if (!pools_active) {
  5875. applog(LOG_ERR, "No servers were found that could be used to get work from.");
  5876. applog(LOG_ERR, "Please check the details from the list below of the servers you have input");
  5877. applog(LOG_ERR, "Most likely you have input the wrong URL, forgotten to add a port, or have not set up workers");
  5878. for (i = 0; i < total_pools; i++) {
  5879. struct pool *pool;
  5880. pool = pools[i];
  5881. applog(LOG_WARNING, "Pool: %d URL: %s User: %s Password: %s",
  5882. i, pool->rpc_url, pool->rpc_user, pool->rpc_pass);
  5883. }
  5884. #ifdef HAVE_CURSES
  5885. if (use_curses) {
  5886. halfdelay(150);
  5887. applog(LOG_ERR, "Press any key to exit, or BFGMiner will try again in 15s.");
  5888. if (getch() != ERR)
  5889. quit(0, "No servers could be used! Exiting.");
  5890. nocbreak();
  5891. } else
  5892. #endif
  5893. quit(0, "No servers could be used! Exiting.");
  5894. }
  5895. } while (!pools_active);
  5896. #ifdef USE_SCRYPT
  5897. if (detect_algo == 1 && !opt_scrypt) {
  5898. applog(LOG_NOTICE, "Detected scrypt algorithm");
  5899. opt_scrypt = true;
  5900. }
  5901. #endif
  5902. detect_algo = 0;
  5903. begin_bench:
  5904. total_mhashes_done = 0;
  5905. for (i = 0; i < total_devices; i++) {
  5906. struct cgpu_info *cgpu = devices[i];
  5907. cgpu->rolling = cgpu->total_mhashes = 0;
  5908. }
  5909. gettimeofday(&total_tv_start, NULL);
  5910. gettimeofday(&total_tv_end, NULL);
  5911. miner_started = total_tv_start;
  5912. if (schedstart.tm.tm_sec)
  5913. schedstart.tm = *localtime(&miner_started.tv_sec);
  5914. if (schedstop.tm.tm_sec)
  5915. schedstop .tm = *localtime(&miner_started.tv_sec);
  5916. get_datestamp(datestamp, &total_tv_start);
  5917. // Start threads
  5918. k = 0;
  5919. for (i = 0; i < total_devices; ++i) {
  5920. struct cgpu_info *cgpu = devices[i];
  5921. cgpu->thr = calloc(cgpu->threads+1, sizeof(*cgpu->thr));
  5922. cgpu->thr[cgpu->threads] = NULL;
  5923. cgpu->status = LIFE_INIT;
  5924. // Setup thread structs before starting any of the threads, in case they try to interact
  5925. for (j = 0; j < cgpu->threads; ++j, ++k) {
  5926. thr = &thr_info[k];
  5927. thr->id = k;
  5928. thr->cgpu = cgpu;
  5929. thr->device_thread = j;
  5930. thr->work_restart_fd = thr->_work_restart_fd_w = -1;
  5931. thr->q = tq_new();
  5932. if (!thr->q)
  5933. quit(1, "tq_new failed in starting %s%d mining thread (#%d)", cgpu->api->name, cgpu->device_id, i);
  5934. /* Enable threads for devices set not to mine but disable
  5935. * their queue in case we wish to enable them later */
  5936. if (cgpu->deven != DEV_DISABLED) {
  5937. applog(LOG_DEBUG, "Pushing ping to thread %d", thr->id);
  5938. tq_push(thr->q, &ping);
  5939. }
  5940. cgpu->thr[j] = thr;
  5941. }
  5942. for (j = 0; j < cgpu->threads; ++j) {
  5943. thr = cgpu->thr[j];
  5944. if (cgpu->api->thread_prepare && !cgpu->api->thread_prepare(thr))
  5945. continue;
  5946. if (!thr->work_restart_fd)
  5947. {
  5948. #if defined(unix)
  5949. int pipefd[2];
  5950. if (!pipe(pipefd))
  5951. {
  5952. thr->work_restart_fd = pipefd[0];
  5953. thr->_work_restart_fd_w = pipefd[1];
  5954. }
  5955. else
  5956. #endif
  5957. thr->work_restart_fd = -1;
  5958. }
  5959. thread_reportout(thr);
  5960. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  5961. quit(1, "thread %d create failed", thr->id);
  5962. }
  5963. }
  5964. #ifdef HAVE_OPENCL
  5965. applog(LOG_INFO, "%d gpu miner threads started", gpu_threads);
  5966. for (i = 0; i < nDevs; i++)
  5967. pause_dynamic_threads(i);
  5968. #endif
  5969. #ifdef WANT_CPUMINE
  5970. applog(LOG_INFO, "%d cpu miner threads started, "
  5971. "using SHA256 '%s' algorithm.",
  5972. opt_n_threads,
  5973. algo_names[opt_algo]);
  5974. #endif
  5975. gettimeofday(&total_tv_start, NULL);
  5976. gettimeofday(&total_tv_end, NULL);
  5977. watchpool_thr_id = mining_threads + 2;
  5978. thr = &thr_info[watchpool_thr_id];
  5979. /* start watchpool thread */
  5980. if (thr_info_create(thr, NULL, watchpool_thread, NULL))
  5981. quit(1, "watchpool thread create failed");
  5982. pthread_detach(thr->pth);
  5983. watchdog_thr_id = mining_threads + 3;
  5984. thr = &thr_info[watchdog_thr_id];
  5985. /* start watchdog thread */
  5986. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  5987. quit(1, "watchdog thread create failed");
  5988. pthread_detach(thr->pth);
  5989. #ifdef HAVE_OPENCL
  5990. /* Create reinit gpu thread */
  5991. gpur_thr_id = mining_threads + 4;
  5992. thr = &thr_info[gpur_thr_id];
  5993. thr->q = tq_new();
  5994. if (!thr->q)
  5995. quit(1, "tq_new failed for gpur_thr_id");
  5996. if (thr_info_create(thr, NULL, reinit_gpu, thr))
  5997. quit(1, "reinit_gpu thread create failed");
  5998. #endif
  5999. /* Create API socket thread */
  6000. api_thr_id = mining_threads + 5;
  6001. thr = &thr_info[api_thr_id];
  6002. if (thr_info_create(thr, NULL, api_thread, thr))
  6003. quit(1, "API thread create failed");
  6004. #ifdef HAVE_CURSES
  6005. /* Create curses input thread for keyboard input. Create this last so
  6006. * that we know all threads are created since this can call kill_work
  6007. * to try and shut down ll previous threads. */
  6008. input_thr_id = mining_threads + 6;
  6009. thr = &thr_info[input_thr_id];
  6010. if (thr_info_create(thr, NULL, input_thread, thr))
  6011. quit(1, "input thread create failed");
  6012. pthread_detach(thr->pth);
  6013. #endif
  6014. for (i = 0; i < mining_threads + opt_queue; i++)
  6015. queue_request();
  6016. /* main loop - simply wait for workio thread to exit. This is not the
  6017. * normal exit path and only occurs should the workio_thread die
  6018. * unexpectedly */
  6019. pthread_join(thr_info[work_thr_id].pth, NULL);
  6020. applog(LOG_INFO, "workio thread dead, exiting.");
  6021. clean_up();
  6022. /* Not really necessary, but let's clean this up too anyway */
  6023. HASH_ITER(hh, staged_work, work, tmpwork) {
  6024. HASH_DEL(staged_work, work);
  6025. free_work(work);
  6026. }
  6027. HASH_ITER(hh, blocks, block, tmpblock) {
  6028. HASH_DEL(blocks, block);
  6029. free(block);
  6030. }
  6031. #if defined(unix)
  6032. if (forkpid > 0) {
  6033. kill(forkpid, SIGTERM);
  6034. forkpid = 0;
  6035. }
  6036. #endif
  6037. return 0;
  6038. }