cgminer.c 165 KB

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