main.c 162 KB

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