cgminer.c 164 KB

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