cgminer.c 202 KB

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