miner.c 170 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698
  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. dec_queued(pool);
  2489. goto out;
  2490. }
  2491. ret_work = make_work();
  2492. ret_work->thr = NULL;
  2493. if (opt_benchmark) {
  2494. get_benchmark_work(ret_work);
  2495. ret_work->queued = true;
  2496. } else {
  2497. ret_work->pool = wc->pool;
  2498. if (!ce)
  2499. ce = pop_curl_entry(pool);
  2500. /* obtain new work from bitcoin via JSON-RPC */
  2501. if (!get_upstream_work(ret_work, ce->curl)) {
  2502. /* pause, then restart work-request loop */
  2503. applog(LOG_DEBUG, "json_rpc_call failed on get work, retrying");
  2504. dec_queued(pool);
  2505. queue_request();
  2506. free_work(ret_work);
  2507. goto out;
  2508. }
  2509. ret_work->queued = true;
  2510. }
  2511. applog(LOG_DEBUG, "Pushing work to requesting thread");
  2512. /* send work to requesting thread */
  2513. if (unlikely(!tq_push(thr_info[stage_thr_id].q, ret_work))) {
  2514. applog(LOG_ERR, "Failed to tq_push work in workio_get_work");
  2515. kill_work();
  2516. free_work(ret_work);
  2517. }
  2518. out:
  2519. workio_cmd_free(wc);
  2520. if (ce)
  2521. push_curl_entry(ce, pool);
  2522. return NULL;
  2523. }
  2524. /* As per the submit work system, we try to reuse the existing curl handles,
  2525. * but start recruiting extra connections if we start accumulating queued
  2526. * requests */
  2527. static bool workio_get_work(struct workio_cmd *wc)
  2528. {
  2529. pthread_t get_thread;
  2530. if (unlikely(pthread_create(&get_thread, NULL, get_work_thread, (void *)wc))) {
  2531. applog(LOG_ERR, "Failed to create get_work_thread");
  2532. return false;
  2533. }
  2534. return true;
  2535. }
  2536. static bool stale_work(struct work *work, bool share)
  2537. {
  2538. struct timeval now;
  2539. time_t work_expiry;
  2540. struct pool *pool;
  2541. uint32_t block_id;
  2542. int getwork_delay;
  2543. block_id = ((uint32_t*)work->data)[1];
  2544. pool = work->pool;
  2545. /* Technically the rolltime should be correct but some pools
  2546. * advertise a broken expire= that is lower than a meaningful
  2547. * scantime */
  2548. if (work->rolltime > opt_scantime)
  2549. work_expiry = work->rolltime;
  2550. else
  2551. work_expiry = opt_expiry;
  2552. if (share) {
  2553. /* If the share isn't on this pool's latest block, it's stale */
  2554. if (pool->block_id != block_id)
  2555. {
  2556. applog(LOG_DEBUG, "Share stale due to block mismatch (%08lx != %08lx)", (long)block_id, (long)pool->block_id);
  2557. return true;
  2558. }
  2559. /* If the pool doesn't want old shares, then any found in work before
  2560. * the most recent longpoll is stale */
  2561. if ((!pool->submit_old) && work->work_restart_id != pool->work_restart_id)
  2562. {
  2563. applog(LOG_DEBUG, "Share stale due to work restart (%02x != %02x)", work->work_restart_id, pool->work_restart_id);
  2564. return true;
  2565. }
  2566. } else {
  2567. /* If this work isn't for the latest Bitcoin block, it's stale */
  2568. /* But only care about the current pool if failover-only */
  2569. if (block_id != ((enabled_pools <= 1 || opt_fail_only) ? pool->block_id : current_block_id))
  2570. {
  2571. 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);
  2572. return true;
  2573. }
  2574. /* If the pool has asked us to restart since this work, it's stale */
  2575. if (work->work_restart_id != pool->work_restart_id)
  2576. {
  2577. applog(LOG_DEBUG, "Work stale due to work restart (%02x != %02x)", work->work_restart_id, pool->work_restart_id);
  2578. return true;
  2579. }
  2580. /* Factor in the average getwork delay of this pool, rounding it up to
  2581. * the nearest second */
  2582. getwork_delay = pool->cgminer_pool_stats.getwork_wait_rolling * 5 + 1;
  2583. work_expiry -= getwork_delay;
  2584. if (unlikely(work_expiry < 5))
  2585. work_expiry = 5;
  2586. }
  2587. gettimeofday(&now, NULL);
  2588. if ((now.tv_sec - work->tv_staged.tv_sec) >= work_expiry) {
  2589. applog(LOG_DEBUG, "%s stale due to expiry (%d - %d >= %d)", share?"Share":"Work", now.tv_sec, work->tv_staged.tv_sec, work_expiry);
  2590. return true;
  2591. }
  2592. /* If the user only wants strict failover, any work from a pool other than
  2593. * the current one is always considered stale */
  2594. if (opt_fail_only && !share && pool != current_pool() && !work->mandatory &&
  2595. pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  2596. applog(LOG_DEBUG, "Work stale due to fail only pool mismatch (pool %u vs %u)", pool->pool_no, current_pool()->pool_no);
  2597. return true;
  2598. }
  2599. return false;
  2600. }
  2601. static void check_solve(struct work *work)
  2602. {
  2603. work->block = regeneratehash(work);
  2604. if (unlikely(work->block)) {
  2605. work->pool->solved++;
  2606. found_blocks++;
  2607. work->mandatory = true;
  2608. applog(LOG_NOTICE, "Found block for pool %d!", work->pool->pool_no);
  2609. }
  2610. }
  2611. static void submit_discard_share(struct work *work)
  2612. {
  2613. sharelog("discard", work);
  2614. ++total_stale;
  2615. ++(work->pool->stale_shares);
  2616. }
  2617. static void *submit_work_thread(void *userdata)
  2618. {
  2619. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  2620. struct work *work;
  2621. struct pool *pool;
  2622. bool resubmit;
  2623. struct curl_ent *ce;
  2624. int failures;
  2625. time_t staleexpire;
  2626. pthread_detach(pthread_self());
  2627. rename_thr("bfg-submit_work");
  2628. applog(LOG_DEBUG, "Creating extra submit work thread");
  2629. next_submit:
  2630. work = wc->work;
  2631. pool = work->pool;
  2632. resubmit = false;
  2633. failures = 0;
  2634. check_solve(work);
  2635. if (stale_work(work, true)) {
  2636. work->stale = true;
  2637. if (unlikely(!list_empty(&submit_waiting))) {
  2638. applog(LOG_WARNING, "Stale share detected while queued submissions are waiting, discarding");
  2639. submit_discard_share(work);
  2640. goto out;
  2641. }
  2642. if (opt_submit_stale)
  2643. applog(LOG_NOTICE, "Stale share detected, submitting as user requested");
  2644. else if (pool->submit_old)
  2645. applog(LOG_NOTICE, "Stale share detected, submitting as pool requested");
  2646. else {
  2647. applog(LOG_NOTICE, "Stale share detected, discarding");
  2648. submit_discard_share(work);
  2649. goto out;
  2650. }
  2651. staleexpire = time(NULL) + 300;
  2652. }
  2653. ce = pop_curl_entry(pool);
  2654. /* submit solution to bitcoin via JSON-RPC */
  2655. while (!submit_upstream_work(work, ce->curl, resubmit)) {
  2656. resubmit = true;
  2657. if ((!work->stale) && stale_work(work, true)) {
  2658. work->stale = true;
  2659. if (opt_submit_stale)
  2660. applog(LOG_NOTICE, "Share become stale during submission failure, will retry as user requested");
  2661. else if (pool->submit_old)
  2662. applog(LOG_NOTICE, "Share become stale during submission failure, will retry as pool requested");
  2663. else {
  2664. applog(LOG_NOTICE, "Share become stale during submission failure, discarding");
  2665. submit_discard_share(work);
  2666. break;
  2667. }
  2668. staleexpire = time(NULL) + 300;
  2669. }
  2670. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  2671. applog(LOG_ERR, "Failed %d retries, discarding", opt_retries);
  2672. submit_discard_share(work);
  2673. break;
  2674. }
  2675. else if (work->stale) {
  2676. if (unlikely(!list_empty(&submit_waiting))) {
  2677. applog(LOG_WARNING, "Stale share failed to submit while queued submissions are waiting, discarding");
  2678. submit_discard_share(work);
  2679. break;
  2680. } else if (unlikely(opt_retries < 0 && staleexpire <= time(NULL))) {
  2681. applog(LOG_NOTICE, "Stale share failed to submit for 5 minutes, discarding");
  2682. submit_discard_share(work);
  2683. break;
  2684. }
  2685. }
  2686. /* pause, then restart work-request loop */
  2687. applog(LOG_INFO, "json_rpc_call failed on submit_work, retrying");
  2688. }
  2689. push_curl_entry(ce, pool);
  2690. out:
  2691. workio_cmd_free(wc);
  2692. mutex_lock(&submitting_lock);
  2693. if (!list_empty(&submit_waiting)) {
  2694. applog(LOG_DEBUG, "submit_work continuing with queued submission");
  2695. wc = list_entry(submit_waiting.next, struct workio_cmd, list);
  2696. list_del(&wc->list);
  2697. mutex_unlock(&submitting_lock);
  2698. goto next_submit;
  2699. }
  2700. --submitting;
  2701. mutex_unlock(&submitting_lock);
  2702. return NULL;
  2703. }
  2704. /* We try to reuse curl handles as much as possible, but if there is already
  2705. * work queued to be submitted, we start generating extra handles to submit
  2706. * the shares to avoid ever increasing backlogs. This allows us to scale to
  2707. * any size hardware */
  2708. static bool workio_submit_work(struct workio_cmd *wc)
  2709. {
  2710. pthread_t submit_thread;
  2711. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, (void *)wc))) {
  2712. applog(LOG_ERR, "Failed to create submit_work_thread");
  2713. return false;
  2714. }
  2715. return true;
  2716. }
  2717. /* Find the pool that currently has the highest priority */
  2718. static struct pool *priority_pool(int choice)
  2719. {
  2720. struct pool *ret = NULL;
  2721. int i;
  2722. for (i = 0; i < total_pools; i++) {
  2723. struct pool *pool = pools[i];
  2724. if (pool->prio == choice) {
  2725. ret = pool;
  2726. break;
  2727. }
  2728. }
  2729. if (unlikely(!ret)) {
  2730. applog(LOG_ERR, "WTF No pool %d found!", choice);
  2731. return pools[choice];
  2732. }
  2733. return ret;
  2734. }
  2735. void switch_pools(struct pool *selected)
  2736. {
  2737. struct pool *pool, *last_pool;
  2738. int i, pool_no, next_pool;
  2739. mutex_lock(&control_lock);
  2740. last_pool = currentpool;
  2741. pool_no = currentpool->pool_no;
  2742. /* Switch selected to pool number 0 and move the rest down */
  2743. if (selected) {
  2744. if (selected->prio != 0) {
  2745. for (i = 0; i < total_pools; i++) {
  2746. pool = pools[i];
  2747. if (pool->prio < selected->prio)
  2748. pool->prio++;
  2749. }
  2750. selected->prio = 0;
  2751. }
  2752. }
  2753. switch (pool_strategy) {
  2754. /* Both of these set to the master pool */
  2755. case POOL_BALANCE:
  2756. case POOL_FAILOVER:
  2757. case POOL_LOADBALANCE:
  2758. for (i = 0; i < total_pools; i++) {
  2759. pool = priority_pool(i);
  2760. if (!pool->idle && pool->enabled == POOL_ENABLED) {
  2761. pool_no = pool->pool_no;
  2762. break;
  2763. }
  2764. }
  2765. break;
  2766. /* Both of these simply increment and cycle */
  2767. case POOL_ROUNDROBIN:
  2768. case POOL_ROTATE:
  2769. if (selected && !selected->idle) {
  2770. pool_no = selected->pool_no;
  2771. break;
  2772. }
  2773. next_pool = pool_no;
  2774. /* Select the next alive pool */
  2775. for (i = 1; i < total_pools; i++) {
  2776. next_pool++;
  2777. if (next_pool >= total_pools)
  2778. next_pool = 0;
  2779. pool = pools[next_pool];
  2780. if (!pool->idle && pool->enabled == POOL_ENABLED) {
  2781. pool_no = next_pool;
  2782. break;
  2783. }
  2784. }
  2785. break;
  2786. default:
  2787. break;
  2788. }
  2789. currentpool = pools[pool_no];
  2790. pool = currentpool;
  2791. pool->block_id = 0;
  2792. mutex_unlock(&control_lock);
  2793. /* Set the lagging flag to avoid pool not providing work fast enough
  2794. * messages in failover only mode since we have to get all fresh work
  2795. * as in restart_threads */
  2796. if (opt_fail_only)
  2797. pool_tset(pool, &pool->lagging);
  2798. if (pool != last_pool)
  2799. applog(LOG_WARNING, "Switching to %s", pool->rpc_url);
  2800. mutex_lock(&lp_lock);
  2801. pthread_cond_broadcast(&lp_cond);
  2802. mutex_unlock(&lp_lock);
  2803. }
  2804. static void discard_work(struct work *work)
  2805. {
  2806. if (!work->clone && !work->rolls && !work->mined) {
  2807. if (work->pool)
  2808. work->pool->discarded_work++;
  2809. total_discarded++;
  2810. applog(LOG_DEBUG, "Discarded work");
  2811. } else
  2812. applog(LOG_DEBUG, "Discarded cloned or rolled work");
  2813. free_work(work);
  2814. }
  2815. static void discard_stale(void)
  2816. {
  2817. struct work *work, *tmp;
  2818. int stale = 0;
  2819. mutex_lock(stgd_lock);
  2820. HASH_ITER(hh, staged_work, work, tmp) {
  2821. if (stale_work(work, false)) {
  2822. HASH_DEL(staged_work, work);
  2823. work->pool->staged--;
  2824. discard_work(work);
  2825. stale++;
  2826. }
  2827. }
  2828. mutex_unlock(stgd_lock);
  2829. if (stale) {
  2830. applog(LOG_DEBUG, "Discarded %d stales that didn't match current hash", stale);
  2831. while (stale-- > 0)
  2832. queue_request();
  2833. }
  2834. }
  2835. void ms_to_abstime(unsigned int mstime, struct timespec *abstime)
  2836. {
  2837. struct timeval now, then, tdiff;
  2838. tdiff.tv_sec = mstime / 1000;
  2839. tdiff.tv_usec = mstime * 1000 - (tdiff.tv_sec * 1000000);
  2840. gettimeofday(&now, NULL);
  2841. timeradd(&now, &tdiff, &then);
  2842. abstime->tv_sec = then.tv_sec;
  2843. abstime->tv_nsec = then.tv_usec * 1000;
  2844. }
  2845. /* A generic wait function for threads that poll that will wait a specified
  2846. * time tdiff waiting on the pthread conditional that is broadcast when a
  2847. * work restart is required. Returns the value of pthread_cond_timedwait
  2848. * which is zero if the condition was met or ETIMEDOUT if not.
  2849. */
  2850. int restart_wait(unsigned int mstime)
  2851. {
  2852. struct timespec abstime;
  2853. int rc;
  2854. ms_to_abstime(mstime, &abstime);
  2855. mutex_lock(&restart_lock);
  2856. rc = pthread_cond_timedwait(&restart_cond, &restart_lock, &abstime);
  2857. mutex_unlock(&restart_lock);
  2858. return rc;
  2859. }
  2860. /* A generic wait function for threads that poll that will wait a specified
  2861. * time waiting on a share to become stale. Returns positive if the share
  2862. * became stale or zero if the timer expired first. If checkend is true, will
  2863. * immediatley return negative if the share is guaranteed to become stale
  2864. * before the timer expires.
  2865. */
  2866. int stale_wait(unsigned int mstime, struct work*work, bool checkend)
  2867. {
  2868. struct timespec abstime;
  2869. int rc;
  2870. if (checkend) {
  2871. struct timeval tv, orig;
  2872. ldiv_t d;
  2873. d = ldiv(mstime, 1000);
  2874. tv.tv_sec = d.quot;
  2875. tv.tv_usec = d.rem * 1000;
  2876. orig = work->tv_staged;
  2877. timersub(&orig, &tv, &work->tv_staged);
  2878. rc = stale_work(work, true);
  2879. work->tv_staged = orig;
  2880. if (rc)
  2881. return -1;
  2882. }
  2883. ms_to_abstime(mstime, &abstime);
  2884. rc = -1;
  2885. while (1) {
  2886. mutex_lock(&restart_lock);
  2887. if (stale_work(work, true)) {
  2888. rc = 1;
  2889. } else if (pthread_cond_timedwait(&restart_cond, &restart_lock, &abstime)) {
  2890. rc = 0;
  2891. }
  2892. mutex_unlock(&restart_lock);
  2893. if (rc != -1)
  2894. return rc;
  2895. }
  2896. }
  2897. static void restart_threads(void)
  2898. {
  2899. struct pool *cp = current_pool();
  2900. int i, fd;
  2901. struct thr_info *thr;
  2902. /* Artificially set the lagging flag to avoid pool not providing work
  2903. * fast enough messages after every long poll */
  2904. pool_tset(cp, &cp->lagging);
  2905. /* Discard staged work that is now stale */
  2906. discard_stale();
  2907. for (i = 0; i < mining_threads; i++)
  2908. {
  2909. thr = &thr_info[i];
  2910. fd = thr->_work_restart_fd_w;
  2911. thr->work_restart = true;
  2912. if (fd != -1)
  2913. write(fd, "\0", 1);
  2914. }
  2915. mutex_lock(&restart_lock);
  2916. pthread_cond_broadcast(&restart_cond);
  2917. mutex_unlock(&restart_lock);
  2918. }
  2919. static char *blkhashstr(unsigned char *hash)
  2920. {
  2921. unsigned char hash_swap[32];
  2922. swap256(hash_swap, hash);
  2923. swap32tole(hash_swap, hash_swap, 32 / 4);
  2924. return bin2hex(hash_swap, 32);
  2925. }
  2926. static void set_curblock(char *hexstr, unsigned char *hash)
  2927. {
  2928. unsigned char hash_swap[32];
  2929. char *old_hash;
  2930. current_block_id = ((uint32_t*)hash)[0];
  2931. strcpy(current_block, hexstr);
  2932. swap256(hash_swap, hash);
  2933. swap32tole(hash_swap, hash_swap, 32 / 4);
  2934. /* Don't free current_hash directly to avoid dereferencing when read
  2935. * elsewhere - and update block_timeval inside the same lock */
  2936. mutex_lock(&ch_lock);
  2937. gettimeofday(&block_timeval, NULL);
  2938. old_hash = current_hash;
  2939. current_hash = bin2hex(hash_swap + 4, 16);
  2940. free(old_hash);
  2941. old_hash = current_fullhash;
  2942. current_fullhash = bin2hex(hash_swap, 32);
  2943. free(old_hash);
  2944. mutex_unlock(&ch_lock);
  2945. get_timestamp(blocktime, &block_timeval);
  2946. if (unlikely(!current_hash))
  2947. quit (1, "set_curblock OOM");
  2948. applog(LOG_INFO, "New block: %s...", current_hash);
  2949. }
  2950. /* Search to see if this string is from a block that has been seen before */
  2951. static bool block_exists(char *hexstr)
  2952. {
  2953. struct block *s;
  2954. rd_lock(&blk_lock);
  2955. HASH_FIND_STR(blocks, hexstr, s);
  2956. rd_unlock(&blk_lock);
  2957. if (s)
  2958. return true;
  2959. return false;
  2960. }
  2961. /* Tests if this work is from a block that has been seen before */
  2962. static inline bool from_existing_block(struct work *work)
  2963. {
  2964. char *hexstr = bin2hex(work->data, 18);
  2965. bool ret;
  2966. if (unlikely(!hexstr)) {
  2967. applog(LOG_ERR, "from_existing_block OOM");
  2968. return true;
  2969. }
  2970. ret = block_exists(hexstr);
  2971. free(hexstr);
  2972. return ret;
  2973. }
  2974. static int block_sort(struct block *blocka, struct block *blockb)
  2975. {
  2976. return blocka->block_no - blockb->block_no;
  2977. }
  2978. static void test_work_current(struct work *work)
  2979. {
  2980. char *hexstr;
  2981. if (work->mandatory)
  2982. return;
  2983. uint32_t block_id = ((uint32_t*)(work->data))[1];
  2984. hexstr = bin2hex(&work->data[4], 18);
  2985. if (unlikely(!hexstr)) {
  2986. applog(LOG_ERR, "stage_thread OOM");
  2987. return;
  2988. }
  2989. /* Search to see if this block exists yet and if not, consider it a
  2990. * new block and set the current block details to this one */
  2991. if (!block_exists(hexstr)) {
  2992. struct block *s = calloc(sizeof(struct block), 1);
  2993. int deleted_block = 0;
  2994. if (unlikely(!s))
  2995. quit (1, "test_work_current OOM");
  2996. strcpy(s->hash, hexstr);
  2997. s->block_no = new_blocks++;
  2998. wr_lock(&blk_lock);
  2999. /* Only keep the last hour's worth of blocks in memory since
  3000. * work from blocks before this is virtually impossible and we
  3001. * want to prevent memory usage from continually rising */
  3002. if (HASH_COUNT(blocks) > 6) {
  3003. struct block *oldblock;
  3004. HASH_SORT(blocks, block_sort);
  3005. oldblock = blocks;
  3006. deleted_block = oldblock->block_no;
  3007. HASH_DEL(blocks, oldblock);
  3008. free(oldblock);
  3009. }
  3010. HASH_ADD_STR(blocks, hash, s);
  3011. wr_unlock(&blk_lock);
  3012. work->pool->block_id = block_id;
  3013. if (deleted_block)
  3014. applog(LOG_DEBUG, "Deleted block %d from database", deleted_block);
  3015. set_curblock(hexstr, &work->data[4]);
  3016. if (unlikely(new_blocks == 1))
  3017. goto out_free;
  3018. if (work->longpoll) {
  3019. applog(LOG_NOTICE, "LONGPOLL from pool %d detected new block",
  3020. work->pool->pool_no);
  3021. work->longpoll = false;
  3022. } else if (have_longpoll)
  3023. applog(LOG_NOTICE, "New block detected on network before longpoll");
  3024. else
  3025. applog(LOG_NOTICE, "New block detected on network");
  3026. restart_threads();
  3027. } else {
  3028. bool restart = false;
  3029. struct pool *curpool = NULL;
  3030. if (unlikely(work->pool->block_id != block_id)) {
  3031. bool was_active = work->pool->block_id != 0;
  3032. work->pool->block_id = block_id;
  3033. if (was_active) { // Pool actively changed block
  3034. if (work->pool == (curpool = current_pool()))
  3035. restart = true;
  3036. if (block_id == current_block_id) {
  3037. // Caught up, only announce if this pool is the one in use
  3038. if (restart)
  3039. applog(LOG_NOTICE, "%s %d caught up to new block",
  3040. work->longpoll ? "LONGPOLL from pool" : "Pool",
  3041. work->pool->pool_no);
  3042. } else {
  3043. // Switched to a block we know, but not the latest... why?
  3044. // This might detect pools trying to double-spend or 51%,
  3045. // but let's not make any accusations until it's had time
  3046. // in the real world.
  3047. free(hexstr);
  3048. hexstr = blkhashstr(&work->data[4]);
  3049. applog(LOG_WARNING, "%s %d is issuing work for an old block: %s",
  3050. work->longpoll ? "LONGPOLL from pool" : "Pool",
  3051. work->pool->pool_no,
  3052. hexstr);
  3053. }
  3054. }
  3055. }
  3056. if (work->longpoll) {
  3057. work->longpoll = false;
  3058. ++work->pool->work_restart_id;
  3059. if ((!restart) && work->pool == current_pool()) {
  3060. applog(LOG_NOTICE, "LONGPOLL from pool %d requested work restart",
  3061. work->pool->pool_no);
  3062. restart = true;
  3063. }
  3064. }
  3065. if (restart)
  3066. restart_threads();
  3067. }
  3068. out_free:
  3069. free(hexstr);
  3070. }
  3071. static int tv_sort(struct work *worka, struct work *workb)
  3072. {
  3073. return worka->tv_staged.tv_sec - workb->tv_staged.tv_sec;
  3074. }
  3075. static bool work_rollable(struct work *work)
  3076. {
  3077. return (!work->clone && work->rolltime);
  3078. }
  3079. static bool hash_push(struct work *work)
  3080. {
  3081. bool rc = true;
  3082. mutex_lock(stgd_lock);
  3083. if (work_rollable(work))
  3084. staged_rollable++;
  3085. if (likely(!getq->frozen)) {
  3086. HASH_ADD_INT(staged_work, id, work);
  3087. HASH_SORT(staged_work, tv_sort);
  3088. } else
  3089. rc = false;
  3090. pthread_cond_signal(&getq->cond);
  3091. mutex_unlock(stgd_lock);
  3092. work->pool->staged++;
  3093. if (work->queued) {
  3094. work->queued = false;
  3095. dec_queued(work->pool);
  3096. }
  3097. return rc;
  3098. }
  3099. static void *stage_thread(void *userdata)
  3100. {
  3101. struct thr_info *mythr = userdata;
  3102. bool ok = true;
  3103. rename_thr("bfg-stage");
  3104. while (ok) {
  3105. struct work *work = NULL;
  3106. applog(LOG_DEBUG, "Popping work to stage thread");
  3107. work = tq_pop(mythr->q, NULL);
  3108. if (unlikely(!work)) {
  3109. applog(LOG_ERR, "Failed to tq_pop in stage_thread");
  3110. ok = false;
  3111. break;
  3112. }
  3113. work->work_restart_id = work->pool->work_restart_id;
  3114. test_work_current(work);
  3115. applog(LOG_DEBUG, "Pushing work to getwork queue");
  3116. if (unlikely(!hash_push(work))) {
  3117. applog(LOG_WARNING, "Failed to hash_push in stage_thread");
  3118. continue;
  3119. }
  3120. }
  3121. tq_freeze(mythr->q);
  3122. return NULL;
  3123. }
  3124. static bool stage_work(struct work *work)
  3125. {
  3126. applog(LOG_DEBUG, "Pushing work to stage thread");
  3127. if (unlikely(!tq_push(thr_info[stage_thr_id].q, work))) {
  3128. applog(LOG_ERR, "Could not tq_push work in stage_work");
  3129. return false;
  3130. }
  3131. return true;
  3132. }
  3133. #ifdef HAVE_CURSES
  3134. int curses_int(const char *query)
  3135. {
  3136. int ret;
  3137. char *cvar;
  3138. cvar = curses_input(query);
  3139. ret = atoi(cvar);
  3140. free(cvar);
  3141. return ret;
  3142. }
  3143. #endif
  3144. #ifdef HAVE_CURSES
  3145. static bool input_pool(bool live);
  3146. #endif
  3147. #ifdef HAVE_CURSES
  3148. static void display_pool_summary(struct pool *pool)
  3149. {
  3150. double efficiency = 0.0;
  3151. if (curses_active_locked()) {
  3152. wlog("Pool: %s\n", pool->rpc_url);
  3153. if (pool->solved)
  3154. wlog("SOLVED %d BLOCK%s!\n", pool->solved, pool->solved > 1 ? "S" : "");
  3155. wlog("%s own long-poll support\n", pool->lp_url ? "Has" : "Does not have");
  3156. wlog(" Queued work requests: %d\n", pool->getwork_requested);
  3157. wlog(" Share submissions: %d\n", pool->accepted + pool->rejected);
  3158. wlog(" Accepted shares: %d\n", pool->accepted);
  3159. wlog(" Rejected shares: %d\n", pool->rejected);
  3160. if (pool->accepted || pool->rejected)
  3161. wlog(" Reject ratio: %.1f%%\n", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  3162. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  3163. wlog(" Efficiency (accepted / queued): %.0f%%\n", efficiency);
  3164. wlog(" Discarded work due to new blocks: %d\n", pool->discarded_work);
  3165. wlog(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  3166. wlog(" Unable to get work from server occasions: %d\n", pool->getfail_occasions);
  3167. wlog(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  3168. unlock_curses();
  3169. }
  3170. }
  3171. #endif
  3172. /* We can't remove the memory used for this struct pool because there may
  3173. * still be work referencing it. We just remove it from the pools list */
  3174. void remove_pool(struct pool *pool)
  3175. {
  3176. int i, last_pool = total_pools - 1;
  3177. struct pool *other;
  3178. /* Boost priority of any lower prio than this one */
  3179. for (i = 0; i < total_pools; i++) {
  3180. other = pools[i];
  3181. if (other->prio > pool->prio)
  3182. other->prio--;
  3183. }
  3184. if (pool->pool_no < last_pool) {
  3185. /* Swap the last pool for this one */
  3186. (pools[last_pool])->pool_no = pool->pool_no;
  3187. pools[pool->pool_no] = pools[last_pool];
  3188. }
  3189. /* Give it an invalid number */
  3190. pool->pool_no = total_pools;
  3191. pool->removed = true;
  3192. total_pools--;
  3193. }
  3194. /* add a mutex if this needs to be thread safe in the future */
  3195. static struct JE {
  3196. char *buf;
  3197. struct JE *next;
  3198. } *jedata = NULL;
  3199. static void json_escape_free()
  3200. {
  3201. struct JE *jeptr = jedata;
  3202. struct JE *jenext;
  3203. jedata = NULL;
  3204. while (jeptr) {
  3205. jenext = jeptr->next;
  3206. free(jeptr->buf);
  3207. free(jeptr);
  3208. jeptr = jenext;
  3209. }
  3210. }
  3211. static char *json_escape(char *str)
  3212. {
  3213. struct JE *jeptr;
  3214. char *buf, *ptr;
  3215. /* 2x is the max, may as well just allocate that */
  3216. ptr = buf = malloc(strlen(str) * 2 + 1);
  3217. jeptr = malloc(sizeof(*jeptr));
  3218. jeptr->buf = buf;
  3219. jeptr->next = jedata;
  3220. jedata = jeptr;
  3221. while (*str) {
  3222. if (*str == '\\' || *str == '"')
  3223. *(ptr++) = '\\';
  3224. *(ptr++) = *(str++);
  3225. }
  3226. *ptr = '\0';
  3227. return buf;
  3228. }
  3229. void write_config(FILE *fcfg)
  3230. {
  3231. int i;
  3232. /* Write pool values */
  3233. fputs("{\n\"pools\" : [", fcfg);
  3234. for(i = 0; i < total_pools; i++) {
  3235. fprintf(fcfg, "%s\n\t{\n\t\t\"url\" : \"%s\",", i > 0 ? "," : "", json_escape(pools[i]->rpc_url));
  3236. if (pools[i]->rpc_proxy)
  3237. fprintf(fcfg, "\n\t\t\"pool-proxy\" : \"%s\",", json_escape(pools[i]->rpc_proxy));
  3238. fprintf(fcfg, "\n\t\t\"user\" : \"%s\",", json_escape(pools[i]->rpc_user));
  3239. fprintf(fcfg, "\n\t\t\"pass\" : \"%s\"\n\t}", json_escape(pools[i]->rpc_pass));
  3240. }
  3241. fputs("\n]\n", fcfg);
  3242. #ifdef HAVE_OPENCL
  3243. if (nDevs) {
  3244. /* Write GPU device values */
  3245. fputs(",\n\"intensity\" : \"", fcfg);
  3246. for(i = 0; i < nDevs; i++)
  3247. fprintf(fcfg, gpus[i].dynamic ? "%sd" : "%s%d", i > 0 ? "," : "", gpus[i].intensity);
  3248. fputs("\",\n\"vectors\" : \"", fcfg);
  3249. for(i = 0; i < nDevs; i++)
  3250. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  3251. gpus[i].vwidth);
  3252. fputs("\",\n\"worksize\" : \"", fcfg);
  3253. for(i = 0; i < nDevs; i++)
  3254. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  3255. (int)gpus[i].work_size);
  3256. fputs("\",\n\"kernel\" : \"", fcfg);
  3257. for(i = 0; i < nDevs; i++) {
  3258. fprintf(fcfg, "%s", i > 0 ? "," : "");
  3259. switch (gpus[i].kernel) {
  3260. case KL_NONE: // Shouldn't happen
  3261. break;
  3262. case KL_POCLBM:
  3263. fprintf(fcfg, "poclbm");
  3264. break;
  3265. case KL_PHATK:
  3266. fprintf(fcfg, "phatk");
  3267. break;
  3268. case KL_DIAKGCN:
  3269. fprintf(fcfg, "diakgcn");
  3270. break;
  3271. case KL_DIABLO:
  3272. fprintf(fcfg, "diablo");
  3273. break;
  3274. case KL_SCRYPT:
  3275. fprintf(fcfg, "scrypt");
  3276. break;
  3277. }
  3278. }
  3279. #ifdef USE_SCRYPT
  3280. fputs("\",\n\"lookup-gap\" : \"", fcfg);
  3281. for(i = 0; i < nDevs; i++)
  3282. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  3283. (int)gpus[i].opt_lg);
  3284. fputs("\",\n\"thread-concurrency\" : \"", fcfg);
  3285. for(i = 0; i < nDevs; i++)
  3286. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  3287. (int)gpus[i].opt_tc);
  3288. fputs("\",\n\"shaders\" : \"", fcfg);
  3289. for(i = 0; i < nDevs; i++)
  3290. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  3291. (int)gpus[i].shaders);
  3292. #endif
  3293. #ifdef HAVE_ADL
  3294. fputs("\",\n\"gpu-engine\" : \"", fcfg);
  3295. for(i = 0; i < nDevs; i++)
  3296. fprintf(fcfg, "%s%d-%d", i > 0 ? "," : "", gpus[i].min_engine, gpus[i].gpu_engine);
  3297. fputs("\",\n\"gpu-fan\" : \"", fcfg);
  3298. for(i = 0; i < nDevs; i++)
  3299. fprintf(fcfg, "%s%d-%d", i > 0 ? "," : "", gpus[i].min_fan, gpus[i].gpu_fan);
  3300. fputs("\",\n\"gpu-memclock\" : \"", fcfg);
  3301. for(i = 0; i < nDevs; i++)
  3302. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_memclock);
  3303. fputs("\",\n\"gpu-memdiff\" : \"", fcfg);
  3304. for(i = 0; i < nDevs; i++)
  3305. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_memdiff);
  3306. fputs("\",\n\"gpu-powertune\" : \"", fcfg);
  3307. for(i = 0; i < nDevs; i++)
  3308. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_powertune);
  3309. fputs("\",\n\"gpu-vddc\" : \"", fcfg);
  3310. for(i = 0; i < nDevs; i++)
  3311. fprintf(fcfg, "%s%1.3f", i > 0 ? "," : "", gpus[i].gpu_vddc);
  3312. fputs("\",\n\"temp-cutoff\" : \"", fcfg);
  3313. for(i = 0; i < nDevs; i++)
  3314. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].cutofftemp);
  3315. fputs("\",\n\"temp-overheat\" : \"", fcfg);
  3316. for(i = 0; i < nDevs; i++)
  3317. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].adl.overtemp);
  3318. fputs("\",\n\"temp-target\" : \"", fcfg);
  3319. for(i = 0; i < nDevs; i++)
  3320. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].adl.targettemp);
  3321. #endif
  3322. fputs("\"", fcfg);
  3323. }
  3324. #endif
  3325. #ifdef HAVE_ADL
  3326. if (opt_reorder)
  3327. fprintf(fcfg, ",\n\"gpu-reorder\" : true");
  3328. #endif
  3329. #ifdef WANT_CPUMINE
  3330. fprintf(fcfg, ",\n\"algo\" : \"%s\"", algo_names[opt_algo]);
  3331. #endif
  3332. /* Simple bool and int options */
  3333. struct opt_table *opt;
  3334. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  3335. char *p, *name = strdup(opt->names);
  3336. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  3337. if (p[1] != '-')
  3338. continue;
  3339. if (opt->type & OPT_NOARG &&
  3340. ((void *)opt->cb == (void *)opt_set_bool || (void *)opt->cb == (void *)opt_set_invbool) &&
  3341. (*(bool *)opt->u.arg == ((void *)opt->cb == (void *)opt_set_bool)))
  3342. fprintf(fcfg, ",\n\"%s\" : true", p+2);
  3343. if (opt->type & OPT_HASARG &&
  3344. ((void *)opt->cb_arg == (void *)set_int_0_to_9999 ||
  3345. (void *)opt->cb_arg == (void *)set_int_1_to_65535 ||
  3346. (void *)opt->cb_arg == (void *)set_int_0_to_10 ||
  3347. (void *)opt->cb_arg == (void *)set_int_1_to_10) &&
  3348. opt->desc != opt_hidden &&
  3349. 0 <= *(int *)opt->u.arg)
  3350. fprintf(fcfg, ",\n\"%s\" : \"%d\"", p+2, *(int *)opt->u.arg);
  3351. }
  3352. }
  3353. /* Special case options */
  3354. fprintf(fcfg, ",\n\"shares\" : \"%d\"", opt_shares);
  3355. if (pool_strategy == POOL_BALANCE)
  3356. fputs(",\n\"balance\" : true", fcfg);
  3357. if (pool_strategy == POOL_LOADBALANCE)
  3358. fputs(",\n\"load-balance\" : true", fcfg);
  3359. if (pool_strategy == POOL_ROUNDROBIN)
  3360. fputs(",\n\"round-robin\" : true", fcfg);
  3361. if (pool_strategy == POOL_ROTATE)
  3362. fprintf(fcfg, ",\n\"rotate\" : \"%d\"", opt_rotate_period);
  3363. #if defined(unix)
  3364. if (opt_stderr_cmd && *opt_stderr_cmd)
  3365. fprintf(fcfg, ",\n\"monitor\" : \"%s\"", json_escape(opt_stderr_cmd));
  3366. #endif // defined(unix)
  3367. if (opt_kernel_path && *opt_kernel_path) {
  3368. char *kpath = strdup(opt_kernel_path);
  3369. if (kpath[strlen(kpath)-1] == '/')
  3370. kpath[strlen(kpath)-1] = 0;
  3371. fprintf(fcfg, ",\n\"kernel-path\" : \"%s\"", json_escape(kpath));
  3372. }
  3373. if (schedstart.enable)
  3374. fprintf(fcfg, ",\n\"sched-time\" : \"%d:%d\"", schedstart.tm.tm_hour, schedstart.tm.tm_min);
  3375. if (schedstop.enable)
  3376. fprintf(fcfg, ",\n\"stop-time\" : \"%d:%d\"", schedstop.tm.tm_hour, schedstop.tm.tm_min);
  3377. if (opt_socks_proxy && *opt_socks_proxy)
  3378. fprintf(fcfg, ",\n\"socks-proxy\" : \"%s\"", json_escape(opt_socks_proxy));
  3379. #ifdef HAVE_OPENCL
  3380. for(i = 0; i < nDevs; i++)
  3381. if (gpus[i].deven == DEV_DISABLED)
  3382. break;
  3383. if (i < nDevs)
  3384. for (i = 0; i < nDevs; i++)
  3385. if (gpus[i].deven != DEV_DISABLED)
  3386. fprintf(fcfg, ",\n\"device\" : \"%d\"", i);
  3387. #endif
  3388. if (opt_api_allow)
  3389. fprintf(fcfg, ",\n\"api-allow\" : \"%s\"", json_escape(opt_api_allow));
  3390. if (strcmp(opt_api_description, PACKAGE_STRING) != 0)
  3391. fprintf(fcfg, ",\n\"api-description\" : \"%s\"", json_escape(opt_api_description));
  3392. if (opt_api_groups)
  3393. fprintf(fcfg, ",\n\"api-groups\" : \"%s\"", json_escape(opt_api_groups));
  3394. if (opt_icarus_options)
  3395. fprintf(fcfg, ",\n\"icarus-options\" : \"%s\"", json_escape(opt_icarus_options));
  3396. if (opt_icarus_timing)
  3397. fprintf(fcfg, ",\n\"icarus-timing\" : \"%s\"", json_escape(opt_icarus_timing));
  3398. fputs("\n}\n", fcfg);
  3399. json_escape_free();
  3400. }
  3401. #ifdef HAVE_CURSES
  3402. static void display_pools(void)
  3403. {
  3404. struct pool *pool;
  3405. int selected, i;
  3406. char input;
  3407. opt_loginput = true;
  3408. immedok(logwin, true);
  3409. clear_logwin();
  3410. updated:
  3411. for (i = 0; i < total_pools; i++) {
  3412. pool = pools[i];
  3413. if (pool == current_pool())
  3414. wattron(logwin, A_BOLD);
  3415. if (pool->enabled != POOL_ENABLED)
  3416. wattron(logwin, A_DIM);
  3417. wlogprint("%d: ", pool->pool_no);
  3418. switch (pool->enabled) {
  3419. case POOL_ENABLED:
  3420. wlogprint("Enabled ");
  3421. break;
  3422. case POOL_DISABLED:
  3423. wlogprint("Disabled ");
  3424. break;
  3425. case POOL_REJECTING:
  3426. wlogprint("Rejectin ");
  3427. break;
  3428. }
  3429. if (pool->idle)
  3430. wlogprint("Dead ");
  3431. else
  3432. if (pool->lp_url && pool->proto != pool->lp_proto)
  3433. wlogprint("Mixed");
  3434. else
  3435. switch (pool->proto) {
  3436. case PLP_GETBLOCKTEMPLATE:
  3437. wlogprint(" GBT ");
  3438. break;
  3439. case PLP_GETWORK:
  3440. wlogprint("GWork");
  3441. break;
  3442. default:
  3443. wlogprint("Alive");
  3444. }
  3445. wlogprint(" Priority %d: %s User:%s\n",
  3446. pool->prio,
  3447. pool->rpc_url, pool->rpc_user);
  3448. wattroff(logwin, A_BOLD | A_DIM);
  3449. }
  3450. retry:
  3451. wlogprint("\nCurrent pool management strategy: %s\n",
  3452. strategies[pool_strategy]);
  3453. if (pool_strategy == POOL_ROTATE)
  3454. wlogprint("Set to rotate every %d minutes\n", opt_rotate_period);
  3455. wlogprint("[F]ailover only %s\n", opt_fail_only ? "enabled" : "disabled");
  3456. wlogprint("[A]dd pool [R]emove pool [D]isable pool [E]nable pool\n");
  3457. wlogprint("[C]hange management strategy [S]witch pool [I]nformation\n");
  3458. wlogprint("Or press any other key to continue\n");
  3459. input = getch();
  3460. if (!strncasecmp(&input, "a", 1)) {
  3461. input_pool(true);
  3462. goto updated;
  3463. } else if (!strncasecmp(&input, "r", 1)) {
  3464. if (total_pools <= 1) {
  3465. wlogprint("Cannot remove last pool");
  3466. goto retry;
  3467. }
  3468. selected = curses_int("Select pool number");
  3469. if (selected < 0 || selected >= total_pools) {
  3470. wlogprint("Invalid selection\n");
  3471. goto retry;
  3472. }
  3473. pool = pools[selected];
  3474. if (pool == current_pool())
  3475. switch_pools(NULL);
  3476. if (pool == current_pool()) {
  3477. wlogprint("Unable to remove pool due to activity\n");
  3478. goto retry;
  3479. }
  3480. disable_pool(pool);
  3481. remove_pool(pool);
  3482. goto updated;
  3483. } else if (!strncasecmp(&input, "s", 1)) {
  3484. selected = curses_int("Select pool number");
  3485. if (selected < 0 || selected >= total_pools) {
  3486. wlogprint("Invalid selection\n");
  3487. goto retry;
  3488. }
  3489. pool = pools[selected];
  3490. enable_pool(pool);
  3491. switch_pools(pool);
  3492. goto updated;
  3493. } else if (!strncasecmp(&input, "d", 1)) {
  3494. if (enabled_pools <= 1) {
  3495. wlogprint("Cannot disable last pool");
  3496. goto retry;
  3497. }
  3498. selected = curses_int("Select pool number");
  3499. if (selected < 0 || selected >= total_pools) {
  3500. wlogprint("Invalid selection\n");
  3501. goto retry;
  3502. }
  3503. pool = pools[selected];
  3504. disable_pool(pool);
  3505. if (pool == current_pool())
  3506. switch_pools(NULL);
  3507. goto updated;
  3508. } else if (!strncasecmp(&input, "e", 1)) {
  3509. selected = curses_int("Select pool number");
  3510. if (selected < 0 || selected >= total_pools) {
  3511. wlogprint("Invalid selection\n");
  3512. goto retry;
  3513. }
  3514. pool = pools[selected];
  3515. enable_pool(pool);
  3516. if (pool->prio < current_pool()->prio)
  3517. switch_pools(pool);
  3518. goto updated;
  3519. } else if (!strncasecmp(&input, "c", 1)) {
  3520. for (i = 0; i <= TOP_STRATEGY; i++)
  3521. wlogprint("%d: %s\n", i, strategies[i]);
  3522. selected = curses_int("Select strategy number type");
  3523. if (selected < 0 || selected > TOP_STRATEGY) {
  3524. wlogprint("Invalid selection\n");
  3525. goto retry;
  3526. }
  3527. if (selected == POOL_ROTATE) {
  3528. opt_rotate_period = curses_int("Select interval in minutes");
  3529. if (opt_rotate_period < 0 || opt_rotate_period > 9999) {
  3530. opt_rotate_period = 0;
  3531. wlogprint("Invalid selection\n");
  3532. goto retry;
  3533. }
  3534. }
  3535. pool_strategy = selected;
  3536. switch_pools(NULL);
  3537. goto updated;
  3538. } else if (!strncasecmp(&input, "i", 1)) {
  3539. selected = curses_int("Select pool number");
  3540. if (selected < 0 || selected >= total_pools) {
  3541. wlogprint("Invalid selection\n");
  3542. goto retry;
  3543. }
  3544. pool = pools[selected];
  3545. display_pool_summary(pool);
  3546. goto retry;
  3547. } else if (!strncasecmp(&input, "f", 1)) {
  3548. opt_fail_only ^= true;
  3549. goto updated;
  3550. } else
  3551. clear_logwin();
  3552. immedok(logwin, false);
  3553. opt_loginput = false;
  3554. }
  3555. static void display_options(void)
  3556. {
  3557. int selected;
  3558. char input;
  3559. opt_loginput = true;
  3560. immedok(logwin, true);
  3561. clear_logwin();
  3562. retry:
  3563. wlogprint("[N]ormal [C]lear [S]ilent mode (disable all output)\n");
  3564. 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",
  3565. opt_debug_console ? "on" : "off",
  3566. want_per_device_stats? "on" : "off",
  3567. opt_quiet ? "on" : "off",
  3568. opt_log_output ? "on" : "off",
  3569. opt_protocol ? "on" : "off",
  3570. opt_log_interval);
  3571. wlogprint("Select an option or any other key to return\n");
  3572. input = getch();
  3573. if (!strncasecmp(&input, "q", 1)) {
  3574. opt_quiet ^= true;
  3575. wlogprint("Quiet mode %s\n", opt_quiet ? "enabled" : "disabled");
  3576. goto retry;
  3577. } else if (!strncasecmp(&input, "v", 1)) {
  3578. opt_log_output ^= true;
  3579. if (opt_log_output)
  3580. opt_quiet = false;
  3581. wlogprint("Verbose mode %s\n", opt_log_output ? "enabled" : "disabled");
  3582. goto retry;
  3583. } else if (!strncasecmp(&input, "n", 1)) {
  3584. opt_log_output = false;
  3585. opt_debug_console = false;
  3586. opt_quiet = false;
  3587. opt_protocol = false;
  3588. want_per_device_stats = false;
  3589. wlogprint("Output mode reset to normal\n");
  3590. goto retry;
  3591. } else if (!strncasecmp(&input, "d", 1)) {
  3592. opt_debug = true;
  3593. opt_debug_console ^= true;
  3594. opt_log_output = opt_debug_console;
  3595. if (opt_debug_console)
  3596. opt_quiet = false;
  3597. wlogprint("Debug mode %s\n", opt_debug_console ? "enabled" : "disabled");
  3598. goto retry;
  3599. } else if (!strncasecmp(&input, "p", 1)) {
  3600. want_per_device_stats ^= true;
  3601. opt_log_output = want_per_device_stats;
  3602. wlogprint("Per-device stats %s\n", want_per_device_stats ? "enabled" : "disabled");
  3603. goto retry;
  3604. } else if (!strncasecmp(&input, "r", 1)) {
  3605. opt_protocol ^= true;
  3606. if (opt_protocol)
  3607. opt_quiet = false;
  3608. wlogprint("RPC protocol debugging %s\n", opt_protocol ? "enabled" : "disabled");
  3609. goto retry;
  3610. } else if (!strncasecmp(&input, "c", 1))
  3611. clear_logwin();
  3612. else if (!strncasecmp(&input, "l", 1)) {
  3613. selected = curses_int("Interval in seconds");
  3614. if (selected < 0 || selected > 9999) {
  3615. wlogprint("Invalid selection\n");
  3616. goto retry;
  3617. }
  3618. opt_log_interval = selected;
  3619. wlogprint("Log interval set to %d seconds\n", opt_log_interval);
  3620. goto retry;
  3621. } else if (!strncasecmp(&input, "s", 1)) {
  3622. opt_realquiet = true;
  3623. } else
  3624. clear_logwin();
  3625. immedok(logwin, false);
  3626. opt_loginput = false;
  3627. }
  3628. #endif
  3629. void default_save_file(char *filename)
  3630. {
  3631. #if defined(unix)
  3632. if (getenv("HOME") && *getenv("HOME")) {
  3633. strcpy(filename, getenv("HOME"));
  3634. strcat(filename, "/");
  3635. }
  3636. else
  3637. strcpy(filename, "");
  3638. strcat(filename, ".bfgminer/");
  3639. mkdir(filename, 0777);
  3640. #else
  3641. strcpy(filename, "");
  3642. #endif
  3643. strcat(filename, def_conf);
  3644. }
  3645. #ifdef HAVE_CURSES
  3646. static void set_options(void)
  3647. {
  3648. int selected;
  3649. char input;
  3650. opt_loginput = true;
  3651. immedok(logwin, true);
  3652. clear_logwin();
  3653. retry:
  3654. wlogprint("\n[L]ongpoll: %s\n", want_longpoll ? "On" : "Off");
  3655. wlogprint("[Q]ueue: %d\n[S]cantime: %d\n[E]xpiry: %d\n[R]etries: %d\n"
  3656. "[W]rite config file\n[B]FGMiner restart\n",
  3657. opt_queue, opt_scantime, opt_expiry, opt_retries);
  3658. wlogprint("Select an option or any other key to return\n");
  3659. input = getch();
  3660. if (!strncasecmp(&input, "q", 1)) {
  3661. selected = curses_int("Extra work items to queue");
  3662. if (selected < 0 || selected > 9999) {
  3663. wlogprint("Invalid selection\n");
  3664. goto retry;
  3665. }
  3666. opt_queue = selected;
  3667. goto retry;
  3668. } else if (!strncasecmp(&input, "l", 1)) {
  3669. if (want_longpoll)
  3670. stop_longpoll();
  3671. else
  3672. start_longpoll();
  3673. applog(LOG_WARNING, "Longpoll %s", want_longpoll ? "enabled" : "disabled");
  3674. goto retry;
  3675. } else if (!strncasecmp(&input, "s", 1)) {
  3676. selected = curses_int("Set scantime in seconds");
  3677. if (selected < 0 || selected > 9999) {
  3678. wlogprint("Invalid selection\n");
  3679. goto retry;
  3680. }
  3681. opt_scantime = selected;
  3682. goto retry;
  3683. } else if (!strncasecmp(&input, "e", 1)) {
  3684. selected = curses_int("Set expiry time in seconds");
  3685. if (selected < 0 || selected > 9999) {
  3686. wlogprint("Invalid selection\n");
  3687. goto retry;
  3688. }
  3689. opt_expiry = selected;
  3690. goto retry;
  3691. } else if (!strncasecmp(&input, "r", 1)) {
  3692. selected = curses_int("Retries before failing (-1 infinite)");
  3693. if (selected < -1 || selected > 9999) {
  3694. wlogprint("Invalid selection\n");
  3695. goto retry;
  3696. }
  3697. opt_retries = selected;
  3698. goto retry;
  3699. } else if (!strncasecmp(&input, "w", 1)) {
  3700. FILE *fcfg;
  3701. char *str, filename[PATH_MAX], prompt[PATH_MAX + 50];
  3702. default_save_file(filename);
  3703. sprintf(prompt, "Config filename to write (Enter for default) [%s]", filename);
  3704. str = curses_input(prompt);
  3705. if (strcmp(str, "-1")) {
  3706. struct stat statbuf;
  3707. strcpy(filename, str);
  3708. if (!stat(filename, &statbuf)) {
  3709. wlogprint("File exists, overwrite?\n");
  3710. input = getch();
  3711. if (strncasecmp(&input, "y", 1))
  3712. goto retry;
  3713. }
  3714. }
  3715. fcfg = fopen(filename, "w");
  3716. if (!fcfg) {
  3717. wlogprint("Cannot open or create file\n");
  3718. goto retry;
  3719. }
  3720. write_config(fcfg);
  3721. fclose(fcfg);
  3722. goto retry;
  3723. } else if (!strncasecmp(&input, "b", 1)) {
  3724. wlogprint("Are you sure?\n");
  3725. input = getch();
  3726. if (!strncasecmp(&input, "y", 1))
  3727. app_restart();
  3728. else
  3729. clear_logwin();
  3730. } else
  3731. clear_logwin();
  3732. immedok(logwin, false);
  3733. opt_loginput = false;
  3734. }
  3735. static void *input_thread(void __maybe_unused *userdata)
  3736. {
  3737. rename_thr("bfg-input");
  3738. if (!curses_active)
  3739. return NULL;
  3740. while (1) {
  3741. int input;
  3742. input = getch();
  3743. switch (input) {
  3744. case 'q': case 'Q':
  3745. kill_work();
  3746. return NULL;
  3747. case 'd': case 'D':
  3748. display_options();
  3749. break;
  3750. case 'p': case 'P':
  3751. display_pools();
  3752. break;
  3753. case 's': case 'S':
  3754. set_options();
  3755. break;
  3756. case 'g': case 'G':
  3757. if (have_opencl)
  3758. manage_gpu();
  3759. break;
  3760. #ifdef HAVE_CURSES
  3761. case KEY_DOWN:
  3762. if (devsummaryYOffset < -(total_devices + devcursor - statusy))
  3763. break;
  3764. devsummaryYOffset -= 2;
  3765. case KEY_UP:
  3766. if (devsummaryYOffset == 0)
  3767. break;
  3768. ++devsummaryYOffset;
  3769. if (curses_active_locked()) {
  3770. int i;
  3771. for (i = 0; i < mining_threads; i++)
  3772. curses_print_devstatus(i);
  3773. touchwin(statuswin);
  3774. wrefresh(statuswin);
  3775. unlock_curses();
  3776. }
  3777. break;
  3778. #endif
  3779. }
  3780. if (opt_realquiet) {
  3781. disable_curses();
  3782. break;
  3783. }
  3784. }
  3785. return NULL;
  3786. }
  3787. #endif
  3788. /* This thread should not be shut down unless a problem occurs */
  3789. static void *workio_thread(void *userdata)
  3790. {
  3791. struct thr_info *mythr = userdata;
  3792. bool ok = true;
  3793. rename_thr("bfg-workio");
  3794. while (ok) {
  3795. struct workio_cmd *wc;
  3796. applog(LOG_DEBUG, "Popping work to work thread");
  3797. /* wait for workio_cmd sent to us, on our queue */
  3798. wc = tq_pop(mythr->q, NULL);
  3799. if (unlikely(!wc)) {
  3800. applog(LOG_ERR, "Failed to tq_pop in workio_thread");
  3801. ok = false;
  3802. break;
  3803. }
  3804. /* process workio_cmd */
  3805. switch (wc->cmd) {
  3806. case WC_GET_WORK:
  3807. ok = workio_get_work(wc);
  3808. break;
  3809. case WC_SUBMIT_WORK:
  3810. {
  3811. mutex_lock(&submitting_lock);
  3812. if (submitting >= opt_submit_threads) {
  3813. if (list_empty(&submit_waiting))
  3814. applog(LOG_WARNING, "workio_thread queuing submissions (see --submit-threads)");
  3815. else
  3816. applog(LOG_DEBUG, "workio_thread queuing submission");
  3817. list_add_tail(&wc->list, &submit_waiting);
  3818. mutex_unlock(&submitting_lock);
  3819. break;
  3820. }
  3821. ++submitting;
  3822. mutex_unlock(&submitting_lock);
  3823. ok = workio_submit_work(wc);
  3824. break;
  3825. }
  3826. default:
  3827. ok = false;
  3828. break;
  3829. }
  3830. }
  3831. tq_freeze(mythr->q);
  3832. return NULL;
  3833. }
  3834. static void *api_thread(void *userdata)
  3835. {
  3836. struct thr_info *mythr = userdata;
  3837. pthread_detach(pthread_self());
  3838. rename_thr("bfg-rpc");
  3839. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3840. api(api_thr_id);
  3841. PTH(mythr) = 0L;
  3842. return NULL;
  3843. }
  3844. void thread_reportin(struct thr_info *thr)
  3845. {
  3846. gettimeofday(&thr->last, NULL);
  3847. thr->cgpu->status = LIFE_WELL;
  3848. thr->getwork = 0;
  3849. thr->cgpu->device_last_well = time(NULL);
  3850. }
  3851. static inline void thread_reportout(struct thr_info *thr)
  3852. {
  3853. thr->getwork = time(NULL);
  3854. }
  3855. static void hashmeter(int thr_id, struct timeval *diff,
  3856. unsigned long long hashes_done)
  3857. {
  3858. struct timeval temp_tv_end, total_diff;
  3859. double secs;
  3860. double local_secs;
  3861. double utility, efficiency = 0.0;
  3862. static double local_mhashes_done = 0;
  3863. static double rolling = 0;
  3864. double local_mhashes = (double)hashes_done / 1000000.0;
  3865. bool showlog = false;
  3866. char cHr[h2bs_fmt_size[H2B_NOUNIT]], aHr[h2bs_fmt_size[H2B_NOUNIT]], uHr[h2bs_fmt_size[H2B_SPACED]];
  3867. /* Update the last time this thread reported in */
  3868. if (thr_id >= 0) {
  3869. gettimeofday(&thr_info[thr_id].last, NULL);
  3870. thr_info[thr_id].cgpu->device_last_well = time(NULL);
  3871. }
  3872. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  3873. /* So we can call hashmeter from a non worker thread */
  3874. if (thr_id >= 0) {
  3875. struct thr_info *thr = &thr_info[thr_id];
  3876. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  3877. double thread_rolling = 0.0;
  3878. int i;
  3879. applog(LOG_DEBUG, "[thread %d: %llu hashes, %.1f khash/sec]",
  3880. thr_id, hashes_done, hashes_done / 1000 / secs);
  3881. /* Rolling average for each thread and each device */
  3882. decay_time(&thr->rolling, local_mhashes / secs);
  3883. for (i = 0; i < cgpu->threads; i++)
  3884. thread_rolling += cgpu->thr[i]->rolling;
  3885. mutex_lock(&hash_lock);
  3886. decay_time(&cgpu->rolling, thread_rolling);
  3887. cgpu->total_mhashes += local_mhashes;
  3888. mutex_unlock(&hash_lock);
  3889. // If needed, output detailed, per-device stats
  3890. if (want_per_device_stats) {
  3891. struct timeval now;
  3892. struct timeval elapsed;
  3893. gettimeofday(&now, NULL);
  3894. timersub(&now, &thr->cgpu->last_message_tv, &elapsed);
  3895. if (opt_log_interval <= elapsed.tv_sec) {
  3896. struct cgpu_info *cgpu = thr->cgpu;
  3897. char logline[255];
  3898. cgpu->last_message_tv = now;
  3899. get_statline(logline, cgpu);
  3900. if (!curses_active) {
  3901. printf("%s \r", logline);
  3902. fflush(stdout);
  3903. } else
  3904. applog(LOG_INFO, "%s", logline);
  3905. }
  3906. }
  3907. }
  3908. /* Totals are updated by all threads so can race without locking */
  3909. mutex_lock(&hash_lock);
  3910. gettimeofday(&temp_tv_end, NULL);
  3911. timersub(&temp_tv_end, &total_tv_end, &total_diff);
  3912. total_mhashes_done += local_mhashes;
  3913. local_mhashes_done += local_mhashes;
  3914. if (total_diff.tv_sec < opt_log_interval)
  3915. /* Only update the total every opt_log_interval seconds */
  3916. goto out_unlock;
  3917. showlog = true;
  3918. gettimeofday(&total_tv_end, NULL);
  3919. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  3920. decay_time(&rolling, local_mhashes_done / local_secs);
  3921. global_hashrate = roundl(rolling) * 1000000;
  3922. timersub(&total_tv_end, &total_tv_start, &total_diff);
  3923. total_secs = (double)total_diff.tv_sec +
  3924. ((double)total_diff.tv_usec / 1000000.0);
  3925. utility = total_accepted / total_secs * 60;
  3926. efficiency = total_getworks ? total_accepted * 100.0 / total_getworks : 0.0;
  3927. ti_hashrate_bufstr(
  3928. (char*[]){cHr, aHr, uHr},
  3929. 1e6*rolling,
  3930. 1e6*total_mhashes_done / total_secs,
  3931. utility_to_hashrate(total_accepted_weighed / (total_secs ?: 1) * 60),
  3932. H2B_SPACED);
  3933. sprintf(statusline, "%s%ds:%s avg:%s u:%s | A:%d R:%d HW:%d E:%.0f%% U:%.1f/m",
  3934. want_per_device_stats ? "ALL " : "",
  3935. opt_log_interval,
  3936. cHr, aHr,
  3937. uHr,
  3938. total_accepted, total_rejected, hw_errors, efficiency, utility);
  3939. local_mhashes_done = 0;
  3940. out_unlock:
  3941. mutex_unlock(&hash_lock);
  3942. if (showlog) {
  3943. if (!curses_active) {
  3944. printf("%s \r", statusline);
  3945. fflush(stdout);
  3946. } else
  3947. applog(LOG_INFO, "%s", statusline);
  3948. }
  3949. }
  3950. static void *longpoll_thread(void *userdata);
  3951. // NOTE: This assumes reference URI is a root
  3952. static char *absolute_uri(char *uri, const char *ref)
  3953. {
  3954. if (strstr(uri, "://"))
  3955. return strdup(uri);
  3956. char *copy_start, *abs;
  3957. bool need_slash = false;
  3958. copy_start = (uri[0] == '/') ? &uri[1] : uri;
  3959. if (ref[strlen(ref) - 1] != '/')
  3960. need_slash = true;
  3961. abs = malloc(strlen(ref) + strlen(copy_start) + 2);
  3962. if (!abs) {
  3963. applog(LOG_ERR, "Malloc failure in absolute_uri");
  3964. return NULL;
  3965. }
  3966. sprintf(abs, "%s%s%s", ref, need_slash ? "/" : "", copy_start);
  3967. return abs;
  3968. }
  3969. static bool pool_active(struct pool *pool, bool pinging)
  3970. {
  3971. bool ret = false;
  3972. json_t *val;
  3973. CURL *curl;
  3974. int rolltime;
  3975. char *rpc_req;
  3976. struct work *work;
  3977. enum pool_protocol proto;
  3978. curl = curl_easy_init();
  3979. if (unlikely(!curl)) {
  3980. applog(LOG_ERR, "CURL initialisation failed");
  3981. return false;
  3982. }
  3983. work = make_work();
  3984. work->pool = pool;
  3985. proto = want_gbt ? PLP_GETBLOCKTEMPLATE : PLP_GETWORK;
  3986. tryagain:
  3987. rpc_req = prepare_rpc_req(work, proto, NULL);
  3988. if (!rpc_req)
  3989. return false;
  3990. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  3991. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  3992. true, false, &rolltime, pool, false);
  3993. if (val) {
  3994. bool rc;
  3995. json_t *res;
  3996. res = json_object_get(val, "result");
  3997. if ((!json_is_object(res)) || (proto == PLP_GETBLOCKTEMPLATE && !json_object_get(res, "bits")))
  3998. goto badwork;
  3999. rc = work_decode(res, work);
  4000. if (rc) {
  4001. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  4002. pool->pool_no, pool->rpc_url);
  4003. work->pool = pool;
  4004. work->rolltime = rolltime;
  4005. applog(LOG_DEBUG, "Pushing pooltest work to base pool");
  4006. tq_push(thr_info[stage_thr_id].q, work);
  4007. total_getworks++;
  4008. pool->getwork_requested++;
  4009. ret = true;
  4010. gettimeofday(&pool->tv_idle, NULL);
  4011. } else {
  4012. badwork:
  4013. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher work from pool %u %s",
  4014. pool->pool_no, pool->rpc_url);
  4015. if (PLP_NONE != (proto = pool_protocol_fallback(proto)))
  4016. goto tryagain;
  4017. free_work(work);
  4018. goto out;
  4019. }
  4020. json_decref(val);
  4021. if (proto != pool->proto) {
  4022. pool->proto = proto;
  4023. applog(LOG_INFO, "Selected %s protocol for pool %u", pool_protocol_name(proto), pool->pool_no);
  4024. }
  4025. if (pool->lp_url)
  4026. goto out;
  4027. /* Decipher the longpoll URL, if any, and store it in ->lp_url */
  4028. const struct blktmpl_longpoll_req *lp;
  4029. if (work->tmpl && (lp = blktmpl_get_longpoll(work->tmpl))) {
  4030. // NOTE: work_decode takes care of lp id
  4031. pool->lp_url = lp->uri ? absolute_uri(lp->uri, pool->rpc_url) : pool->rpc_url;
  4032. if (!pool->lp_url)
  4033. return false;
  4034. pool->lp_proto = PLP_GETBLOCKTEMPLATE;
  4035. }
  4036. else
  4037. if (pool->hdr_path) {
  4038. pool->lp_url = absolute_uri(pool->hdr_path, pool->rpc_url);
  4039. if (!pool->lp_url)
  4040. return false;
  4041. pool->lp_proto = PLP_GETWORK;
  4042. } else
  4043. pool->lp_url = NULL;
  4044. if (want_longpoll && !pool->lp_started) {
  4045. pool->lp_started = true;
  4046. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  4047. quit(1, "Failed to create pool longpoll thread");
  4048. }
  4049. } else if (PLP_NONE != (proto = pool_protocol_fallback(proto))) {
  4050. goto tryagain;
  4051. } else {
  4052. free_work(work);
  4053. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  4054. pool->pool_no, pool->rpc_url);
  4055. if (!pinging)
  4056. applog(LOG_WARNING, "Pool %u slow/down or URL or credentials invalid", pool->pool_no);
  4057. }
  4058. out:
  4059. curl_easy_cleanup(curl);
  4060. return ret;
  4061. }
  4062. static void pool_died(struct pool *pool)
  4063. {
  4064. if (!pool_tset(pool, &pool->idle)) {
  4065. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  4066. gettimeofday(&pool->tv_idle, NULL);
  4067. switch_pools(NULL);
  4068. }
  4069. }
  4070. static inline int cp_prio(void)
  4071. {
  4072. int prio;
  4073. mutex_lock(&control_lock);
  4074. prio = currentpool->prio;
  4075. mutex_unlock(&control_lock);
  4076. return prio;
  4077. }
  4078. static void pool_resus(struct pool *pool)
  4079. {
  4080. applog(LOG_WARNING, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  4081. if (pool->prio < cp_prio() && pool_strategy == POOL_FAILOVER)
  4082. switch_pools(NULL);
  4083. }
  4084. static bool queue_request(void)
  4085. {
  4086. int ts, tq, maxq = opt_queue + mining_threads;
  4087. struct pool *pool, *cp;
  4088. struct workio_cmd *wc;
  4089. bool lagging;
  4090. ts = total_staged();
  4091. tq = global_queued();
  4092. if (ts && ts + tq >= maxq)
  4093. return true;
  4094. cp = current_pool();
  4095. lagging = !opt_fail_only && cp->lagging && !ts && cp->queued >= maxq;
  4096. if (!lagging && cp->staged + cp->queued >= maxq)
  4097. return true;
  4098. pool = select_pool(lagging);
  4099. if (pool->staged + pool->queued >= maxq)
  4100. return true;
  4101. inc_queued(pool);
  4102. /* fill out work request message */
  4103. wc = calloc(1, sizeof(*wc));
  4104. if (unlikely(!wc)) {
  4105. applog(LOG_ERR, "Failed to calloc wc in queue_request");
  4106. return false;
  4107. }
  4108. wc->cmd = WC_GET_WORK;
  4109. wc->pool = pool;
  4110. applog(LOG_DEBUG, "Queueing getwork request to work thread");
  4111. /* send work request to workio thread */
  4112. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  4113. applog(LOG_ERR, "Failed to tq_push in queue_request");
  4114. workio_cmd_free(wc);
  4115. return false;
  4116. }
  4117. return true;
  4118. }
  4119. static struct work *hash_pop(const struct timespec *abstime)
  4120. {
  4121. struct work *work = NULL, *tmp;
  4122. int rc = 0, hc;
  4123. mutex_lock(stgd_lock);
  4124. while (!getq->frozen && !HASH_COUNT(staged_work) && !rc)
  4125. rc = pthread_cond_timedwait(&getq->cond, stgd_lock, abstime);
  4126. hc = HASH_COUNT(staged_work);
  4127. if (likely(hc)) {
  4128. /* Find clone work if possible, to allow masters to be reused */
  4129. if (hc > staged_rollable) {
  4130. HASH_ITER(hh, staged_work, work, tmp) {
  4131. if (!work_rollable(work))
  4132. break;
  4133. }
  4134. } else
  4135. work = staged_work;
  4136. HASH_DEL(staged_work, work);
  4137. work->pool->staged--;
  4138. if (work_rollable(work))
  4139. staged_rollable--;
  4140. }
  4141. mutex_unlock(stgd_lock);
  4142. queue_request();
  4143. return work;
  4144. }
  4145. static bool reuse_work(struct work *work)
  4146. {
  4147. if (can_roll(work) && should_roll(work)) {
  4148. roll_work(work);
  4149. return true;
  4150. }
  4151. return false;
  4152. }
  4153. /* Clones work by rolling it if possible, and returning a clone instead of the
  4154. * original work item which gets staged again to possibly be rolled again in
  4155. * the future */
  4156. static struct work *clone_work(struct work *work)
  4157. {
  4158. int mrs = mining_threads + opt_queue - total_staged();
  4159. struct work *work_clone;
  4160. bool cloned;
  4161. if (mrs < 1)
  4162. return work;
  4163. cloned = false;
  4164. work_clone = make_clone(work);
  4165. while (mrs-- > 0 && can_roll(work) && should_roll(work)) {
  4166. applog(LOG_DEBUG, "Pushing rolled converted work to stage thread");
  4167. if (unlikely(!stage_work(work_clone))) {
  4168. cloned = false;
  4169. break;
  4170. }
  4171. roll_work(work);
  4172. work_clone = make_clone(work);
  4173. /* Roll it again to prevent duplicates should this be used
  4174. * directly later on */
  4175. roll_work(work);
  4176. cloned = true;
  4177. }
  4178. if (cloned) {
  4179. stage_work(work);
  4180. return work_clone;
  4181. }
  4182. free_work(work_clone);
  4183. return work;
  4184. }
  4185. static void get_work(struct work *work, struct thr_info *thr, const int thr_id)
  4186. {
  4187. struct timespec abstime = {0, 0};
  4188. struct work *work_heap;
  4189. struct timeval now;
  4190. struct pool *pool;
  4191. /* Tell the watchdog thread this thread is waiting on getwork and
  4192. * should not be restarted */
  4193. thread_reportout(thr);
  4194. if (opt_benchmark) {
  4195. get_benchmark_work(work);
  4196. goto out;
  4197. }
  4198. retry:
  4199. pool = current_pool();
  4200. if (reuse_work(work))
  4201. goto out;
  4202. if (!pool->lagging && !total_staged() && global_queued() >= mining_threads + opt_queue) {
  4203. struct cgpu_info *cgpu = thr->cgpu;
  4204. bool stalled = true;
  4205. int i;
  4206. /* Check to see if all the threads on the device that called
  4207. * get_work are waiting on work and only consider the pool
  4208. * lagging if true */
  4209. for (i = 0; i < cgpu->threads; i++) {
  4210. if (!cgpu->thr[i]->getwork) {
  4211. stalled = false;
  4212. break;
  4213. }
  4214. }
  4215. if (stalled && !pool_tset(pool, &pool->lagging)) {
  4216. applog(LOG_WARNING, "Pool %d not providing work fast enough", pool->pool_no);
  4217. pool->getfail_occasions++;
  4218. total_go++;
  4219. }
  4220. }
  4221. gettimeofday(&now, NULL);
  4222. abstime.tv_sec = now.tv_sec + 60;
  4223. applog(LOG_DEBUG, "Popping work from get queue to get work");
  4224. keepwaiting:
  4225. /* wait for 1st response, or get cached response */
  4226. work_heap = hash_pop(&abstime);
  4227. if (unlikely(!work_heap)) {
  4228. /* Attempt to switch pools if this one times out */
  4229. pool_died(pool);
  4230. if (pool == current_pool())
  4231. goto keepwaiting;
  4232. goto retry;
  4233. }
  4234. if (stale_work(work_heap, false)) {
  4235. discard_work(work_heap);
  4236. goto retry;
  4237. }
  4238. pool = work_heap->pool;
  4239. /* If we make it here we have succeeded in getting fresh work */
  4240. if (!work_heap->mined) {
  4241. /* Only clear the lagging flag if we are staging them at a
  4242. * rate faster then we're using them */
  4243. if (pool->lagging && total_staged())
  4244. pool_tclear(pool, &pool->lagging);
  4245. if (pool_tclear(pool, &pool->idle))
  4246. pool_resus(pool);
  4247. }
  4248. memcpy(work, work_heap, sizeof(struct work));
  4249. free(work_heap);
  4250. out:
  4251. work->thr_id = thr_id;
  4252. thread_reportin(thr);
  4253. work->mined = true;
  4254. }
  4255. bool submit_work_sync(struct thr_info *thr, const struct work *work_in)
  4256. {
  4257. struct workio_cmd *wc;
  4258. /* fill out work request message */
  4259. wc = calloc(1, sizeof(*wc));
  4260. if (unlikely(!wc)) {
  4261. applog(LOG_ERR, "Failed to calloc wc in submit_work_sync");
  4262. return false;
  4263. }
  4264. wc->work = make_work();
  4265. wc->cmd = WC_SUBMIT_WORK;
  4266. wc->thr = thr;
  4267. workcpy(wc->work, work_in);
  4268. wc->work->share_found_time = time(NULL);
  4269. applog(LOG_DEBUG, "Pushing submit work to work thread");
  4270. /* send solution to workio thread */
  4271. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  4272. applog(LOG_ERR, "Failed to tq_push work in submit_work_sync");
  4273. goto err_out;
  4274. }
  4275. return true;
  4276. err_out:
  4277. workio_cmd_free(wc);
  4278. return false;
  4279. }
  4280. bool hashtest(const struct work *work, bool checktarget)
  4281. {
  4282. uint32_t *data32 = (uint32_t *)(work->data);
  4283. unsigned char swap[128];
  4284. uint32_t *swap32 = (uint32_t *)swap;
  4285. unsigned char hash1[32];
  4286. unsigned char hash2[32];
  4287. uint32_t *hash2_32 = (uint32_t *)hash2;
  4288. swap32yes(swap32, data32, 80 / 4);
  4289. sha2(swap, 80, hash1, false);
  4290. sha2(hash1, 32, hash2, false);
  4291. if (!checktarget)
  4292. return hash2_32[7] == 0;
  4293. swap32yes(hash2_32, hash2_32, 32 / 4);
  4294. memcpy((void*)work->hash, hash2, 32);
  4295. return fulltest(work->hash, work->target);
  4296. }
  4297. bool test_nonce(struct work *work, uint32_t nonce, bool checktarget)
  4298. {
  4299. if (opt_scrypt) {
  4300. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  4301. *work_nonce = nonce;
  4302. return true;
  4303. }
  4304. work->data[64 + 12 + 0] = (nonce >> 0) & 0xff;
  4305. work->data[64 + 12 + 1] = (nonce >> 8) & 0xff;
  4306. work->data[64 + 12 + 2] = (nonce >> 16) & 0xff;
  4307. work->data[64 + 12 + 3] = (nonce >> 24) & 0xff;
  4308. return hashtest(work, checktarget);
  4309. }
  4310. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  4311. {
  4312. total_diff1++;
  4313. thr->cgpu->diff1++;
  4314. work->pool->diff1++;
  4315. /* Do one last check before attempting to submit the work */
  4316. /* Side effect: sets work->data for us */
  4317. if (!test_nonce(work, nonce, true)) {
  4318. applog(LOG_INFO, "Pool %d share below target", work->pool->pool_no);
  4319. return true;
  4320. }
  4321. return submit_work_sync(thr, work);
  4322. }
  4323. static inline bool abandon_work(struct work *work, struct timeval *wdiff, uint64_t hashes)
  4324. {
  4325. if (wdiff->tv_sec > opt_scantime ||
  4326. work->blk.nonce >= MAXTHREADS - hashes ||
  4327. hashes >= 0xfffffffe ||
  4328. stale_work(work, false))
  4329. return true;
  4330. return false;
  4331. }
  4332. static void mt_disable(struct thr_info *mythr, const int thr_id,
  4333. const struct device_api *api)
  4334. {
  4335. applog(LOG_WARNING, "Thread %d being disabled", thr_id);
  4336. mythr->rolling = mythr->cgpu->rolling = 0;
  4337. applog(LOG_DEBUG, "Popping wakeup ping in miner thread");
  4338. thread_reportout(mythr);
  4339. tq_pop(mythr->q, NULL); /* Ignore ping that's popped */
  4340. thread_reportin(mythr);
  4341. applog(LOG_WARNING, "Thread %d being re-enabled", thr_id);
  4342. if (api->thread_enable)
  4343. api->thread_enable(mythr);
  4344. }
  4345. void *miner_thread(void *userdata)
  4346. {
  4347. struct thr_info *mythr = userdata;
  4348. const int thr_id = mythr->id;
  4349. struct cgpu_info *cgpu = mythr->cgpu;
  4350. const struct device_api *api = cgpu->api;
  4351. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  4352. struct cgminer_stats *pool_stats;
  4353. struct timeval getwork_start;
  4354. {
  4355. char thrname[16];
  4356. sprintf(thrname, "bfg-miner-%s%d", api->name, cgpu->device_id);
  4357. rename_thr(thrname);
  4358. }
  4359. /* Try to cycle approximately 5 times before each log update */
  4360. const long cycle = opt_log_interval / 5 ? : 1;
  4361. struct timeval tv_start, tv_end, tv_workstart, tv_lastupdate;
  4362. struct timeval diff, sdiff, wdiff = {0, 0};
  4363. uint32_t max_nonce = api->can_limit_work ? api->can_limit_work(mythr) : 0xffffffff;
  4364. int64_t hashes_done = 0;
  4365. int64_t hashes;
  4366. struct work *work = make_work();
  4367. const bool primary = (!mythr->device_thread) || mythr->primary_thread;
  4368. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  4369. gettimeofday(&getwork_start, NULL);
  4370. if (api->thread_init && !api->thread_init(mythr)) {
  4371. cgpu->device_last_not_well = time(NULL);
  4372. cgpu->device_not_well_reason = REASON_THREAD_FAIL_INIT;
  4373. cgpu->thread_fail_init_count++;
  4374. goto out;
  4375. }
  4376. thread_reportout(mythr);
  4377. applog(LOG_DEBUG, "Popping ping in miner thread");
  4378. tq_pop(mythr->q, NULL); /* Wait for a ping to start */
  4379. sdiff.tv_sec = sdiff.tv_usec = 0;
  4380. gettimeofday(&tv_lastupdate, NULL);
  4381. while (1) {
  4382. mythr->work_restart = false;
  4383. if (api->free_work && likely(work->pool))
  4384. api->free_work(mythr, work);
  4385. get_work(work, mythr, thr_id);
  4386. cgpu->new_work = true;
  4387. gettimeofday(&tv_workstart, NULL);
  4388. work->blk.nonce = 0;
  4389. cgpu->max_hashes = 0;
  4390. if (api->prepare_work && !api->prepare_work(mythr, work)) {
  4391. applog(LOG_ERR, "work prepare failed, exiting "
  4392. "mining thread %d", thr_id);
  4393. break;
  4394. }
  4395. do {
  4396. gettimeofday(&tv_start, NULL);
  4397. timersub(&tv_start, &getwork_start, &getwork_start);
  4398. timeradd(&getwork_start,
  4399. &(dev_stats->getwork_wait),
  4400. &(dev_stats->getwork_wait));
  4401. if (timercmp(&getwork_start, &(dev_stats->getwork_wait_max), >)) {
  4402. dev_stats->getwork_wait_max.tv_sec = getwork_start.tv_sec;
  4403. dev_stats->getwork_wait_max.tv_usec = getwork_start.tv_usec;
  4404. }
  4405. if (timercmp(&getwork_start, &(dev_stats->getwork_wait_min), <)) {
  4406. dev_stats->getwork_wait_min.tv_sec = getwork_start.tv_sec;
  4407. dev_stats->getwork_wait_min.tv_usec = getwork_start.tv_usec;
  4408. }
  4409. dev_stats->getwork_calls++;
  4410. pool_stats = &(work->pool->cgminer_stats);
  4411. timeradd(&getwork_start,
  4412. &(pool_stats->getwork_wait),
  4413. &(pool_stats->getwork_wait));
  4414. if (timercmp(&getwork_start, &(pool_stats->getwork_wait_max), >)) {
  4415. pool_stats->getwork_wait_max.tv_sec = getwork_start.tv_sec;
  4416. pool_stats->getwork_wait_max.tv_usec = getwork_start.tv_usec;
  4417. }
  4418. if (timercmp(&getwork_start, &(pool_stats->getwork_wait_min), <)) {
  4419. pool_stats->getwork_wait_min.tv_sec = getwork_start.tv_sec;
  4420. pool_stats->getwork_wait_min.tv_usec = getwork_start.tv_usec;
  4421. }
  4422. pool_stats->getwork_calls++;
  4423. thread_reportin(mythr);
  4424. hashes = api->scanhash(mythr, work, work->blk.nonce + max_nonce);
  4425. thread_reportin(mythr);
  4426. gettimeofday(&getwork_start, NULL);
  4427. if (unlikely(hashes == -1)) {
  4428. applog(LOG_ERR, "%s %d failure, disabling!", api->name, cgpu->device_id);
  4429. cgpu->deven = DEV_DISABLED;
  4430. cgpu->device_last_not_well = time(NULL);
  4431. cgpu->device_not_well_reason = REASON_THREAD_ZERO_HASH;
  4432. cgpu->thread_zero_hash_count++;
  4433. mt_disable(mythr, thr_id, api);
  4434. }
  4435. hashes_done += hashes;
  4436. if (hashes > cgpu->max_hashes)
  4437. cgpu->max_hashes = hashes;
  4438. gettimeofday(&tv_end, NULL);
  4439. timersub(&tv_end, &tv_start, &diff);
  4440. sdiff.tv_sec += diff.tv_sec;
  4441. sdiff.tv_usec += diff.tv_usec;
  4442. if (sdiff.tv_usec > 1000000) {
  4443. ++sdiff.tv_sec;
  4444. sdiff.tv_usec -= 1000000;
  4445. }
  4446. timersub(&tv_end, &tv_workstart, &wdiff);
  4447. if (unlikely((long)sdiff.tv_sec < cycle)) {
  4448. int mult;
  4449. if (likely(!api->can_limit_work || max_nonce == 0xffffffff))
  4450. continue;
  4451. mult = 1000000 / ((sdiff.tv_usec + 0x400) / 0x400) + 0x10;
  4452. mult *= cycle;
  4453. if (max_nonce > (0xffffffff * 0x400) / mult)
  4454. max_nonce = 0xffffffff;
  4455. else
  4456. max_nonce = (max_nonce * mult) / 0x400;
  4457. } else if (unlikely(sdiff.tv_sec > cycle) && api->can_limit_work)
  4458. max_nonce = max_nonce * cycle / sdiff.tv_sec;
  4459. else if (unlikely(sdiff.tv_usec > 100000) && api->can_limit_work)
  4460. max_nonce = max_nonce * 0x400 / (((cycle * 1000000) + sdiff.tv_usec) / (cycle * 1000000 / 0x400));
  4461. timersub(&tv_end, &tv_lastupdate, &diff);
  4462. if (diff.tv_sec >= opt_log_interval) {
  4463. hashmeter(thr_id, &diff, hashes_done);
  4464. hashes_done = 0;
  4465. tv_lastupdate = tv_end;
  4466. }
  4467. if (unlikely(mythr->work_restart)) {
  4468. /* Apart from device_thread 0, we stagger the
  4469. * starting of every next thread to try and get
  4470. * all devices busy before worrying about
  4471. * getting work for their extra threads */
  4472. if (!primary) {
  4473. struct timespec rgtp;
  4474. rgtp.tv_sec = 0;
  4475. rgtp.tv_nsec = 250 * mythr->device_thread * 1000000;
  4476. nanosleep(&rgtp, NULL);
  4477. }
  4478. break;
  4479. }
  4480. if (unlikely(mythr->pause || cgpu->deven != DEV_ENABLED))
  4481. mt_disable(mythr, thr_id, api);
  4482. sdiff.tv_sec = sdiff.tv_usec = 0;
  4483. } while (!abandon_work(work, &wdiff, cgpu->max_hashes));
  4484. }
  4485. out:
  4486. if (api->thread_shutdown)
  4487. api->thread_shutdown(mythr);
  4488. thread_reportin(mythr);
  4489. applog(LOG_ERR, "Thread %d failure, exiting", thr_id);
  4490. tq_freeze(mythr->q);
  4491. return NULL;
  4492. }
  4493. enum {
  4494. STAT_SLEEP_INTERVAL = 1,
  4495. STAT_CTR_INTERVAL = 10000000,
  4496. FAILURE_INTERVAL = 30,
  4497. };
  4498. /* Stage another work item from the work returned in a longpoll */
  4499. static void convert_to_work(json_t *val, int rolltime, struct pool *pool, struct work *work)
  4500. {
  4501. bool rc;
  4502. rc = work_decode(json_object_get(val, "result"), work);
  4503. if (unlikely(!rc)) {
  4504. applog(LOG_ERR, "Could not convert longpoll data to work");
  4505. free_work(work);
  4506. return;
  4507. }
  4508. work->pool = pool;
  4509. work->rolltime = rolltime;
  4510. work->longpoll = true;
  4511. if (pool->enabled == POOL_REJECTING)
  4512. work->mandatory = true;
  4513. /* We'll be checking this work item twice, but we already know it's
  4514. * from a new block so explicitly force the new block detection now
  4515. * rather than waiting for it to hit the stage thread. This also
  4516. * allows testwork to know whether LP discovered the block or not. */
  4517. test_work_current(work);
  4518. /* Don't use backup LPs as work if we have failover-only enabled. Use
  4519. * the longpoll work from a pool that has been rejecting shares as a
  4520. * way to detect when the pool has recovered.
  4521. */
  4522. if (pool != current_pool() && opt_fail_only && pool->enabled != POOL_REJECTING) {
  4523. free_work(work);
  4524. return;
  4525. }
  4526. work = clone_work(work);
  4527. applog(LOG_DEBUG, "Pushing converted work to stage thread");
  4528. if (unlikely(!stage_work(work)))
  4529. free_work(work);
  4530. else
  4531. applog(LOG_DEBUG, "Converted longpoll data to work");
  4532. }
  4533. /* If we want longpoll, enable it for the chosen default pool, or, if
  4534. * the pool does not support longpoll, find the first one that does
  4535. * and use its longpoll support */
  4536. static struct pool *select_longpoll_pool(struct pool *cp)
  4537. {
  4538. int i;
  4539. if (cp->lp_url)
  4540. return cp;
  4541. for (i = 0; i < total_pools; i++) {
  4542. struct pool *pool = pools[i];
  4543. if (pool->lp_url)
  4544. return pool;
  4545. }
  4546. return NULL;
  4547. }
  4548. /* This will make the longpoll thread wait till it's the current pool, or it
  4549. * has been flagged as rejecting, before attempting to open any connections.
  4550. */
  4551. static void wait_lpcurrent(struct pool *pool)
  4552. {
  4553. if (pool->enabled == POOL_REJECTING || pool_strategy == POOL_LOADBALANCE || pool_strategy == POOL_BALANCE)
  4554. return;
  4555. while (pool != current_pool() && pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  4556. mutex_lock(&lp_lock);
  4557. pthread_cond_wait(&lp_cond, &lp_lock);
  4558. mutex_unlock(&lp_lock);
  4559. }
  4560. }
  4561. static curl_socket_t save_curl_socket(void *vpool, __maybe_unused curlsocktype purpose, struct curl_sockaddr *addr) {
  4562. struct pool *pool = vpool;
  4563. curl_socket_t sock = socket(addr->family, addr->socktype, addr->protocol);
  4564. pool->lp_socket = sock;
  4565. return sock;
  4566. }
  4567. static void *longpoll_thread(void *userdata)
  4568. {
  4569. struct pool *cp = (struct pool *)userdata;
  4570. /* This *pool is the source of the actual longpoll, not the pool we've
  4571. * tied it to */
  4572. struct pool *pool = NULL;
  4573. struct timeval start, end;
  4574. CURL *curl = NULL;
  4575. int failures = 0;
  4576. int rolltime;
  4577. rename_thr("bfg-longpoll");
  4578. curl = curl_easy_init();
  4579. if (unlikely(!curl)) {
  4580. applog(LOG_ERR, "CURL initialisation failed");
  4581. goto out;
  4582. }
  4583. retry_pool:
  4584. pool = select_longpoll_pool(cp);
  4585. if (!pool) {
  4586. applog(LOG_WARNING, "No suitable long-poll found for pool %s", cp->rpc_url);
  4587. while (!pool) {
  4588. sleep(60);
  4589. pool = select_longpoll_pool(cp);
  4590. }
  4591. }
  4592. /* Any longpoll from any pool is enough for this to be true */
  4593. have_longpoll = true;
  4594. wait_lpcurrent(cp);
  4595. if (cp == pool)
  4596. applog(LOG_WARNING, "Long-polling activated via %s (%s)", pool->lp_url, pool_protocol_name(pool->lp_proto));
  4597. else
  4598. applog(LOG_WARNING, "Long-polling activated for pool %s via %s (%s)", cp->rpc_url, pool->lp_url, pool_protocol_name(pool->lp_proto));
  4599. while (42) {
  4600. json_t *val, *soval;
  4601. struct work *work = make_work();
  4602. work->pool = pool;
  4603. const char *rpc_req;
  4604. rpc_req = prepare_rpc_req(work, pool->lp_proto, pool->lp_id);
  4605. if (!rpc_req)
  4606. goto lpfail;
  4607. wait_lpcurrent(cp);
  4608. gettimeofday(&start, NULL);
  4609. /* Longpoll connections can be persistent for a very long time
  4610. * and any number of issues could have come up in the meantime
  4611. * so always establish a fresh connection instead of relying on
  4612. * a persistent one. */
  4613. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  4614. curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, save_curl_socket);
  4615. curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, pool);
  4616. val = json_rpc_call(curl, pool->lp_url, pool->rpc_userpass, rpc_req,
  4617. false, true, &rolltime, pool, false);
  4618. pool->lp_socket = CURL_SOCKET_BAD;
  4619. if (likely(val)) {
  4620. soval = json_object_get(json_object_get(val, "result"), "submitold");
  4621. if (soval)
  4622. pool->submit_old = json_is_true(soval);
  4623. else
  4624. pool->submit_old = false;
  4625. convert_to_work(val, rolltime, pool, work);
  4626. failures = 0;
  4627. json_decref(val);
  4628. } else {
  4629. /* Some pools regularly drop the longpoll request so
  4630. * only see this as longpoll failure if it happens
  4631. * immediately and just restart it the rest of the
  4632. * time. */
  4633. gettimeofday(&end, NULL);
  4634. free_work(work);
  4635. if (end.tv_sec - start.tv_sec > 30)
  4636. continue;
  4637. if (failures == 1)
  4638. applog(LOG_WARNING, "longpoll failed for %s, retrying every 30s", pool->lp_url);
  4639. lpfail:
  4640. sleep(30);
  4641. }
  4642. if (pool != cp) {
  4643. pool = select_longpoll_pool(cp);
  4644. if (unlikely(!pool))
  4645. goto retry_pool;
  4646. }
  4647. if (unlikely(pool->removed))
  4648. break;
  4649. }
  4650. out:
  4651. if (curl)
  4652. curl_easy_cleanup(curl);
  4653. return NULL;
  4654. }
  4655. static void stop_longpoll(void)
  4656. {
  4657. int i;
  4658. want_longpoll = false;
  4659. for (i = 0; i < total_pools; ++i)
  4660. {
  4661. struct pool *pool = pools[i];
  4662. if (unlikely(!pool->lp_started))
  4663. continue;
  4664. pool->lp_started = false;
  4665. pthread_cancel(pool->longpoll_thread);
  4666. }
  4667. have_longpoll = false;
  4668. }
  4669. static void start_longpoll(void)
  4670. {
  4671. int i;
  4672. want_longpoll = true;
  4673. for (i = 0; i < total_pools; ++i)
  4674. {
  4675. struct pool *pool = pools[i];
  4676. if (unlikely(pool->removed || pool->lp_started || !pool->lp_url))
  4677. continue;
  4678. pool->lp_started = true;
  4679. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  4680. quit(1, "Failed to create pool longpoll thread");
  4681. }
  4682. }
  4683. void reinit_device(struct cgpu_info *cgpu)
  4684. {
  4685. if (cgpu->api->reinit_device)
  4686. cgpu->api->reinit_device(cgpu);
  4687. }
  4688. static struct timeval rotate_tv;
  4689. /* We reap curls if they are unused for over a minute */
  4690. static void reap_curl(struct pool *pool)
  4691. {
  4692. struct curl_ent *ent, *iter;
  4693. struct timeval now;
  4694. int reaped = 0;
  4695. gettimeofday(&now, NULL);
  4696. mutex_lock(&pool->pool_lock);
  4697. list_for_each_entry_safe(ent, iter, &pool->curlring, node) {
  4698. if (pool->curls < 2)
  4699. break;
  4700. if (now.tv_sec - ent->tv.tv_sec > 300) {
  4701. reaped++;
  4702. pool->curls--;
  4703. list_del(&ent->node);
  4704. curl_easy_cleanup(ent->curl);
  4705. free(ent);
  4706. }
  4707. }
  4708. mutex_unlock(&pool->pool_lock);
  4709. if (reaped)
  4710. applog(LOG_DEBUG, "Reaped %d curl%s from pool %d", reaped, reaped > 1 ? "s" : "", pool->pool_no);
  4711. }
  4712. static void *watchpool_thread(void __maybe_unused *userdata)
  4713. {
  4714. int intervals = 0;
  4715. rename_thr("bfg-watchpool");
  4716. while (42) {
  4717. struct timeval now;
  4718. int i;
  4719. if (++intervals > 20)
  4720. intervals = 0;
  4721. gettimeofday(&now, NULL);
  4722. for (i = 0; i < total_pools; i++) {
  4723. struct pool *pool = pools[i];
  4724. if (!opt_benchmark)
  4725. reap_curl(pool);
  4726. if (pool->enabled == POOL_DISABLED)
  4727. continue;
  4728. /* Test pool is idle once every minute */
  4729. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 60) {
  4730. gettimeofday(&pool->tv_idle, NULL);
  4731. if (pool_active(pool, true) && pool_tclear(pool, &pool->idle))
  4732. pool_resus(pool);
  4733. }
  4734. /* Get a rolling utility per pool over 10 mins */
  4735. if (intervals > 19) {
  4736. int shares = pool->diff1 - pool->last_shares;
  4737. pool->last_shares = pool->diff1;
  4738. pool->utility = (pool->utility + (double)shares * 0.63) / 1.63;
  4739. pool->shares = pool->utility;
  4740. }
  4741. }
  4742. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  4743. gettimeofday(&rotate_tv, NULL);
  4744. switch_pools(NULL);
  4745. }
  4746. sleep(30);
  4747. }
  4748. return NULL;
  4749. }
  4750. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  4751. * the screen at regular intervals, and restarts threads if they appear to have
  4752. * died. */
  4753. #define WATCHDOG_INTERVAL 3
  4754. #define WATCHDOG_SICK_TIME 60
  4755. #define WATCHDOG_DEAD_TIME 600
  4756. #define WATCHDOG_SICK_COUNT (WATCHDOG_SICK_TIME/WATCHDOG_INTERVAL)
  4757. #define WATCHDOG_DEAD_COUNT (WATCHDOG_DEAD_TIME/WATCHDOG_INTERVAL)
  4758. static void *watchdog_thread(void __maybe_unused *userdata)
  4759. {
  4760. const unsigned int interval = WATCHDOG_INTERVAL;
  4761. struct timeval zero_tv;
  4762. rename_thr("bfg-watchdog");
  4763. memset(&zero_tv, 0, sizeof(struct timeval));
  4764. gettimeofday(&rotate_tv, NULL);
  4765. while (1) {
  4766. int i;
  4767. struct timeval now;
  4768. sleep(interval);
  4769. discard_stale();
  4770. hashmeter(-1, &zero_tv, 0);
  4771. #ifdef HAVE_CURSES
  4772. if (curses_active_locked()) {
  4773. change_logwinsize();
  4774. curses_print_status();
  4775. for (i = 0; i < mining_threads; i++)
  4776. curses_print_devstatus(i);
  4777. touchwin(statuswin);
  4778. wrefresh(statuswin);
  4779. touchwin(logwin);
  4780. wrefresh(logwin);
  4781. unlock_curses();
  4782. }
  4783. #endif
  4784. gettimeofday(&now, NULL);
  4785. if (!sched_paused && !should_run()) {
  4786. applog(LOG_WARNING, "Pausing execution as per stop time %02d:%02d scheduled",
  4787. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  4788. if (!schedstart.enable) {
  4789. quit(0, "Terminating execution as planned");
  4790. break;
  4791. }
  4792. applog(LOG_WARNING, "Will restart execution as scheduled at %02d:%02d",
  4793. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  4794. sched_paused = true;
  4795. for (i = 0; i < mining_threads; i++) {
  4796. struct thr_info *thr;
  4797. thr = &thr_info[i];
  4798. thr->pause = true;
  4799. }
  4800. } else if (sched_paused && should_run()) {
  4801. applog(LOG_WARNING, "Restarting execution as per start time %02d:%02d scheduled",
  4802. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  4803. if (schedstop.enable)
  4804. applog(LOG_WARNING, "Will pause execution as scheduled at %02d:%02d",
  4805. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  4806. sched_paused = false;
  4807. for (i = 0; i < mining_threads; i++) {
  4808. struct thr_info *thr;
  4809. thr = &thr_info[i];
  4810. /* Don't touch disabled devices */
  4811. if (thr->cgpu->deven == DEV_DISABLED)
  4812. continue;
  4813. thr->pause = false;
  4814. tq_push(thr->q, &ping);
  4815. }
  4816. }
  4817. for (i = 0; i < total_devices; ++i) {
  4818. struct cgpu_info *cgpu = devices[i];
  4819. struct thr_info *thr = cgpu->thr[0];
  4820. enum dev_enable *denable;
  4821. char dev_str[8];
  4822. int gpu;
  4823. if (cgpu->api->get_stats)
  4824. cgpu->api->get_stats(cgpu);
  4825. gpu = cgpu->device_id;
  4826. denable = &cgpu->deven;
  4827. sprintf(dev_str, "%s%d", cgpu->api->name, gpu);
  4828. #ifdef HAVE_ADL
  4829. if (adl_active && cgpu->has_adl)
  4830. gpu_autotune(gpu, denable);
  4831. if (opt_debug && cgpu->has_adl) {
  4832. int engineclock = 0, memclock = 0, activity = 0, fanspeed = 0, fanpercent = 0, powertune = 0;
  4833. float temp = 0, vddc = 0;
  4834. if (gpu_stats(gpu, &temp, &engineclock, &memclock, &vddc, &activity, &fanspeed, &fanpercent, &powertune))
  4835. applog(LOG_DEBUG, "%.1f C F: %d%%(%dRPM) E: %dMHz M: %dMhz V: %.3fV A: %d%% P: %d%%",
  4836. temp, fanpercent, fanspeed, engineclock, memclock, vddc, activity, powertune);
  4837. }
  4838. #endif
  4839. /* Thread is disabled */
  4840. if (*denable == DEV_DISABLED)
  4841. continue;
  4842. if (thr->getwork) {
  4843. if (cgpu->status == LIFE_WELL && thr->getwork < now.tv_sec - opt_log_interval) {
  4844. int thrid;
  4845. bool cgpu_idle = true;
  4846. thr->rolling = 0;
  4847. for (thrid = 0; thrid < cgpu->threads; ++thrid)
  4848. if (!cgpu->thr[thrid]->getwork)
  4849. cgpu_idle = false;
  4850. if (cgpu_idle) {
  4851. cgpu->rolling = 0;
  4852. cgpu->status = LIFE_WAIT;
  4853. }
  4854. }
  4855. continue;
  4856. }
  4857. else if (cgpu->status == LIFE_WAIT)
  4858. cgpu->status = LIFE_WELL;
  4859. #ifdef WANT_CPUMINE
  4860. if (!strcmp(cgpu->api->dname, "cpu"))
  4861. continue;
  4862. #endif
  4863. if (cgpu->status != LIFE_WELL && (now.tv_sec - thr->last.tv_sec < WATCHDOG_SICK_TIME)) {
  4864. if (cgpu->status != LIFE_INIT)
  4865. applog(LOG_ERR, "%s: Recovered, declaring WELL!", dev_str);
  4866. cgpu->status = LIFE_WELL;
  4867. cgpu->device_last_well = time(NULL);
  4868. } else if (cgpu->status == LIFE_WELL && (now.tv_sec - thr->last.tv_sec > WATCHDOG_SICK_TIME)) {
  4869. thr->rolling = cgpu->rolling = 0;
  4870. cgpu->status = LIFE_SICK;
  4871. applog(LOG_ERR, "%s: Idle for more than 60 seconds, declaring SICK!", dev_str);
  4872. gettimeofday(&thr->sick, NULL);
  4873. cgpu->device_last_not_well = time(NULL);
  4874. cgpu->device_not_well_reason = REASON_DEV_SICK_IDLE_60;
  4875. cgpu->dev_sick_idle_60_count++;
  4876. #ifdef HAVE_ADL
  4877. if (adl_active && cgpu->has_adl && gpu_activity(gpu) > 50) {
  4878. applog(LOG_ERR, "GPU still showing activity suggesting a hard hang.");
  4879. applog(LOG_ERR, "Will not attempt to auto-restart it.");
  4880. } else
  4881. #endif
  4882. if (opt_restart) {
  4883. applog(LOG_ERR, "%s: Attempting to restart", dev_str);
  4884. reinit_device(cgpu);
  4885. }
  4886. } else if (cgpu->status == LIFE_SICK && (now.tv_sec - thr->last.tv_sec > WATCHDOG_DEAD_TIME)) {
  4887. cgpu->status = LIFE_DEAD;
  4888. applog(LOG_ERR, "%s: Not responded for more than 10 minutes, declaring DEAD!", dev_str);
  4889. gettimeofday(&thr->sick, NULL);
  4890. cgpu->device_last_not_well = time(NULL);
  4891. cgpu->device_not_well_reason = REASON_DEV_DEAD_IDLE_600;
  4892. cgpu->dev_dead_idle_600_count++;
  4893. } else if (now.tv_sec - thr->sick.tv_sec > 60 &&
  4894. (cgpu->status == LIFE_SICK || cgpu->status == LIFE_DEAD)) {
  4895. /* Attempt to restart a GPU that's sick or dead once every minute */
  4896. gettimeofday(&thr->sick, NULL);
  4897. #ifdef HAVE_ADL
  4898. if (adl_active && cgpu->has_adl && gpu_activity(gpu) > 50) {
  4899. /* Again do not attempt to restart a device that may have hard hung */
  4900. } else
  4901. #endif
  4902. if (opt_restart)
  4903. reinit_device(cgpu);
  4904. }
  4905. }
  4906. }
  4907. return NULL;
  4908. }
  4909. static void log_print_status(struct cgpu_info *cgpu)
  4910. {
  4911. char logline[255];
  4912. get_statline(logline, cgpu);
  4913. applog(LOG_WARNING, "%s", logline);
  4914. }
  4915. static void print_summary(void)
  4916. {
  4917. struct timeval diff;
  4918. int hours, mins, secs, i;
  4919. double utility, efficiency = 0.0, work_util;
  4920. timersub(&total_tv_end, &total_tv_start, &diff);
  4921. hours = diff.tv_sec / 3600;
  4922. mins = (diff.tv_sec % 3600) / 60;
  4923. secs = diff.tv_sec % 60;
  4924. utility = total_accepted / total_secs * 60;
  4925. efficiency = total_getworks ? total_accepted * 100.0 / total_getworks : 0.0;
  4926. work_util = total_diff1 / total_secs * 60;
  4927. applog(LOG_WARNING, "\nSummary of runtime statistics:\n");
  4928. applog(LOG_WARNING, "Started at %s", datestamp);
  4929. if (total_pools == 1)
  4930. applog(LOG_WARNING, "Pool: %s", pools[0]->rpc_url);
  4931. #ifdef WANT_CPUMINE
  4932. if (opt_n_threads)
  4933. applog(LOG_WARNING, "CPU hasher algorithm used: %s", algo_names[opt_algo]);
  4934. #endif
  4935. applog(LOG_WARNING, "Runtime: %d hrs : %d mins : %d secs", hours, mins, secs);
  4936. applog(LOG_WARNING, "Average hashrate: %.1f Megahash/s", total_mhashes_done / total_secs);
  4937. applog(LOG_WARNING, "Solved blocks: %d", found_blocks);
  4938. applog(LOG_WARNING, "Queued work requests: %d", total_getworks);
  4939. applog(LOG_WARNING, "Share submissions: %d", total_accepted + total_rejected);
  4940. applog(LOG_WARNING, "Accepted shares: %d", total_accepted);
  4941. applog(LOG_WARNING, "Rejected shares: %d", total_rejected);
  4942. if (total_accepted || total_rejected)
  4943. applog(LOG_WARNING, "Reject ratio: %.1f%%", (double)(total_rejected * 100) / (double)(total_accepted + total_rejected));
  4944. applog(LOG_WARNING, "Hardware errors: %d", hw_errors);
  4945. applog(LOG_WARNING, "Efficiency (accepted / queued): %.0f%%", efficiency);
  4946. applog(LOG_WARNING, "Utility (accepted shares / min): %.2f/min\n", utility);
  4947. applog(LOG_WARNING, "Discarded work due to new blocks: %d", total_discarded);
  4948. applog(LOG_WARNING, "Stale submissions discarded due to new blocks: %d", total_stale);
  4949. applog(LOG_WARNING, "Unable to get work from server occasions: %d", total_go);
  4950. applog(LOG_WARNING, "Work items generated locally: %d", local_work);
  4951. applog(LOG_WARNING, "Submitting work remotely delay occasions: %d", total_ro);
  4952. applog(LOG_WARNING, "New blocks detected on network: %d\n", new_blocks);
  4953. if (total_pools > 1) {
  4954. for (i = 0; i < total_pools; i++) {
  4955. struct pool *pool = pools[i];
  4956. applog(LOG_WARNING, "Pool: %s", pool->rpc_url);
  4957. if (pool->solved)
  4958. applog(LOG_WARNING, "SOLVED %d BLOCK%s!", pool->solved, pool->solved > 1 ? "S" : "");
  4959. applog(LOG_WARNING, " Queued work requests: %d", pool->getwork_requested);
  4960. applog(LOG_WARNING, " Share submissions: %d", pool->accepted + pool->rejected);
  4961. applog(LOG_WARNING, " Accepted shares: %d", pool->accepted);
  4962. applog(LOG_WARNING, " Rejected shares: %d", pool->rejected);
  4963. if (pool->accepted || pool->rejected)
  4964. applog(LOG_WARNING, " Reject ratio: %.1f%%", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  4965. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  4966. applog(LOG_WARNING, " Efficiency (accepted / queued): %.0f%%", efficiency);
  4967. applog(LOG_WARNING, " Discarded work due to new blocks: %d", pool->discarded_work);
  4968. applog(LOG_WARNING, " Stale submissions discarded due to new blocks: %d", pool->stale_shares);
  4969. applog(LOG_WARNING, " Unable to get work from server occasions: %d", pool->getfail_occasions);
  4970. applog(LOG_WARNING, " Submitting work remotely delay occasions: %d\n", pool->remotefail_occasions);
  4971. }
  4972. }
  4973. applog(LOG_WARNING, "Summary of per device statistics:\n");
  4974. for (i = 0; i < total_devices; ++i)
  4975. log_print_status(devices[i]);
  4976. if (opt_shares)
  4977. applog(LOG_WARNING, "Mined %d accepted shares of %d requested\n", total_accepted, opt_shares);
  4978. fflush(stdout);
  4979. fflush(stderr);
  4980. if (opt_shares > total_accepted)
  4981. applog(LOG_WARNING, "WARNING - Mined only %d shares of %d requested.", total_accepted, opt_shares);
  4982. }
  4983. static void clean_up(void)
  4984. {
  4985. #ifdef HAVE_OPENCL
  4986. clear_adl(nDevs);
  4987. opencl_dynamic_cleanup();
  4988. #endif
  4989. #ifdef HAVE_LIBUSB
  4990. libusb_exit(NULL);
  4991. #endif
  4992. gettimeofday(&total_tv_end, NULL);
  4993. #ifdef HAVE_CURSES
  4994. disable_curses();
  4995. #endif
  4996. if (!opt_realquiet && successful_connect)
  4997. print_summary();
  4998. if (opt_n_threads)
  4999. free(cpus);
  5000. curl_global_cleanup();
  5001. }
  5002. void quit(int status, const char *format, ...)
  5003. {
  5004. va_list ap;
  5005. clean_up();
  5006. if (format) {
  5007. va_start(ap, format);
  5008. vfprintf(stderr, format, ap);
  5009. va_end(ap);
  5010. }
  5011. fprintf(stderr, "\n");
  5012. fflush(stderr);
  5013. if (status) {
  5014. const char *ev = getenv("__BFGMINER_SEGFAULT_ERRQUIT");
  5015. if (unlikely(ev && ev[0] && ev[0] != '0')) {
  5016. const char **p = NULL;
  5017. // NOTE debugger can bypass with: p = &p
  5018. *p = format; // Segfault, hopefully dumping core
  5019. }
  5020. }
  5021. #if defined(unix)
  5022. if (forkpid > 0) {
  5023. kill(forkpid, SIGTERM);
  5024. forkpid = 0;
  5025. }
  5026. #endif
  5027. exit(status);
  5028. }
  5029. #ifdef HAVE_CURSES
  5030. char *curses_input(const char *query)
  5031. {
  5032. char *input;
  5033. echo();
  5034. input = malloc(255);
  5035. if (!input)
  5036. quit(1, "Failed to malloc input");
  5037. leaveok(logwin, false);
  5038. wlogprint("%s:\n", query);
  5039. wgetnstr(logwin, input, 255);
  5040. if (!strlen(input))
  5041. strcpy(input, "-1");
  5042. leaveok(logwin, true);
  5043. noecho();
  5044. return input;
  5045. }
  5046. #endif
  5047. void add_pool_details5(bool live, char *url, char *user, char *pass, char *proxy)
  5048. {
  5049. struct pool *pool;
  5050. pool = add_pool();
  5051. pool->rpc_url = url;
  5052. pool->rpc_user = user;
  5053. pool->rpc_pass = pass;
  5054. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  5055. if (!pool->rpc_userpass)
  5056. quit(1, "Failed to malloc userpass");
  5057. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  5058. pool->rpc_proxy = proxy;
  5059. /* Test the pool is not idle if we're live running, otherwise
  5060. * it will be tested separately */
  5061. enable_pool(pool);
  5062. if (live && !pool_active(pool, false))
  5063. pool->idle = true;
  5064. }
  5065. void add_pool_details(bool live, char *url, char *user, char *pass)
  5066. {
  5067. add_pool_details5(live, url, user, pass, NULL);
  5068. }
  5069. #ifdef HAVE_CURSES
  5070. static bool input_pool(bool live)
  5071. {
  5072. char *url = NULL, *user = NULL, *pass = NULL;
  5073. bool ret = false;
  5074. immedok(logwin, true);
  5075. wlogprint("Input server details.\n");
  5076. url = curses_input("URL");
  5077. if (!url)
  5078. goto out;
  5079. if (strncmp(url, "http://", 7) &&
  5080. strncmp(url, "https://", 8)) {
  5081. char *httpinput;
  5082. httpinput = malloc(255);
  5083. if (!httpinput)
  5084. quit(1, "Failed to malloc httpinput");
  5085. strcpy(httpinput, "http://");
  5086. strncat(httpinput, url, 248);
  5087. free(url);
  5088. url = httpinput;
  5089. }
  5090. user = curses_input("Username");
  5091. if (!user)
  5092. goto out;
  5093. pass = curses_input("Password");
  5094. if (!pass)
  5095. goto out;
  5096. add_pool_details(live, url, user, pass);
  5097. ret = true;
  5098. out:
  5099. immedok(logwin, false);
  5100. if (!ret) {
  5101. if (url)
  5102. free(url);
  5103. if (user)
  5104. free(user);
  5105. if (pass)
  5106. free(pass);
  5107. }
  5108. return ret;
  5109. }
  5110. #endif
  5111. #if defined(unix)
  5112. static void fork_monitor()
  5113. {
  5114. // Make a pipe: [readFD, writeFD]
  5115. int pfd[2];
  5116. int r = pipe(pfd);
  5117. if (r < 0) {
  5118. perror("pipe - failed to create pipe for --monitor");
  5119. exit(1);
  5120. }
  5121. // Make stderr write end of pipe
  5122. fflush(stderr);
  5123. r = dup2(pfd[1], 2);
  5124. if (r < 0) {
  5125. perror("dup2 - failed to alias stderr to write end of pipe for --monitor");
  5126. exit(1);
  5127. }
  5128. r = close(pfd[1]);
  5129. if (r < 0) {
  5130. perror("close - failed to close write end of pipe for --monitor");
  5131. exit(1);
  5132. }
  5133. // Don't allow a dying monitor to kill the main process
  5134. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  5135. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  5136. if (SIG_ERR == sr0 || SIG_ERR == sr1) {
  5137. perror("signal - failed to edit signal mask for --monitor");
  5138. exit(1);
  5139. }
  5140. // Fork a child process
  5141. forkpid = fork();
  5142. if (forkpid < 0) {
  5143. perror("fork - failed to fork child process for --monitor");
  5144. exit(1);
  5145. }
  5146. // Child: launch monitor command
  5147. if (0 == forkpid) {
  5148. // Make stdin read end of pipe
  5149. r = dup2(pfd[0], 0);
  5150. if (r < 0) {
  5151. perror("dup2 - in child, failed to alias read end of pipe to stdin for --monitor");
  5152. exit(1);
  5153. }
  5154. close(pfd[0]);
  5155. if (r < 0) {
  5156. perror("close - in child, failed to close read end of pipe for --monitor");
  5157. exit(1);
  5158. }
  5159. // Launch user specified command
  5160. execl("/bin/bash", "/bin/bash", "-c", opt_stderr_cmd, (char*)NULL);
  5161. perror("execl - in child failed to exec user specified command for --monitor");
  5162. exit(1);
  5163. }
  5164. // Parent: clean up unused fds and bail
  5165. r = close(pfd[0]);
  5166. if (r < 0) {
  5167. perror("close - failed to close read end of pipe for --monitor");
  5168. exit(1);
  5169. }
  5170. }
  5171. #endif // defined(unix)
  5172. #ifdef HAVE_CURSES
  5173. void enable_curses(void) {
  5174. int x,y;
  5175. lock_curses();
  5176. if (curses_active) {
  5177. unlock_curses();
  5178. return;
  5179. }
  5180. mainwin = initscr();
  5181. keypad(mainwin, true);
  5182. getmaxyx(mainwin, y, x);
  5183. statuswin = newwin(logstart, x, 0, 0);
  5184. leaveok(statuswin, true);
  5185. // For whatever reason, PDCurses crashes if the logwin is initialized to height y-logcursor
  5186. // We resize the window later anyway, so just start it off at 1 :)
  5187. logwin = newwin(1, 0, logcursor, 0);
  5188. idlok(logwin, true);
  5189. scrollok(logwin, true);
  5190. leaveok(logwin, true);
  5191. cbreak();
  5192. noecho();
  5193. curses_active = true;
  5194. statusy = logstart;
  5195. unlock_curses();
  5196. }
  5197. #endif
  5198. /* TODO: fix need a dummy CPU device_api even if no support for CPU mining */
  5199. #ifndef WANT_CPUMINE
  5200. struct device_api cpu_api;
  5201. struct device_api cpu_api = {
  5202. .name = "CPU",
  5203. };
  5204. #endif
  5205. #ifdef USE_BITFORCE
  5206. extern struct device_api bitforce_api;
  5207. #endif
  5208. #ifdef USE_ICARUS
  5209. extern struct device_api cairnsmore_api;
  5210. extern struct device_api icarus_api;
  5211. #endif
  5212. #ifdef USE_MODMINER
  5213. extern struct device_api modminer_api;
  5214. #endif
  5215. #ifdef USE_ZTEX
  5216. extern struct device_api ztex_api;
  5217. #endif
  5218. static int cgminer_id_count = 0;
  5219. void enable_device(struct cgpu_info *cgpu)
  5220. {
  5221. cgpu->deven = DEV_ENABLED;
  5222. devices[cgpu->cgminer_id = cgminer_id_count++] = cgpu;
  5223. mining_threads += cgpu->threads;
  5224. #ifdef HAVE_CURSES
  5225. adj_width(mining_threads, &dev_width);
  5226. #endif
  5227. #ifdef HAVE_OPENCL
  5228. if (cgpu->api == &opencl_api) {
  5229. gpu_threads += cgpu->threads;
  5230. }
  5231. #endif
  5232. }
  5233. struct _cgpu_devid_counter {
  5234. char name[4];
  5235. int lastid;
  5236. UT_hash_handle hh;
  5237. };
  5238. void renumber_cgpu(struct cgpu_info *cgpu)
  5239. {
  5240. static struct _cgpu_devid_counter *devids = NULL;
  5241. struct _cgpu_devid_counter *d;
  5242. HASH_FIND_STR(devids, cgpu->api->name, d);
  5243. if (d)
  5244. cgpu->device_id = ++d->lastid;
  5245. else {
  5246. d = malloc(sizeof(*d));
  5247. memcpy(d->name, cgpu->api->name, sizeof(d->name));
  5248. cgpu->device_id = d->lastid = 0;
  5249. HASH_ADD_STR(devids, name, d);
  5250. }
  5251. }
  5252. bool add_cgpu(struct cgpu_info*cgpu)
  5253. {
  5254. renumber_cgpu(cgpu);
  5255. devices = realloc(devices, sizeof(struct cgpu_info *) * (total_devices + 2));
  5256. devices[total_devices++] = cgpu;
  5257. return true;
  5258. }
  5259. static bool my_blkmaker_sha256_callback(void *digest, const void *buffer, size_t length)
  5260. {
  5261. sha2(buffer, length, digest, false);
  5262. return true;
  5263. }
  5264. int main(int argc, char *argv[])
  5265. {
  5266. struct block *block, *tmpblock;
  5267. struct work *work, *tmpwork;
  5268. bool pools_active = false;
  5269. struct sigaction handler;
  5270. struct thr_info *thr;
  5271. char *s;
  5272. unsigned int k;
  5273. int i, j;
  5274. blkmk_sha256_impl = my_blkmaker_sha256_callback;
  5275. /* This dangerous functions tramples random dynamically allocated
  5276. * variables so do it before anything at all */
  5277. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  5278. quit(1, "Failed to curl_global_init");
  5279. initial_args = malloc(sizeof(char *) * (argc + 1));
  5280. for (i = 0; i < argc; i++)
  5281. initial_args[i] = strdup(argv[i]);
  5282. initial_args[argc] = NULL;
  5283. #ifdef HAVE_LIBUSB
  5284. libusb_init(NULL);
  5285. #endif
  5286. mutex_init(&hash_lock);
  5287. mutex_init(&qd_lock);
  5288. mutex_init(&console_lock);
  5289. mutex_init(&control_lock);
  5290. mutex_init(&sharelog_lock);
  5291. mutex_init(&ch_lock);
  5292. rwlock_init(&blk_lock);
  5293. rwlock_init(&netacc_lock);
  5294. mutex_init(&lp_lock);
  5295. if (unlikely(pthread_cond_init(&lp_cond, NULL)))
  5296. quit(1, "Failed to pthread_cond_init lp_cond");
  5297. mutex_init(&restart_lock);
  5298. if (unlikely(pthread_cond_init(&restart_cond, NULL)))
  5299. quit(1, "Failed to pthread_cond_init restart_cond");
  5300. sprintf(packagename, "%s %s", PACKAGE, VERSION);
  5301. #ifdef WANT_CPUMINE
  5302. init_max_name_len();
  5303. #endif
  5304. handler.sa_handler = &sighandler;
  5305. handler.sa_flags = 0;
  5306. sigemptyset(&handler.sa_mask);
  5307. sigaction(SIGTERM, &handler, &termhandler);
  5308. sigaction(SIGINT, &handler, &inthandler);
  5309. opt_kernel_path = alloca(PATH_MAX);
  5310. strcpy(opt_kernel_path, CGMINER_PREFIX);
  5311. cgminer_path = alloca(PATH_MAX);
  5312. s = strdup(argv[0]);
  5313. strcpy(cgminer_path, dirname(s));
  5314. free(s);
  5315. strcat(cgminer_path, "/");
  5316. #ifdef WANT_CPUMINE
  5317. // Hack to make cgminer silent when called recursively on WIN32
  5318. int skip_to_bench = 0;
  5319. #if defined(WIN32)
  5320. char buf[32];
  5321. if (GetEnvironmentVariable("BFGMINER_BENCH_ALGO", buf, 16))
  5322. skip_to_bench = 1;
  5323. if (GetEnvironmentVariable("CGMINER_BENCH_ALGO", buf, 16))
  5324. skip_to_bench = 1;
  5325. #endif // defined(WIN32)
  5326. #endif
  5327. devcursor = 8;
  5328. logstart = devcursor + 1;
  5329. logcursor = logstart + 1;
  5330. block = calloc(sizeof(struct block), 1);
  5331. if (unlikely(!block))
  5332. quit (1, "main OOM");
  5333. for (i = 0; i < 36; i++)
  5334. strcat(block->hash, "0");
  5335. HASH_ADD_STR(blocks, hash, block);
  5336. strcpy(current_block, block->hash);
  5337. INIT_LIST_HEAD(&scan_devices);
  5338. mutex_init(&submitting_lock);
  5339. INIT_LIST_HEAD(&submit_waiting);
  5340. #ifdef HAVE_OPENCL
  5341. memset(gpus, 0, sizeof(gpus));
  5342. for (i = 0; i < MAX_GPUDEVICES; i++)
  5343. gpus[i].dynamic = true;
  5344. #endif
  5345. schedstart.tm.tm_sec = 1;
  5346. schedstop .tm.tm_sec = 1;
  5347. /* parse command line */
  5348. opt_register_table(opt_config_table,
  5349. "Options for both config file and command line");
  5350. opt_register_table(opt_cmdline_table,
  5351. "Options for command line only");
  5352. opt_parse(&argc, argv, applog_and_exit);
  5353. if (argc != 1)
  5354. quit(1, "Unexpected extra commandline arguments");
  5355. if (!config_loaded)
  5356. load_default_config();
  5357. if (opt_benchmark) {
  5358. struct pool *pool;
  5359. want_longpoll = false;
  5360. pool = add_pool();
  5361. pool->rpc_url = malloc(255);
  5362. strcpy(pool->rpc_url, "Benchmark");
  5363. pool->rpc_user = pool->rpc_url;
  5364. pool->rpc_pass = pool->rpc_url;
  5365. enable_pool(pool);
  5366. pool->idle = false;
  5367. successful_connect = true;
  5368. }
  5369. #ifdef HAVE_CURSES
  5370. if (opt_realquiet || devices_enabled == -1)
  5371. use_curses = false;
  5372. if (use_curses)
  5373. enable_curses();
  5374. #endif
  5375. applog(LOG_WARNING, "Started %s", packagename);
  5376. if (cnfbuf) {
  5377. applog(LOG_NOTICE, "Loaded configuration file %s", cnfbuf);
  5378. switch (fileconf_load) {
  5379. case 0:
  5380. applog(LOG_WARNING, "Fatal JSON error in configuration file.");
  5381. applog(LOG_WARNING, "Configuration file could not be used.");
  5382. break;
  5383. case -1:
  5384. applog(LOG_WARNING, "Error in configuration file, partially loaded.");
  5385. if (use_curses)
  5386. applog(LOG_WARNING, "Start BFGMiner with -T to see what failed to load.");
  5387. break;
  5388. default:
  5389. break;
  5390. }
  5391. free(cnfbuf);
  5392. cnfbuf = NULL;
  5393. }
  5394. strcat(opt_kernel_path, "/");
  5395. if (want_per_device_stats)
  5396. opt_log_output = true;
  5397. #ifdef WANT_CPUMINE
  5398. #ifdef USE_SCRYPT
  5399. if (opt_scrypt)
  5400. set_scrypt_algo(&opt_algo);
  5401. else
  5402. #endif
  5403. if (0 <= opt_bench_algo) {
  5404. double rate = bench_algo_stage3(opt_bench_algo);
  5405. if (!skip_to_bench)
  5406. printf("%.5f (%s)\n", rate, algo_names[opt_bench_algo]);
  5407. else {
  5408. // Write result to shared memory for parent
  5409. #if defined(WIN32)
  5410. char unique_name[64];
  5411. if (GetEnvironmentVariable("BFGMINER_SHARED_MEM", unique_name, 32) || GetEnvironmentVariable("CGMINER_SHARED_MEM", unique_name, 32)) {
  5412. HANDLE map_handle = CreateFileMapping(
  5413. INVALID_HANDLE_VALUE, // use paging file
  5414. NULL, // default security attributes
  5415. PAGE_READWRITE, // read/write access
  5416. 0, // size: high 32-bits
  5417. 4096, // size: low 32-bits
  5418. unique_name // name of map object
  5419. );
  5420. if (NULL != map_handle) {
  5421. void *shared_mem = MapViewOfFile(
  5422. map_handle, // object to map view of
  5423. FILE_MAP_WRITE, // read/write access
  5424. 0, // high offset: map from
  5425. 0, // low offset: beginning
  5426. 0 // default: map entire file
  5427. );
  5428. if (NULL != shared_mem)
  5429. CopyMemory(shared_mem, &rate, sizeof(rate));
  5430. (void)UnmapViewOfFile(shared_mem);
  5431. }
  5432. (void)CloseHandle(map_handle);
  5433. }
  5434. #endif
  5435. }
  5436. exit(0);
  5437. }
  5438. #endif
  5439. #ifdef HAVE_OPENCL
  5440. if (!opt_nogpu)
  5441. opencl_api.api_detect();
  5442. gpu_threads = 0;
  5443. #endif
  5444. #ifdef USE_ICARUS
  5445. if (!opt_scrypt)
  5446. {
  5447. cairnsmore_api.api_detect();
  5448. icarus_api.api_detect();
  5449. }
  5450. #endif
  5451. #ifdef USE_BITFORCE
  5452. if (!opt_scrypt)
  5453. bitforce_api.api_detect();
  5454. #endif
  5455. #ifdef USE_MODMINER
  5456. if (!opt_scrypt)
  5457. modminer_api.api_detect();
  5458. #endif
  5459. #ifdef USE_ZTEX
  5460. if (!opt_scrypt)
  5461. ztex_api.api_detect();
  5462. #endif
  5463. #ifdef WANT_CPUMINE
  5464. cpu_api.api_detect();
  5465. #endif
  5466. for (i = 0; i < total_devices; ++i)
  5467. if (!devices[i]->devtype)
  5468. devices[i]->devtype = "PGA";
  5469. if (devices_enabled == -1) {
  5470. applog(LOG_ERR, "Devices detected:");
  5471. for (i = 0; i < total_devices; ++i) {
  5472. struct cgpu_info *cgpu = devices[i];
  5473. if (cgpu->name)
  5474. applog(LOG_ERR, " %2d. %s %d: %s (driver: %s)", i, cgpu->api->name, cgpu->device_id, cgpu->name, cgpu->api->dname);
  5475. else
  5476. applog(LOG_ERR, " %2d. %s %d (driver: %s)", i, cgpu->api->name, cgpu->device_id, cgpu->api->dname);
  5477. }
  5478. quit(0, "%d devices listed", total_devices);
  5479. }
  5480. mining_threads = 0;
  5481. if (devices_enabled) {
  5482. for (i = 0; i < (int)(sizeof(devices_enabled) * 8) - 1; ++i) {
  5483. if (devices_enabled & (1 << i)) {
  5484. if (i >= total_devices)
  5485. quit (1, "Command line options set a device that doesn't exist");
  5486. enable_device(devices[i]);
  5487. } else if (i < total_devices) {
  5488. if (opt_removedisabled) {
  5489. if (devices[i]->api == &cpu_api)
  5490. --opt_n_threads;
  5491. } else {
  5492. enable_device(devices[i]);
  5493. }
  5494. devices[i]->deven = DEV_DISABLED;
  5495. }
  5496. }
  5497. total_devices = cgminer_id_count;
  5498. } else {
  5499. for (i = 0; i < total_devices; ++i)
  5500. enable_device(devices[i]);
  5501. }
  5502. if (!total_devices)
  5503. quit(1, "All devices disabled, cannot mine!");
  5504. load_temp_cutoffs();
  5505. for (i = 0; i < total_devices; ++i)
  5506. devices[i]->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  5507. logstart += total_devices;
  5508. logcursor = logstart + 1;
  5509. #ifdef HAVE_CURSES
  5510. check_winsizes();
  5511. #endif
  5512. if (!total_pools) {
  5513. applog(LOG_WARNING, "Need to specify at least one pool server.");
  5514. #ifdef HAVE_CURSES
  5515. if (!use_curses || !input_pool(false))
  5516. #endif
  5517. quit(1, "Pool setup failed");
  5518. }
  5519. for (i = 0; i < total_pools; i++) {
  5520. struct pool *pool = pools[i];
  5521. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  5522. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  5523. if (!pool->rpc_userpass) {
  5524. if (!pool->rpc_user || !pool->rpc_pass)
  5525. quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  5526. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  5527. if (!pool->rpc_userpass)
  5528. quit(1, "Failed to malloc userpass");
  5529. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  5530. } else {
  5531. pool->rpc_user = malloc(strlen(pool->rpc_userpass) + 1);
  5532. if (!pool->rpc_user)
  5533. quit(1, "Failed to malloc user");
  5534. strcpy(pool->rpc_user, pool->rpc_userpass);
  5535. pool->rpc_user = strtok(pool->rpc_user, ":");
  5536. if (!pool->rpc_user)
  5537. quit(1, "Failed to find colon delimiter in userpass");
  5538. }
  5539. }
  5540. /* Set the currentpool to pool 0 */
  5541. currentpool = pools[0];
  5542. #ifdef HAVE_SYSLOG_H
  5543. if (use_syslog)
  5544. openlog(PACKAGE, LOG_PID, LOG_USER);
  5545. #endif
  5546. #if defined(unix)
  5547. if (opt_stderr_cmd)
  5548. fork_monitor();
  5549. #endif // defined(unix)
  5550. total_threads = mining_threads + 7;
  5551. thr_info = calloc(total_threads, sizeof(*thr));
  5552. if (!thr_info)
  5553. quit(1, "Failed to calloc thr_info");
  5554. /* init workio thread info */
  5555. work_thr_id = mining_threads;
  5556. thr = &thr_info[work_thr_id];
  5557. thr->id = work_thr_id;
  5558. thr->q = tq_new();
  5559. if (!thr->q)
  5560. quit(1, "Failed to tq_new");
  5561. /* start work I/O thread */
  5562. if (thr_info_create(thr, NULL, workio_thread, thr))
  5563. quit(1, "workio thread create failed");
  5564. stage_thr_id = mining_threads + 1;
  5565. thr = &thr_info[stage_thr_id];
  5566. thr->q = tq_new();
  5567. if (!thr->q)
  5568. quit(1, "Failed to tq_new");
  5569. /* start stage thread */
  5570. if (thr_info_create(thr, NULL, stage_thread, thr))
  5571. quit(1, "stage thread create failed");
  5572. pthread_detach(thr->pth);
  5573. /* Create a unique get work queue */
  5574. getq = tq_new();
  5575. if (!getq)
  5576. quit(1, "Failed to create getq");
  5577. /* We use the getq mutex as the staged lock */
  5578. stgd_lock = &getq->mutex;
  5579. if (opt_benchmark)
  5580. goto begin_bench;
  5581. for (i = 0; i < total_pools; i++) {
  5582. struct pool *pool = pools[i];
  5583. enable_pool(pool);
  5584. pool->idle = true;
  5585. }
  5586. applog(LOG_NOTICE, "Probing for an alive pool");
  5587. do {
  5588. /* Look for at least one active pool before starting */
  5589. for (i = 0; i < total_pools; i++) {
  5590. struct pool *pool = pools[i];
  5591. if (pool_active(pool, false)) {
  5592. if (!currentpool)
  5593. currentpool = pool;
  5594. applog(LOG_INFO, "Pool %d %s active", pool->pool_no, pool->rpc_url);
  5595. pools_active = true;
  5596. break;
  5597. } else {
  5598. if (pool == currentpool)
  5599. currentpool = NULL;
  5600. applog(LOG_WARNING, "Unable to get work from pool %d %s", pool->pool_no, pool->rpc_url);
  5601. }
  5602. }
  5603. if (!pools_active) {
  5604. applog(LOG_ERR, "No servers were found that could be used to get work from.");
  5605. applog(LOG_ERR, "Please check the details from the list below of the servers you have input");
  5606. applog(LOG_ERR, "Most likely you have input the wrong URL, forgotten to add a port, or have not set up workers");
  5607. for (i = 0; i < total_pools; i++) {
  5608. struct pool *pool;
  5609. pool = pools[i];
  5610. applog(LOG_WARNING, "Pool: %d URL: %s User: %s Password: %s",
  5611. i, pool->rpc_url, pool->rpc_user, pool->rpc_pass);
  5612. }
  5613. #ifdef HAVE_CURSES
  5614. if (use_curses) {
  5615. halfdelay(150);
  5616. applog(LOG_ERR, "Press any key to exit, or BFGMiner will try again in 15s.");
  5617. if (getch() != ERR)
  5618. quit(0, "No servers could be used! Exiting.");
  5619. nocbreak();
  5620. } else
  5621. #endif
  5622. quit(0, "No servers could be used! Exiting.");
  5623. }
  5624. } while (!pools_active);
  5625. #ifdef USE_SCRYPT
  5626. if (detect_algo == 1 && !opt_scrypt) {
  5627. applog(LOG_NOTICE, "Detected scrypt algorithm");
  5628. opt_scrypt = true;
  5629. }
  5630. #endif
  5631. detect_algo = 0;
  5632. begin_bench:
  5633. total_mhashes_done = 0;
  5634. for (i = 0; i < total_devices; i++) {
  5635. struct cgpu_info *cgpu = devices[i];
  5636. cgpu->rolling = cgpu->total_mhashes = 0;
  5637. }
  5638. gettimeofday(&total_tv_start, NULL);
  5639. gettimeofday(&total_tv_end, NULL);
  5640. miner_started = total_tv_start;
  5641. if (schedstart.tm.tm_sec)
  5642. schedstart.tm = *localtime(&miner_started.tv_sec);
  5643. if (schedstop.tm.tm_sec)
  5644. schedstop .tm = *localtime(&miner_started.tv_sec);
  5645. get_datestamp(datestamp, &total_tv_start);
  5646. // Start threads
  5647. k = 0;
  5648. for (i = 0; i < total_devices; ++i) {
  5649. struct cgpu_info *cgpu = devices[i];
  5650. cgpu->thr = calloc(cgpu->threads+1, sizeof(*cgpu->thr));
  5651. cgpu->thr[cgpu->threads] = NULL;
  5652. cgpu->status = LIFE_INIT;
  5653. // Setup thread structs before starting any of the threads, in case they try to interact
  5654. for (j = 0; j < cgpu->threads; ++j, ++k) {
  5655. thr = &thr_info[k];
  5656. thr->id = k;
  5657. thr->cgpu = cgpu;
  5658. thr->device_thread = j;
  5659. thr->work_restart_fd = thr->_work_restart_fd_w = -1;
  5660. thr->q = tq_new();
  5661. if (!thr->q)
  5662. quit(1, "tq_new failed in starting %s%d mining thread (#%d)", cgpu->api->name, cgpu->device_id, i);
  5663. /* Enable threads for devices set not to mine but disable
  5664. * their queue in case we wish to enable them later */
  5665. if (cgpu->deven != DEV_DISABLED) {
  5666. applog(LOG_DEBUG, "Pushing ping to thread %d", thr->id);
  5667. tq_push(thr->q, &ping);
  5668. }
  5669. cgpu->thr[j] = thr;
  5670. }
  5671. for (j = 0; j < cgpu->threads; ++j) {
  5672. thr = cgpu->thr[j];
  5673. if (cgpu->api->thread_prepare && !cgpu->api->thread_prepare(thr))
  5674. continue;
  5675. if (!thr->work_restart_fd)
  5676. {
  5677. #if defined(unix)
  5678. int pipefd[2];
  5679. if (!pipe(pipefd))
  5680. {
  5681. thr->work_restart_fd = pipefd[0];
  5682. thr->_work_restart_fd_w = pipefd[1];
  5683. }
  5684. else
  5685. #endif
  5686. thr->work_restart_fd = -1;
  5687. }
  5688. thread_reportout(thr);
  5689. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  5690. quit(1, "thread %d create failed", thr->id);
  5691. }
  5692. }
  5693. #ifdef HAVE_OPENCL
  5694. applog(LOG_INFO, "%d gpu miner threads started", gpu_threads);
  5695. for (i = 0; i < nDevs; i++)
  5696. pause_dynamic_threads(i);
  5697. #endif
  5698. #ifdef WANT_CPUMINE
  5699. applog(LOG_INFO, "%d cpu miner threads started, "
  5700. "using SHA256 '%s' algorithm.",
  5701. opt_n_threads,
  5702. algo_names[opt_algo]);
  5703. #endif
  5704. gettimeofday(&total_tv_start, NULL);
  5705. gettimeofday(&total_tv_end, NULL);
  5706. watchpool_thr_id = mining_threads + 2;
  5707. thr = &thr_info[watchpool_thr_id];
  5708. /* start watchpool thread */
  5709. if (thr_info_create(thr, NULL, watchpool_thread, NULL))
  5710. quit(1, "watchpool thread create failed");
  5711. pthread_detach(thr->pth);
  5712. watchdog_thr_id = mining_threads + 3;
  5713. thr = &thr_info[watchdog_thr_id];
  5714. /* start watchdog thread */
  5715. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  5716. quit(1, "watchdog thread create failed");
  5717. pthread_detach(thr->pth);
  5718. #ifdef HAVE_OPENCL
  5719. /* Create reinit gpu thread */
  5720. gpur_thr_id = mining_threads + 4;
  5721. thr = &thr_info[gpur_thr_id];
  5722. thr->q = tq_new();
  5723. if (!thr->q)
  5724. quit(1, "tq_new failed for gpur_thr_id");
  5725. if (thr_info_create(thr, NULL, reinit_gpu, thr))
  5726. quit(1, "reinit_gpu thread create failed");
  5727. #endif
  5728. /* Create API socket thread */
  5729. api_thr_id = mining_threads + 5;
  5730. thr = &thr_info[api_thr_id];
  5731. if (thr_info_create(thr, NULL, api_thread, thr))
  5732. quit(1, "API thread create failed");
  5733. #ifdef HAVE_CURSES
  5734. /* Create curses input thread for keyboard input. Create this last so
  5735. * that we know all threads are created since this can call kill_work
  5736. * to try and shut down ll previous threads. */
  5737. input_thr_id = mining_threads + 6;
  5738. thr = &thr_info[input_thr_id];
  5739. if (thr_info_create(thr, NULL, input_thread, thr))
  5740. quit(1, "input thread create failed");
  5741. pthread_detach(thr->pth);
  5742. #endif
  5743. for (i = 0; i < mining_threads + opt_queue; i++)
  5744. queue_request();
  5745. /* main loop - simply wait for workio thread to exit. This is not the
  5746. * normal exit path and only occurs should the workio_thread die
  5747. * unexpectedly */
  5748. pthread_join(thr_info[work_thr_id].pth, NULL);
  5749. applog(LOG_INFO, "workio thread dead, exiting.");
  5750. clean_up();
  5751. /* Not really necessary, but let's clean this up too anyway */
  5752. HASH_ITER(hh, staged_work, work, tmpwork) {
  5753. HASH_DEL(staged_work, work);
  5754. free_work(work);
  5755. }
  5756. HASH_ITER(hh, blocks, block, tmpblock) {
  5757. HASH_DEL(blocks, block);
  5758. free(block);
  5759. }
  5760. #if defined(unix)
  5761. if (forkpid > 0) {
  5762. kill(forkpid, SIGTERM);
  5763. forkpid = 0;
  5764. }
  5765. #endif
  5766. return 0;
  5767. }