main.c 163 KB

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