miner.c 198 KB

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