cgminer.c 166 KB

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