miner.c 175 KB

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