cgminer.c 199 KB

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