miner.c 170 KB

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