miner.c 210 KB

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