miner.c 183 KB

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