miner.c 170 KB

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