miner.c 169 KB

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