miner.c 168 KB

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