main.c 160 KB

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