main.c 161 KB

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