miner.c 229 KB

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