cgminer.c 199 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706
  1. /*
  2. * Copyright 2011-2013 Con Kolivas
  3. * Copyright 2011-2012 Luke Dashjr
  4. * Copyright 2010 Jeff Garzik
  5. *
  6. * This program is free software; you can redistribute it and/or modify it
  7. * under the terms of the GNU General Public License as published by the Free
  8. * Software Foundation; either version 3 of the License, or (at your option)
  9. * any later version. See COPYING for more details.
  10. */
  11. #include "config.h"
  12. #ifdef HAVE_CURSES
  13. #include <curses.h>
  14. #endif
  15. #include <stdio.h>
  16. #include <stdlib.h>
  17. #include <string.h>
  18. #include <stdbool.h>
  19. #include <stdint.h>
  20. #include <unistd.h>
  21. #include <sys/time.h>
  22. #include <time.h>
  23. #include <math.h>
  24. #include <stdarg.h>
  25. #include <assert.h>
  26. #include <signal.h>
  27. #include <sys/stat.h>
  28. #include <sys/types.h>
  29. #ifndef WIN32
  30. #include <sys/resource.h>
  31. #endif
  32. #include <ccan/opt/opt.h>
  33. #include <jansson.h>
  34. #include <curl/curl.h>
  35. #include <libgen.h>
  36. #include <sha2.h>
  37. #include "compat.h"
  38. #include "miner.h"
  39. #include "findnonce.h"
  40. #include "adl.h"
  41. #include "driver-cpu.h"
  42. #include "driver-opencl.h"
  43. #include "bench_block.h"
  44. #include "scrypt.h"
  45. #if defined(unix)
  46. #include <errno.h>
  47. #include <fcntl.h>
  48. #include <sys/wait.h>
  49. #endif
  50. #if defined(USE_BITFORCE) || defined(USE_ICARUS) || defined(USE_MODMINER)
  51. # define USE_FPGA
  52. #if defined(USE_ICARUS)
  53. # define USE_FPGA_SERIAL
  54. #endif
  55. #elif defined(USE_ZTEX)
  56. # define USE_FPGA
  57. #endif
  58. struct strategies strategies[] = {
  59. { "Failover" },
  60. { "Round Robin" },
  61. { "Rotate" },
  62. { "Load Balance" },
  63. { "Balance" },
  64. };
  65. static char packagename[256];
  66. bool opt_protocol;
  67. static bool opt_benchmark;
  68. bool have_longpoll;
  69. bool want_per_device_stats;
  70. bool use_syslog;
  71. bool opt_quiet;
  72. bool opt_realquiet;
  73. bool opt_loginput;
  74. bool opt_compact;
  75. const int opt_cutofftemp = 95;
  76. int opt_log_interval = 5;
  77. int opt_queue = 1;
  78. int opt_scantime = 60;
  79. int opt_expiry = 120;
  80. int opt_bench_algo = -1;
  81. static const bool opt_time = true;
  82. unsigned long long global_hashrate;
  83. #if defined(HAVE_OPENCL) || defined(USE_USBUTILS)
  84. int nDevs;
  85. #endif
  86. #ifdef HAVE_OPENCL
  87. int opt_dynamic_interval = 7;
  88. int opt_g_threads = -1;
  89. int gpu_threads;
  90. #ifdef USE_SCRYPT
  91. bool opt_scrypt;
  92. #endif
  93. #endif
  94. bool opt_restart = true;
  95. static bool opt_nogpu;
  96. struct list_head scan_devices;
  97. static signed int devices_enabled;
  98. static bool opt_removedisabled;
  99. int total_devices;
  100. struct cgpu_info **devices;
  101. bool have_opencl;
  102. int opt_n_threads = -1;
  103. int mining_threads;
  104. int num_processors;
  105. #ifdef HAVE_CURSES
  106. bool use_curses = true;
  107. #else
  108. bool use_curses;
  109. #endif
  110. static bool opt_submit_stale = true;
  111. static int opt_shares;
  112. bool opt_fail_only;
  113. static bool opt_fix_protocol;
  114. bool opt_autofan;
  115. bool opt_autoengine;
  116. bool opt_noadl;
  117. char *opt_api_allow = NULL;
  118. char *opt_api_groups;
  119. char *opt_api_description = PACKAGE_STRING;
  120. int opt_api_port = 4028;
  121. bool opt_api_listen;
  122. bool opt_api_network;
  123. bool opt_delaynet;
  124. bool opt_disable_pool;
  125. char *opt_icarus_options = NULL;
  126. char *opt_icarus_timing = NULL;
  127. bool opt_worktime;
  128. #ifdef USE_USBUTILS
  129. char *opt_usb_select = NULL;
  130. int opt_usbdump = -1;
  131. bool opt_usb_list_all;
  132. #endif
  133. char *opt_kernel_path;
  134. char *cgminer_path;
  135. #if defined(USE_BITFORCE)
  136. bool opt_bfl_noncerange;
  137. #endif
  138. #define QUIET (opt_quiet || opt_realquiet)
  139. struct thr_info *control_thr;
  140. struct thr_info **mining_thr;
  141. static int gwsched_thr_id;
  142. static int stage_thr_id;
  143. static int watchpool_thr_id;
  144. static int watchdog_thr_id;
  145. #ifdef HAVE_CURSES
  146. static int input_thr_id;
  147. #endif
  148. int gpur_thr_id;
  149. static int api_thr_id;
  150. #ifdef USE_USBUTILS
  151. static int hotplug_thr_id;
  152. #endif
  153. static int total_control_threads;
  154. bool hotplug_mode;
  155. static int new_devices;
  156. static int new_threads;
  157. static int start_devices;
  158. int hotplug_time = 5;
  159. #ifdef USE_USBUTILS
  160. pthread_mutex_t cgusb_lock;
  161. #endif
  162. pthread_mutex_t hash_lock;
  163. static pthread_mutex_t *stgd_lock;
  164. pthread_mutex_t console_lock;
  165. cglock_t ch_lock;
  166. static pthread_rwlock_t blk_lock;
  167. static pthread_mutex_t sshare_lock;
  168. pthread_rwlock_t netacc_lock;
  169. pthread_rwlock_t mining_thr_lock;
  170. pthread_rwlock_t devices_lock;
  171. static pthread_mutex_t lp_lock;
  172. static pthread_cond_t lp_cond;
  173. pthread_mutex_t restart_lock;
  174. pthread_cond_t restart_cond;
  175. pthread_cond_t gws_cond;
  176. double total_mhashes_done;
  177. static struct timeval total_tv_start, total_tv_end;
  178. cglock_t control_lock;
  179. pthread_mutex_t stats_lock;
  180. int hw_errors;
  181. int total_accepted, total_rejected, total_diff1;
  182. int total_getworks, total_stale, total_discarded;
  183. double total_diff_accepted, total_diff_rejected, total_diff_stale;
  184. static int staged_rollable;
  185. unsigned int new_blocks;
  186. static unsigned int work_block;
  187. unsigned int found_blocks;
  188. unsigned int local_work;
  189. unsigned int total_go, total_ro;
  190. struct pool **pools;
  191. static struct pool *currentpool = NULL;
  192. int total_pools, enabled_pools;
  193. enum pool_strategy pool_strategy = POOL_FAILOVER;
  194. int opt_rotate_period;
  195. static int total_urls, total_users, total_passes, total_userpasses;
  196. static
  197. #ifndef HAVE_CURSES
  198. const
  199. #endif
  200. bool curses_active;
  201. static char current_block[40];
  202. /* Protected by ch_lock */
  203. static char *current_hash;
  204. char *current_fullhash;
  205. static char datestamp[40];
  206. static char blocktime[32];
  207. struct timeval block_timeval;
  208. static char best_share[8] = "0";
  209. double current_diff;
  210. static char block_diff[8];
  211. uint64_t best_diff = 0;
  212. struct block {
  213. char hash[40];
  214. UT_hash_handle hh;
  215. int block_no;
  216. };
  217. static struct block *blocks = NULL;
  218. int swork_id;
  219. /* For creating a hash database of stratum shares submitted that have not had
  220. * a response yet */
  221. struct stratum_share {
  222. UT_hash_handle hh;
  223. bool block;
  224. struct work *work;
  225. int id;
  226. time_t sshare_time;
  227. };
  228. static struct stratum_share *stratum_shares = NULL;
  229. char *opt_socks_proxy = NULL;
  230. static const char def_conf[] = "cgminer.conf";
  231. static char *default_config;
  232. static bool config_loaded;
  233. static int include_count;
  234. #define JSON_INCLUDE_CONF "include"
  235. #define JSON_LOAD_ERROR "JSON decode of file '%s' failed\n %s"
  236. #define JSON_LOAD_ERROR_LEN strlen(JSON_LOAD_ERROR)
  237. #define JSON_MAX_DEPTH 10
  238. #define JSON_MAX_DEPTH_ERR "Too many levels of JSON includes (limit 10) or a loop"
  239. #if defined(unix)
  240. static char *opt_stderr_cmd = NULL;
  241. static int forkpid;
  242. #endif // defined(unix)
  243. bool ping = true;
  244. struct sigaction termhandler, inthandler;
  245. struct thread_q *getq;
  246. static int total_work;
  247. struct work *staged_work = NULL;
  248. struct schedtime {
  249. bool enable;
  250. struct tm tm;
  251. };
  252. struct schedtime schedstart;
  253. struct schedtime schedstop;
  254. bool sched_paused;
  255. static bool time_before(struct tm *tm1, struct tm *tm2)
  256. {
  257. if (tm1->tm_hour < tm2->tm_hour)
  258. return true;
  259. if (tm1->tm_hour == tm2->tm_hour && tm1->tm_min < tm2->tm_min)
  260. return true;
  261. return false;
  262. }
  263. static bool should_run(void)
  264. {
  265. struct timeval tv;
  266. struct tm *tm;
  267. if (!schedstart.enable && !schedstop.enable)
  268. return true;
  269. gettimeofday(&tv, NULL);
  270. tm = localtime(&tv.tv_sec);
  271. if (schedstart.enable) {
  272. if (!schedstop.enable) {
  273. if (time_before(tm, &schedstart.tm))
  274. return false;
  275. /* This is a once off event with no stop time set */
  276. schedstart.enable = false;
  277. return true;
  278. }
  279. if (time_before(&schedstart.tm, &schedstop.tm)) {
  280. if (time_before(tm, &schedstop.tm) && !time_before(tm, &schedstart.tm))
  281. return true;
  282. return false;
  283. } /* Times are reversed */
  284. if (time_before(tm, &schedstart.tm)) {
  285. if (time_before(tm, &schedstop.tm))
  286. return true;
  287. return false;
  288. }
  289. return true;
  290. }
  291. /* only schedstop.enable == true */
  292. if (!time_before(tm, &schedstop.tm))
  293. return false;
  294. return true;
  295. }
  296. void get_datestamp(char *f, struct timeval *tv)
  297. {
  298. struct tm *tm;
  299. tm = localtime(&tv->tv_sec);
  300. sprintf(f, "[%d-%02d-%02d %02d:%02d:%02d]",
  301. tm->tm_year + 1900,
  302. tm->tm_mon + 1,
  303. tm->tm_mday,
  304. tm->tm_hour,
  305. tm->tm_min,
  306. tm->tm_sec);
  307. }
  308. void get_timestamp(char *f, struct timeval *tv)
  309. {
  310. struct tm *tm;
  311. tm = localtime(&tv->tv_sec);
  312. sprintf(f, "[%02d:%02d:%02d]",
  313. tm->tm_hour,
  314. tm->tm_min,
  315. tm->tm_sec);
  316. }
  317. static void applog_and_exit(const char *fmt, ...)
  318. {
  319. va_list ap;
  320. va_start(ap, fmt);
  321. vapplog(LOG_ERR, fmt, ap);
  322. va_end(ap);
  323. exit(1);
  324. }
  325. static pthread_mutex_t sharelog_lock;
  326. static FILE *sharelog_file = NULL;
  327. struct thr_info *get_thread(int thr_id)
  328. {
  329. struct thr_info *thr;
  330. rd_lock(&mining_thr_lock);
  331. thr = mining_thr[thr_id];
  332. rd_unlock(&mining_thr_lock);
  333. return thr;
  334. }
  335. static struct cgpu_info *get_thr_cgpu(int thr_id)
  336. {
  337. struct thr_info *thr = get_thread(thr_id);
  338. return thr->cgpu;
  339. }
  340. struct cgpu_info *get_devices(int id)
  341. {
  342. struct cgpu_info *cgpu;
  343. rd_lock(&devices_lock);
  344. cgpu = devices[id];
  345. rd_unlock(&devices_lock);
  346. return cgpu;
  347. }
  348. static void sharelog(const char*disposition, const struct work*work)
  349. {
  350. char *target, *hash, *data;
  351. struct cgpu_info *cgpu;
  352. unsigned long int t;
  353. struct pool *pool;
  354. int thr_id, rv;
  355. char s[1024];
  356. size_t ret;
  357. if (!sharelog_file)
  358. return;
  359. thr_id = work->thr_id;
  360. cgpu = get_thr_cgpu(thr_id);
  361. pool = work->pool;
  362. t = (unsigned long int)(work->tv_work_found.tv_sec);
  363. target = bin2hex(work->target, sizeof(work->target));
  364. hash = bin2hex(work->hash, sizeof(work->hash));
  365. data = bin2hex(work->data, sizeof(work->data));
  366. // timestamp,disposition,target,pool,dev,thr,sharehash,sharedata
  367. rv = snprintf(s, sizeof(s), "%lu,%s,%s,%s,%s%u,%u,%s,%s\n", t, disposition, target, pool->rpc_url, cgpu->drv->name, cgpu->device_id, thr_id, hash, data);
  368. free(target);
  369. free(hash);
  370. free(data);
  371. if (rv >= (int)(sizeof(s)))
  372. s[sizeof(s) - 1] = '\0';
  373. else if (rv < 0) {
  374. applog(LOG_ERR, "sharelog printf error");
  375. return;
  376. }
  377. mutex_lock(&sharelog_lock);
  378. ret = fwrite(s, rv, 1, sharelog_file);
  379. fflush(sharelog_file);
  380. mutex_unlock(&sharelog_lock);
  381. if (ret != 1)
  382. applog(LOG_ERR, "sharelog fwrite error");
  383. }
  384. static char *getwork_req = "{\"method\": \"getwork\", \"params\": [], \"id\":0}\n";
  385. static char *gbt_req = "{\"id\": 0, \"method\": \"getblocktemplate\", \"params\": [{\"capabilities\": [\"coinbasetxn\", \"workid\", \"coinbase/append\"]}]}\n";
  386. /* Return value is ignored if not called from add_pool_details */
  387. struct pool *add_pool(void)
  388. {
  389. struct pool *pool;
  390. pool = calloc(sizeof(struct pool), 1);
  391. if (!pool)
  392. quit(1, "Failed to malloc pool in add_pool");
  393. pool->pool_no = pool->prio = total_pools;
  394. pools = realloc(pools, sizeof(struct pool *) * (total_pools + 2));
  395. pools[total_pools++] = pool;
  396. mutex_init(&pool->pool_lock);
  397. if (unlikely(pthread_cond_init(&pool->cr_cond, NULL)))
  398. quit(1, "Failed to pthread_cond_init in add_pool");
  399. cglock_init(&pool->data_lock);
  400. mutex_init(&pool->stratum_lock);
  401. cglock_init(&pool->gbt_lock);
  402. INIT_LIST_HEAD(&pool->curlring);
  403. /* Make sure the pool doesn't think we've been idle since time 0 */
  404. pool->tv_idle.tv_sec = ~0UL;
  405. pool->rpc_req = getwork_req;
  406. pool->rpc_proxy = NULL;
  407. return pool;
  408. }
  409. /* Pool variant of test and set */
  410. static bool pool_tset(struct pool *pool, bool *var)
  411. {
  412. bool ret;
  413. mutex_lock(&pool->pool_lock);
  414. ret = *var;
  415. *var = true;
  416. mutex_unlock(&pool->pool_lock);
  417. return ret;
  418. }
  419. bool pool_tclear(struct pool *pool, bool *var)
  420. {
  421. bool ret;
  422. mutex_lock(&pool->pool_lock);
  423. ret = *var;
  424. *var = false;
  425. mutex_unlock(&pool->pool_lock);
  426. return ret;
  427. }
  428. struct pool *current_pool(void)
  429. {
  430. struct pool *pool;
  431. cg_rlock(&control_lock);
  432. pool = currentpool;
  433. cg_runlock(&control_lock);
  434. return pool;
  435. }
  436. char *set_int_range(const char *arg, int *i, int min, int max)
  437. {
  438. char *err = opt_set_intval(arg, i);
  439. if (err)
  440. return err;
  441. if (*i < min || *i > max)
  442. return "Value out of range";
  443. return NULL;
  444. }
  445. static char *set_int_0_to_9999(const char *arg, int *i)
  446. {
  447. return set_int_range(arg, i, 0, 9999);
  448. }
  449. static char *set_int_1_to_65535(const char *arg, int *i)
  450. {
  451. return set_int_range(arg, i, 1, 65535);
  452. }
  453. static char *set_int_0_to_10(const char *arg, int *i)
  454. {
  455. return set_int_range(arg, i, 0, 10);
  456. }
  457. static char *set_int_1_to_10(const char *arg, int *i)
  458. {
  459. return set_int_range(arg, i, 1, 10);
  460. }
  461. #ifdef USE_FPGA_SERIAL
  462. static char *add_serial(char *arg)
  463. {
  464. string_elist_add(arg, &scan_devices);
  465. return NULL;
  466. }
  467. #endif
  468. static char *set_devices(char *arg)
  469. {
  470. int i = strtol(arg, &arg, 0);
  471. if (*arg) {
  472. if (*arg == '?') {
  473. devices_enabled = -1;
  474. return NULL;
  475. }
  476. return "Invalid device number";
  477. }
  478. if (i < 0 || i >= (int)(sizeof(devices_enabled) * 8) - 1)
  479. return "Invalid device number";
  480. devices_enabled |= 1 << i;
  481. return NULL;
  482. }
  483. static char *set_balance(enum pool_strategy *strategy)
  484. {
  485. *strategy = POOL_BALANCE;
  486. return NULL;
  487. }
  488. static char *set_loadbalance(enum pool_strategy *strategy)
  489. {
  490. *strategy = POOL_LOADBALANCE;
  491. return NULL;
  492. }
  493. static char *set_rotate(const char *arg, int *i)
  494. {
  495. pool_strategy = POOL_ROTATE;
  496. return set_int_range(arg, i, 0, 9999);
  497. }
  498. static char *set_rr(enum pool_strategy *strategy)
  499. {
  500. *strategy = POOL_ROUNDROBIN;
  501. return NULL;
  502. }
  503. /* Detect that url is for a stratum protocol either via the presence of
  504. * stratum+tcp or by detecting a stratum server response */
  505. bool detect_stratum(struct pool *pool, char *url)
  506. {
  507. if (!extract_sockaddr(pool, url))
  508. return false;
  509. if (!strncasecmp(url, "stratum+tcp://", 14)) {
  510. pool->rpc_url = strdup(url);
  511. pool->has_stratum = true;
  512. pool->stratum_url = pool->sockaddr_url;
  513. return true;
  514. }
  515. return false;
  516. }
  517. static char *set_url(char *arg)
  518. {
  519. struct pool *pool;
  520. total_urls++;
  521. if (total_urls > total_pools)
  522. add_pool();
  523. pool = pools[total_urls - 1];
  524. arg = get_proxy(arg, pool);
  525. if (detect_stratum(pool, arg))
  526. return NULL;
  527. opt_set_charp(arg, &pool->rpc_url);
  528. if (strncmp(arg, "http://", 7) &&
  529. strncmp(arg, "https://", 8)) {
  530. char *httpinput;
  531. httpinput = malloc(255);
  532. if (!httpinput)
  533. quit(1, "Failed to malloc httpinput");
  534. strcpy(httpinput, "http://");
  535. strncat(httpinput, arg, 248);
  536. pool->rpc_url = httpinput;
  537. }
  538. return NULL;
  539. }
  540. static char *set_user(const char *arg)
  541. {
  542. struct pool *pool;
  543. if (total_userpasses)
  544. return "Use only user + pass or userpass, but not both";
  545. total_users++;
  546. if (total_users > total_pools)
  547. add_pool();
  548. pool = pools[total_users - 1];
  549. opt_set_charp(arg, &pool->rpc_user);
  550. return NULL;
  551. }
  552. static char *set_pass(const char *arg)
  553. {
  554. struct pool *pool;
  555. if (total_userpasses)
  556. return "Use only user + pass or userpass, but not both";
  557. total_passes++;
  558. if (total_passes > total_pools)
  559. add_pool();
  560. pool = pools[total_passes - 1];
  561. opt_set_charp(arg, &pool->rpc_pass);
  562. return NULL;
  563. }
  564. static char *set_userpass(const char *arg)
  565. {
  566. struct pool *pool;
  567. char *updup;
  568. if (total_users || total_passes)
  569. return "Use only user + pass or userpass, but not both";
  570. total_userpasses++;
  571. if (total_userpasses > total_pools)
  572. add_pool();
  573. pool = pools[total_userpasses - 1];
  574. updup = strdup(arg);
  575. opt_set_charp(arg, &pool->rpc_userpass);
  576. pool->rpc_user = strtok(updup, ":");
  577. if (!pool->rpc_user)
  578. return "Failed to find : delimited user info";
  579. pool->rpc_pass = strtok(NULL, ":");
  580. if (!pool->rpc_pass)
  581. return "Failed to find : delimited pass info";
  582. return NULL;
  583. }
  584. static char *enable_debug(bool *flag)
  585. {
  586. *flag = true;
  587. /* Turn on verbose output, too. */
  588. opt_log_output = true;
  589. return NULL;
  590. }
  591. static char *set_schedtime(const char *arg, struct schedtime *st)
  592. {
  593. if (sscanf(arg, "%d:%d", &st->tm.tm_hour, &st->tm.tm_min) != 2)
  594. return "Invalid time set, should be HH:MM";
  595. if (st->tm.tm_hour > 23 || st->tm.tm_min > 59 || st->tm.tm_hour < 0 || st->tm.tm_min < 0)
  596. return "Invalid time set.";
  597. st->enable = true;
  598. return NULL;
  599. }
  600. static char* set_sharelog(char *arg)
  601. {
  602. char *r = "";
  603. long int i = strtol(arg, &r, 10);
  604. if ((!*r) && i >= 0 && i <= INT_MAX) {
  605. sharelog_file = fdopen((int)i, "a");
  606. if (!sharelog_file)
  607. applog(LOG_ERR, "Failed to open fd %u for share log", (unsigned int)i);
  608. } else if (!strcmp(arg, "-")) {
  609. sharelog_file = stdout;
  610. if (!sharelog_file)
  611. applog(LOG_ERR, "Standard output missing for share log");
  612. } else {
  613. sharelog_file = fopen(arg, "a");
  614. if (!sharelog_file)
  615. applog(LOG_ERR, "Failed to open %s for share log", arg);
  616. }
  617. return NULL;
  618. }
  619. static char *temp_cutoff_str = NULL;
  620. char *set_temp_cutoff(char *arg)
  621. {
  622. int val;
  623. if (!(arg && arg[0]))
  624. return "Invalid parameters for set temp cutoff";
  625. val = atoi(arg);
  626. if (val < 0 || val > 200)
  627. return "Invalid value passed to set temp cutoff";
  628. temp_cutoff_str = arg;
  629. return NULL;
  630. }
  631. static void load_temp_cutoffs()
  632. {
  633. int i, val = 0, device = 0;
  634. char *nextptr;
  635. if (temp_cutoff_str) {
  636. for (device = 0, nextptr = strtok(temp_cutoff_str, ","); nextptr; ++device, nextptr = strtok(NULL, ",")) {
  637. if (device >= total_devices)
  638. quit(1, "Too many values passed to set temp cutoff");
  639. val = atoi(nextptr);
  640. if (val < 0 || val > 200)
  641. quit(1, "Invalid value passed to set temp cutoff");
  642. rd_lock(&devices_lock);
  643. devices[device]->cutofftemp = val;
  644. rd_unlock(&devices_lock);
  645. }
  646. } else {
  647. rd_lock(&devices_lock);
  648. for (i = device; i < total_devices; ++i) {
  649. if (!devices[i]->cutofftemp)
  650. devices[i]->cutofftemp = opt_cutofftemp;
  651. }
  652. rd_unlock(&devices_lock);
  653. return;
  654. }
  655. if (device <= 1) {
  656. rd_lock(&devices_lock);
  657. for (i = device; i < total_devices; ++i)
  658. devices[i]->cutofftemp = val;
  659. rd_unlock(&devices_lock);
  660. }
  661. }
  662. static char *set_api_allow(const char *arg)
  663. {
  664. opt_set_charp(arg, &opt_api_allow);
  665. return NULL;
  666. }
  667. static char *set_api_groups(const char *arg)
  668. {
  669. opt_set_charp(arg, &opt_api_groups);
  670. return NULL;
  671. }
  672. static char *set_api_description(const char *arg)
  673. {
  674. opt_set_charp(arg, &opt_api_description);
  675. return NULL;
  676. }
  677. #ifdef USE_ICARUS
  678. static char *set_icarus_options(const char *arg)
  679. {
  680. opt_set_charp(arg, &opt_icarus_options);
  681. return NULL;
  682. }
  683. static char *set_icarus_timing(const char *arg)
  684. {
  685. opt_set_charp(arg, &opt_icarus_timing);
  686. return NULL;
  687. }
  688. #endif
  689. #ifdef USE_USBUTILS
  690. static char *set_usb_select(const char *arg)
  691. {
  692. opt_set_charp(arg, &opt_usb_select);
  693. return NULL;
  694. }
  695. #endif
  696. static char *set_null(const char __maybe_unused *arg)
  697. {
  698. return NULL;
  699. }
  700. /* These options are available from config file or commandline */
  701. static struct opt_table opt_config_table[] = {
  702. #ifdef WANT_CPUMINE
  703. OPT_WITH_ARG("--algo|-a",
  704. set_algo, show_algo, &opt_algo,
  705. "Specify sha256 implementation for CPU mining:\n"
  706. "\tauto\t\tBenchmark at startup and pick fastest algorithm"
  707. "\n\tc\t\tLinux kernel sha256, implemented in C"
  708. #ifdef WANT_SSE2_4WAY
  709. "\n\t4way\t\ttcatm's 4-way SSE2 implementation"
  710. #endif
  711. #ifdef WANT_VIA_PADLOCK
  712. "\n\tvia\t\tVIA padlock implementation"
  713. #endif
  714. "\n\tcryptopp\tCrypto++ C/C++ implementation"
  715. #ifdef WANT_CRYPTOPP_ASM32
  716. "\n\tcryptopp_asm32\tCrypto++ 32-bit assembler implementation"
  717. #endif
  718. #ifdef WANT_X8632_SSE2
  719. "\n\tsse2_32\t\tSSE2 32 bit implementation for i386 machines"
  720. #endif
  721. #ifdef WANT_X8664_SSE2
  722. "\n\tsse2_64\t\tSSE2 64 bit implementation for x86_64 machines"
  723. #endif
  724. #ifdef WANT_X8664_SSE4
  725. "\n\tsse4_64\t\tSSE4.1 64 bit implementation for x86_64 machines"
  726. #endif
  727. #ifdef WANT_ALTIVEC_4WAY
  728. "\n\taltivec_4way\tAltivec implementation for PowerPC G4 and G5 machines"
  729. #endif
  730. ),
  731. #endif
  732. OPT_WITH_ARG("--api-allow",
  733. set_api_allow, NULL, NULL,
  734. "Allow API access only to the given list of [G:]IP[/Prefix] addresses[/subnets]"),
  735. OPT_WITH_ARG("--api-description",
  736. set_api_description, NULL, NULL,
  737. "Description placed in the API status header, default: cgminer version"),
  738. OPT_WITH_ARG("--api-groups",
  739. set_api_groups, NULL, NULL,
  740. "API one letter groups G:cmd:cmd[,P:cmd:*...] defining the cmds a groups can use"),
  741. OPT_WITHOUT_ARG("--api-listen",
  742. opt_set_bool, &opt_api_listen,
  743. "Enable API, default: disabled"),
  744. OPT_WITHOUT_ARG("--api-network",
  745. opt_set_bool, &opt_api_network,
  746. "Allow API (if enabled) to listen on/for any address, default: only 127.0.0.1"),
  747. OPT_WITH_ARG("--api-port",
  748. set_int_1_to_65535, opt_show_intval, &opt_api_port,
  749. "Port number of miner API"),
  750. #ifdef HAVE_ADL
  751. OPT_WITHOUT_ARG("--auto-fan",
  752. opt_set_bool, &opt_autofan,
  753. "Automatically adjust all GPU fan speeds to maintain a target temperature"),
  754. OPT_WITHOUT_ARG("--auto-gpu",
  755. opt_set_bool, &opt_autoengine,
  756. "Automatically adjust all GPU engine clock speeds to maintain a target temperature"),
  757. #endif
  758. OPT_WITHOUT_ARG("--balance",
  759. set_balance, &pool_strategy,
  760. "Change multipool strategy from failover to even share balance"),
  761. OPT_WITHOUT_ARG("--benchmark",
  762. opt_set_bool, &opt_benchmark,
  763. "Run cgminer in benchmark mode - produces no shares"),
  764. #if defined(USE_BITFORCE)
  765. OPT_WITHOUT_ARG("--bfl-range",
  766. opt_set_bool, &opt_bfl_noncerange,
  767. "Use nonce range on bitforce devices if supported"),
  768. #endif
  769. #ifdef WANT_CPUMINE
  770. OPT_WITH_ARG("--bench-algo|-b",
  771. set_int_0_to_9999, opt_show_intval, &opt_bench_algo,
  772. opt_hidden),
  773. #endif
  774. #ifdef HAVE_CURSES
  775. OPT_WITHOUT_ARG("--compact",
  776. opt_set_bool, &opt_compact,
  777. "Use compact display without per device statistics"),
  778. #endif
  779. #ifdef WANT_CPUMINE
  780. OPT_WITH_ARG("--cpu-threads|-t",
  781. force_nthreads_int, opt_show_intval, &opt_n_threads,
  782. "Number of miner CPU threads"),
  783. #endif
  784. OPT_WITHOUT_ARG("--debug|-D",
  785. enable_debug, &opt_debug,
  786. "Enable debug output"),
  787. OPT_WITH_ARG("--device|-d",
  788. set_devices, NULL, NULL,
  789. "Select device to use, (Use repeat -d for multiple devices, default: all)"),
  790. OPT_WITHOUT_ARG("--disable-gpu|-G",
  791. opt_set_bool, &opt_nogpu,
  792. #ifdef HAVE_OPENCL
  793. "Disable GPU mining even if suitable devices exist"
  794. #else
  795. opt_hidden
  796. #endif
  797. ),
  798. OPT_WITHOUT_ARG("--disable-rejecting",
  799. opt_set_bool, &opt_disable_pool,
  800. "Automatically disable pools that continually reject shares"),
  801. #if defined(WANT_CPUMINE) && (defined(HAVE_OPENCL) || defined(USE_FPGA))
  802. OPT_WITHOUT_ARG("--enable-cpu|-C",
  803. opt_set_bool, &opt_usecpu,
  804. "Enable CPU mining with other mining (default: no CPU mining if other devices exist)"),
  805. #endif
  806. OPT_WITH_ARG("--expiry|-E",
  807. set_int_0_to_9999, opt_show_intval, &opt_expiry,
  808. "Upper bound on how many seconds after getting work we consider a share from it stale"),
  809. OPT_WITHOUT_ARG("--failover-only",
  810. opt_set_bool, &opt_fail_only,
  811. "Don't leak work to backup pools when primary pool is lagging"),
  812. OPT_WITHOUT_ARG("--fix-protocol",
  813. opt_set_bool, &opt_fix_protocol,
  814. "Do not redirect to a different getwork protocol (eg. stratum)"),
  815. #ifdef HAVE_OPENCL
  816. OPT_WITH_ARG("--gpu-dyninterval",
  817. set_int_1_to_65535, opt_show_intval, &opt_dynamic_interval,
  818. "Set the refresh interval in ms for GPUs using dynamic intensity"),
  819. OPT_WITH_ARG("--gpu-platform",
  820. set_int_0_to_9999, opt_show_intval, &opt_platform_id,
  821. "Select OpenCL platform ID to use for GPU mining"),
  822. OPT_WITH_ARG("--gpu-threads|-g",
  823. set_int_1_to_10, opt_show_intval, &opt_g_threads,
  824. "Number of threads per GPU (1 - 10)"),
  825. #ifdef HAVE_ADL
  826. OPT_WITH_ARG("--gpu-engine",
  827. set_gpu_engine, NULL, NULL,
  828. "GPU engine (over)clock range in Mhz - one value, range and/or comma separated list (e.g. 850-900,900,750-850)"),
  829. OPT_WITH_ARG("--gpu-fan",
  830. set_gpu_fan, NULL, NULL,
  831. "GPU fan percentage range - one value, range and/or comma separated list (e.g. 0-85,85,65)"),
  832. OPT_WITH_ARG("--gpu-map",
  833. set_gpu_map, NULL, NULL,
  834. "Map OpenCL to ADL device order manually, paired CSV (e.g. 1:0,2:1 maps OpenCL 1 to ADL 0, 2 to 1)"),
  835. OPT_WITH_ARG("--gpu-memclock",
  836. set_gpu_memclock, NULL, NULL,
  837. "Set the GPU memory (over)clock in Mhz - one value for all or separate by commas for per card"),
  838. OPT_WITH_ARG("--gpu-memdiff",
  839. set_gpu_memdiff, NULL, NULL,
  840. "Set a fixed difference in clock speed between the GPU and memory in auto-gpu mode"),
  841. OPT_WITH_ARG("--gpu-powertune",
  842. set_gpu_powertune, NULL, NULL,
  843. "Set the GPU powertune percentage - one value for all or separate by commas for per card"),
  844. OPT_WITHOUT_ARG("--gpu-reorder",
  845. opt_set_bool, &opt_reorder,
  846. "Attempt to reorder GPU devices according to PCI Bus ID"),
  847. OPT_WITH_ARG("--gpu-vddc",
  848. set_gpu_vddc, NULL, NULL,
  849. "Set the GPU voltage in Volts - one value for all or separate by commas for per card"),
  850. #endif
  851. #ifdef USE_SCRYPT
  852. OPT_WITH_ARG("--lookup-gap",
  853. set_lookup_gap, NULL, NULL,
  854. "Set GPU lookup gap for scrypt mining, comma separated"),
  855. #endif
  856. OPT_WITH_ARG("--intensity|-I",
  857. set_intensity, NULL, NULL,
  858. "Intensity of GPU scanning (d or " _MIN_INTENSITY_STR " -> " _MAX_INTENSITY_STR ", default: d to maintain desktop interactivity)"),
  859. #endif
  860. OPT_WITH_ARG("--hotplug",
  861. set_int_0_to_9999, NULL, &hotplug_time,
  862. #ifdef USE_USBUTILS
  863. "Seconds between hotplug checks (0 means never check)"
  864. #else
  865. opt_hidden
  866. #endif
  867. ),
  868. #if defined(HAVE_OPENCL) || defined(HAVE_MODMINER)
  869. OPT_WITH_ARG("--kernel-path|-K",
  870. opt_set_charp, opt_show_charp, &opt_kernel_path,
  871. "Specify a path to where bitstream and kernel files are"),
  872. #endif
  873. #ifdef HAVE_OPENCL
  874. OPT_WITH_ARG("--kernel|-k",
  875. set_kernel, NULL, NULL,
  876. "Override sha256 kernel to use (diablo, poclbm, phatk or diakgcn) - one value or comma separated"),
  877. #endif
  878. #ifdef USE_ICARUS
  879. OPT_WITH_ARG("--icarus-options",
  880. set_icarus_options, NULL, NULL,
  881. opt_hidden),
  882. OPT_WITH_ARG("--icarus-timing",
  883. set_icarus_timing, NULL, NULL,
  884. opt_hidden),
  885. #endif
  886. OPT_WITHOUT_ARG("--load-balance",
  887. set_loadbalance, &pool_strategy,
  888. "Change multipool strategy from failover to efficiency based balance"),
  889. OPT_WITH_ARG("--log|-l",
  890. set_int_0_to_9999, opt_show_intval, &opt_log_interval,
  891. "Interval in seconds between log output"),
  892. #if defined(unix)
  893. OPT_WITH_ARG("--monitor|-m",
  894. opt_set_charp, NULL, &opt_stderr_cmd,
  895. "Use custom pipe cmd for output messages"),
  896. #endif // defined(unix)
  897. OPT_WITHOUT_ARG("--net-delay",
  898. opt_set_bool, &opt_delaynet,
  899. "Impose small delays in networking to not overload slow routers"),
  900. OPT_WITHOUT_ARG("--no-adl",
  901. opt_set_bool, &opt_noadl,
  902. #ifdef HAVE_ADL
  903. "Disable the ATI display library used for monitoring and setting GPU parameters"
  904. #else
  905. opt_hidden
  906. #endif
  907. ),
  908. OPT_WITHOUT_ARG("--no-pool-disable",
  909. opt_set_invbool, &opt_disable_pool,
  910. opt_hidden),
  911. OPT_WITHOUT_ARG("--no-restart",
  912. opt_set_invbool, &opt_restart,
  913. #ifdef HAVE_OPENCL
  914. "Do not attempt to restart GPUs that hang"
  915. #else
  916. opt_hidden
  917. #endif
  918. ),
  919. OPT_WITHOUT_ARG("--no-submit-stale",
  920. opt_set_invbool, &opt_submit_stale,
  921. "Don't submit shares if they are detected as stale"),
  922. OPT_WITH_ARG("--pass|-p",
  923. set_pass, NULL, NULL,
  924. "Password for bitcoin JSON-RPC server"),
  925. OPT_WITHOUT_ARG("--per-device-stats",
  926. opt_set_bool, &want_per_device_stats,
  927. "Force verbose mode and output per-device statistics"),
  928. OPT_WITHOUT_ARG("--protocol-dump|-P",
  929. opt_set_bool, &opt_protocol,
  930. "Verbose dump of protocol-level activities"),
  931. OPT_WITH_ARG("--queue|-Q",
  932. set_int_0_to_9999, opt_show_intval, &opt_queue,
  933. "Minimum number of work items to have queued (0+)"),
  934. OPT_WITHOUT_ARG("--quiet|-q",
  935. opt_set_bool, &opt_quiet,
  936. "Disable logging output, display status and errors"),
  937. OPT_WITHOUT_ARG("--real-quiet",
  938. opt_set_bool, &opt_realquiet,
  939. "Disable all output"),
  940. OPT_WITHOUT_ARG("--remove-disabled",
  941. opt_set_bool, &opt_removedisabled,
  942. "Remove disabled devices entirely, as if they didn't exist"),
  943. OPT_WITH_ARG("--retries",
  944. set_null, NULL, NULL,
  945. opt_hidden),
  946. OPT_WITH_ARG("--retry-pause",
  947. set_null, NULL, NULL,
  948. opt_hidden),
  949. OPT_WITH_ARG("--rotate",
  950. set_rotate, opt_show_intval, &opt_rotate_period,
  951. "Change multipool strategy from failover to regularly rotate at N minutes"),
  952. OPT_WITHOUT_ARG("--round-robin",
  953. set_rr, &pool_strategy,
  954. "Change multipool strategy from failover to round robin on failure"),
  955. #ifdef USE_FPGA_SERIAL
  956. OPT_WITH_ARG("--scan-serial|-S",
  957. add_serial, NULL, NULL,
  958. "Serial port to probe for FPGA Mining device"),
  959. #endif
  960. OPT_WITH_ARG("--scan-time|-s",
  961. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  962. "Upper bound on time spent scanning current work, in seconds"),
  963. OPT_WITH_ARG("--sched-start",
  964. set_schedtime, NULL, &schedstart,
  965. "Set a time of day in HH:MM to start mining (a once off without a stop time)"),
  966. OPT_WITH_ARG("--sched-stop",
  967. set_schedtime, NULL, &schedstop,
  968. "Set a time of day in HH:MM to stop mining (will quit without a start time)"),
  969. #ifdef USE_SCRYPT
  970. OPT_WITHOUT_ARG("--scrypt",
  971. opt_set_bool, &opt_scrypt,
  972. "Use the scrypt algorithm for mining (litecoin only)"),
  973. OPT_WITH_ARG("--shaders",
  974. set_shaders, NULL, NULL,
  975. "GPU shaders per card for tuning scrypt, comma separated"),
  976. #endif
  977. OPT_WITH_ARG("--sharelog",
  978. set_sharelog, NULL, NULL,
  979. "Append share log to file"),
  980. OPT_WITH_ARG("--shares",
  981. opt_set_intval, NULL, &opt_shares,
  982. "Quit after mining N shares (default: unlimited)"),
  983. OPT_WITH_ARG("--socks-proxy",
  984. opt_set_charp, NULL, &opt_socks_proxy,
  985. "Set socks4 proxy (host:port)"),
  986. #ifdef HAVE_SYSLOG_H
  987. OPT_WITHOUT_ARG("--syslog",
  988. opt_set_bool, &use_syslog,
  989. "Use system log for output messages (default: standard error)"),
  990. #endif
  991. #if defined(HAVE_ADL) || defined(USE_BITFORCE) || defined(USE_MODMINER) || defined(USE_BFLSC)
  992. OPT_WITH_ARG("--temp-cutoff",
  993. set_temp_cutoff, opt_show_intval, &opt_cutofftemp,
  994. "Temperature where a device will be automatically disabled, one value or comma separated list"),
  995. #endif
  996. #ifdef HAVE_ADL
  997. OPT_WITH_ARG("--temp-hysteresis",
  998. set_int_1_to_10, opt_show_intval, &opt_hysteresis,
  999. "Set how much the temperature can fluctuate outside limits when automanaging speeds"),
  1000. OPT_WITH_ARG("--temp-overheat",
  1001. set_temp_overheat, opt_show_intval, &opt_overheattemp,
  1002. "Overheat temperature when automatically managing fan and GPU speeds, one value or comma separated list"),
  1003. OPT_WITH_ARG("--temp-target",
  1004. set_temp_target, opt_show_intval, &opt_targettemp,
  1005. "Target temperature when automatically managing fan and GPU speeds, one value or comma separated list"),
  1006. #endif
  1007. OPT_WITHOUT_ARG("--text-only|-T",
  1008. opt_set_invbool, &use_curses,
  1009. #ifdef HAVE_CURSES
  1010. "Disable ncurses formatted screen output"
  1011. #else
  1012. opt_hidden
  1013. #endif
  1014. ),
  1015. #ifdef USE_SCRYPT
  1016. OPT_WITH_ARG("--thread-concurrency",
  1017. set_thread_concurrency, NULL, NULL,
  1018. "Set GPU thread concurrency for scrypt mining, comma separated"),
  1019. #endif
  1020. OPT_WITH_ARG("--url|-o",
  1021. set_url, NULL, NULL,
  1022. "URL for bitcoin JSON-RPC server"),
  1023. OPT_WITH_ARG("--user|-u",
  1024. set_user, NULL, NULL,
  1025. "Username for bitcoin JSON-RPC server"),
  1026. #ifdef USE_USBUTILS
  1027. OPT_WITH_ARG("--usb",
  1028. set_usb_select, NULL, NULL,
  1029. "USB device selection"),
  1030. OPT_WITH_ARG("--usb-dump",
  1031. set_int_0_to_10, opt_show_intval, &opt_usbdump,
  1032. opt_hidden),
  1033. OPT_WITHOUT_ARG("--usb-list-all",
  1034. opt_set_bool, &opt_usb_list_all,
  1035. opt_hidden),
  1036. #endif
  1037. #ifdef HAVE_OPENCL
  1038. OPT_WITH_ARG("--vectors|-v",
  1039. set_vector, NULL, NULL,
  1040. "Override detected optimal vector (1, 2 or 4) - one value or comma separated list"),
  1041. #endif
  1042. OPT_WITHOUT_ARG("--verbose",
  1043. opt_set_bool, &opt_log_output,
  1044. "Log verbose output to stderr as well as status output"),
  1045. #ifdef HAVE_OPENCL
  1046. OPT_WITH_ARG("--worksize|-w",
  1047. set_worksize, NULL, NULL,
  1048. "Override detected optimal worksize - one value or comma separated list"),
  1049. #endif
  1050. OPT_WITH_ARG("--userpass|-O",
  1051. set_userpass, NULL, NULL,
  1052. "Username:Password pair for bitcoin JSON-RPC server"),
  1053. OPT_WITHOUT_ARG("--worktime",
  1054. opt_set_bool, &opt_worktime,
  1055. "Display extra work time debug information"),
  1056. OPT_WITH_ARG("--pools",
  1057. opt_set_bool, NULL, NULL, opt_hidden),
  1058. OPT_ENDTABLE
  1059. };
  1060. static char *load_config(const char *arg, void __maybe_unused *unused);
  1061. static int fileconf_load;
  1062. static char *parse_config(json_t *config, bool fileconf)
  1063. {
  1064. static char err_buf[200];
  1065. struct opt_table *opt;
  1066. json_t *val;
  1067. if (fileconf && !fileconf_load)
  1068. fileconf_load = 1;
  1069. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  1070. char *p, *name;
  1071. /* We don't handle subtables. */
  1072. assert(!(opt->type & OPT_SUBTABLE));
  1073. /* Pull apart the option name(s). */
  1074. name = strdup(opt->names);
  1075. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  1076. char *err = NULL;
  1077. /* Ignore short options. */
  1078. if (p[1] != '-')
  1079. continue;
  1080. val = json_object_get(config, p+2);
  1081. if (!val)
  1082. continue;
  1083. if ((opt->type & OPT_HASARG) && json_is_string(val)) {
  1084. err = opt->cb_arg(json_string_value(val),
  1085. opt->u.arg);
  1086. } else if ((opt->type & OPT_HASARG) && json_is_array(val)) {
  1087. int n, size = json_array_size(val);
  1088. for (n = 0; n < size && !err; n++) {
  1089. if (json_is_string(json_array_get(val, n)))
  1090. err = opt->cb_arg(json_string_value(json_array_get(val, n)), opt->u.arg);
  1091. else if (json_is_object(json_array_get(val, n)))
  1092. err = parse_config(json_array_get(val, n), false);
  1093. }
  1094. } else if ((opt->type & OPT_NOARG) && json_is_true(val))
  1095. err = opt->cb(opt->u.arg);
  1096. else
  1097. err = "Invalid value";
  1098. if (err) {
  1099. /* Allow invalid values to be in configuration
  1100. * file, just skipping over them provided the
  1101. * JSON is still valid after that. */
  1102. if (fileconf) {
  1103. applog(LOG_ERR, "Invalid config option %s: %s", p, err);
  1104. fileconf_load = -1;
  1105. } else {
  1106. sprintf(err_buf, "Parsing JSON option %s: %s",
  1107. p, err);
  1108. return err_buf;
  1109. }
  1110. }
  1111. }
  1112. free(name);
  1113. }
  1114. val = json_object_get(config, JSON_INCLUDE_CONF);
  1115. if (val && json_is_string(val))
  1116. return load_config(json_string_value(val), NULL);
  1117. return NULL;
  1118. }
  1119. char *cnfbuf = NULL;
  1120. static char *load_config(const char *arg, void __maybe_unused *unused)
  1121. {
  1122. json_error_t err;
  1123. json_t *config;
  1124. char *json_error;
  1125. if (!cnfbuf)
  1126. cnfbuf = strdup(arg);
  1127. if (++include_count > JSON_MAX_DEPTH)
  1128. return JSON_MAX_DEPTH_ERR;
  1129. #if JANSSON_MAJOR_VERSION > 1
  1130. config = json_load_file(arg, 0, &err);
  1131. #else
  1132. config = json_load_file(arg, &err);
  1133. #endif
  1134. if (!json_is_object(config)) {
  1135. json_error = malloc(JSON_LOAD_ERROR_LEN + strlen(arg) + strlen(err.text));
  1136. if (!json_error)
  1137. quit(1, "Malloc failure in json error");
  1138. sprintf(json_error, JSON_LOAD_ERROR, arg, err.text);
  1139. return json_error;
  1140. }
  1141. config_loaded = true;
  1142. /* Parse the config now, so we can override it. That can keep pointers
  1143. * so don't free config object. */
  1144. return parse_config(config, true);
  1145. }
  1146. static char *set_default_config(const char *arg)
  1147. {
  1148. opt_set_charp(arg, &default_config);
  1149. return NULL;
  1150. }
  1151. void default_save_file(char *filename);
  1152. static void load_default_config(void)
  1153. {
  1154. cnfbuf = malloc(PATH_MAX);
  1155. default_save_file(cnfbuf);
  1156. if (!access(cnfbuf, R_OK))
  1157. load_config(cnfbuf, NULL);
  1158. else {
  1159. free(cnfbuf);
  1160. cnfbuf = NULL;
  1161. }
  1162. }
  1163. extern const char *opt_argv0;
  1164. static char *opt_verusage_and_exit(const char *extra)
  1165. {
  1166. printf("%s\nBuilt with "
  1167. #ifdef USE_BFLSC
  1168. "bflsc "
  1169. #endif
  1170. #ifdef HAVE_OPENCL
  1171. "GPU "
  1172. #endif
  1173. #ifdef WANT_CPUMINE
  1174. "CPU "
  1175. #endif
  1176. #ifdef USE_BITFORCE
  1177. "bitforce "
  1178. #endif
  1179. #ifdef USE_ICARUS
  1180. "icarus "
  1181. #endif
  1182. #ifdef USE_MODMINER
  1183. "modminer "
  1184. #endif
  1185. #ifdef USE_ZTEX
  1186. "ztex "
  1187. #endif
  1188. #ifdef USE_SCRYPT
  1189. "scrypt "
  1190. #endif
  1191. "mining support.\n"
  1192. , packagename);
  1193. printf("%s", opt_usage(opt_argv0, extra));
  1194. fflush(stdout);
  1195. exit(0);
  1196. }
  1197. #if defined(HAVE_OPENCL) || defined(USE_USBUTILS)
  1198. char *display_devs(int *ndevs)
  1199. {
  1200. *ndevs = 0;
  1201. #ifdef HAVE_OPENCL
  1202. print_ndevs(ndevs);
  1203. #endif
  1204. #ifdef USE_USBUTILS
  1205. usb_all(0);
  1206. #endif
  1207. exit(*ndevs);
  1208. }
  1209. #endif
  1210. /* These options are available from commandline only */
  1211. static struct opt_table opt_cmdline_table[] = {
  1212. OPT_WITH_ARG("--config|-c",
  1213. load_config, NULL, NULL,
  1214. "Load a JSON-format configuration file\n"
  1215. "See example.conf for an example configuration."),
  1216. OPT_WITH_ARG("--default-config",
  1217. set_default_config, NULL, NULL,
  1218. "Specify the filename of the default config file\n"
  1219. "Loaded at start and used when saving without a name."),
  1220. OPT_WITHOUT_ARG("--help|-h",
  1221. opt_verusage_and_exit, NULL,
  1222. "Print this message"),
  1223. #if defined(HAVE_OPENCL) || defined(USE_USBUTILS)
  1224. OPT_WITHOUT_ARG("--ndevs|-n",
  1225. display_devs, &nDevs,
  1226. "Display "
  1227. #ifdef HAVE_OPENCL
  1228. "number of detected GPUs, OpenCL platform information, "
  1229. #endif
  1230. #ifdef USE_USBUTILS
  1231. "all USB devices, "
  1232. #endif
  1233. "and exit"),
  1234. #endif
  1235. OPT_WITHOUT_ARG("--version|-V",
  1236. opt_version_and_exit, packagename,
  1237. "Display version and exit"),
  1238. OPT_ENDTABLE
  1239. };
  1240. static bool jobj_binary(const json_t *obj, const char *key,
  1241. void *buf, size_t buflen, bool required)
  1242. {
  1243. const char *hexstr;
  1244. json_t *tmp;
  1245. tmp = json_object_get(obj, key);
  1246. if (unlikely(!tmp)) {
  1247. if (unlikely(required))
  1248. applog(LOG_ERR, "JSON key '%s' not found", key);
  1249. return false;
  1250. }
  1251. hexstr = json_string_value(tmp);
  1252. if (unlikely(!hexstr)) {
  1253. applog(LOG_ERR, "JSON key '%s' is not a string", key);
  1254. return false;
  1255. }
  1256. if (!hex2bin(buf, hexstr, buflen))
  1257. return false;
  1258. return true;
  1259. }
  1260. static void calc_midstate(struct work *work)
  1261. {
  1262. union {
  1263. unsigned char c[64];
  1264. uint32_t i[16];
  1265. } data;
  1266. int swapcounter;
  1267. for (swapcounter = 0; swapcounter < 16; swapcounter++)
  1268. data.i[swapcounter] = swab32(((uint32_t*) (work->data))[swapcounter]);
  1269. sha2_context ctx;
  1270. sha2_starts(&ctx);
  1271. sha2_update(&ctx, data.c, 64);
  1272. memcpy(work->midstate, ctx.state, sizeof(work->midstate));
  1273. #if defined(__BIG_ENDIAN__) || defined(MIPSEB)
  1274. int i;
  1275. for (i = 0; i < 8; i++)
  1276. (((uint32_t*) (work->midstate))[i]) = swab32(((uint32_t*) (work->midstate))[i]);
  1277. #endif
  1278. }
  1279. static struct work *make_work(void)
  1280. {
  1281. struct work *work = calloc(1, sizeof(struct work));
  1282. if (unlikely(!work))
  1283. quit(1, "Failed to calloc work in make_work");
  1284. cg_wlock(&control_lock);
  1285. work->id = total_work++;
  1286. cg_wunlock(&control_lock);
  1287. return work;
  1288. }
  1289. /* This is the central place all work that is about to be retired should be
  1290. * cleaned to remove any dynamically allocated arrays within the struct */
  1291. void clean_work(struct work *work)
  1292. {
  1293. free(work->job_id);
  1294. free(work->nonce2);
  1295. free(work->ntime);
  1296. free(work->gbt_coinbase);
  1297. free(work->nonce1);
  1298. memset(work, 0, sizeof(struct work));
  1299. }
  1300. /* All dynamically allocated work structs should be freed here to not leak any
  1301. * ram from arrays allocated within the work struct */
  1302. void free_work(struct work *work)
  1303. {
  1304. clean_work(work);
  1305. free(work);
  1306. }
  1307. /* Generate a GBT coinbase from the existing GBT variables stored. Must be
  1308. * entered under gbt_lock */
  1309. static void __build_gbt_coinbase(struct pool *pool)
  1310. {
  1311. unsigned char *coinbase;
  1312. int cbt_len, orig_len;
  1313. uint8_t *extra_len;
  1314. size_t cal_len;
  1315. cbt_len = strlen(pool->coinbasetxn) / 2;
  1316. pool->coinbase_len = cbt_len + 4;
  1317. /* We add 4 bytes of extra data corresponding to nonce2 of stratum */
  1318. cal_len = pool->coinbase_len + 1;
  1319. align_len(&cal_len);
  1320. coinbase = calloc(cal_len, 1);
  1321. hex2bin(coinbase, pool->coinbasetxn, 42);
  1322. extra_len = (uint8_t *)(coinbase + 41);
  1323. orig_len = *extra_len;
  1324. hex2bin(coinbase + 42, pool->coinbasetxn + 84, orig_len);
  1325. memcpy(coinbase + 42 + orig_len, &pool->nonce2, 4);
  1326. *extra_len += 4;
  1327. hex2bin(coinbase + 42 + *extra_len, pool->coinbasetxn + 84 + (orig_len * 2), cbt_len - orig_len - 42);
  1328. pool->nonce2++;
  1329. free(pool->gbt_coinbase);
  1330. pool->gbt_coinbase = coinbase;
  1331. }
  1332. static void gen_hash(unsigned char *data, unsigned char *hash, int len);
  1333. /* Process transactions with GBT by storing the binary value of the first
  1334. * transaction, and the hashes of the remaining transactions since these
  1335. * remain constant with an altered coinbase when generating work. Must be
  1336. * entered under gbt_lock */
  1337. static bool __build_gbt_txns(struct pool *pool, json_t *res_val)
  1338. {
  1339. json_t *txn_array;
  1340. bool ret = false;
  1341. size_t cal_len;
  1342. int i;
  1343. free(pool->txn_hashes);
  1344. pool->txn_hashes = NULL;
  1345. pool->gbt_txns = 0;
  1346. txn_array = json_object_get(res_val, "transactions");
  1347. if (!json_is_array(txn_array))
  1348. goto out;
  1349. ret = true;
  1350. pool->gbt_txns = json_array_size(txn_array);
  1351. if (!pool->gbt_txns)
  1352. goto out;
  1353. pool->txn_hashes = calloc(32 * (pool->gbt_txns + 1), 1);
  1354. if (unlikely(!pool->txn_hashes))
  1355. quit(1, "Failed to calloc txn_hashes in __build_gbt_txns");
  1356. for (i = 0; i < pool->gbt_txns; i++) {
  1357. json_t *txn_val = json_object_get(json_array_get(txn_array, i), "data");
  1358. const char *txn = json_string_value(txn_val);
  1359. int txn_len = strlen(txn);
  1360. unsigned char *txn_bin;
  1361. cal_len = txn_len;
  1362. align_len(&cal_len);
  1363. txn_bin = calloc(cal_len, 1);
  1364. if (unlikely(!txn_bin))
  1365. quit(1, "Failed to calloc txn_bin in __build_gbt_txns");
  1366. if (unlikely(!hex2bin(txn_bin, txn, txn_len / 2)))
  1367. quit(1, "Failed to hex2bin txn_bin");
  1368. gen_hash(txn_bin, pool->txn_hashes + (32 * i), txn_len / 2);
  1369. free(txn_bin);
  1370. }
  1371. out:
  1372. return ret;
  1373. }
  1374. static unsigned char *__gbt_merkleroot(struct pool *pool)
  1375. {
  1376. unsigned char *merkle_hash;
  1377. int i, txns;
  1378. merkle_hash = calloc(32 * (pool->gbt_txns + 2), 1);
  1379. if (unlikely(!merkle_hash))
  1380. quit(1, "Failed to calloc merkle_hash in __gbt_merkleroot");
  1381. gen_hash(pool->gbt_coinbase, merkle_hash, pool->coinbase_len);
  1382. if (pool->gbt_txns)
  1383. memcpy(merkle_hash + 32, pool->txn_hashes, pool->gbt_txns * 32);
  1384. txns = pool->gbt_txns + 1;
  1385. while (txns > 1) {
  1386. if (txns % 2) {
  1387. memcpy(&merkle_hash[txns * 32], &merkle_hash[(txns - 1) * 32], 32);
  1388. txns++;
  1389. }
  1390. for (i = 0; i < txns; i += 2){
  1391. unsigned char hashout[32];
  1392. gen_hash(merkle_hash + (i * 32), hashout, 64);
  1393. memcpy(merkle_hash + (i / 2 * 32), hashout, 32);
  1394. }
  1395. txns /= 2;
  1396. }
  1397. return merkle_hash;
  1398. }
  1399. static void calc_diff(struct work *work, int known);
  1400. static bool work_decode(struct pool *pool, struct work *work, json_t *val);
  1401. static void update_gbt(struct pool *pool)
  1402. {
  1403. int rolltime;
  1404. json_t *val;
  1405. CURL *curl;
  1406. curl = curl_easy_init();
  1407. if (unlikely(!curl))
  1408. quit (1, "CURL initialisation failed in update_gbt");
  1409. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass,
  1410. pool->rpc_req, true, false, &rolltime, pool, false);
  1411. if (val) {
  1412. struct work *work = make_work();
  1413. bool rc = work_decode(pool, work, val);
  1414. total_getworks++;
  1415. pool->getwork_requested++;
  1416. if (rc) {
  1417. applog(LOG_DEBUG, "Successfully retrieved and updated GBT from pool %u %s",
  1418. pool->pool_no, pool->rpc_url);
  1419. gettimeofday(&pool->tv_idle, NULL);
  1420. } else {
  1421. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher GBT from pool %u %s",
  1422. pool->pool_no, pool->rpc_url);
  1423. }
  1424. json_decref(val);
  1425. free_work(work);
  1426. } else {
  1427. applog(LOG_DEBUG, "FAILED to update GBT from pool %u %s",
  1428. pool->pool_no, pool->rpc_url);
  1429. }
  1430. curl_easy_cleanup(curl);
  1431. }
  1432. static char *workpadding = "000000800000000000000000000000000000000000000000000000000000000000000000000000000000000080020000";
  1433. static void gen_gbt_work(struct pool *pool, struct work *work)
  1434. {
  1435. unsigned char *merkleroot;
  1436. struct timeval now;
  1437. gettimeofday(&now, NULL);
  1438. if (now.tv_sec - pool->tv_lastwork.tv_sec > 60)
  1439. update_gbt(pool);
  1440. cg_ilock(&pool->gbt_lock);
  1441. __build_gbt_coinbase(pool);
  1442. cg_dlock(&pool->gbt_lock);
  1443. merkleroot = __gbt_merkleroot(pool);
  1444. memcpy(work->data, &pool->gbt_version, 4);
  1445. memcpy(work->data + 4, pool->previousblockhash, 32);
  1446. memcpy(work->data + 4 + 32 + 32, &pool->curtime, 4);
  1447. memcpy(work->data + 4 + 32 + 32 + 4, &pool->gbt_bits, 4);
  1448. memcpy(work->target, pool->gbt_target, 32);
  1449. work->gbt_coinbase = bin2hex(pool->gbt_coinbase, pool->coinbase_len);
  1450. /* For encoding the block data on submission */
  1451. work->gbt_txns = pool->gbt_txns + 1;
  1452. if (pool->gbt_workid)
  1453. work->job_id = strdup(pool->gbt_workid);
  1454. cg_runlock(&pool->gbt_lock);
  1455. memcpy(work->data + 4 + 32, merkleroot, 32);
  1456. flip32(work->data + 4 + 32, merkleroot);
  1457. free(merkleroot);
  1458. memset(work->data + 4 + 32 + 32 + 4 + 4, 0, 4); /* nonce */
  1459. hex2bin(work->data + 4 + 32 + 32 + 4 + 4 + 4, workpadding, 48);
  1460. if (opt_debug) {
  1461. char *header = bin2hex(work->data, 128);
  1462. applog(LOG_DEBUG, "Generated GBT header %s", header);
  1463. applog(LOG_DEBUG, "Work coinbase %s", work->gbt_coinbase);
  1464. free(header);
  1465. }
  1466. calc_midstate(work);
  1467. local_work++;
  1468. work->pool = pool;
  1469. work->gbt = true;
  1470. work->id = total_work++;
  1471. work->longpoll = false;
  1472. work->getwork_mode = GETWORK_MODE_GBT;
  1473. work->work_block = work_block;
  1474. calc_diff(work, 0);
  1475. gettimeofday(&work->tv_staged, NULL);
  1476. }
  1477. static bool gbt_decode(struct pool *pool, json_t *res_val)
  1478. {
  1479. const char *previousblockhash;
  1480. const char *target;
  1481. const char *coinbasetxn;
  1482. const char *longpollid;
  1483. unsigned char hash_swap[32];
  1484. int expires;
  1485. int version;
  1486. int curtime;
  1487. bool submitold;
  1488. const char *bits;
  1489. const char *workid;
  1490. previousblockhash = json_string_value(json_object_get(res_val, "previousblockhash"));
  1491. target = json_string_value(json_object_get(res_val, "target"));
  1492. coinbasetxn = json_string_value(json_object_get(json_object_get(res_val, "coinbasetxn"), "data"));
  1493. longpollid = json_string_value(json_object_get(res_val, "longpollid"));
  1494. expires = json_integer_value(json_object_get(res_val, "expires"));
  1495. version = json_integer_value(json_object_get(res_val, "version"));
  1496. curtime = json_integer_value(json_object_get(res_val, "curtime"));
  1497. submitold = json_is_true(json_object_get(res_val, "submitold"));
  1498. bits = json_string_value(json_object_get(res_val, "bits"));
  1499. workid = json_string_value(json_object_get(res_val, "workid"));
  1500. if (!previousblockhash || !target || !coinbasetxn || !longpollid ||
  1501. !expires || !version || !curtime || !bits) {
  1502. applog(LOG_ERR, "JSON failed to decode GBT");
  1503. return false;
  1504. }
  1505. applog(LOG_DEBUG, "previousblockhash: %s", previousblockhash);
  1506. applog(LOG_DEBUG, "target: %s", target);
  1507. applog(LOG_DEBUG, "coinbasetxn: %s", coinbasetxn);
  1508. applog(LOG_DEBUG, "longpollid: %s", longpollid);
  1509. applog(LOG_DEBUG, "expires: %d", expires);
  1510. applog(LOG_DEBUG, "version: %d", version);
  1511. applog(LOG_DEBUG, "curtime: %d", curtime);
  1512. applog(LOG_DEBUG, "submitold: %s", submitold ? "true" : "false");
  1513. applog(LOG_DEBUG, "bits: %s", bits);
  1514. if (workid)
  1515. applog(LOG_DEBUG, "workid: %s", workid);
  1516. cg_wlock(&pool->gbt_lock);
  1517. free(pool->coinbasetxn);
  1518. pool->coinbasetxn = strdup(coinbasetxn);
  1519. free(pool->longpollid);
  1520. pool->longpollid = strdup(longpollid);
  1521. free(pool->gbt_workid);
  1522. if (workid)
  1523. pool->gbt_workid = strdup(workid);
  1524. else
  1525. pool->gbt_workid = NULL;
  1526. hex2bin(hash_swap, previousblockhash, 32);
  1527. swap256(pool->previousblockhash, hash_swap);
  1528. hex2bin(hash_swap, target, 32);
  1529. swab256(pool->gbt_target, hash_swap);
  1530. pool->gbt_expires = expires;
  1531. pool->gbt_version = htobe32(version);
  1532. pool->curtime = htobe32(curtime);
  1533. pool->submit_old = submitold;
  1534. hex2bin((unsigned char *)&pool->gbt_bits, bits, 4);
  1535. __build_gbt_txns(pool, res_val);
  1536. cg_wunlock(&pool->gbt_lock);
  1537. return true;
  1538. }
  1539. static bool getwork_decode(json_t *res_val, struct work *work)
  1540. {
  1541. if (unlikely(!jobj_binary(res_val, "data", work->data, sizeof(work->data), true))) {
  1542. applog(LOG_ERR, "JSON inval data");
  1543. return false;
  1544. }
  1545. if (!jobj_binary(res_val, "midstate", work->midstate, sizeof(work->midstate), false)) {
  1546. // Calculate it ourselves
  1547. applog(LOG_DEBUG, "Calculating midstate locally");
  1548. calc_midstate(work);
  1549. }
  1550. if (unlikely(!jobj_binary(res_val, "target", work->target, sizeof(work->target), true))) {
  1551. applog(LOG_ERR, "JSON inval target");
  1552. return false;
  1553. }
  1554. return true;
  1555. }
  1556. static bool work_decode(struct pool *pool, struct work *work, json_t *val)
  1557. {
  1558. json_t *res_val = json_object_get(val, "result");
  1559. bool ret = false;
  1560. gettimeofday(&pool->tv_lastwork, NULL);
  1561. if (!res_val || json_is_null(res_val)) {
  1562. applog(LOG_ERR, "JSON Failed to decode result");
  1563. goto out;
  1564. }
  1565. if (pool->has_gbt) {
  1566. if (unlikely(!gbt_decode(pool, res_val)))
  1567. goto out;
  1568. work->gbt = true;
  1569. ret = true;
  1570. goto out;
  1571. } else if (unlikely(!getwork_decode(res_val, work)))
  1572. goto out;
  1573. memset(work->hash, 0, sizeof(work->hash));
  1574. gettimeofday(&work->tv_staged, NULL);
  1575. ret = true;
  1576. out:
  1577. return ret;
  1578. }
  1579. int dev_from_id(int thr_id)
  1580. {
  1581. struct cgpu_info *cgpu = get_thr_cgpu(thr_id);
  1582. return cgpu->device_id;
  1583. }
  1584. /* Make the change in the recent value adjust dynamically when the difference
  1585. * is large, but damp it when the values are closer together. This allows the
  1586. * value to change quickly, but not fluctuate too dramatically when it has
  1587. * stabilised. */
  1588. void decay_time(double *f, double fadd)
  1589. {
  1590. double ratio = 0;
  1591. if (likely(*f > 0)) {
  1592. ratio = fadd / *f;
  1593. if (ratio > 1)
  1594. ratio = 1 / ratio;
  1595. }
  1596. if (ratio > 0.63)
  1597. *f = (fadd * 0.58 + *f) / 1.58;
  1598. else
  1599. *f = (fadd + *f * 0.58) / 1.58;
  1600. }
  1601. static int __total_staged(void)
  1602. {
  1603. return HASH_COUNT(staged_work);
  1604. }
  1605. static int total_staged(void)
  1606. {
  1607. int ret;
  1608. mutex_lock(stgd_lock);
  1609. ret = __total_staged();
  1610. mutex_unlock(stgd_lock);
  1611. return ret;
  1612. }
  1613. #ifdef HAVE_CURSES
  1614. WINDOW *mainwin, *statuswin, *logwin;
  1615. #endif
  1616. double total_secs = 1.0;
  1617. static char statusline[256];
  1618. /* logstart is where the log window should start */
  1619. static int devcursor, logstart, logcursor;
  1620. #ifdef HAVE_CURSES
  1621. /* statusy is where the status window goes up to in cases where it won't fit at startup */
  1622. static int statusy;
  1623. #endif
  1624. #ifdef HAVE_OPENCL
  1625. struct cgpu_info gpus[MAX_GPUDEVICES]; /* Maximum number apparently possible */
  1626. #endif
  1627. struct cgpu_info *cpus;
  1628. #ifdef HAVE_CURSES
  1629. static inline void unlock_curses(void)
  1630. {
  1631. mutex_unlock(&console_lock);
  1632. }
  1633. static inline void lock_curses(void)
  1634. {
  1635. mutex_lock(&console_lock);
  1636. }
  1637. static bool curses_active_locked(void)
  1638. {
  1639. bool ret;
  1640. lock_curses();
  1641. ret = curses_active;
  1642. if (!ret)
  1643. unlock_curses();
  1644. return ret;
  1645. }
  1646. #endif
  1647. void tailsprintf(char *f, const char *fmt, ...)
  1648. {
  1649. va_list ap;
  1650. va_start(ap, fmt);
  1651. vsprintf(f + strlen(f), fmt, ap);
  1652. va_end(ap);
  1653. }
  1654. /* Convert a uint64_t value into a truncated string for displaying with its
  1655. * associated suitable for Mega, Giga etc. Buf array needs to be long enough */
  1656. static void suffix_string(uint64_t val, char *buf, int sigdigits)
  1657. {
  1658. const double dkilo = 1000.0;
  1659. const uint64_t kilo = 1000ull;
  1660. const uint64_t mega = 1000000ull;
  1661. const uint64_t giga = 1000000000ull;
  1662. const uint64_t tera = 1000000000000ull;
  1663. const uint64_t peta = 1000000000000000ull;
  1664. const uint64_t exa = 1000000000000000000ull;
  1665. char suffix[2] = "";
  1666. bool decimal = true;
  1667. double dval;
  1668. if (val >= exa) {
  1669. val /= peta;
  1670. dval = (double)val / dkilo;
  1671. sprintf(suffix, "E");
  1672. } else if (val >= peta) {
  1673. val /= tera;
  1674. dval = (double)val / dkilo;
  1675. sprintf(suffix, "P");
  1676. } else if (val >= tera) {
  1677. val /= giga;
  1678. dval = (double)val / dkilo;
  1679. sprintf(suffix, "T");
  1680. } else if (val >= giga) {
  1681. val /= mega;
  1682. dval = (double)val / dkilo;
  1683. sprintf(suffix, "G");
  1684. } else if (val >= mega) {
  1685. val /= kilo;
  1686. dval = (double)val / dkilo;
  1687. sprintf(suffix, "M");
  1688. } else if (val >= kilo) {
  1689. dval = (double)val / dkilo;
  1690. sprintf(suffix, "K");
  1691. } else {
  1692. dval = val;
  1693. decimal = false;
  1694. }
  1695. if (!sigdigits) {
  1696. if (decimal)
  1697. sprintf(buf, "%.3g%s", dval, suffix);
  1698. else
  1699. sprintf(buf, "%d%s", (unsigned int)dval, suffix);
  1700. } else {
  1701. /* Always show sigdigits + 1, padded on right with zeroes
  1702. * followed by suffix */
  1703. int ndigits = sigdigits - 1 - (dval > 0.0 ? floor(log10(dval)) : 0);
  1704. sprintf(buf, "%*.*f%s", sigdigits + 1, ndigits, dval, suffix);
  1705. }
  1706. }
  1707. static void get_statline(char *buf, struct cgpu_info *cgpu)
  1708. {
  1709. char displayed_hashes[16], displayed_rolling[16];
  1710. uint64_t dh64, dr64;
  1711. dh64 = (double)cgpu->total_mhashes / total_secs * 1000000ull;
  1712. dr64 = (double)cgpu->rolling * 1000000ull;
  1713. suffix_string(dh64, displayed_hashes, 4);
  1714. suffix_string(dr64, displayed_rolling, 4);
  1715. sprintf(buf, "%s%d ", cgpu->drv->name, cgpu->device_id);
  1716. cgpu->drv->get_statline_before(buf, cgpu);
  1717. tailsprintf(buf, "(%ds):%s (avg):%sh/s | A:%d R:%d HW:%d U:%.1f/m",
  1718. opt_log_interval,
  1719. displayed_rolling,
  1720. displayed_hashes,
  1721. cgpu->accepted,
  1722. cgpu->rejected,
  1723. cgpu->hw_errors,
  1724. cgpu->utility);
  1725. cgpu->drv->get_statline(buf, cgpu);
  1726. }
  1727. static void text_print_status(int thr_id)
  1728. {
  1729. struct cgpu_info *cgpu;
  1730. char logline[256];
  1731. cgpu = get_thr_cgpu(thr_id);
  1732. if (cgpu) {
  1733. get_statline(logline, cgpu);
  1734. printf("%s\n", logline);
  1735. }
  1736. }
  1737. #ifdef HAVE_CURSES
  1738. /* Must be called with curses mutex lock held and curses_active */
  1739. static void curses_print_status(void)
  1740. {
  1741. struct pool *pool = current_pool();
  1742. wattron(statuswin, A_BOLD);
  1743. mvwprintw(statuswin, 0, 0, " " PACKAGE " version " VERSION " - Started: %s", datestamp);
  1744. #ifdef WANT_CPUMINE
  1745. if (opt_n_threads)
  1746. wprintw(statuswin, " CPU Algo: %s", algo_names[opt_algo]);
  1747. #endif
  1748. wattroff(statuswin, A_BOLD);
  1749. mvwhline(statuswin, 1, 0, '-', 80);
  1750. mvwprintw(statuswin, 2, 0, " %s", statusline);
  1751. wclrtoeol(statuswin);
  1752. mvwprintw(statuswin, 3, 0, " ST: %d SS: %d NB: %d LW: %d GF: %d RF: %d",
  1753. total_staged(), total_stale, new_blocks,
  1754. local_work, total_go, total_ro);
  1755. wclrtoeol(statuswin);
  1756. if ((pool_strategy == POOL_LOADBALANCE || pool_strategy == POOL_BALANCE) && total_pools > 1) {
  1757. mvwprintw(statuswin, 4, 0, " Connected to multiple pools with%s LP",
  1758. have_longpoll ? "": "out");
  1759. } else if (pool->has_stratum) {
  1760. mvwprintw(statuswin, 4, 0, " Connected to %s diff %s with stratum as user %s",
  1761. pool->sockaddr_url, pool->diff, pool->rpc_user);
  1762. } else {
  1763. mvwprintw(statuswin, 4, 0, " Connected to %s diff %s with%s %s as user %s",
  1764. pool->sockaddr_url, pool->diff, have_longpoll ? "": "out",
  1765. pool->has_gbt ? "GBT" : "LP", pool->rpc_user);
  1766. }
  1767. wclrtoeol(statuswin);
  1768. cg_rlock(&ch_lock);
  1769. mvwprintw(statuswin, 5, 0, " Block: %s... Diff:%s Started: %s Best share: %s ",
  1770. current_hash, block_diff, blocktime, best_share);
  1771. cg_runlock(&ch_lock);
  1772. mvwhline(statuswin, 6, 0, '-', 80);
  1773. mvwhline(statuswin, statusy - 1, 0, '-', 80);
  1774. mvwprintw(statuswin, devcursor - 1, 1, "[P]ool management %s[S]ettings [D]isplay options [Q]uit",
  1775. have_opencl ? "[G]PU management " : "");
  1776. }
  1777. static void adj_width(int var, int *length)
  1778. {
  1779. if ((int)(log10(var) + 1) > *length)
  1780. (*length)++;
  1781. }
  1782. static int dev_width;
  1783. static void curses_print_devstatus(int thr_id)
  1784. {
  1785. static int awidth = 1, rwidth = 1, hwwidth = 1, uwidth = 1;
  1786. struct cgpu_info *cgpu;
  1787. char logline[256];
  1788. char displayed_hashes[16], displayed_rolling[16];
  1789. uint64_t dh64, dr64;
  1790. if (opt_compact)
  1791. return;
  1792. cgpu = get_thr_cgpu(thr_id);
  1793. if (cgpu->cgminer_id >= start_devices || devcursor + cgpu->cgminer_id > LINES - 2)
  1794. return;
  1795. cgpu->utility = cgpu->accepted / total_secs * 60;
  1796. wmove(statuswin,devcursor + cgpu->cgminer_id, 0);
  1797. wprintw(statuswin, " %s %*d: ", cgpu->drv->name, dev_width, cgpu->device_id);
  1798. logline[0] = '\0';
  1799. cgpu->drv->get_statline_before(logline, cgpu);
  1800. wprintw(statuswin, "%s", logline);
  1801. dh64 = (double)cgpu->total_mhashes / total_secs * 1000000ull;
  1802. dr64 = (double)cgpu->rolling * 1000000ull;
  1803. suffix_string(dh64, displayed_hashes, 4);
  1804. suffix_string(dr64, displayed_rolling, 4);
  1805. #ifdef USE_USBUTILS
  1806. if (cgpu->usbinfo.nodev)
  1807. wprintw(statuswin, "ZOMBIE");
  1808. else
  1809. #endif
  1810. if (cgpu->status == LIFE_DEAD)
  1811. wprintw(statuswin, "DEAD ");
  1812. else if (cgpu->status == LIFE_SICK)
  1813. wprintw(statuswin, "SICK ");
  1814. else if (cgpu->deven == DEV_DISABLED)
  1815. wprintw(statuswin, "OFF ");
  1816. else if (cgpu->deven == DEV_RECOVER)
  1817. wprintw(statuswin, "REST ");
  1818. else
  1819. wprintw(statuswin, "%6s", displayed_rolling);
  1820. adj_width(cgpu->accepted, &awidth);
  1821. adj_width(cgpu->rejected, &rwidth);
  1822. adj_width(cgpu->hw_errors, &hwwidth);
  1823. adj_width(cgpu->utility, &uwidth);
  1824. wprintw(statuswin, "/%6sh/s | A:%*d R:%*d HW:%*d U:%*.2f/m",
  1825. displayed_hashes,
  1826. awidth, cgpu->accepted,
  1827. rwidth, cgpu->rejected,
  1828. hwwidth, cgpu->hw_errors,
  1829. uwidth + 3, cgpu->utility);
  1830. logline[0] = '\0';
  1831. cgpu->drv->get_statline(logline, cgpu);
  1832. wprintw(statuswin, "%s", logline);
  1833. wclrtoeol(statuswin);
  1834. }
  1835. #endif
  1836. static void print_status(int thr_id)
  1837. {
  1838. if (!curses_active)
  1839. text_print_status(thr_id);
  1840. }
  1841. #ifdef HAVE_CURSES
  1842. /* Check for window resize. Called with curses mutex locked */
  1843. static inline void change_logwinsize(void)
  1844. {
  1845. int x, y, logx, logy;
  1846. getmaxyx(mainwin, y, x);
  1847. if (x < 80 || y < 25)
  1848. return;
  1849. if (y > statusy + 2 && statusy < logstart) {
  1850. if (y - 2 < logstart)
  1851. statusy = y - 2;
  1852. else
  1853. statusy = logstart;
  1854. logcursor = statusy + 1;
  1855. mvwin(logwin, logcursor, 0);
  1856. wresize(statuswin, statusy, x);
  1857. }
  1858. y -= logcursor;
  1859. getmaxyx(logwin, logy, logx);
  1860. /* Detect screen size change */
  1861. if (x != logx || y != logy)
  1862. wresize(logwin, y, x);
  1863. }
  1864. static void check_winsizes(void)
  1865. {
  1866. if (!use_curses)
  1867. return;
  1868. if (curses_active_locked()) {
  1869. int y, x;
  1870. erase();
  1871. x = getmaxx(statuswin);
  1872. if (logstart > LINES - 2)
  1873. statusy = LINES - 2;
  1874. else
  1875. statusy = logstart;
  1876. logcursor = statusy + 1;
  1877. wresize(statuswin, statusy, x);
  1878. getmaxyx(mainwin, y, x);
  1879. y -= logcursor;
  1880. wresize(logwin, y, x);
  1881. mvwin(logwin, logcursor, 0);
  1882. unlock_curses();
  1883. }
  1884. }
  1885. static void switch_compact(void)
  1886. {
  1887. if (opt_compact) {
  1888. logstart = devcursor + 1;
  1889. logcursor = logstart + 1;
  1890. } else {
  1891. logstart = devcursor + total_devices + 1;
  1892. logcursor = logstart + 1;
  1893. }
  1894. check_winsizes();
  1895. }
  1896. /* For mandatory printing when mutex is already locked */
  1897. void wlog(const char *f, ...)
  1898. {
  1899. va_list ap;
  1900. va_start(ap, f);
  1901. vw_printw(logwin, f, ap);
  1902. va_end(ap);
  1903. }
  1904. /* Mandatory printing */
  1905. void wlogprint(const char *f, ...)
  1906. {
  1907. va_list ap;
  1908. if (curses_active_locked()) {
  1909. va_start(ap, f);
  1910. vw_printw(logwin, f, ap);
  1911. va_end(ap);
  1912. unlock_curses();
  1913. }
  1914. }
  1915. #endif
  1916. #ifdef HAVE_CURSES
  1917. bool log_curses_only(int prio, const char *f, va_list ap)
  1918. {
  1919. bool high_prio;
  1920. high_prio = (prio == LOG_WARNING || prio == LOG_ERR);
  1921. if (curses_active_locked()) {
  1922. if (!opt_loginput || high_prio) {
  1923. vw_printw(logwin, f, ap);
  1924. if (high_prio) {
  1925. touchwin(logwin);
  1926. wrefresh(logwin);
  1927. }
  1928. }
  1929. unlock_curses();
  1930. return true;
  1931. }
  1932. return false;
  1933. }
  1934. void clear_logwin(void)
  1935. {
  1936. if (curses_active_locked()) {
  1937. erase();
  1938. wclear(logwin);
  1939. unlock_curses();
  1940. }
  1941. }
  1942. #endif
  1943. /* Returns true if the regenerated work->hash solves a block */
  1944. static bool solves_block(const struct work *work)
  1945. {
  1946. uint32_t *hash32 = (uint32_t *)(work->hash);
  1947. uint32_t difficulty = 0;
  1948. uint32_t diffbytes = 0;
  1949. uint32_t diffvalue = 0;
  1950. uint32_t diffcmp[8];
  1951. int diffshift = 0;
  1952. int i;
  1953. difficulty = swab32(*((uint32_t *)(work->data + 72)));
  1954. diffbytes = ((difficulty >> 24) & 0xff) - 3;
  1955. diffvalue = difficulty & 0x00ffffff;
  1956. diffshift = (diffbytes % 4) * 8;
  1957. if (diffshift == 0) {
  1958. diffshift = 32;
  1959. diffbytes--;
  1960. }
  1961. memset(diffcmp, 0, 32);
  1962. diffbytes >>= 2;
  1963. /* Sanity check looking for overflow */
  1964. if (unlikely(diffbytes > 6))
  1965. return false;
  1966. diffcmp[diffbytes + 1] = diffvalue >> (32 - diffshift);
  1967. diffcmp[diffbytes] = diffvalue << diffshift;
  1968. for (i = 7; i >= 0; i--) {
  1969. if (hash32[i] > diffcmp[i])
  1970. return false;
  1971. if (hash32[i] < diffcmp[i])
  1972. return true;
  1973. }
  1974. // https://en.bitcoin.it/wiki/Block says: "numerically below"
  1975. // https://en.bitcoin.it/wiki/Target says: "lower than or equal to"
  1976. // code in bitcoind 0.3.24 main.cpp CheckWork() says: if (hash > hashTarget) return false;
  1977. if (hash32[0] == diffcmp[0])
  1978. return true;
  1979. else
  1980. return false;
  1981. }
  1982. static void enable_pool(struct pool *pool)
  1983. {
  1984. if (pool->enabled != POOL_ENABLED) {
  1985. enabled_pools++;
  1986. pool->enabled = POOL_ENABLED;
  1987. }
  1988. }
  1989. static void disable_pool(struct pool *pool)
  1990. {
  1991. if (pool->enabled == POOL_ENABLED)
  1992. enabled_pools--;
  1993. pool->enabled = POOL_DISABLED;
  1994. }
  1995. static void reject_pool(struct pool *pool)
  1996. {
  1997. if (pool->enabled == POOL_ENABLED)
  1998. enabled_pools--;
  1999. pool->enabled = POOL_REJECTING;
  2000. }
  2001. /* Theoretically threads could race when modifying accepted and
  2002. * rejected values but the chance of two submits completing at the
  2003. * same time is zero so there is no point adding extra locking */
  2004. static void
  2005. share_result(json_t *val, json_t *res, json_t *err, const struct work *work,
  2006. char *hashshow, bool resubmit, char *worktime)
  2007. {
  2008. struct pool *pool = work->pool;
  2009. struct cgpu_info *cgpu;
  2010. cgpu = get_thr_cgpu(work->thr_id);
  2011. if (json_is_true(res) || (work->gbt && json_is_null(res))) {
  2012. mutex_lock(&stats_lock);
  2013. cgpu->accepted++;
  2014. total_accepted++;
  2015. pool->accepted++;
  2016. cgpu->diff_accepted += work->work_difficulty;
  2017. total_diff_accepted += work->work_difficulty;
  2018. pool->diff_accepted += work->work_difficulty;
  2019. mutex_unlock(&stats_lock);
  2020. pool->seq_rejects = 0;
  2021. cgpu->last_share_pool = pool->pool_no;
  2022. cgpu->last_share_pool_time = time(NULL);
  2023. cgpu->last_share_diff = work->work_difficulty;
  2024. pool->last_share_time = cgpu->last_share_pool_time;
  2025. pool->last_share_diff = work->work_difficulty;
  2026. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  2027. if (!QUIET) {
  2028. if (total_pools > 1)
  2029. applog(LOG_NOTICE, "Accepted %s %s %d pool %d %s%s",
  2030. hashshow, cgpu->drv->name, cgpu->device_id, work->pool->pool_no, resubmit ? "(resubmit)" : "", worktime);
  2031. else
  2032. applog(LOG_NOTICE, "Accepted %s %s %d %s%s",
  2033. hashshow, cgpu->drv->name, cgpu->device_id, resubmit ? "(resubmit)" : "", worktime);
  2034. }
  2035. sharelog("accept", work);
  2036. if (opt_shares && total_accepted >= opt_shares) {
  2037. applog(LOG_WARNING, "Successfully mined %d accepted shares as requested and exiting.", opt_shares);
  2038. kill_work();
  2039. return;
  2040. }
  2041. /* Detect if a pool that has been temporarily disabled for
  2042. * continually rejecting shares has started accepting shares.
  2043. * This will only happen with the work returned from a
  2044. * longpoll */
  2045. if (unlikely(pool->enabled == POOL_REJECTING)) {
  2046. applog(LOG_WARNING, "Rejecting pool %d now accepting shares, re-enabling!", pool->pool_no);
  2047. enable_pool(pool);
  2048. switch_pools(NULL);
  2049. }
  2050. } else {
  2051. mutex_lock(&stats_lock);
  2052. cgpu->rejected++;
  2053. total_rejected++;
  2054. pool->rejected++;
  2055. cgpu->diff_rejected += work->work_difficulty;
  2056. total_diff_rejected += work->work_difficulty;
  2057. pool->diff_rejected += work->work_difficulty;
  2058. pool->seq_rejects++;
  2059. mutex_unlock(&stats_lock);
  2060. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  2061. if (!QUIET) {
  2062. char where[20];
  2063. char disposition[36] = "reject";
  2064. char reason[32];
  2065. strcpy(reason, "");
  2066. if (total_pools > 1)
  2067. sprintf(where, "pool %d", work->pool->pool_no);
  2068. else
  2069. strcpy(where, "");
  2070. if (!work->gbt)
  2071. res = json_object_get(val, "reject-reason");
  2072. if (res) {
  2073. const char *reasontmp = json_string_value(res);
  2074. size_t reasonLen = strlen(reasontmp);
  2075. if (reasonLen > 28)
  2076. reasonLen = 28;
  2077. reason[0] = ' '; reason[1] = '(';
  2078. memcpy(2 + reason, reasontmp, reasonLen);
  2079. reason[reasonLen + 2] = ')'; reason[reasonLen + 3] = '\0';
  2080. memcpy(disposition + 7, reasontmp, reasonLen);
  2081. disposition[6] = ':'; disposition[reasonLen + 7] = '\0';
  2082. } else if (work->stratum && err && json_is_array(err)) {
  2083. json_t *reason_val = json_array_get(err, 1);
  2084. char *reason_str;
  2085. if (reason_val && json_is_string(reason_val)) {
  2086. reason_str = (char *)json_string_value(reason_val);
  2087. snprintf(reason, 31, " (%s)", reason_str);
  2088. }
  2089. }
  2090. applog(LOG_NOTICE, "Rejected %s %s %d %s%s %s%s",
  2091. hashshow, cgpu->drv->name, cgpu->device_id, where, reason, resubmit ? "(resubmit)" : "", worktime);
  2092. sharelog(disposition, work);
  2093. }
  2094. /* Once we have more than a nominal amount of sequential rejects,
  2095. * at least 10 and more than 3 mins at the current utility,
  2096. * disable the pool because some pool error is likely to have
  2097. * ensued. Do not do this if we know the share just happened to
  2098. * be stale due to networking delays.
  2099. */
  2100. if (pool->seq_rejects > 10 && !work->stale && opt_disable_pool && enabled_pools > 1) {
  2101. double utility = total_accepted / total_secs * 60;
  2102. if (pool->seq_rejects > utility * 3) {
  2103. applog(LOG_WARNING, "Pool %d rejected %d sequential shares, disabling!",
  2104. pool->pool_no, pool->seq_rejects);
  2105. reject_pool(pool);
  2106. if (pool == current_pool())
  2107. switch_pools(NULL);
  2108. pool->seq_rejects = 0;
  2109. }
  2110. }
  2111. }
  2112. }
  2113. static const uint64_t diffone = 0xFFFF000000000000ull;
  2114. static uint64_t share_diff(const struct work *work)
  2115. {
  2116. uint64_t *data64, d64;
  2117. char rhash[32];
  2118. uint64_t ret;
  2119. swab256(rhash, work->hash);
  2120. if (opt_scrypt)
  2121. data64 = (uint64_t *)(rhash + 2);
  2122. else
  2123. data64 = (uint64_t *)(rhash + 4);
  2124. d64 = be64toh(*data64);
  2125. if (unlikely(!d64))
  2126. d64 = 1;
  2127. ret = diffone / d64;
  2128. cg_wlock(&control_lock);
  2129. if (ret > best_diff) {
  2130. best_diff = ret;
  2131. suffix_string(best_diff, best_share, 0);
  2132. }
  2133. if (ret > work->pool->best_diff)
  2134. work->pool->best_diff = ret;
  2135. cg_wunlock(&control_lock);
  2136. return ret;
  2137. }
  2138. static bool submit_upstream_work(struct work *work, CURL *curl, bool resubmit)
  2139. {
  2140. char *hexstr = NULL;
  2141. json_t *val, *res, *err;
  2142. char *s;
  2143. bool rc = false;
  2144. int thr_id = work->thr_id;
  2145. struct cgpu_info *cgpu;
  2146. struct pool *pool = work->pool;
  2147. int rolltime;
  2148. struct timeval tv_submit, tv_submit_reply;
  2149. char hashshow[64 + 4] = "";
  2150. char worktime[200] = "";
  2151. cgpu = get_thr_cgpu(thr_id);
  2152. #ifdef __BIG_ENDIAN__
  2153. int swapcounter = 0;
  2154. for (swapcounter = 0; swapcounter < 32; swapcounter++)
  2155. (((uint32_t*) (work->data))[swapcounter]) = swab32(((uint32_t*) (work->data))[swapcounter]);
  2156. #endif
  2157. /* build hex string */
  2158. hexstr = bin2hex(work->data, sizeof(work->data));
  2159. /* build JSON-RPC request */
  2160. if (work->gbt) {
  2161. char *gbt_block, *varint;
  2162. unsigned char data[80];
  2163. flip80(data, work->data);
  2164. gbt_block = bin2hex(data, 80);
  2165. if (work->gbt_txns < 0xfd) {
  2166. uint8_t val = work->gbt_txns;
  2167. varint = bin2hex((const unsigned char *)&val, 1);
  2168. } else if (work->gbt_txns <= 0xffff) {
  2169. uint16_t val = htole16(work->gbt_txns);
  2170. gbt_block = realloc_strcat(gbt_block, "fd");
  2171. varint = bin2hex((const unsigned char *)&val, 2);
  2172. } else {
  2173. uint32_t val = htole32(work->gbt_txns);
  2174. gbt_block = realloc_strcat(gbt_block, "fe");
  2175. varint = bin2hex((const unsigned char *)&val, 4);
  2176. }
  2177. gbt_block = realloc_strcat(gbt_block, varint);
  2178. free(varint);
  2179. gbt_block = realloc_strcat(gbt_block, work->gbt_coinbase);
  2180. s = strdup("{\"id\": 0, \"method\": \"submitblock\", \"params\": [\"");
  2181. s = realloc_strcat(s, gbt_block);
  2182. if (work->job_id) {
  2183. s = realloc_strcat(s, "\", {\"workid\": \"");
  2184. s = realloc_strcat(s, work->job_id);
  2185. s = realloc_strcat(s, "\"}]}");
  2186. } else
  2187. s = realloc_strcat(s, "\", {}]}");
  2188. free(gbt_block);
  2189. } else {
  2190. s = strdup("{\"method\": \"getwork\", \"params\": [ \"");
  2191. s = realloc_strcat(s, hexstr);
  2192. s = realloc_strcat(s, "\" ], \"id\":1}");
  2193. }
  2194. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->rpc_url, s);
  2195. s = realloc_strcat(s, "\n");
  2196. gettimeofday(&tv_submit, NULL);
  2197. /* issue JSON-RPC request */
  2198. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, s, false, false, &rolltime, pool, true);
  2199. gettimeofday(&tv_submit_reply, NULL);
  2200. free(s);
  2201. if (unlikely(!val)) {
  2202. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  2203. if (!pool_tset(pool, &pool->submit_fail)) {
  2204. total_ro++;
  2205. pool->remotefail_occasions++;
  2206. applog(LOG_WARNING, "Pool %d communication failure, caching submissions", pool->pool_no);
  2207. }
  2208. nmsleep(5000);
  2209. goto out;
  2210. } else if (pool_tclear(pool, &pool->submit_fail))
  2211. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  2212. res = json_object_get(val, "result");
  2213. err = json_object_get(val, "error");
  2214. if (!QUIET) {
  2215. int intdiff = floor(work->work_difficulty);
  2216. char diffdisp[16], *outhash;
  2217. unsigned char rhash[32];
  2218. uint64_t sharediff;
  2219. swab256(rhash, work->hash);
  2220. if (opt_scrypt)
  2221. outhash = bin2hex(rhash + 2, 4);
  2222. else
  2223. outhash = bin2hex(rhash + 4, 4);
  2224. sharediff = share_diff(work);
  2225. suffix_string(sharediff, diffdisp, 0);
  2226. sprintf(hashshow, "%s Diff %s/%d%s", outhash, diffdisp, intdiff,
  2227. work->block? " BLOCK!" : "");
  2228. free(outhash);
  2229. if (opt_worktime) {
  2230. char workclone[20];
  2231. struct tm *tm, tm_getwork, tm_submit_reply;
  2232. double getwork_time = tdiff((struct timeval *)&(work->tv_getwork_reply),
  2233. (struct timeval *)&(work->tv_getwork));
  2234. double getwork_to_work = tdiff((struct timeval *)&(work->tv_work_start),
  2235. (struct timeval *)&(work->tv_getwork_reply));
  2236. double work_time = tdiff((struct timeval *)&(work->tv_work_found),
  2237. (struct timeval *)&(work->tv_work_start));
  2238. double work_to_submit = tdiff(&tv_submit,
  2239. (struct timeval *)&(work->tv_work_found));
  2240. double submit_time = tdiff(&tv_submit_reply, &tv_submit);
  2241. int diffplaces = 3;
  2242. tm = localtime(&(work->tv_getwork.tv_sec));
  2243. memcpy(&tm_getwork, tm, sizeof(struct tm));
  2244. tm = localtime(&(tv_submit_reply.tv_sec));
  2245. memcpy(&tm_submit_reply, tm, sizeof(struct tm));
  2246. if (work->clone) {
  2247. sprintf(workclone, "C:%1.3f",
  2248. tdiff((struct timeval *)&(work->tv_cloned),
  2249. (struct timeval *)&(work->tv_getwork_reply)));
  2250. }
  2251. else
  2252. strcpy(workclone, "O");
  2253. if (work->work_difficulty < 1)
  2254. diffplaces = 6;
  2255. sprintf(worktime, " <-%08lx.%08lx M:%c D:%1.*f G:%02d:%02d:%02d:%1.3f %s (%1.3f) W:%1.3f (%1.3f) S:%1.3f R:%02d:%02d:%02d",
  2256. (unsigned long)swab32(*(uint32_t *)&(work->data[opt_scrypt ? 32 : 28])),
  2257. (unsigned long)swab32(*(uint32_t *)&(work->data[opt_scrypt ? 28 : 24])),
  2258. work->getwork_mode, diffplaces, work->work_difficulty,
  2259. tm_getwork.tm_hour, tm_getwork.tm_min,
  2260. tm_getwork.tm_sec, getwork_time, workclone,
  2261. getwork_to_work, work_time, work_to_submit, submit_time,
  2262. tm_submit_reply.tm_hour, tm_submit_reply.tm_min,
  2263. tm_submit_reply.tm_sec);
  2264. }
  2265. }
  2266. share_result(val, res, err, work, hashshow, resubmit, worktime);
  2267. cgpu->utility = cgpu->accepted / total_secs * 60;
  2268. if (!opt_realquiet)
  2269. print_status(thr_id);
  2270. if (!want_per_device_stats) {
  2271. char logline[256];
  2272. get_statline(logline, cgpu);
  2273. applog(LOG_INFO, "%s", logline);
  2274. }
  2275. json_decref(val);
  2276. rc = true;
  2277. out:
  2278. free(hexstr);
  2279. return rc;
  2280. }
  2281. /* Specifies whether we can use this pool for work or not. */
  2282. static bool pool_unworkable(struct pool *pool)
  2283. {
  2284. if (pool->idle)
  2285. return true;
  2286. if (pool->enabled != POOL_ENABLED)
  2287. return true;
  2288. if (pool->has_stratum && !pool->stratum_active)
  2289. return true;
  2290. return false;
  2291. }
  2292. /* In balanced mode, the amount of diff1 solutions per pool is monitored as a
  2293. * rolling average per 10 minutes and if pools start getting more, it biases
  2294. * away from them to distribute work evenly. The share count is reset to the
  2295. * rolling average every 10 minutes to not send all work to one pool after it
  2296. * has been disabled/out for an extended period. */
  2297. static struct pool *select_balanced(struct pool *cp)
  2298. {
  2299. int i, lowest = cp->shares;
  2300. struct pool *ret = cp;
  2301. for (i = 0; i < total_pools; i++) {
  2302. struct pool *pool = pools[i];
  2303. if (pool_unworkable(pool))
  2304. continue;
  2305. if (pool->shares < lowest) {
  2306. lowest = pool->shares;
  2307. ret = pool;
  2308. }
  2309. }
  2310. ret->shares++;
  2311. return ret;
  2312. }
  2313. /* Select any active pool in a rotating fashion when loadbalance is chosen */
  2314. static inline struct pool *select_pool(bool lagging)
  2315. {
  2316. static int rotating_pool = 0;
  2317. struct pool *pool, *cp;
  2318. int tested;
  2319. cp = current_pool();
  2320. if (pool_strategy == POOL_BALANCE)
  2321. return select_balanced(cp);
  2322. if (pool_strategy != POOL_LOADBALANCE && (!lagging || opt_fail_only))
  2323. pool = cp;
  2324. else
  2325. pool = NULL;
  2326. /* Try to find the first pool in the rotation that is usable */
  2327. tested = 0;
  2328. while (!pool && tested++ < total_pools) {
  2329. if (++rotating_pool >= total_pools)
  2330. rotating_pool = 0;
  2331. pool = pools[rotating_pool];
  2332. if (!pool_unworkable(pool))
  2333. break;
  2334. pool = NULL;
  2335. }
  2336. /* If still nothing is usable, use the current pool */
  2337. if (!pool)
  2338. pool = cp;
  2339. return pool;
  2340. }
  2341. static double DIFFEXACTONE = 26959946667150639794667015087019630673637144422540572481103610249215.0;
  2342. /*
  2343. * Calculate the work share difficulty
  2344. */
  2345. static void calc_diff(struct work *work, int known)
  2346. {
  2347. struct cgminer_pool_stats *pool_stats = &(work->pool->cgminer_pool_stats);
  2348. double difficulty;
  2349. if (opt_scrypt) {
  2350. uint64_t *data64, d64;
  2351. char rtarget[32];
  2352. swab256(rtarget, work->target);
  2353. data64 = (uint64_t *)(rtarget + 2);
  2354. d64 = be64toh(*data64);
  2355. if (unlikely(!d64))
  2356. d64 = 1;
  2357. work->work_difficulty = diffone / d64;
  2358. } else if (!known) {
  2359. double targ = 0;
  2360. int i;
  2361. for (i = 31; i >= 0; i--) {
  2362. targ *= 256;
  2363. targ += work->target[i];
  2364. }
  2365. work->work_difficulty = DIFFEXACTONE / (targ ? : DIFFEXACTONE);
  2366. } else
  2367. work->work_difficulty = known;
  2368. difficulty = work->work_difficulty;
  2369. pool_stats->last_diff = difficulty;
  2370. suffix_string((uint64_t)difficulty, work->pool->diff, 0);
  2371. if (difficulty == pool_stats->min_diff)
  2372. pool_stats->min_diff_count++;
  2373. else if (difficulty < pool_stats->min_diff || pool_stats->min_diff == 0) {
  2374. pool_stats->min_diff = difficulty;
  2375. pool_stats->min_diff_count = 1;
  2376. }
  2377. if (difficulty == pool_stats->max_diff)
  2378. pool_stats->max_diff_count++;
  2379. else if (difficulty > pool_stats->max_diff) {
  2380. pool_stats->max_diff = difficulty;
  2381. pool_stats->max_diff_count = 1;
  2382. }
  2383. }
  2384. static void get_benchmark_work(struct work *work)
  2385. {
  2386. // Use a random work block pulled from a pool
  2387. static uint8_t bench_block[] = { CGMINER_BENCHMARK_BLOCK };
  2388. size_t bench_size = sizeof(*work);
  2389. size_t work_size = sizeof(bench_block);
  2390. size_t min_size = (work_size < bench_size ? work_size : bench_size);
  2391. memset(work, 0, sizeof(*work));
  2392. memcpy(work, &bench_block, min_size);
  2393. work->mandatory = true;
  2394. work->pool = pools[0];
  2395. gettimeofday(&(work->tv_getwork), NULL);
  2396. memcpy(&(work->tv_getwork_reply), &(work->tv_getwork), sizeof(struct timeval));
  2397. work->getwork_mode = GETWORK_MODE_BENCHMARK;
  2398. calc_diff(work, 0);
  2399. }
  2400. static bool get_upstream_work(struct work *work, CURL *curl)
  2401. {
  2402. struct pool *pool = work->pool;
  2403. struct cgminer_pool_stats *pool_stats = &(pool->cgminer_pool_stats);
  2404. struct timeval tv_elapsed;
  2405. json_t *val = NULL;
  2406. bool rc = false;
  2407. char *url;
  2408. applog(LOG_DEBUG, "DBG: sending %s get RPC call: %s", pool->rpc_url, pool->rpc_req);
  2409. url = pool->rpc_url;
  2410. gettimeofday(&(work->tv_getwork), NULL);
  2411. val = json_rpc_call(curl, url, pool->rpc_userpass, pool->rpc_req, false,
  2412. false, &work->rolltime, pool, false);
  2413. pool_stats->getwork_attempts++;
  2414. if (likely(val)) {
  2415. rc = work_decode(pool, work, val);
  2416. if (unlikely(!rc))
  2417. applog(LOG_DEBUG, "Failed to decode work in get_upstream_work");
  2418. } else
  2419. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  2420. gettimeofday(&(work->tv_getwork_reply), NULL);
  2421. timersub(&(work->tv_getwork_reply), &(work->tv_getwork), &tv_elapsed);
  2422. pool_stats->getwork_wait_rolling += ((double)tv_elapsed.tv_sec + ((double)tv_elapsed.tv_usec / 1000000)) * 0.63;
  2423. pool_stats->getwork_wait_rolling /= 1.63;
  2424. timeradd(&tv_elapsed, &(pool_stats->getwork_wait), &(pool_stats->getwork_wait));
  2425. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_max), >)) {
  2426. pool_stats->getwork_wait_max.tv_sec = tv_elapsed.tv_sec;
  2427. pool_stats->getwork_wait_max.tv_usec = tv_elapsed.tv_usec;
  2428. }
  2429. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_min), <)) {
  2430. pool_stats->getwork_wait_min.tv_sec = tv_elapsed.tv_sec;
  2431. pool_stats->getwork_wait_min.tv_usec = tv_elapsed.tv_usec;
  2432. }
  2433. pool_stats->getwork_calls++;
  2434. work->pool = pool;
  2435. work->longpoll = false;
  2436. work->getwork_mode = GETWORK_MODE_POOL;
  2437. calc_diff(work, 0);
  2438. total_getworks++;
  2439. pool->getwork_requested++;
  2440. if (likely(val))
  2441. json_decref(val);
  2442. return rc;
  2443. }
  2444. #ifdef HAVE_CURSES
  2445. static void disable_curses(void)
  2446. {
  2447. if (curses_active_locked()) {
  2448. curses_active = false;
  2449. leaveok(logwin, false);
  2450. leaveok(statuswin, false);
  2451. leaveok(mainwin, false);
  2452. nocbreak();
  2453. echo();
  2454. delwin(logwin);
  2455. delwin(statuswin);
  2456. delwin(mainwin);
  2457. endwin();
  2458. #ifdef WIN32
  2459. // Move the cursor to after curses output.
  2460. HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
  2461. CONSOLE_SCREEN_BUFFER_INFO csbi;
  2462. COORD coord;
  2463. if (GetConsoleScreenBufferInfo(hout, &csbi)) {
  2464. coord.X = 0;
  2465. coord.Y = csbi.dwSize.Y - 1;
  2466. SetConsoleCursorPosition(hout, coord);
  2467. }
  2468. #endif
  2469. unlock_curses();
  2470. }
  2471. }
  2472. #endif
  2473. static void __kill_work(void)
  2474. {
  2475. struct thr_info *thr;
  2476. int i;
  2477. if (!successful_connect)
  2478. return;
  2479. applog(LOG_INFO, "Received kill message");
  2480. #ifdef USE_USBUTILS
  2481. /* Best to get rid of it first so it doesn't
  2482. * try to create any new devices */
  2483. if (!opt_scrypt) {
  2484. applog(LOG_DEBUG, "Killing off HotPlug thread");
  2485. thr = &control_thr[hotplug_thr_id];
  2486. thr_info_cancel(thr);
  2487. }
  2488. #endif
  2489. applog(LOG_DEBUG, "Killing off watchpool thread");
  2490. /* Kill the watchpool thread */
  2491. thr = &control_thr[watchpool_thr_id];
  2492. thr_info_cancel(thr);
  2493. applog(LOG_DEBUG, "Killing off watchdog thread");
  2494. /* Kill the watchdog thread */
  2495. thr = &control_thr[watchdog_thr_id];
  2496. thr_info_cancel(thr);
  2497. applog(LOG_DEBUG, "Stopping mining threads");
  2498. /* Stop the mining threads*/
  2499. for (i = 0; i < mining_threads; i++) {
  2500. thr = get_thread(i);
  2501. thr_info_freeze(thr);
  2502. thr->pause = true;
  2503. }
  2504. nmsleep(1000);
  2505. applog(LOG_DEBUG, "Killing off mining threads");
  2506. /* Kill the mining threads*/
  2507. for (i = 0; i < mining_threads; i++) {
  2508. thr = get_thread(i);
  2509. thr_info_cancel(thr);
  2510. }
  2511. applog(LOG_DEBUG, "Killing off stage thread");
  2512. /* Stop the others */
  2513. thr = &control_thr[stage_thr_id];
  2514. thr_info_cancel(thr);
  2515. applog(LOG_DEBUG, "Killing off API thread");
  2516. thr = &control_thr[api_thr_id];
  2517. thr_info_cancel(thr);
  2518. #ifdef USE_USBUTILS
  2519. /* Release USB resources in case it's a restart
  2520. * and not a QUIT */
  2521. if (!opt_scrypt) {
  2522. applog(LOG_DEBUG, "Releasing all USB devices");
  2523. usb_cleanup();
  2524. }
  2525. #endif
  2526. }
  2527. /* This should be the common exit path */
  2528. void kill_work(void)
  2529. {
  2530. __kill_work();
  2531. quit(0, "Shutdown signal received.");
  2532. }
  2533. static
  2534. #ifdef WIN32
  2535. const
  2536. #endif
  2537. char **initial_args;
  2538. static void clean_up(void);
  2539. void app_restart(void)
  2540. {
  2541. applog(LOG_WARNING, "Attempting to restart %s", packagename);
  2542. __kill_work();
  2543. clean_up();
  2544. #if defined(unix)
  2545. if (forkpid > 0) {
  2546. kill(forkpid, SIGTERM);
  2547. forkpid = 0;
  2548. }
  2549. #endif
  2550. execv(initial_args[0], initial_args);
  2551. applog(LOG_WARNING, "Failed to restart application");
  2552. }
  2553. static void sighandler(int __maybe_unused sig)
  2554. {
  2555. /* Restore signal handlers so we can still quit if kill_work fails */
  2556. sigaction(SIGTERM, &termhandler, NULL);
  2557. sigaction(SIGINT, &inthandler, NULL);
  2558. kill_work();
  2559. }
  2560. /* Called with pool_lock held. Recruit an extra curl if none are available for
  2561. * this pool. */
  2562. static void recruit_curl(struct pool *pool)
  2563. {
  2564. struct curl_ent *ce = calloc(sizeof(struct curl_ent), 1);
  2565. if (unlikely(!ce))
  2566. quit(1, "Failed to calloc in recruit_curl");
  2567. ce->curl = curl_easy_init();
  2568. if (unlikely(!ce->curl))
  2569. quit(1, "Failed to init in recruit_curl");
  2570. list_add(&ce->node, &pool->curlring);
  2571. pool->curls++;
  2572. applog(LOG_DEBUG, "Recruited curl %d for pool %d", pool->curls, pool->pool_no);
  2573. }
  2574. /* Grab an available curl if there is one. If not, then recruit extra curls
  2575. * unless we are in a submit_fail situation, or we have opt_delaynet enabled
  2576. * and there are already 5 curls in circulation. Limit total number to the
  2577. * number of mining threads per pool as well to prevent blasting a pool during
  2578. * network delays/outages. */
  2579. static struct curl_ent *pop_curl_entry(struct pool *pool)
  2580. {
  2581. int curl_limit = opt_delaynet ? 5 : (mining_threads + opt_queue) * 2;
  2582. struct curl_ent *ce;
  2583. mutex_lock(&pool->pool_lock);
  2584. retry:
  2585. if (!pool->curls)
  2586. recruit_curl(pool);
  2587. else if (list_empty(&pool->curlring)) {
  2588. if (pool->curls >= curl_limit) {
  2589. pthread_cond_wait(&pool->cr_cond, &pool->pool_lock);
  2590. goto retry;
  2591. } else
  2592. recruit_curl(pool);
  2593. }
  2594. ce = list_entry(pool->curlring.next, struct curl_ent, node);
  2595. list_del(&ce->node);
  2596. mutex_unlock(&pool->pool_lock);
  2597. return ce;
  2598. }
  2599. static void push_curl_entry(struct curl_ent *ce, struct pool *pool)
  2600. {
  2601. mutex_lock(&pool->pool_lock);
  2602. list_add_tail(&ce->node, &pool->curlring);
  2603. gettimeofday(&ce->tv, NULL);
  2604. pthread_cond_broadcast(&pool->cr_cond);
  2605. mutex_unlock(&pool->pool_lock);
  2606. }
  2607. static bool stale_work(struct work *work, bool share);
  2608. static inline bool should_roll(struct work *work)
  2609. {
  2610. struct timeval now;
  2611. time_t expiry;
  2612. if (work->pool != current_pool() && pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE)
  2613. return false;
  2614. if (work->rolltime > opt_scantime)
  2615. expiry = work->rolltime;
  2616. else
  2617. expiry = opt_scantime;
  2618. expiry = expiry * 2 / 3;
  2619. /* We shouldn't roll if we're unlikely to get one shares' duration
  2620. * work out of doing so */
  2621. gettimeofday(&now, NULL);
  2622. if (now.tv_sec - work->tv_staged.tv_sec > expiry)
  2623. return false;
  2624. return true;
  2625. }
  2626. /* Limit rolls to 7000 to not beyond 2 hours in the future where bitcoind will
  2627. * reject blocks as invalid. */
  2628. static inline bool can_roll(struct work *work)
  2629. {
  2630. return (!work->stratum && work->pool && work->rolltime && !work->clone &&
  2631. work->rolls < 7000 && !stale_work(work, false));
  2632. }
  2633. static void roll_work(struct work *work)
  2634. {
  2635. uint32_t *work_ntime;
  2636. uint32_t ntime;
  2637. work_ntime = (uint32_t *)(work->data + 68);
  2638. ntime = be32toh(*work_ntime);
  2639. ntime++;
  2640. *work_ntime = htobe32(ntime);
  2641. local_work++;
  2642. work->rolls++;
  2643. work->blk.nonce = 0;
  2644. applog(LOG_DEBUG, "Successfully rolled work");
  2645. /* This is now a different work item so it needs a different ID for the
  2646. * hashtable */
  2647. work->id = total_work++;
  2648. }
  2649. /* Duplicates any dynamically allocated arrays within the work struct to
  2650. * prevent a copied work struct from freeing ram belonging to another struct */
  2651. void __copy_work(struct work *work, struct work *base_work)
  2652. {
  2653. int id = work->id;
  2654. clean_work(work);
  2655. memcpy(work, base_work, sizeof(struct work));
  2656. /* Keep the unique new id assigned during make_work to prevent copied
  2657. * work from having the same id. */
  2658. work->id = id;
  2659. if (base_work->job_id)
  2660. work->job_id = strdup(base_work->job_id);
  2661. if (base_work->nonce1)
  2662. work->nonce1 = strdup(base_work->nonce1);
  2663. if (base_work->nonce2)
  2664. work->nonce2 = strdup(base_work->nonce2);
  2665. if (base_work->ntime)
  2666. work->ntime = strdup(base_work->ntime);
  2667. if (base_work->gbt_coinbase)
  2668. work->gbt_coinbase = strdup(base_work->gbt_coinbase);
  2669. }
  2670. /* Generates a copy of an existing work struct, creating fresh heap allocations
  2671. * for all dynamically allocated arrays within the struct */
  2672. struct work *copy_work(struct work *base_work)
  2673. {
  2674. struct work *work = make_work();
  2675. __copy_work(work, base_work);
  2676. return work;
  2677. }
  2678. static struct work *make_clone(struct work *work)
  2679. {
  2680. struct work *work_clone = copy_work(work);
  2681. work_clone->clone = true;
  2682. gettimeofday((struct timeval *)&(work_clone->tv_cloned), NULL);
  2683. work_clone->longpoll = false;
  2684. work_clone->mandatory = false;
  2685. /* Make cloned work appear slightly older to bias towards keeping the
  2686. * master work item which can be further rolled */
  2687. work_clone->tv_staged.tv_sec -= 1;
  2688. return work_clone;
  2689. }
  2690. static void stage_work(struct work *work);
  2691. static bool clone_available(void)
  2692. {
  2693. struct work *work_clone = NULL, *work, *tmp;
  2694. bool cloned = false;
  2695. mutex_lock(stgd_lock);
  2696. if (!staged_rollable)
  2697. goto out_unlock;
  2698. HASH_ITER(hh, staged_work, work, tmp) {
  2699. if (can_roll(work) && should_roll(work)) {
  2700. roll_work(work);
  2701. work_clone = make_clone(work);
  2702. roll_work(work);
  2703. applog(LOG_DEBUG, "Pushing cloned available work to stage thread");
  2704. cloned = true;
  2705. break;
  2706. }
  2707. }
  2708. out_unlock:
  2709. mutex_unlock(stgd_lock);
  2710. if (cloned)
  2711. stage_work(work_clone);
  2712. return cloned;
  2713. }
  2714. static void pool_died(struct pool *pool)
  2715. {
  2716. if (!pool_tset(pool, &pool->idle)) {
  2717. gettimeofday(&pool->tv_idle, NULL);
  2718. if (pool == current_pool()) {
  2719. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  2720. switch_pools(NULL);
  2721. } else
  2722. applog(LOG_INFO, "Pool %d %s failed to return work", pool->pool_no, pool->rpc_url);
  2723. }
  2724. }
  2725. static bool stale_work(struct work *work, bool share)
  2726. {
  2727. struct timeval now;
  2728. time_t work_expiry;
  2729. struct pool *pool;
  2730. int getwork_delay;
  2731. if (opt_benchmark)
  2732. return false;
  2733. if (work->work_block != work_block) {
  2734. applog(LOG_DEBUG, "Work stale due to block mismatch");
  2735. return true;
  2736. }
  2737. /* Technically the rolltime should be correct but some pools
  2738. * advertise a broken expire= that is lower than a meaningful
  2739. * scantime */
  2740. if (work->rolltime > opt_scantime)
  2741. work_expiry = work->rolltime;
  2742. else
  2743. work_expiry = opt_expiry;
  2744. pool = work->pool;
  2745. if (!share && pool->has_stratum) {
  2746. bool same_job;
  2747. if (!pool->stratum_active || !pool->stratum_notify) {
  2748. applog(LOG_DEBUG, "Work stale due to stratum inactive");
  2749. return true;
  2750. }
  2751. same_job = true;
  2752. cg_rlock(&pool->data_lock);
  2753. if (strcmp(work->job_id, pool->swork.job_id))
  2754. same_job = false;
  2755. cg_runlock(&pool->data_lock);
  2756. if (!same_job) {
  2757. applog(LOG_DEBUG, "Work stale due to stratum job_id mismatch");
  2758. return true;
  2759. }
  2760. }
  2761. /* Factor in the average getwork delay of this pool, rounding it up to
  2762. * the nearest second */
  2763. getwork_delay = pool->cgminer_pool_stats.getwork_wait_rolling * 5 + 1;
  2764. work_expiry -= getwork_delay;
  2765. if (unlikely(work_expiry < 5))
  2766. work_expiry = 5;
  2767. gettimeofday(&now, NULL);
  2768. if ((now.tv_sec - work->tv_staged.tv_sec) >= work_expiry) {
  2769. applog(LOG_DEBUG, "Work stale due to expiry");
  2770. return true;
  2771. }
  2772. if (opt_fail_only && !share && pool != current_pool() && !work->mandatory &&
  2773. pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  2774. applog(LOG_DEBUG, "Work stale due to fail only pool mismatch");
  2775. return true;
  2776. }
  2777. return false;
  2778. }
  2779. static void regen_hash(struct work *work)
  2780. {
  2781. uint32_t *data32 = (uint32_t *)(work->data);
  2782. unsigned char swap[80];
  2783. uint32_t *swap32 = (uint32_t *)swap;
  2784. unsigned char hash1[32];
  2785. flip80(swap32, data32);
  2786. sha2(swap, 80, hash1);
  2787. sha2(hash1, 32, (unsigned char *)(work->hash));
  2788. }
  2789. static void check_solve(struct work *work)
  2790. {
  2791. if (opt_scrypt)
  2792. scrypt_outputhash(work);
  2793. else
  2794. regen_hash(work);
  2795. work->block = solves_block(work);
  2796. if (unlikely(work->block)) {
  2797. work->pool->solved++;
  2798. found_blocks++;
  2799. work->mandatory = true;
  2800. applog(LOG_NOTICE, "Found block for pool %d!", work->pool->pool_no);
  2801. }
  2802. }
  2803. static bool cnx_needed(struct pool *pool);
  2804. static void *submit_work_thread(void *userdata)
  2805. {
  2806. struct work *work = (struct work *)userdata;
  2807. struct pool *pool = work->pool;
  2808. bool resubmit = false;
  2809. struct curl_ent *ce;
  2810. pthread_detach(pthread_self());
  2811. RenameThread("submit_work");
  2812. applog(LOG_DEBUG, "Creating extra submit work thread");
  2813. check_solve(work);
  2814. if (stale_work(work, true)) {
  2815. if (opt_submit_stale)
  2816. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as user requested", pool->pool_no);
  2817. else if (pool->submit_old)
  2818. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as pool requested", pool->pool_no);
  2819. else {
  2820. applog(LOG_NOTICE, "Pool %d stale share detected, discarding", pool->pool_no);
  2821. sharelog("discard", work);
  2822. mutex_lock(&stats_lock);
  2823. total_stale++;
  2824. pool->stale_shares++;
  2825. total_diff_stale += work->work_difficulty;
  2826. pool->diff_stale += work->work_difficulty;
  2827. mutex_unlock(&stats_lock);
  2828. goto out;
  2829. }
  2830. work->stale = true;
  2831. }
  2832. if (work->stratum) {
  2833. struct stratum_share *sshare = calloc(sizeof(struct stratum_share), 1);
  2834. uint32_t *hash32 = (uint32_t *)work->hash, nonce;
  2835. bool submitted = false;
  2836. char *noncehex;
  2837. char s[1024];
  2838. sshare->sshare_time = time(NULL);
  2839. /* This work item is freed in parse_stratum_response */
  2840. sshare->work = work;
  2841. nonce = *((uint32_t *)(work->data + 76));
  2842. noncehex = bin2hex((const unsigned char *)&nonce, 4);
  2843. memset(s, 0, 1024);
  2844. mutex_lock(&sshare_lock);
  2845. /* Give the stratum share a unique id */
  2846. sshare->id = swork_id++;
  2847. mutex_unlock(&sshare_lock);
  2848. sprintf(s, "{\"params\": [\"%s\", \"%s\", \"%s\", \"%s\", \"%s\"], \"id\": %d, \"method\": \"mining.submit\"}",
  2849. pool->rpc_user, work->job_id, work->nonce2, work->ntime, noncehex, sshare->id);
  2850. free(noncehex);
  2851. applog(LOG_INFO, "Submitting share %08lx to pool %d", hash32[6], pool->pool_no);
  2852. /* Try resubmitting for up to 2 minutes if we fail to submit
  2853. * once and the stratum pool nonce1 still matches suggesting
  2854. * we may be able to resume. */
  2855. while (time(NULL) < sshare->sshare_time + 120) {
  2856. bool sessionid_match;
  2857. if (likely(stratum_send(pool, s, strlen(s)))) {
  2858. if (pool_tclear(pool, &pool->submit_fail))
  2859. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  2860. mutex_lock(&sshare_lock);
  2861. HASH_ADD_INT(stratum_shares, id, sshare);
  2862. pool->sshares++;
  2863. mutex_unlock(&sshare_lock);
  2864. applog(LOG_DEBUG, "Successfully submitted, adding to stratum_shares db");
  2865. submitted = true;
  2866. break;
  2867. }
  2868. if (!pool_tset(pool, &pool->submit_fail) && cnx_needed(pool)) {
  2869. applog(LOG_WARNING, "Pool %d stratum share submission failure", pool->pool_no);
  2870. total_ro++;
  2871. pool->remotefail_occasions++;
  2872. }
  2873. cg_rlock(&pool->data_lock);
  2874. sessionid_match = (pool->nonce1 && !strcmp(work->nonce1, pool->nonce1));
  2875. cg_runlock(&pool->data_lock);
  2876. if (!sessionid_match) {
  2877. applog(LOG_DEBUG, "No matching session id for resubmitting stratum share");
  2878. break;
  2879. }
  2880. /* Retry every 5 seconds */
  2881. sleep(5);
  2882. }
  2883. if (unlikely(!submitted)) {
  2884. applog(LOG_DEBUG, "Failed to submit stratum share, discarding");
  2885. free_work(work);
  2886. free(sshare);
  2887. pool->stale_shares++;
  2888. total_stale++;
  2889. }
  2890. goto out;
  2891. }
  2892. ce = pop_curl_entry(pool);
  2893. /* submit solution to bitcoin via JSON-RPC */
  2894. while (!submit_upstream_work(work, ce->curl, resubmit)) {
  2895. resubmit = true;
  2896. if (stale_work(work, true)) {
  2897. applog(LOG_NOTICE, "Pool %d share became stale while retrying submit, discarding", pool->pool_no);
  2898. mutex_lock(&stats_lock);
  2899. total_stale++;
  2900. pool->stale_shares++;
  2901. total_diff_stale += work->work_difficulty;
  2902. pool->diff_stale += work->work_difficulty;
  2903. mutex_unlock(&stats_lock);
  2904. break;
  2905. }
  2906. /* pause, then restart work-request loop */
  2907. applog(LOG_INFO, "json_rpc_call failed on submit_work, retrying");
  2908. }
  2909. push_curl_entry(ce, pool);
  2910. out:
  2911. return NULL;
  2912. }
  2913. /* Find the pool that currently has the highest priority */
  2914. static struct pool *priority_pool(int choice)
  2915. {
  2916. struct pool *ret = NULL;
  2917. int i;
  2918. for (i = 0; i < total_pools; i++) {
  2919. struct pool *pool = pools[i];
  2920. if (pool->prio == choice) {
  2921. ret = pool;
  2922. break;
  2923. }
  2924. }
  2925. if (unlikely(!ret)) {
  2926. applog(LOG_ERR, "WTF No pool %d found!", choice);
  2927. return pools[choice];
  2928. }
  2929. return ret;
  2930. }
  2931. static void clear_pool_work(struct pool *pool);
  2932. /* Specifies whether we can switch to this pool or not. */
  2933. static bool pool_unusable(struct pool *pool)
  2934. {
  2935. if (pool->idle)
  2936. return true;
  2937. if (pool->enabled != POOL_ENABLED)
  2938. return true;
  2939. return false;
  2940. }
  2941. void switch_pools(struct pool *selected)
  2942. {
  2943. struct pool *pool, *last_pool;
  2944. int i, pool_no, next_pool;
  2945. cg_wlock(&control_lock);
  2946. last_pool = currentpool;
  2947. pool_no = currentpool->pool_no;
  2948. /* Switch selected to pool number 0 and move the rest down */
  2949. if (selected) {
  2950. if (selected->prio != 0) {
  2951. for (i = 0; i < total_pools; i++) {
  2952. pool = pools[i];
  2953. if (pool->prio < selected->prio)
  2954. pool->prio++;
  2955. }
  2956. selected->prio = 0;
  2957. }
  2958. }
  2959. switch (pool_strategy) {
  2960. /* Both of these set to the master pool */
  2961. case POOL_BALANCE:
  2962. case POOL_FAILOVER:
  2963. case POOL_LOADBALANCE:
  2964. for (i = 0; i < total_pools; i++) {
  2965. pool = priority_pool(i);
  2966. if (pool_unusable(pool))
  2967. continue;
  2968. pool_no = pool->pool_no;
  2969. break;
  2970. }
  2971. break;
  2972. /* Both of these simply increment and cycle */
  2973. case POOL_ROUNDROBIN:
  2974. case POOL_ROTATE:
  2975. if (selected && !selected->idle) {
  2976. pool_no = selected->pool_no;
  2977. break;
  2978. }
  2979. next_pool = pool_no;
  2980. /* Select the next alive pool */
  2981. for (i = 1; i < total_pools; i++) {
  2982. next_pool++;
  2983. if (next_pool >= total_pools)
  2984. next_pool = 0;
  2985. pool = pools[next_pool];
  2986. if (pool_unusable(pool))
  2987. continue;
  2988. pool_no = next_pool;
  2989. break;
  2990. }
  2991. break;
  2992. default:
  2993. break;
  2994. }
  2995. currentpool = pools[pool_no];
  2996. pool = currentpool;
  2997. cg_wunlock(&control_lock);
  2998. /* Set the lagging flag to avoid pool not providing work fast enough
  2999. * messages in failover only mode since we have to get all fresh work
  3000. * as in restart_threads */
  3001. if (opt_fail_only)
  3002. pool_tset(pool, &pool->lagging);
  3003. if (pool != last_pool && pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  3004. applog(LOG_WARNING, "Switching to pool %d %s", pool->pool_no, pool->rpc_url);
  3005. if (pool->has_gbt || pool->has_stratum || opt_fail_only)
  3006. clear_pool_work(last_pool);
  3007. }
  3008. mutex_lock(&lp_lock);
  3009. pthread_cond_broadcast(&lp_cond);
  3010. mutex_unlock(&lp_lock);
  3011. }
  3012. void discard_work(struct work *work)
  3013. {
  3014. if (!work->clone && !work->rolls && !work->mined) {
  3015. if (work->pool)
  3016. work->pool->discarded_work++;
  3017. total_discarded++;
  3018. applog(LOG_DEBUG, "Discarded work");
  3019. } else
  3020. applog(LOG_DEBUG, "Discarded cloned or rolled work");
  3021. free_work(work);
  3022. }
  3023. static void wake_gws(void)
  3024. {
  3025. mutex_lock(stgd_lock);
  3026. pthread_cond_signal(&gws_cond);
  3027. mutex_unlock(stgd_lock);
  3028. }
  3029. static void discard_stale(void)
  3030. {
  3031. struct work *work, *tmp;
  3032. int stale = 0;
  3033. mutex_lock(stgd_lock);
  3034. HASH_ITER(hh, staged_work, work, tmp) {
  3035. if (stale_work(work, false)) {
  3036. HASH_DEL(staged_work, work);
  3037. discard_work(work);
  3038. stale++;
  3039. }
  3040. }
  3041. pthread_cond_signal(&gws_cond);
  3042. mutex_unlock(stgd_lock);
  3043. if (stale)
  3044. applog(LOG_DEBUG, "Discarded %d stales that didn't match current hash", stale);
  3045. }
  3046. /* A generic wait function for threads that poll that will wait a specified
  3047. * time tdiff waiting on the pthread conditional that is broadcast when a
  3048. * work restart is required. Returns the value of pthread_cond_timedwait
  3049. * which is zero if the condition was met or ETIMEDOUT if not.
  3050. */
  3051. int restart_wait(unsigned int mstime)
  3052. {
  3053. struct timeval now, then, tdiff;
  3054. struct timespec abstime;
  3055. int rc;
  3056. tdiff.tv_sec = mstime / 1000;
  3057. tdiff.tv_usec = mstime * 1000 - (tdiff.tv_sec * 1000000);
  3058. gettimeofday(&now, NULL);
  3059. timeradd(&now, &tdiff, &then);
  3060. abstime.tv_sec = then.tv_sec;
  3061. abstime.tv_nsec = then.tv_usec * 1000;
  3062. mutex_lock(&restart_lock);
  3063. rc = pthread_cond_timedwait(&restart_cond, &restart_lock, &abstime);
  3064. mutex_unlock(&restart_lock);
  3065. return rc;
  3066. }
  3067. static void restart_threads(void)
  3068. {
  3069. struct pool *cp = current_pool();
  3070. int i;
  3071. /* Artificially set the lagging flag to avoid pool not providing work
  3072. * fast enough messages after every long poll */
  3073. pool_tset(cp, &cp->lagging);
  3074. /* Discard staged work that is now stale */
  3075. discard_stale();
  3076. rd_lock(&mining_thr_lock);
  3077. for (i = 0; i < mining_threads; i++)
  3078. mining_thr[i]->work_restart = true;
  3079. rd_unlock(&mining_thr_lock);
  3080. mutex_lock(&restart_lock);
  3081. pthread_cond_broadcast(&restart_cond);
  3082. mutex_unlock(&restart_lock);
  3083. }
  3084. static void set_curblock(char *hexstr, unsigned char *hash)
  3085. {
  3086. unsigned char hash_swap[32];
  3087. unsigned char block_hash_swap[32];
  3088. strcpy(current_block, hexstr);
  3089. swap256(hash_swap, hash);
  3090. swap256(block_hash_swap, hash + 4);
  3091. cg_wlock(&ch_lock);
  3092. gettimeofday(&block_timeval, NULL);
  3093. free(current_hash);
  3094. current_hash = bin2hex(hash_swap + 2, 8);
  3095. free(current_fullhash);
  3096. current_fullhash = bin2hex(block_hash_swap, 32);
  3097. get_timestamp(blocktime, &block_timeval);
  3098. applog(LOG_INFO, "New block: %s... diff %s", current_hash, block_diff);
  3099. cg_wunlock(&ch_lock);
  3100. }
  3101. /* Search to see if this string is from a block that has been seen before */
  3102. static bool block_exists(char *hexstr)
  3103. {
  3104. struct block *s;
  3105. rd_lock(&blk_lock);
  3106. HASH_FIND_STR(blocks, hexstr, s);
  3107. rd_unlock(&blk_lock);
  3108. if (s)
  3109. return true;
  3110. return false;
  3111. }
  3112. /* Tests if this work is from a block that has been seen before */
  3113. static inline bool from_existing_block(struct work *work)
  3114. {
  3115. char *hexstr = bin2hex(work->data + 8, 18);
  3116. bool ret;
  3117. ret = block_exists(hexstr);
  3118. free(hexstr);
  3119. return ret;
  3120. }
  3121. static int block_sort(struct block *blocka, struct block *blockb)
  3122. {
  3123. return blocka->block_no - blockb->block_no;
  3124. }
  3125. static void set_blockdiff(const struct work *work)
  3126. {
  3127. uint64_t *data64, d64, diff64;
  3128. uint32_t diffhash[8];
  3129. uint32_t difficulty;
  3130. uint32_t diffbytes;
  3131. uint32_t diffvalue;
  3132. char rhash[32];
  3133. int diffshift;
  3134. difficulty = swab32(*((uint32_t *)(work->data + 72)));
  3135. diffbytes = ((difficulty >> 24) & 0xff) - 3;
  3136. diffvalue = difficulty & 0x00ffffff;
  3137. diffshift = (diffbytes % 4) * 8;
  3138. if (diffshift == 0) {
  3139. diffshift = 32;
  3140. diffbytes--;
  3141. }
  3142. memset(diffhash, 0, 32);
  3143. diffbytes >>= 2;
  3144. if (unlikely(diffbytes > 6))
  3145. return;
  3146. diffhash[diffbytes + 1] = diffvalue >> (32 - diffshift);
  3147. diffhash[diffbytes] = diffvalue << diffshift;
  3148. swab256(rhash, diffhash);
  3149. if (opt_scrypt)
  3150. data64 = (uint64_t *)(rhash + 2);
  3151. else
  3152. data64 = (uint64_t *)(rhash + 4);
  3153. d64 = be64toh(*data64);
  3154. if (unlikely(!d64))
  3155. d64 = 1;
  3156. diff64 = diffone / d64;
  3157. suffix_string(diff64, block_diff, 0);
  3158. current_diff = (double)diffone / (double)d64;
  3159. }
  3160. static bool test_work_current(struct work *work)
  3161. {
  3162. bool ret = true;
  3163. char *hexstr;
  3164. if (work->mandatory)
  3165. return ret;
  3166. /* Hack to work around dud work sneaking into test */
  3167. hexstr = bin2hex(work->data + 8, 18);
  3168. if (!strncmp(hexstr, "000000000000000000000000000000000000", 36))
  3169. goto out_free;
  3170. /* Search to see if this block exists yet and if not, consider it a
  3171. * new block and set the current block details to this one */
  3172. if (!block_exists(hexstr)) {
  3173. struct block *s = calloc(sizeof(struct block), 1);
  3174. int deleted_block = 0;
  3175. ret = false;
  3176. if (unlikely(!s))
  3177. quit (1, "test_work_current OOM");
  3178. strcpy(s->hash, hexstr);
  3179. s->block_no = new_blocks++;
  3180. wr_lock(&blk_lock);
  3181. /* Only keep the last hour's worth of blocks in memory since
  3182. * work from blocks before this is virtually impossible and we
  3183. * want to prevent memory usage from continually rising */
  3184. if (HASH_COUNT(blocks) > 6) {
  3185. struct block *oldblock;
  3186. HASH_SORT(blocks, block_sort);
  3187. oldblock = blocks;
  3188. deleted_block = oldblock->block_no;
  3189. HASH_DEL(blocks, oldblock);
  3190. free(oldblock);
  3191. }
  3192. HASH_ADD_STR(blocks, hash, s);
  3193. set_blockdiff(work);
  3194. wr_unlock(&blk_lock);
  3195. if (deleted_block)
  3196. applog(LOG_DEBUG, "Deleted block %d from database", deleted_block);
  3197. set_curblock(hexstr, work->data);
  3198. if (unlikely(new_blocks == 1))
  3199. goto out_free;
  3200. work->work_block = ++work_block;
  3201. if (!work->stratum) {
  3202. if (work->longpoll) {
  3203. applog(LOG_NOTICE, "%sLONGPOLL from pool %d detected new block",
  3204. work->gbt ? "GBT " : "", work->pool->pool_no);
  3205. } else if (have_longpoll)
  3206. applog(LOG_NOTICE, "New block detected on network before longpoll");
  3207. else
  3208. applog(LOG_NOTICE, "New block detected on network");
  3209. }
  3210. restart_threads();
  3211. } else if (work->longpoll) {
  3212. work->work_block = ++work_block;
  3213. if (work->pool == current_pool()) {
  3214. applog(LOG_NOTICE, "%sLONGPOLL from pool %d requested work restart",
  3215. work->gbt ? "GBT " : "", work->pool->pool_no);
  3216. restart_threads();
  3217. }
  3218. }
  3219. work->longpoll = false;
  3220. out_free:
  3221. free(hexstr);
  3222. return ret;
  3223. }
  3224. static int tv_sort(struct work *worka, struct work *workb)
  3225. {
  3226. return worka->tv_staged.tv_sec - workb->tv_staged.tv_sec;
  3227. }
  3228. static bool work_rollable(struct work *work)
  3229. {
  3230. return (!work->clone && work->rolltime);
  3231. }
  3232. static bool hash_push(struct work *work)
  3233. {
  3234. bool rc = true;
  3235. mutex_lock(stgd_lock);
  3236. if (work_rollable(work))
  3237. staged_rollable++;
  3238. if (likely(!getq->frozen)) {
  3239. HASH_ADD_INT(staged_work, id, work);
  3240. HASH_SORT(staged_work, tv_sort);
  3241. } else
  3242. rc = false;
  3243. pthread_cond_broadcast(&getq->cond);
  3244. mutex_unlock(stgd_lock);
  3245. return rc;
  3246. }
  3247. static void *stage_thread(void *userdata)
  3248. {
  3249. struct thr_info *mythr = userdata;
  3250. bool ok = true;
  3251. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3252. RenameThread("stage");
  3253. while (ok) {
  3254. struct work *work = NULL;
  3255. applog(LOG_DEBUG, "Popping work to stage thread");
  3256. work = tq_pop(mythr->q, NULL);
  3257. if (unlikely(!work)) {
  3258. applog(LOG_ERR, "Failed to tq_pop in stage_thread");
  3259. ok = false;
  3260. break;
  3261. }
  3262. work->work_block = work_block;
  3263. test_work_current(work);
  3264. applog(LOG_DEBUG, "Pushing work to getwork queue");
  3265. if (unlikely(!hash_push(work))) {
  3266. applog(LOG_WARNING, "Failed to hash_push in stage_thread");
  3267. continue;
  3268. }
  3269. }
  3270. tq_freeze(mythr->q);
  3271. return NULL;
  3272. }
  3273. static void stage_work(struct work *work)
  3274. {
  3275. applog(LOG_DEBUG, "Pushing work from pool %d to hash queue", work->pool->pool_no);
  3276. work->work_block = work_block;
  3277. test_work_current(work);
  3278. hash_push(work);
  3279. }
  3280. #ifdef HAVE_CURSES
  3281. int curses_int(const char *query)
  3282. {
  3283. int ret;
  3284. char *cvar;
  3285. cvar = curses_input(query);
  3286. ret = atoi(cvar);
  3287. free(cvar);
  3288. return ret;
  3289. }
  3290. #endif
  3291. #ifdef HAVE_CURSES
  3292. static bool input_pool(bool live);
  3293. #endif
  3294. #ifdef HAVE_CURSES
  3295. static void display_pool_summary(struct pool *pool)
  3296. {
  3297. double efficiency = 0.0;
  3298. if (curses_active_locked()) {
  3299. wlog("Pool: %s\n", pool->rpc_url);
  3300. if (pool->solved)
  3301. wlog("SOLVED %d BLOCK%s!\n", pool->solved, pool->solved > 1 ? "S" : "");
  3302. wlog("%s own long-poll support\n", pool->hdr_path ? "Has" : "Does not have");
  3303. wlog(" Queued work requests: %d\n", pool->getwork_requested);
  3304. wlog(" Share submissions: %d\n", pool->accepted + pool->rejected);
  3305. wlog(" Accepted shares: %d\n", pool->accepted);
  3306. wlog(" Rejected shares: %d\n", pool->rejected);
  3307. wlog(" Accepted difficulty shares: %1.f\n", pool->diff_accepted);
  3308. wlog(" Rejected difficulty shares: %1.f\n", pool->diff_rejected);
  3309. if (pool->accepted || pool->rejected)
  3310. wlog(" Reject ratio: %.1f%%\n", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  3311. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  3312. wlog(" Efficiency (accepted / queued): %.0f%%\n", efficiency);
  3313. wlog(" Discarded work due to new blocks: %d\n", pool->discarded_work);
  3314. wlog(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  3315. wlog(" Unable to get work from server occasions: %d\n", pool->getfail_occasions);
  3316. wlog(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  3317. unlock_curses();
  3318. }
  3319. }
  3320. #endif
  3321. /* We can't remove the memory used for this struct pool because there may
  3322. * still be work referencing it. We just remove it from the pools list */
  3323. void remove_pool(struct pool *pool)
  3324. {
  3325. int i, last_pool = total_pools - 1;
  3326. struct pool *other;
  3327. /* Boost priority of any lower prio than this one */
  3328. for (i = 0; i < total_pools; i++) {
  3329. other = pools[i];
  3330. if (other->prio > pool->prio)
  3331. other->prio--;
  3332. }
  3333. if (pool->pool_no < last_pool) {
  3334. /* Swap the last pool for this one */
  3335. (pools[last_pool])->pool_no = pool->pool_no;
  3336. pools[pool->pool_no] = pools[last_pool];
  3337. }
  3338. /* Give it an invalid number */
  3339. pool->pool_no = total_pools;
  3340. pool->removed = true;
  3341. total_pools--;
  3342. }
  3343. /* add a mutex if this needs to be thread safe in the future */
  3344. static struct JE {
  3345. char *buf;
  3346. struct JE *next;
  3347. } *jedata = NULL;
  3348. static void json_escape_free()
  3349. {
  3350. struct JE *jeptr = jedata;
  3351. struct JE *jenext;
  3352. jedata = NULL;
  3353. while (jeptr) {
  3354. jenext = jeptr->next;
  3355. free(jeptr->buf);
  3356. free(jeptr);
  3357. jeptr = jenext;
  3358. }
  3359. }
  3360. static char *json_escape(char *str)
  3361. {
  3362. struct JE *jeptr;
  3363. char *buf, *ptr;
  3364. /* 2x is the max, may as well just allocate that */
  3365. ptr = buf = malloc(strlen(str) * 2 + 1);
  3366. jeptr = malloc(sizeof(*jeptr));
  3367. jeptr->buf = buf;
  3368. jeptr->next = jedata;
  3369. jedata = jeptr;
  3370. while (*str) {
  3371. if (*str == '\\' || *str == '"')
  3372. *(ptr++) = '\\';
  3373. *(ptr++) = *(str++);
  3374. }
  3375. *ptr = '\0';
  3376. return buf;
  3377. }
  3378. void write_config(FILE *fcfg)
  3379. {
  3380. int i;
  3381. /* Write pool values */
  3382. fputs("{\n\"pools\" : [", fcfg);
  3383. for(i = 0; i < total_pools; i++) {
  3384. fprintf(fcfg, "%s\n\t{\n\t\t\"url\" : \"%s%s%s%s\",", i > 0 ? "," : "",
  3385. pools[i]->rpc_proxy ? json_escape((char *)proxytype(pools[i]->rpc_proxytype)) : "",
  3386. pools[i]->rpc_proxy ? json_escape(pools[i]->rpc_proxy) : "",
  3387. pools[i]->rpc_proxy ? "|" : "",
  3388. json_escape(pools[i]->rpc_url));
  3389. fprintf(fcfg, "\n\t\t\"user\" : \"%s\",", json_escape(pools[i]->rpc_user));
  3390. fprintf(fcfg, "\n\t\t\"pass\" : \"%s\"\n\t}", json_escape(pools[i]->rpc_pass));
  3391. }
  3392. fputs("\n]\n", fcfg);
  3393. #ifdef HAVE_OPENCL
  3394. if (nDevs) {
  3395. /* Write GPU device values */
  3396. fputs(",\n\"intensity\" : \"", fcfg);
  3397. for(i = 0; i < nDevs; i++)
  3398. fprintf(fcfg, gpus[i].dynamic ? "%sd" : "%s%d", i > 0 ? "," : "", gpus[i].intensity);
  3399. fputs("\",\n\"vectors\" : \"", fcfg);
  3400. for(i = 0; i < nDevs; i++)
  3401. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  3402. gpus[i].vwidth);
  3403. fputs("\",\n\"worksize\" : \"", fcfg);
  3404. for(i = 0; i < nDevs; i++)
  3405. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  3406. (int)gpus[i].work_size);
  3407. fputs("\",\n\"kernel\" : \"", fcfg);
  3408. for(i = 0; i < nDevs; i++) {
  3409. fprintf(fcfg, "%s", i > 0 ? "," : "");
  3410. switch (gpus[i].kernel) {
  3411. case KL_NONE: // Shouldn't happen
  3412. break;
  3413. case KL_POCLBM:
  3414. fprintf(fcfg, "poclbm");
  3415. break;
  3416. case KL_PHATK:
  3417. fprintf(fcfg, "phatk");
  3418. break;
  3419. case KL_DIAKGCN:
  3420. fprintf(fcfg, "diakgcn");
  3421. break;
  3422. case KL_DIABLO:
  3423. fprintf(fcfg, "diablo");
  3424. break;
  3425. case KL_SCRYPT:
  3426. fprintf(fcfg, "scrypt");
  3427. break;
  3428. }
  3429. }
  3430. #ifdef USE_SCRYPT
  3431. fputs("\",\n\"lookup-gap\" : \"", fcfg);
  3432. for(i = 0; i < nDevs; i++)
  3433. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  3434. (int)gpus[i].opt_lg);
  3435. fputs("\",\n\"thread-concurrency\" : \"", fcfg);
  3436. for(i = 0; i < nDevs; i++)
  3437. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  3438. (int)gpus[i].opt_tc);
  3439. fputs("\",\n\"shaders\" : \"", fcfg);
  3440. for(i = 0; i < nDevs; i++)
  3441. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  3442. (int)gpus[i].shaders);
  3443. #endif
  3444. #ifdef HAVE_ADL
  3445. fputs("\",\n\"gpu-engine\" : \"", fcfg);
  3446. for(i = 0; i < nDevs; i++)
  3447. fprintf(fcfg, "%s%d-%d", i > 0 ? "," : "", gpus[i].min_engine, gpus[i].gpu_engine);
  3448. fputs("\",\n\"gpu-fan\" : \"", fcfg);
  3449. for(i = 0; i < nDevs; i++)
  3450. fprintf(fcfg, "%s%d-%d", i > 0 ? "," : "", gpus[i].min_fan, gpus[i].gpu_fan);
  3451. fputs("\",\n\"gpu-memclock\" : \"", fcfg);
  3452. for(i = 0; i < nDevs; i++)
  3453. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_memclock);
  3454. fputs("\",\n\"gpu-memdiff\" : \"", fcfg);
  3455. for(i = 0; i < nDevs; i++)
  3456. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_memdiff);
  3457. fputs("\",\n\"gpu-powertune\" : \"", fcfg);
  3458. for(i = 0; i < nDevs; i++)
  3459. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_powertune);
  3460. fputs("\",\n\"gpu-vddc\" : \"", fcfg);
  3461. for(i = 0; i < nDevs; i++)
  3462. fprintf(fcfg, "%s%1.3f", i > 0 ? "," : "", gpus[i].gpu_vddc);
  3463. fputs("\",\n\"temp-cutoff\" : \"", fcfg);
  3464. for(i = 0; i < nDevs; i++)
  3465. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].cutofftemp);
  3466. fputs("\",\n\"temp-overheat\" : \"", fcfg);
  3467. for(i = 0; i < nDevs; i++)
  3468. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].adl.overtemp);
  3469. fputs("\",\n\"temp-target\" : \"", fcfg);
  3470. for(i = 0; i < nDevs; i++)
  3471. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].adl.targettemp);
  3472. #endif
  3473. fputs("\"", fcfg);
  3474. }
  3475. #endif
  3476. #ifdef HAVE_ADL
  3477. if (opt_reorder)
  3478. fprintf(fcfg, ",\n\"gpu-reorder\" : true");
  3479. #endif
  3480. #ifdef WANT_CPUMINE
  3481. fprintf(fcfg, ",\n\"algo\" : \"%s\"", algo_names[opt_algo]);
  3482. #endif
  3483. /* Simple bool and int options */
  3484. struct opt_table *opt;
  3485. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  3486. char *p, *name = strdup(opt->names);
  3487. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  3488. if (p[1] != '-')
  3489. continue;
  3490. if (opt->type & OPT_NOARG &&
  3491. ((void *)opt->cb == (void *)opt_set_bool || (void *)opt->cb == (void *)opt_set_invbool) &&
  3492. (*(bool *)opt->u.arg == ((void *)opt->cb == (void *)opt_set_bool)))
  3493. fprintf(fcfg, ",\n\"%s\" : true", p+2);
  3494. if (opt->type & OPT_HASARG &&
  3495. ((void *)opt->cb_arg == (void *)set_int_0_to_9999 ||
  3496. (void *)opt->cb_arg == (void *)set_int_1_to_65535 ||
  3497. (void *)opt->cb_arg == (void *)set_int_0_to_10 ||
  3498. (void *)opt->cb_arg == (void *)set_int_1_to_10) && opt->desc != opt_hidden)
  3499. fprintf(fcfg, ",\n\"%s\" : \"%d\"", p+2, *(int *)opt->u.arg);
  3500. }
  3501. }
  3502. /* Special case options */
  3503. fprintf(fcfg, ",\n\"shares\" : \"%d\"", opt_shares);
  3504. if (pool_strategy == POOL_BALANCE)
  3505. fputs(",\n\"balance\" : true", fcfg);
  3506. if (pool_strategy == POOL_LOADBALANCE)
  3507. fputs(",\n\"load-balance\" : true", fcfg);
  3508. if (pool_strategy == POOL_ROUNDROBIN)
  3509. fputs(",\n\"round-robin\" : true", fcfg);
  3510. if (pool_strategy == POOL_ROTATE)
  3511. fprintf(fcfg, ",\n\"rotate\" : \"%d\"", opt_rotate_period);
  3512. #if defined(unix)
  3513. if (opt_stderr_cmd && *opt_stderr_cmd)
  3514. fprintf(fcfg, ",\n\"monitor\" : \"%s\"", json_escape(opt_stderr_cmd));
  3515. #endif // defined(unix)
  3516. if (opt_kernel_path && *opt_kernel_path) {
  3517. char *kpath = strdup(opt_kernel_path);
  3518. if (kpath[strlen(kpath)-1] == '/')
  3519. kpath[strlen(kpath)-1] = 0;
  3520. fprintf(fcfg, ",\n\"kernel-path\" : \"%s\"", json_escape(kpath));
  3521. }
  3522. if (schedstart.enable)
  3523. fprintf(fcfg, ",\n\"sched-time\" : \"%d:%d\"", schedstart.tm.tm_hour, schedstart.tm.tm_min);
  3524. if (schedstop.enable)
  3525. fprintf(fcfg, ",\n\"stop-time\" : \"%d:%d\"", schedstop.tm.tm_hour, schedstop.tm.tm_min);
  3526. if (opt_socks_proxy && *opt_socks_proxy)
  3527. fprintf(fcfg, ",\n\"socks-proxy\" : \"%s\"", json_escape(opt_socks_proxy));
  3528. #ifdef HAVE_OPENCL
  3529. for(i = 0; i < nDevs; i++)
  3530. if (gpus[i].deven == DEV_DISABLED)
  3531. break;
  3532. if (i < nDevs)
  3533. for (i = 0; i < nDevs; i++)
  3534. if (gpus[i].deven != DEV_DISABLED)
  3535. fprintf(fcfg, ",\n\"device\" : \"%d\"", i);
  3536. #endif
  3537. if (opt_api_allow)
  3538. fprintf(fcfg, ",\n\"api-allow\" : \"%s\"", json_escape(opt_api_allow));
  3539. if (strcmp(opt_api_description, PACKAGE_STRING) != 0)
  3540. fprintf(fcfg, ",\n\"api-description\" : \"%s\"", json_escape(opt_api_description));
  3541. if (opt_api_groups)
  3542. fprintf(fcfg, ",\n\"api-groups\" : \"%s\"", json_escape(opt_api_groups));
  3543. if (opt_icarus_options)
  3544. fprintf(fcfg, ",\n\"icarus-options\" : \"%s\"", json_escape(opt_icarus_options));
  3545. if (opt_icarus_timing)
  3546. fprintf(fcfg, ",\n\"icarus-timing\" : \"%s\"", json_escape(opt_icarus_timing));
  3547. #ifdef USE_USBUTILS
  3548. if (opt_usb_select)
  3549. fprintf(fcfg, ",\n\"usb\" : \"%s\"", json_escape(opt_usb_select));
  3550. #endif
  3551. fputs("\n}\n", fcfg);
  3552. json_escape_free();
  3553. }
  3554. void zero_bestshare(void)
  3555. {
  3556. int i;
  3557. best_diff = 0;
  3558. memset(best_share, 0, 8);
  3559. suffix_string(best_diff, best_share, 0);
  3560. for (i = 0; i < total_pools; i++) {
  3561. struct pool *pool = pools[i];
  3562. pool->best_diff = 0;
  3563. }
  3564. }
  3565. void zero_stats(void)
  3566. {
  3567. int i;
  3568. gettimeofday(&total_tv_start, NULL);
  3569. total_mhashes_done = 0;
  3570. total_getworks = 0;
  3571. total_accepted = 0;
  3572. total_rejected = 0;
  3573. hw_errors = 0;
  3574. total_stale = 0;
  3575. total_discarded = 0;
  3576. local_work = 0;
  3577. total_go = 0;
  3578. total_ro = 0;
  3579. total_secs = 1.0;
  3580. total_diff1 = 0;
  3581. found_blocks = 0;
  3582. total_diff_accepted = 0;
  3583. total_diff_rejected = 0;
  3584. total_diff_stale = 0;
  3585. for (i = 0; i < total_pools; i++) {
  3586. struct pool *pool = pools[i];
  3587. pool->getwork_requested = 0;
  3588. pool->accepted = 0;
  3589. pool->rejected = 0;
  3590. pool->stale_shares = 0;
  3591. pool->discarded_work = 0;
  3592. pool->getfail_occasions = 0;
  3593. pool->remotefail_occasions = 0;
  3594. pool->last_share_time = 0;
  3595. pool->diff1 = 0;
  3596. pool->diff_accepted = 0;
  3597. pool->diff_rejected = 0;
  3598. pool->diff_stale = 0;
  3599. pool->last_share_diff = 0;
  3600. }
  3601. zero_bestshare();
  3602. for (i = 0; i < total_devices; ++i) {
  3603. struct cgpu_info *cgpu = get_devices(i);
  3604. mutex_lock(&hash_lock);
  3605. cgpu->total_mhashes = 0;
  3606. cgpu->accepted = 0;
  3607. cgpu->rejected = 0;
  3608. cgpu->hw_errors = 0;
  3609. cgpu->utility = 0.0;
  3610. cgpu->last_share_pool_time = 0;
  3611. cgpu->diff1 = 0;
  3612. cgpu->diff_accepted = 0;
  3613. cgpu->diff_rejected = 0;
  3614. cgpu->last_share_diff = 0;
  3615. mutex_unlock(&hash_lock);
  3616. }
  3617. }
  3618. #ifdef HAVE_CURSES
  3619. static void display_pools(void)
  3620. {
  3621. struct pool *pool;
  3622. int selected, i;
  3623. char input;
  3624. opt_loginput = true;
  3625. immedok(logwin, true);
  3626. clear_logwin();
  3627. updated:
  3628. for (i = 0; i < total_pools; i++) {
  3629. pool = pools[i];
  3630. if (pool == current_pool())
  3631. wattron(logwin, A_BOLD);
  3632. if (pool->enabled != POOL_ENABLED)
  3633. wattron(logwin, A_DIM);
  3634. wlogprint("%d: ", pool->pool_no);
  3635. switch (pool->enabled) {
  3636. case POOL_ENABLED:
  3637. wlogprint("Enabled ");
  3638. break;
  3639. case POOL_DISABLED:
  3640. wlogprint("Disabled ");
  3641. break;
  3642. case POOL_REJECTING:
  3643. wlogprint("Rejecting ");
  3644. break;
  3645. }
  3646. wlogprint("%s Priority %d: %s User:%s\n",
  3647. pool->idle? "Dead" : "Alive",
  3648. pool->prio,
  3649. pool->rpc_url, pool->rpc_user);
  3650. wattroff(logwin, A_BOLD | A_DIM);
  3651. }
  3652. retry:
  3653. wlogprint("\nCurrent pool management strategy: %s\n",
  3654. strategies[pool_strategy]);
  3655. if (pool_strategy == POOL_ROTATE)
  3656. wlogprint("Set to rotate every %d minutes\n", opt_rotate_period);
  3657. wlogprint("[F]ailover only %s\n", opt_fail_only ? "enabled" : "disabled");
  3658. wlogprint("[A]dd pool [R]emove pool [D]isable pool [E]nable pool\n");
  3659. wlogprint("[C]hange management strategy [S]witch pool [I]nformation\n");
  3660. wlogprint("Or press any other key to continue\n");
  3661. input = getch();
  3662. if (!strncasecmp(&input, "a", 1)) {
  3663. input_pool(true);
  3664. goto updated;
  3665. } else if (!strncasecmp(&input, "r", 1)) {
  3666. if (total_pools <= 1) {
  3667. wlogprint("Cannot remove last pool");
  3668. goto retry;
  3669. }
  3670. selected = curses_int("Select pool number");
  3671. if (selected < 0 || selected >= total_pools) {
  3672. wlogprint("Invalid selection\n");
  3673. goto retry;
  3674. }
  3675. pool = pools[selected];
  3676. if (pool == current_pool())
  3677. switch_pools(NULL);
  3678. if (pool == current_pool()) {
  3679. wlogprint("Unable to remove pool due to activity\n");
  3680. goto retry;
  3681. }
  3682. disable_pool(pool);
  3683. remove_pool(pool);
  3684. goto updated;
  3685. } else if (!strncasecmp(&input, "s", 1)) {
  3686. selected = curses_int("Select pool number");
  3687. if (selected < 0 || selected >= total_pools) {
  3688. wlogprint("Invalid selection\n");
  3689. goto retry;
  3690. }
  3691. pool = pools[selected];
  3692. enable_pool(pool);
  3693. switch_pools(pool);
  3694. goto updated;
  3695. } else if (!strncasecmp(&input, "d", 1)) {
  3696. if (enabled_pools <= 1) {
  3697. wlogprint("Cannot disable last pool");
  3698. goto retry;
  3699. }
  3700. selected = curses_int("Select pool number");
  3701. if (selected < 0 || selected >= total_pools) {
  3702. wlogprint("Invalid selection\n");
  3703. goto retry;
  3704. }
  3705. pool = pools[selected];
  3706. disable_pool(pool);
  3707. if (pool == current_pool())
  3708. switch_pools(NULL);
  3709. goto updated;
  3710. } else if (!strncasecmp(&input, "e", 1)) {
  3711. selected = curses_int("Select pool number");
  3712. if (selected < 0 || selected >= total_pools) {
  3713. wlogprint("Invalid selection\n");
  3714. goto retry;
  3715. }
  3716. pool = pools[selected];
  3717. enable_pool(pool);
  3718. if (pool->prio < current_pool()->prio)
  3719. switch_pools(pool);
  3720. goto updated;
  3721. } else if (!strncasecmp(&input, "c", 1)) {
  3722. for (i = 0; i <= TOP_STRATEGY; i++)
  3723. wlogprint("%d: %s\n", i, strategies[i]);
  3724. selected = curses_int("Select strategy number type");
  3725. if (selected < 0 || selected > TOP_STRATEGY) {
  3726. wlogprint("Invalid selection\n");
  3727. goto retry;
  3728. }
  3729. if (selected == POOL_ROTATE) {
  3730. opt_rotate_period = curses_int("Select interval in minutes");
  3731. if (opt_rotate_period < 0 || opt_rotate_period > 9999) {
  3732. opt_rotate_period = 0;
  3733. wlogprint("Invalid selection\n");
  3734. goto retry;
  3735. }
  3736. }
  3737. pool_strategy = selected;
  3738. switch_pools(NULL);
  3739. goto updated;
  3740. } else if (!strncasecmp(&input, "i", 1)) {
  3741. selected = curses_int("Select pool number");
  3742. if (selected < 0 || selected >= total_pools) {
  3743. wlogprint("Invalid selection\n");
  3744. goto retry;
  3745. }
  3746. pool = pools[selected];
  3747. display_pool_summary(pool);
  3748. goto retry;
  3749. } else if (!strncasecmp(&input, "f", 1)) {
  3750. opt_fail_only ^= true;
  3751. goto updated;
  3752. } else
  3753. clear_logwin();
  3754. immedok(logwin, false);
  3755. opt_loginput = false;
  3756. }
  3757. static void display_options(void)
  3758. {
  3759. int selected;
  3760. char input;
  3761. opt_loginput = true;
  3762. immedok(logwin, true);
  3763. clear_logwin();
  3764. retry:
  3765. wlogprint("[N]ormal [C]lear [S]ilent mode (disable all output)\n");
  3766. wlogprint("[D]ebug:%s\n[P]er-device:%s\n[Q]uiet:%s\n[V]erbose:%s\n"
  3767. "[R]PC debug:%s\n[W]orkTime details:%s\nco[M]pact: %s\n"
  3768. "[L]og interval:%d\n[Z]ero statistics\n",
  3769. opt_debug ? "on" : "off",
  3770. want_per_device_stats? "on" : "off",
  3771. opt_quiet ? "on" : "off",
  3772. opt_log_output ? "on" : "off",
  3773. opt_protocol ? "on" : "off",
  3774. opt_worktime ? "on" : "off",
  3775. opt_compact ? "on" : "off",
  3776. opt_log_interval);
  3777. wlogprint("Select an option or any other key to return\n");
  3778. input = getch();
  3779. if (!strncasecmp(&input, "q", 1)) {
  3780. opt_quiet ^= true;
  3781. wlogprint("Quiet mode %s\n", opt_quiet ? "enabled" : "disabled");
  3782. goto retry;
  3783. } else if (!strncasecmp(&input, "v", 1)) {
  3784. opt_log_output ^= true;
  3785. if (opt_log_output)
  3786. opt_quiet = false;
  3787. wlogprint("Verbose mode %s\n", opt_log_output ? "enabled" : "disabled");
  3788. goto retry;
  3789. } else if (!strncasecmp(&input, "n", 1)) {
  3790. opt_log_output = false;
  3791. opt_debug = false;
  3792. opt_quiet = false;
  3793. opt_protocol = false;
  3794. opt_compact = false;
  3795. want_per_device_stats = false;
  3796. wlogprint("Output mode reset to normal\n");
  3797. switch_compact();
  3798. goto retry;
  3799. } else if (!strncasecmp(&input, "d", 1)) {
  3800. opt_debug ^= true;
  3801. opt_log_output = opt_debug;
  3802. if (opt_debug)
  3803. opt_quiet = false;
  3804. wlogprint("Debug mode %s\n", opt_debug ? "enabled" : "disabled");
  3805. goto retry;
  3806. } else if (!strncasecmp(&input, "m", 1)) {
  3807. opt_compact ^= true;
  3808. wlogprint("Compact mode %s\n", opt_compact ? "enabled" : "disabled");
  3809. switch_compact();
  3810. goto retry;
  3811. } else if (!strncasecmp(&input, "p", 1)) {
  3812. want_per_device_stats ^= true;
  3813. opt_log_output = want_per_device_stats;
  3814. wlogprint("Per-device stats %s\n", want_per_device_stats ? "enabled" : "disabled");
  3815. goto retry;
  3816. } else if (!strncasecmp(&input, "r", 1)) {
  3817. opt_protocol ^= true;
  3818. if (opt_protocol)
  3819. opt_quiet = false;
  3820. wlogprint("RPC protocol debugging %s\n", opt_protocol ? "enabled" : "disabled");
  3821. goto retry;
  3822. } else if (!strncasecmp(&input, "c", 1))
  3823. clear_logwin();
  3824. else if (!strncasecmp(&input, "l", 1)) {
  3825. selected = curses_int("Interval in seconds");
  3826. if (selected < 0 || selected > 9999) {
  3827. wlogprint("Invalid selection\n");
  3828. goto retry;
  3829. }
  3830. opt_log_interval = selected;
  3831. wlogprint("Log interval set to %d seconds\n", opt_log_interval);
  3832. goto retry;
  3833. } else if (!strncasecmp(&input, "s", 1)) {
  3834. opt_realquiet = true;
  3835. } else if (!strncasecmp(&input, "w", 1)) {
  3836. opt_worktime ^= true;
  3837. wlogprint("WorkTime details %s\n", opt_worktime ? "enabled" : "disabled");
  3838. goto retry;
  3839. } else if (!strncasecmp(&input, "z", 1)) {
  3840. zero_stats();
  3841. goto retry;
  3842. } else
  3843. clear_logwin();
  3844. immedok(logwin, false);
  3845. opt_loginput = false;
  3846. }
  3847. #endif
  3848. void default_save_file(char *filename)
  3849. {
  3850. if (default_config && *default_config) {
  3851. strcpy(filename, default_config);
  3852. return;
  3853. }
  3854. #if defined(unix)
  3855. if (getenv("HOME") && *getenv("HOME")) {
  3856. strcpy(filename, getenv("HOME"));
  3857. strcat(filename, "/");
  3858. }
  3859. else
  3860. strcpy(filename, "");
  3861. strcat(filename, ".cgminer/");
  3862. mkdir(filename, 0777);
  3863. #else
  3864. strcpy(filename, "");
  3865. #endif
  3866. strcat(filename, def_conf);
  3867. }
  3868. #ifdef HAVE_CURSES
  3869. static void set_options(void)
  3870. {
  3871. int selected;
  3872. char input;
  3873. opt_loginput = true;
  3874. immedok(logwin, true);
  3875. clear_logwin();
  3876. retry:
  3877. wlogprint("[Q]ueue: %d\n[S]cantime: %d\n[E]xpiry: %d\n"
  3878. "[W]rite config file\n[C]gminer restart\n",
  3879. opt_queue, opt_scantime, opt_expiry);
  3880. wlogprint("Select an option or any other key to return\n");
  3881. input = getch();
  3882. if (!strncasecmp(&input, "q", 1)) {
  3883. selected = curses_int("Extra work items to queue");
  3884. if (selected < 0 || selected > 9999) {
  3885. wlogprint("Invalid selection\n");
  3886. goto retry;
  3887. }
  3888. opt_queue = selected;
  3889. goto retry;
  3890. } else if (!strncasecmp(&input, "s", 1)) {
  3891. selected = curses_int("Set scantime in seconds");
  3892. if (selected < 0 || selected > 9999) {
  3893. wlogprint("Invalid selection\n");
  3894. goto retry;
  3895. }
  3896. opt_scantime = selected;
  3897. goto retry;
  3898. } else if (!strncasecmp(&input, "e", 1)) {
  3899. selected = curses_int("Set expiry time in seconds");
  3900. if (selected < 0 || selected > 9999) {
  3901. wlogprint("Invalid selection\n");
  3902. goto retry;
  3903. }
  3904. opt_expiry = selected;
  3905. goto retry;
  3906. } else if (!strncasecmp(&input, "w", 1)) {
  3907. FILE *fcfg;
  3908. char *str, filename[PATH_MAX], prompt[PATH_MAX + 50];
  3909. default_save_file(filename);
  3910. sprintf(prompt, "Config filename to write (Enter for default) [%s]", filename);
  3911. str = curses_input(prompt);
  3912. if (strcmp(str, "-1")) {
  3913. struct stat statbuf;
  3914. strcpy(filename, str);
  3915. free(str);
  3916. if (!stat(filename, &statbuf)) {
  3917. wlogprint("File exists, overwrite?\n");
  3918. input = getch();
  3919. if (strncasecmp(&input, "y", 1))
  3920. goto retry;
  3921. }
  3922. }
  3923. else
  3924. free(str);
  3925. fcfg = fopen(filename, "w");
  3926. if (!fcfg) {
  3927. wlogprint("Cannot open or create file\n");
  3928. goto retry;
  3929. }
  3930. write_config(fcfg);
  3931. fclose(fcfg);
  3932. goto retry;
  3933. } else if (!strncasecmp(&input, "c", 1)) {
  3934. wlogprint("Are you sure?\n");
  3935. input = getch();
  3936. if (!strncasecmp(&input, "y", 1))
  3937. app_restart();
  3938. else
  3939. clear_logwin();
  3940. } else
  3941. clear_logwin();
  3942. immedok(logwin, false);
  3943. opt_loginput = false;
  3944. }
  3945. static void *input_thread(void __maybe_unused *userdata)
  3946. {
  3947. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3948. RenameThread("input");
  3949. if (!curses_active)
  3950. return NULL;
  3951. while (1) {
  3952. char input;
  3953. input = getch();
  3954. if (!strncasecmp(&input, "q", 1)) {
  3955. kill_work();
  3956. return NULL;
  3957. } else if (!strncasecmp(&input, "d", 1))
  3958. display_options();
  3959. else if (!strncasecmp(&input, "p", 1))
  3960. display_pools();
  3961. else if (!strncasecmp(&input, "s", 1))
  3962. set_options();
  3963. else if (have_opencl && !strncasecmp(&input, "g", 1))
  3964. manage_gpu();
  3965. if (opt_realquiet) {
  3966. disable_curses();
  3967. break;
  3968. }
  3969. }
  3970. return NULL;
  3971. }
  3972. #endif
  3973. static void *api_thread(void *userdata)
  3974. {
  3975. struct thr_info *mythr = userdata;
  3976. pthread_detach(pthread_self());
  3977. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3978. RenameThread("api");
  3979. api(api_thr_id);
  3980. PTH(mythr) = 0L;
  3981. return NULL;
  3982. }
  3983. void thread_reportin(struct thr_info *thr)
  3984. {
  3985. gettimeofday(&thr->last, NULL);
  3986. thr->cgpu->status = LIFE_WELL;
  3987. thr->getwork = false;
  3988. thr->cgpu->device_last_well = time(NULL);
  3989. }
  3990. static inline void thread_reportout(struct thr_info *thr)
  3991. {
  3992. thr->getwork = true;
  3993. }
  3994. static void hashmeter(int thr_id, struct timeval *diff,
  3995. uint64_t hashes_done)
  3996. {
  3997. struct timeval temp_tv_end, total_diff;
  3998. double secs;
  3999. double local_secs;
  4000. double utility;
  4001. static double local_mhashes_done = 0;
  4002. static double rolling = 0;
  4003. double local_mhashes;
  4004. bool showlog = false;
  4005. char displayed_hashes[16], displayed_rolling[16];
  4006. uint64_t dh64, dr64;
  4007. struct thr_info *thr;
  4008. local_mhashes = (double)hashes_done / 1000000.0;
  4009. /* Update the last time this thread reported in */
  4010. if (thr_id >= 0) {
  4011. thr = get_thread(thr_id);
  4012. gettimeofday(&(thr->last), NULL);
  4013. thr->cgpu->device_last_well = time(NULL);
  4014. }
  4015. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  4016. /* So we can call hashmeter from a non worker thread */
  4017. if (thr_id >= 0) {
  4018. struct cgpu_info *cgpu = thr->cgpu;
  4019. double thread_rolling = 0.0;
  4020. int i;
  4021. applog(LOG_DEBUG, "[thread %d: %"PRIu64" hashes, %.1f khash/sec]",
  4022. thr_id, hashes_done, hashes_done / 1000 / secs);
  4023. /* Rolling average for each thread and each device */
  4024. decay_time(&thr->rolling, local_mhashes / secs);
  4025. for (i = 0; i < cgpu->threads; i++)
  4026. thread_rolling += cgpu->thr[i]->rolling;
  4027. mutex_lock(&hash_lock);
  4028. decay_time(&cgpu->rolling, thread_rolling);
  4029. cgpu->total_mhashes += local_mhashes;
  4030. mutex_unlock(&hash_lock);
  4031. // If needed, output detailed, per-device stats
  4032. if (want_per_device_stats) {
  4033. struct timeval now;
  4034. struct timeval elapsed;
  4035. gettimeofday(&now, NULL);
  4036. timersub(&now, &thr->cgpu->last_message_tv, &elapsed);
  4037. if (opt_log_interval <= elapsed.tv_sec) {
  4038. struct cgpu_info *cgpu = thr->cgpu;
  4039. char logline[255];
  4040. cgpu->last_message_tv = now;
  4041. get_statline(logline, cgpu);
  4042. if (!curses_active) {
  4043. printf("%s \r", logline);
  4044. fflush(stdout);
  4045. } else
  4046. applog(LOG_INFO, "%s", logline);
  4047. }
  4048. }
  4049. }
  4050. /* Totals are updated by all threads so can race without locking */
  4051. mutex_lock(&hash_lock);
  4052. gettimeofday(&temp_tv_end, NULL);
  4053. timersub(&temp_tv_end, &total_tv_end, &total_diff);
  4054. total_mhashes_done += local_mhashes;
  4055. local_mhashes_done += local_mhashes;
  4056. /* Only update the total every second */
  4057. if (!total_diff.tv_sec)
  4058. goto out_unlock;
  4059. if (total_diff.tv_sec < opt_log_interval) {
  4060. if (thr_id < 0)
  4061. goto out_unlock;
  4062. } else
  4063. showlog = true;
  4064. gettimeofday(&total_tv_end, NULL);
  4065. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  4066. decay_time(&rolling, local_mhashes_done / local_secs);
  4067. global_hashrate = roundl(rolling) * 1000000;
  4068. timersub(&total_tv_end, &total_tv_start, &total_diff);
  4069. total_secs = (double)total_diff.tv_sec +
  4070. ((double)total_diff.tv_usec / 1000000.0);
  4071. utility = total_accepted / total_secs * 60;
  4072. dh64 = (double)total_mhashes_done / total_secs * 1000000ull;
  4073. dr64 = (double)rolling * 1000000ull;
  4074. suffix_string(dh64, displayed_hashes, 4);
  4075. suffix_string(dr64, displayed_rolling, 4);
  4076. sprintf(statusline, "%s(%ds):%s (avg):%sh/s | A:%d R:%d HW:%d U:%.1f/m WU:%.1f/m",
  4077. want_per_device_stats ? "ALL " : "",
  4078. opt_log_interval, displayed_rolling, displayed_hashes,
  4079. total_accepted, total_rejected, hw_errors, utility,
  4080. total_diff1 / total_secs * 60);
  4081. local_mhashes_done = 0;
  4082. out_unlock:
  4083. mutex_unlock(&hash_lock);
  4084. if (showlog) {
  4085. if (!curses_active) {
  4086. printf("%s \r", statusline);
  4087. fflush(stdout);
  4088. } else
  4089. applog(LOG_INFO, "%s", statusline);
  4090. }
  4091. }
  4092. static void stratum_share_result(json_t *val, json_t *res_val, json_t *err_val,
  4093. struct stratum_share *sshare)
  4094. {
  4095. struct work *work = sshare->work;
  4096. uint64_t sharediff = share_diff(work);
  4097. char hashshow[65];
  4098. uint32_t *hash32;
  4099. char diffdisp[16];
  4100. int intdiff;
  4101. hash32 = (uint32_t *)(work->hash);
  4102. intdiff = floor(work->work_difficulty);
  4103. suffix_string(sharediff, diffdisp, 0);
  4104. sprintf(hashshow, "%08lx Diff %s/%d%s", (unsigned long)(hash32[6]), diffdisp, intdiff,
  4105. work->block? " BLOCK!" : "");
  4106. share_result(val, res_val, err_val, work, hashshow, false, "");
  4107. }
  4108. /* Parses stratum json responses and tries to find the id that the request
  4109. * matched to and treat it accordingly. */
  4110. static bool parse_stratum_response(struct pool *pool, char *s)
  4111. {
  4112. json_t *val = NULL, *err_val, *res_val, *id_val;
  4113. struct stratum_share *sshare;
  4114. json_error_t err;
  4115. bool ret = false;
  4116. int id;
  4117. val = JSON_LOADS(s, &err);
  4118. if (!val) {
  4119. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  4120. goto out;
  4121. }
  4122. res_val = json_object_get(val, "result");
  4123. err_val = json_object_get(val, "error");
  4124. id_val = json_object_get(val, "id");
  4125. if (json_is_null(id_val) || !id_val) {
  4126. char *ss;
  4127. if (err_val)
  4128. ss = json_dumps(err_val, JSON_INDENT(3));
  4129. else
  4130. ss = strdup("(unknown reason)");
  4131. applog(LOG_INFO, "JSON-RPC non method decode failed: %s", ss);
  4132. free(ss);
  4133. goto out;
  4134. }
  4135. id = json_integer_value(id_val);
  4136. mutex_lock(&sshare_lock);
  4137. HASH_FIND_INT(stratum_shares, &id, sshare);
  4138. if (sshare) {
  4139. HASH_DEL(stratum_shares, sshare);
  4140. pool->sshares--;
  4141. }
  4142. mutex_unlock(&sshare_lock);
  4143. if (!sshare) {
  4144. if (json_is_true(res_val))
  4145. applog(LOG_NOTICE, "Accepted untracked stratum share from pool %d", pool->pool_no);
  4146. else
  4147. applog(LOG_NOTICE, "Rejected untracked stratum share from pool %d", pool->pool_no);
  4148. goto out;
  4149. }
  4150. stratum_share_result(val, res_val, err_val, sshare);
  4151. free_work(sshare->work);
  4152. free(sshare);
  4153. ret = true;
  4154. out:
  4155. if (val)
  4156. json_decref(val);
  4157. return ret;
  4158. }
  4159. void clear_stratum_shares(struct pool *pool)
  4160. {
  4161. struct stratum_share *sshare, *tmpshare;
  4162. double diff_cleared = 0;
  4163. int cleared = 0;
  4164. mutex_lock(&sshare_lock);
  4165. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  4166. if (sshare->work->pool == pool) {
  4167. HASH_DEL(stratum_shares, sshare);
  4168. diff_cleared += sshare->work->work_difficulty;
  4169. free_work(sshare->work);
  4170. pool->sshares--;
  4171. free(sshare);
  4172. cleared++;
  4173. }
  4174. }
  4175. mutex_unlock(&sshare_lock);
  4176. if (cleared) {
  4177. applog(LOG_WARNING, "Lost %d shares due to stratum disconnect on pool %d", cleared, pool->pool_no);
  4178. pool->stale_shares += cleared;
  4179. total_stale += cleared;
  4180. pool->diff_stale += diff_cleared;
  4181. total_diff_stale += diff_cleared;
  4182. }
  4183. }
  4184. static void clear_pool_work(struct pool *pool)
  4185. {
  4186. struct work *work, *tmp;
  4187. int cleared = 0;
  4188. mutex_lock(stgd_lock);
  4189. HASH_ITER(hh, staged_work, work, tmp) {
  4190. if (work->pool == pool) {
  4191. HASH_DEL(staged_work, work);
  4192. free_work(work);
  4193. cleared++;
  4194. }
  4195. }
  4196. mutex_unlock(stgd_lock);
  4197. }
  4198. static int cp_prio(void)
  4199. {
  4200. int prio;
  4201. cg_rlock(&control_lock);
  4202. prio = currentpool->prio;
  4203. cg_runlock(&control_lock);
  4204. return prio;
  4205. }
  4206. /* We only need to maintain a secondary pool connection when we need the
  4207. * capacity to get work from the backup pools while still on the primary */
  4208. static bool cnx_needed(struct pool *pool)
  4209. {
  4210. struct pool *cp;
  4211. /* Balance strategies need all pools online */
  4212. if (pool_strategy == POOL_BALANCE)
  4213. return true;
  4214. if (pool_strategy == POOL_LOADBALANCE)
  4215. return true;
  4216. /* Idle stratum pool needs something to kick it alive again */
  4217. if (pool->has_stratum && pool->idle)
  4218. return true;
  4219. /* Getwork pools without opt_fail_only need backup pools up to be able
  4220. * to leak shares */
  4221. cp = current_pool();
  4222. if (cp == pool)
  4223. return true;
  4224. if (!cp->has_gbt && !cp->has_stratum && (!opt_fail_only || !cp->hdr_path))
  4225. return true;
  4226. /* If we're waiting for a response from shares submitted, keep the
  4227. * connection open. */
  4228. if (pool->sshares)
  4229. return true;
  4230. /* If the pool has only just come to life and is higher priority than
  4231. * the current pool keep the connection open so we can fail back to
  4232. * it. */
  4233. if (pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  4234. return true;
  4235. if (pool_unworkable(cp))
  4236. return true;
  4237. return false;
  4238. }
  4239. static void wait_lpcurrent(struct pool *pool);
  4240. static void pool_resus(struct pool *pool);
  4241. static void gen_stratum_work(struct pool *pool, struct work *work);
  4242. static void stratum_resumed(struct pool *pool)
  4243. {
  4244. if (!pool->stratum_notify)
  4245. return;
  4246. if (pool_tclear(pool, &pool->idle)) {
  4247. applog(LOG_INFO, "Stratum connection to pool %d resumed", pool->pool_no);
  4248. pool_resus(pool);
  4249. }
  4250. }
  4251. static bool supports_resume(struct pool *pool)
  4252. {
  4253. bool ret;
  4254. cg_rlock(&pool->data_lock);
  4255. ret = (pool->sessionid != NULL);
  4256. cg_runlock(&pool->data_lock);
  4257. return ret;
  4258. }
  4259. /* One stratum thread per pool that has stratum waits on the socket checking
  4260. * for new messages and for the integrity of the socket connection. We reset
  4261. * the connection based on the integrity of the receive side only as the send
  4262. * side will eventually expire data it fails to send. */
  4263. static void *stratum_thread(void *userdata)
  4264. {
  4265. struct pool *pool = (struct pool *)userdata;
  4266. char threadname[16];
  4267. pthread_detach(pthread_self());
  4268. snprintf(threadname, 16, "stratum/%d", pool->pool_no);
  4269. RenameThread(threadname);
  4270. while (42) {
  4271. struct timeval timeout;
  4272. int sel_ret;
  4273. fd_set rd;
  4274. char *s;
  4275. if (unlikely(pool->removed))
  4276. break;
  4277. /* Check to see whether we need to maintain this connection
  4278. * indefinitely or just bring it up when we switch to this
  4279. * pool */
  4280. if (!sock_full(pool) && !cnx_needed(pool)) {
  4281. suspend_stratum(pool);
  4282. clear_stratum_shares(pool);
  4283. clear_pool_work(pool);
  4284. wait_lpcurrent(pool);
  4285. if (!restart_stratum(pool)) {
  4286. pool_died(pool);
  4287. while (!restart_stratum(pool)) {
  4288. if (pool->removed)
  4289. goto out;
  4290. nmsleep(30000);
  4291. }
  4292. }
  4293. }
  4294. FD_ZERO(&rd);
  4295. FD_SET(pool->sock, &rd);
  4296. timeout.tv_sec = 90;
  4297. timeout.tv_usec = 0;
  4298. /* The protocol specifies that notify messages should be sent
  4299. * every minute so if we fail to receive any for 90 seconds we
  4300. * assume the connection has been dropped and treat this pool
  4301. * as dead */
  4302. if (!sock_full(pool) && (sel_ret = select(pool->sock + 1, &rd, NULL, NULL, &timeout)) < 1) {
  4303. applog(LOG_DEBUG, "Stratum select failed on pool %d with value %d", pool->pool_no, sel_ret);
  4304. s = NULL;
  4305. } else
  4306. s = recv_line(pool);
  4307. if (!s) {
  4308. applog(LOG_NOTICE, "Stratum connection to pool %d interrupted", pool->pool_no);
  4309. pool->getfail_occasions++;
  4310. total_go++;
  4311. /* If the socket to our stratum pool disconnects, all
  4312. * tracked submitted shares are lost and we will leak
  4313. * the memory if we don't discard their records. */
  4314. if (!supports_resume(pool))
  4315. clear_stratum_shares(pool);
  4316. clear_pool_work(pool);
  4317. if (pool == current_pool())
  4318. restart_threads();
  4319. if (restart_stratum(pool))
  4320. continue;
  4321. pool_died(pool);
  4322. while (!restart_stratum(pool)) {
  4323. if (pool->removed)
  4324. goto out;
  4325. nmsleep(30000);
  4326. }
  4327. stratum_resumed(pool);
  4328. continue;
  4329. }
  4330. /* Check this pool hasn't died while being a backup pool and
  4331. * has not had its idle flag cleared */
  4332. stratum_resumed(pool);
  4333. if (!parse_method(pool, s) && !parse_stratum_response(pool, s))
  4334. applog(LOG_INFO, "Unknown stratum msg: %s", s);
  4335. free(s);
  4336. if (pool->swork.clean) {
  4337. struct work *work = make_work();
  4338. /* Generate a single work item to update the current
  4339. * block database */
  4340. pool->swork.clean = false;
  4341. gen_stratum_work(pool, work);
  4342. if (test_work_current(work)) {
  4343. /* Only accept a work restart if this stratum
  4344. * connection is from the current pool */
  4345. if (pool == current_pool()) {
  4346. restart_threads();
  4347. applog(LOG_NOTICE, "Stratum from pool %d requested work restart", pool->pool_no);
  4348. }
  4349. } else
  4350. applog(LOG_NOTICE, "Stratum from pool %d detected new block", pool->pool_no);
  4351. free_work(work);
  4352. }
  4353. }
  4354. out:
  4355. return NULL;
  4356. }
  4357. static void init_stratum_thread(struct pool *pool)
  4358. {
  4359. if (unlikely(pthread_create(&pool->stratum_thread, NULL, stratum_thread, (void *)pool)))
  4360. quit(1, "Failed to create stratum thread");
  4361. }
  4362. static void *longpoll_thread(void *userdata);
  4363. static bool stratum_works(struct pool *pool)
  4364. {
  4365. applog(LOG_INFO, "Testing pool %d stratum %s", pool->pool_no, pool->stratum_url);
  4366. if (!extract_sockaddr(pool, pool->stratum_url))
  4367. return false;
  4368. if (!initiate_stratum(pool))
  4369. return false;
  4370. return true;
  4371. }
  4372. static bool pool_active(struct pool *pool, bool pinging)
  4373. {
  4374. struct timeval tv_getwork, tv_getwork_reply;
  4375. bool ret = false;
  4376. json_t *val;
  4377. CURL *curl;
  4378. int rolltime;
  4379. if (pool->has_gbt)
  4380. applog(LOG_DEBUG, "Retrieving block template from pool %s", pool->rpc_url);
  4381. else
  4382. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  4383. /* This is the central point we activate stratum when we can */
  4384. retry_stratum:
  4385. if (pool->has_stratum) {
  4386. /* We create the stratum thread for each pool just after
  4387. * successful authorisation. Once the init flag has been set
  4388. * we never unset it and the stratum thread is responsible for
  4389. * setting/unsetting the active flag */
  4390. bool init = pool_tset(pool, &pool->stratum_init);
  4391. if (!init) {
  4392. bool ret = initiate_stratum(pool) && auth_stratum(pool);
  4393. if (ret)
  4394. init_stratum_thread(pool);
  4395. else
  4396. pool_tclear(pool, &pool->stratum_init);
  4397. return ret;
  4398. }
  4399. return pool->stratum_active;
  4400. }
  4401. curl = curl_easy_init();
  4402. if (unlikely(!curl)) {
  4403. applog(LOG_ERR, "CURL initialisation failed");
  4404. return false;
  4405. }
  4406. /* Probe for GBT support on first pass */
  4407. if (!pool->probed && !opt_fix_protocol) {
  4408. applog(LOG_DEBUG, "Probing for GBT support");
  4409. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass,
  4410. gbt_req, true, false, &rolltime, pool, false);
  4411. if (val) {
  4412. bool append = false, submit = false;
  4413. json_t *res_val, *mutables;
  4414. int i, mutsize = 0;
  4415. res_val = json_object_get(val, "result");
  4416. if (res_val) {
  4417. mutables = json_object_get(res_val, "mutable");
  4418. mutsize = json_array_size(mutables);
  4419. }
  4420. for (i = 0; i < mutsize; i++) {
  4421. json_t *arrval = json_array_get(mutables, i);
  4422. if (json_is_string(arrval)) {
  4423. const char *mutable = json_string_value(arrval);
  4424. if (!strncasecmp(mutable, "coinbase/append", 15))
  4425. append = true;
  4426. else if (!strncasecmp(mutable, "submit/coinbase", 15))
  4427. submit = true;
  4428. }
  4429. }
  4430. json_decref(val);
  4431. /* Only use GBT if it supports coinbase append and
  4432. * submit coinbase */
  4433. if (append && submit) {
  4434. pool->has_gbt = true;
  4435. pool->rpc_req = gbt_req;
  4436. }
  4437. }
  4438. /* Reset this so we can probe fully just after this. It will be
  4439. * set to true that time.*/
  4440. pool->probed = false;
  4441. if (pool->has_gbt)
  4442. applog(LOG_DEBUG, "GBT coinbase + append support found, switching to GBT protocol");
  4443. else
  4444. applog(LOG_DEBUG, "No GBT coinbase + append support found, using getwork protocol");
  4445. }
  4446. gettimeofday(&tv_getwork, NULL);
  4447. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass,
  4448. pool->rpc_req, true, false, &rolltime, pool, false);
  4449. gettimeofday(&tv_getwork_reply, NULL);
  4450. /* Detect if a http getwork pool has an X-Stratum header at startup,
  4451. * and if so, switch to that in preference to getwork if it works */
  4452. if (pool->stratum_url && !opt_fix_protocol && stratum_works(pool)) {
  4453. applog(LOG_NOTICE, "Switching pool %d %s to %s", pool->pool_no, pool->rpc_url, pool->stratum_url);
  4454. if (!pool->rpc_url)
  4455. pool->rpc_url = strdup(pool->stratum_url);
  4456. pool->has_stratum = true;
  4457. curl_easy_cleanup(curl);
  4458. goto retry_stratum;
  4459. }
  4460. if (val) {
  4461. struct work *work = make_work();
  4462. bool rc;
  4463. rc = work_decode(pool, work, val);
  4464. if (rc) {
  4465. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  4466. pool->pool_no, pool->rpc_url);
  4467. work->pool = pool;
  4468. work->rolltime = rolltime;
  4469. memcpy(&(work->tv_getwork), &tv_getwork, sizeof(struct timeval));
  4470. memcpy(&(work->tv_getwork_reply), &tv_getwork_reply, sizeof(struct timeval));
  4471. work->getwork_mode = GETWORK_MODE_TESTPOOL;
  4472. calc_diff(work, 0);
  4473. applog(LOG_DEBUG, "Pushing pooltest work to base pool");
  4474. tq_push(control_thr[stage_thr_id].q, work);
  4475. total_getworks++;
  4476. pool->getwork_requested++;
  4477. ret = true;
  4478. gettimeofday(&pool->tv_idle, NULL);
  4479. } else {
  4480. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher work from pool %u %s",
  4481. pool->pool_no, pool->rpc_url);
  4482. free_work(work);
  4483. }
  4484. json_decref(val);
  4485. if (pool->lp_url)
  4486. goto out;
  4487. /* Decipher the longpoll URL, if any, and store it in ->lp_url */
  4488. if (pool->hdr_path) {
  4489. char *copy_start, *hdr_path;
  4490. bool need_slash = false;
  4491. hdr_path = pool->hdr_path;
  4492. if (strstr(hdr_path, "://")) {
  4493. pool->lp_url = hdr_path;
  4494. hdr_path = NULL;
  4495. } else {
  4496. /* absolute path, on current server */
  4497. copy_start = (*hdr_path == '/') ? (hdr_path + 1) : hdr_path;
  4498. if (pool->rpc_url[strlen(pool->rpc_url) - 1] != '/')
  4499. need_slash = true;
  4500. pool->lp_url = malloc(strlen(pool->rpc_url) + strlen(copy_start) + 2);
  4501. if (!pool->lp_url) {
  4502. applog(LOG_ERR, "Malloc failure in pool_active");
  4503. return false;
  4504. }
  4505. sprintf(pool->lp_url, "%s%s%s", pool->rpc_url, need_slash ? "/" : "", copy_start);
  4506. }
  4507. } else
  4508. pool->lp_url = NULL;
  4509. if (!pool->lp_started) {
  4510. pool->lp_started = true;
  4511. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  4512. quit(1, "Failed to create pool longpoll thread");
  4513. }
  4514. } else {
  4515. /* If we failed to parse a getwork, this could be a stratum
  4516. * url without the prefix stratum+tcp:// so let's check it */
  4517. if (initiate_stratum(pool)) {
  4518. pool->has_stratum = true;
  4519. goto retry_stratum;
  4520. }
  4521. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  4522. pool->pool_no, pool->rpc_url);
  4523. if (!pinging)
  4524. applog(LOG_WARNING, "Pool %u slow/down or URL or credentials invalid", pool->pool_no);
  4525. }
  4526. out:
  4527. curl_easy_cleanup(curl);
  4528. return ret;
  4529. }
  4530. static void pool_resus(struct pool *pool)
  4531. {
  4532. if (pool_strategy == POOL_FAILOVER && pool->prio < cp_prio()) {
  4533. applog(LOG_WARNING, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  4534. switch_pools(NULL);
  4535. } else
  4536. applog(LOG_INFO, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  4537. }
  4538. static struct work *hash_pop(void)
  4539. {
  4540. struct work *work = NULL, *tmp;
  4541. int hc;
  4542. mutex_lock(stgd_lock);
  4543. while (!getq->frozen && !HASH_COUNT(staged_work))
  4544. pthread_cond_wait(&getq->cond, stgd_lock);
  4545. hc = HASH_COUNT(staged_work);
  4546. /* Find clone work if possible, to allow masters to be reused */
  4547. if (hc > staged_rollable) {
  4548. HASH_ITER(hh, staged_work, work, tmp) {
  4549. if (!work_rollable(work))
  4550. break;
  4551. }
  4552. } else
  4553. work = staged_work;
  4554. HASH_DEL(staged_work, work);
  4555. if (work_rollable(work))
  4556. staged_rollable--;
  4557. /* Signal the getwork scheduler to look for more work */
  4558. pthread_cond_signal(&gws_cond);
  4559. /* Signal hash_pop again in case there are mutliple hash_pop waiters */
  4560. pthread_cond_signal(&getq->cond);
  4561. mutex_unlock(stgd_lock);
  4562. return work;
  4563. }
  4564. /* Clones work by rolling it if possible, and returning a clone instead of the
  4565. * original work item which gets staged again to possibly be rolled again in
  4566. * the future */
  4567. static struct work *clone_work(struct work *work)
  4568. {
  4569. int mrs = mining_threads + opt_queue - total_staged();
  4570. struct work *work_clone;
  4571. bool cloned;
  4572. if (mrs < 1)
  4573. return work;
  4574. cloned = false;
  4575. work_clone = make_clone(work);
  4576. while (mrs-- > 0 && can_roll(work) && should_roll(work)) {
  4577. applog(LOG_DEBUG, "Pushing rolled converted work to stage thread");
  4578. stage_work(work_clone);
  4579. roll_work(work);
  4580. work_clone = make_clone(work);
  4581. /* Roll it again to prevent duplicates should this be used
  4582. * directly later on */
  4583. roll_work(work);
  4584. cloned = true;
  4585. }
  4586. if (cloned) {
  4587. stage_work(work);
  4588. return work_clone;
  4589. }
  4590. free_work(work_clone);
  4591. return work;
  4592. }
  4593. static void gen_hash(unsigned char *data, unsigned char *hash, int len)
  4594. {
  4595. unsigned char hash1[32];
  4596. sha2(data, len, hash1);
  4597. sha2(hash1, 32, hash);
  4598. }
  4599. /* Diff 1 is a 256 bit unsigned integer of
  4600. * 0x00000000ffff0000000000000000000000000000000000000000000000000000
  4601. * so we use a big endian 64 bit unsigned integer centred on the 5th byte to
  4602. * cover a huge range of difficulty targets, though not all 256 bits' worth */
  4603. static void set_work_target(struct work *work, double diff)
  4604. {
  4605. unsigned char target[32];
  4606. uint64_t *data64, h64;
  4607. double d64;
  4608. d64 = diffone;
  4609. d64 /= diff;
  4610. h64 = d64;
  4611. memset(target, 0, 32);
  4612. if (h64) {
  4613. unsigned char rtarget[32];
  4614. memset(rtarget, 0, 32);
  4615. if (opt_scrypt)
  4616. data64 = (uint64_t *)(rtarget + 2);
  4617. else
  4618. data64 = (uint64_t *)(rtarget + 4);
  4619. *data64 = htobe64(h64);
  4620. swab256(target, rtarget);
  4621. } else {
  4622. /* Support for the classic all FFs just-below-1 diff */
  4623. if (opt_scrypt)
  4624. memset(target, 0xff, 30);
  4625. else
  4626. memset(target, 0xff, 28);
  4627. }
  4628. if (opt_debug) {
  4629. char *htarget = bin2hex(target, 32);
  4630. applog(LOG_DEBUG, "Generated target %s", htarget);
  4631. free(htarget);
  4632. }
  4633. memcpy(work->target, target, 32);
  4634. }
  4635. /* Generates stratum based work based on the most recent notify information
  4636. * from the pool. This will keep generating work while a pool is down so we use
  4637. * other means to detect when the pool has died in stratum_thread */
  4638. static void gen_stratum_work(struct pool *pool, struct work *work)
  4639. {
  4640. unsigned char *coinbase, merkle_root[32], merkle_sha[64];
  4641. char *header, *merkle_hash;
  4642. uint32_t *data32, *swap32;
  4643. size_t alloc_len;
  4644. int i;
  4645. /* Use intermediate lock to update the one pool variable */
  4646. cg_ilock(&pool->data_lock);
  4647. /* Generate coinbase */
  4648. work->nonce2 = bin2hex((const unsigned char *)&pool->nonce2, pool->n2size);
  4649. pool->nonce2++;
  4650. /* Downgrade to a read lock to read off the pool variables */
  4651. cg_dlock(&pool->data_lock);
  4652. alloc_len = pool->swork.cb_len;
  4653. align_len(&alloc_len);
  4654. coinbase = calloc(alloc_len, 1);
  4655. if (unlikely(!coinbase))
  4656. quit(1, "Failed to calloc coinbase in gen_stratum_work");
  4657. hex2bin(coinbase, pool->swork.coinbase1, pool->swork.cb1_len);
  4658. hex2bin(coinbase + pool->swork.cb1_len, pool->nonce1, pool->n1_len);
  4659. hex2bin(coinbase + pool->swork.cb1_len + pool->n1_len, work->nonce2, pool->n2size);
  4660. hex2bin(coinbase + pool->swork.cb1_len + pool->n1_len + pool->n2size, pool->swork.coinbase2, pool->swork.cb2_len);
  4661. /* Generate merkle root */
  4662. gen_hash(coinbase, merkle_root, pool->swork.cb_len);
  4663. free(coinbase);
  4664. memcpy(merkle_sha, merkle_root, 32);
  4665. for (i = 0; i < pool->swork.merkles; i++) {
  4666. unsigned char merkle_bin[32];
  4667. hex2bin(merkle_bin, pool->swork.merkle[i], 32);
  4668. memcpy(merkle_sha + 32, merkle_bin, 32);
  4669. gen_hash(merkle_sha, merkle_root, 64);
  4670. memcpy(merkle_sha, merkle_root, 32);
  4671. }
  4672. data32 = (uint32_t *)merkle_sha;
  4673. swap32 = (uint32_t *)merkle_root;
  4674. for (i = 0; i < 32 / 4; i++)
  4675. swap32[i] = swab32(data32[i]);
  4676. merkle_hash = bin2hex((const unsigned char *)merkle_root, 32);
  4677. header = calloc(pool->swork.header_len, 1);
  4678. if (unlikely(!header))
  4679. quit(1, "Failed to calloc header in gen_stratum_work");
  4680. sprintf(header, "%s%s%s%s%s%s%s",
  4681. pool->swork.bbversion,
  4682. pool->swork.prev_hash,
  4683. merkle_hash,
  4684. pool->swork.ntime,
  4685. pool->swork.nbit,
  4686. "00000000", /* nonce */
  4687. workpadding);
  4688. /* Store the stratum work diff to check it still matches the pool's
  4689. * stratum diff when submitting shares */
  4690. work->sdiff = pool->swork.diff;
  4691. /* Copy parameters required for share submission */
  4692. work->job_id = strdup(pool->swork.job_id);
  4693. work->nonce1 = strdup(pool->nonce1);
  4694. work->ntime = strdup(pool->swork.ntime);
  4695. cg_runlock(&pool->data_lock);
  4696. applog(LOG_DEBUG, "Generated stratum merkle %s", merkle_hash);
  4697. applog(LOG_DEBUG, "Generated stratum header %s", header);
  4698. applog(LOG_DEBUG, "Work job_id %s nonce2 %s ntime %s", work->job_id, work->nonce2, work->ntime);
  4699. free(merkle_hash);
  4700. /* Convert hex data to binary data for work */
  4701. if (unlikely(!hex2bin(work->data, header, 128)))
  4702. quit(1, "Failed to convert header to data in gen_stratum_work");
  4703. free(header);
  4704. calc_midstate(work);
  4705. set_work_target(work, work->sdiff);
  4706. local_work++;
  4707. work->pool = pool;
  4708. work->stratum = true;
  4709. work->blk.nonce = 0;
  4710. work->id = total_work++;
  4711. work->longpoll = false;
  4712. work->getwork_mode = GETWORK_MODE_STRATUM;
  4713. work->work_block = work_block;
  4714. calc_diff(work, work->sdiff);
  4715. gettimeofday(&work->tv_staged, NULL);
  4716. }
  4717. static struct work *get_work(struct thr_info *thr, const int thr_id)
  4718. {
  4719. struct work *work = NULL;
  4720. /* Tell the watchdog thread this thread is waiting on getwork and
  4721. * should not be restarted */
  4722. thread_reportout(thr);
  4723. applog(LOG_DEBUG, "Popping work from get queue to get work");
  4724. while (!work) {
  4725. work = hash_pop();
  4726. if (stale_work(work, false)) {
  4727. discard_work(work);
  4728. work = NULL;
  4729. wake_gws();
  4730. }
  4731. }
  4732. applog(LOG_DEBUG, "Got work from get queue to get work for thread %d", thr_id);
  4733. work->thr_id = thr_id;
  4734. thread_reportin(thr);
  4735. work->mined = true;
  4736. return work;
  4737. }
  4738. void submit_work_async(struct work *work_in, struct timeval *tv_work_found)
  4739. {
  4740. struct work *work = copy_work(work_in);
  4741. pthread_t submit_thread;
  4742. if (tv_work_found)
  4743. memcpy(&(work->tv_work_found), tv_work_found, sizeof(struct timeval));
  4744. applog(LOG_DEBUG, "Pushing submit work to work thread");
  4745. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, (void *)work)))
  4746. quit(1, "Failed to create submit_work_thread");
  4747. }
  4748. static bool hashtest(struct thr_info *thr, struct work *work)
  4749. {
  4750. uint32_t *data32 = (uint32_t *)(work->data);
  4751. unsigned char swap[80];
  4752. uint32_t *swap32 = (uint32_t *)swap;
  4753. unsigned char hash1[32];
  4754. unsigned char hash2[32];
  4755. uint32_t *hash2_32 = (uint32_t *)hash2;
  4756. bool ret = false;
  4757. flip80(swap32, data32);
  4758. sha2(swap, 80, hash1);
  4759. sha2(hash1, 32, work->hash);
  4760. flip32(hash2_32, work->hash);
  4761. if (hash2_32[7] != 0) {
  4762. applog(LOG_WARNING, "%s%d: invalid nonce - HW error",
  4763. thr->cgpu->drv->name, thr->cgpu->device_id);
  4764. mutex_lock(&stats_lock);
  4765. hw_errors++;
  4766. thr->cgpu->hw_errors++;
  4767. mutex_unlock(&stats_lock);
  4768. thr->cgpu->drv->hw_error(thr);
  4769. goto out;
  4770. }
  4771. mutex_lock(&stats_lock);
  4772. thr->cgpu->last_device_valid_work = time(NULL);
  4773. mutex_unlock(&stats_lock);
  4774. ret = fulltest(hash2, work->target);
  4775. if (!ret) {
  4776. applog(LOG_INFO, "Share below target");
  4777. /* Check the diff of the share, even if it didn't reach the
  4778. * target, just to set the best share value if it's higher. */
  4779. share_diff(work);
  4780. }
  4781. out:
  4782. return ret;
  4783. }
  4784. void submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  4785. {
  4786. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  4787. struct timeval tv_work_found;
  4788. gettimeofday(&tv_work_found, NULL);
  4789. *work_nonce = htole32(nonce);
  4790. mutex_lock(&stats_lock);
  4791. total_diff1 += work->device_diff;
  4792. thr->cgpu->diff1 += work->device_diff;
  4793. work->pool->diff1 += work->device_diff;
  4794. mutex_unlock(&stats_lock);
  4795. /* Do one last check before attempting to submit the work */
  4796. if (!opt_scrypt && !hashtest(thr, work))
  4797. return;
  4798. submit_work_async(work, &tv_work_found);
  4799. }
  4800. static inline bool abandon_work(struct work *work, struct timeval *wdiff, uint64_t hashes)
  4801. {
  4802. if (wdiff->tv_sec > opt_scantime ||
  4803. work->blk.nonce >= MAXTHREADS - hashes ||
  4804. hashes >= 0xfffffffe ||
  4805. stale_work(work, false))
  4806. return true;
  4807. return false;
  4808. }
  4809. static void mt_disable(struct thr_info *mythr, const int thr_id,
  4810. struct device_drv *drv)
  4811. {
  4812. applog(LOG_WARNING, "Thread %d being disabled", thr_id);
  4813. mythr->rolling = mythr->cgpu->rolling = 0;
  4814. applog(LOG_DEBUG, "Popping wakeup ping in miner thread");
  4815. thread_reportout(mythr);
  4816. do {
  4817. tq_pop(mythr->q, NULL); /* Ignore ping that's popped */
  4818. } while (mythr->pause);
  4819. thread_reportin(mythr);
  4820. applog(LOG_WARNING, "Thread %d being re-enabled", thr_id);
  4821. drv->thread_enable(mythr);
  4822. }
  4823. /* The main hashing loop for devices that are slow enough to work on one work
  4824. * item at a time, without a queue, aborting work before the entire nonce
  4825. * range has been hashed if needed. */
  4826. static void hash_sole_work(struct thr_info *mythr)
  4827. {
  4828. const int thr_id = mythr->id;
  4829. struct cgpu_info *cgpu = mythr->cgpu;
  4830. struct device_drv *drv = cgpu->drv;
  4831. struct timeval getwork_start, tv_start, tv_end, tv_workstart, tv_lastupdate;
  4832. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  4833. struct cgminer_stats *pool_stats;
  4834. /* Try to cycle approximately 5 times before each log update */
  4835. const long cycle = opt_log_interval / 5 ? : 1;
  4836. const bool primary = (!mythr->device_thread) || mythr->primary_thread;
  4837. struct timeval diff, sdiff, wdiff = {0, 0};
  4838. uint32_t max_nonce = drv->can_limit_work(mythr);
  4839. int64_t hashes_done = 0;
  4840. gettimeofday(&getwork_start, NULL);
  4841. sdiff.tv_sec = sdiff.tv_usec = 0;
  4842. gettimeofday(&tv_lastupdate, NULL);
  4843. while (42) {
  4844. struct work *work = get_work(mythr, thr_id);
  4845. int64_t hashes;
  4846. mythr->work_restart = false;
  4847. cgpu->new_work = true;
  4848. gettimeofday(&tv_workstart, NULL);
  4849. work->blk.nonce = 0;
  4850. cgpu->max_hashes = 0;
  4851. if (!drv->prepare_work(mythr, work)) {
  4852. applog(LOG_ERR, "work prepare failed, exiting "
  4853. "mining thread %d", thr_id);
  4854. break;
  4855. }
  4856. work->device_diff = MIN(drv->max_diff, work->work_difficulty);
  4857. do {
  4858. gettimeofday(&tv_start, NULL);
  4859. timersub(&tv_start, &getwork_start, &getwork_start);
  4860. timeradd(&getwork_start,
  4861. &(dev_stats->getwork_wait),
  4862. &(dev_stats->getwork_wait));
  4863. if (timercmp(&getwork_start, &(dev_stats->getwork_wait_max), >)) {
  4864. dev_stats->getwork_wait_max.tv_sec = getwork_start.tv_sec;
  4865. dev_stats->getwork_wait_max.tv_usec = getwork_start.tv_usec;
  4866. }
  4867. if (timercmp(&getwork_start, &(dev_stats->getwork_wait_min), <)) {
  4868. dev_stats->getwork_wait_min.tv_sec = getwork_start.tv_sec;
  4869. dev_stats->getwork_wait_min.tv_usec = getwork_start.tv_usec;
  4870. }
  4871. dev_stats->getwork_calls++;
  4872. pool_stats = &(work->pool->cgminer_stats);
  4873. timeradd(&getwork_start,
  4874. &(pool_stats->getwork_wait),
  4875. &(pool_stats->getwork_wait));
  4876. if (timercmp(&getwork_start, &(pool_stats->getwork_wait_max), >)) {
  4877. pool_stats->getwork_wait_max.tv_sec = getwork_start.tv_sec;
  4878. pool_stats->getwork_wait_max.tv_usec = getwork_start.tv_usec;
  4879. }
  4880. if (timercmp(&getwork_start, &(pool_stats->getwork_wait_min), <)) {
  4881. pool_stats->getwork_wait_min.tv_sec = getwork_start.tv_sec;
  4882. pool_stats->getwork_wait_min.tv_usec = getwork_start.tv_usec;
  4883. }
  4884. pool_stats->getwork_calls++;
  4885. gettimeofday(&(work->tv_work_start), NULL);
  4886. thread_reportin(mythr);
  4887. hashes = drv->scanhash(mythr, work, work->blk.nonce + max_nonce);
  4888. thread_reportin(mythr);
  4889. gettimeofday(&getwork_start, NULL);
  4890. if (unlikely(hashes == -1)) {
  4891. applog(LOG_ERR, "%s %d failure, disabling!", drv->name, cgpu->device_id);
  4892. cgpu->deven = DEV_DISABLED;
  4893. dev_error(cgpu, REASON_THREAD_ZERO_HASH);
  4894. mt_disable(mythr, thr_id, drv);
  4895. }
  4896. hashes_done += hashes;
  4897. if (hashes > cgpu->max_hashes)
  4898. cgpu->max_hashes = hashes;
  4899. gettimeofday(&tv_end, NULL);
  4900. timersub(&tv_end, &tv_start, &diff);
  4901. sdiff.tv_sec += diff.tv_sec;
  4902. sdiff.tv_usec += diff.tv_usec;
  4903. if (sdiff.tv_usec > 1000000) {
  4904. ++sdiff.tv_sec;
  4905. sdiff.tv_usec -= 1000000;
  4906. }
  4907. timersub(&tv_end, &tv_workstart, &wdiff);
  4908. if (unlikely((long)sdiff.tv_sec < cycle)) {
  4909. int mult;
  4910. if (likely(max_nonce == 0xffffffff))
  4911. continue;
  4912. mult = 1000000 / ((sdiff.tv_usec + 0x400) / 0x400) + 0x10;
  4913. mult *= cycle;
  4914. if (max_nonce > (0xffffffff * 0x400) / mult)
  4915. max_nonce = 0xffffffff;
  4916. else
  4917. max_nonce = (max_nonce * mult) / 0x400;
  4918. } else if (unlikely(sdiff.tv_sec > cycle))
  4919. max_nonce = max_nonce * cycle / sdiff.tv_sec;
  4920. else if (unlikely(sdiff.tv_usec > 100000))
  4921. max_nonce = max_nonce * 0x400 / (((cycle * 1000000) + sdiff.tv_usec) / (cycle * 1000000 / 0x400));
  4922. timersub(&tv_end, &tv_lastupdate, &diff);
  4923. /* Update the hashmeter at most 5 times per second */
  4924. if (diff.tv_sec > 0 || diff.tv_usec > 200) {
  4925. hashmeter(thr_id, &diff, hashes_done);
  4926. hashes_done = 0;
  4927. memcpy(&tv_lastupdate, &tv_end, sizeof(struct timeval));
  4928. }
  4929. if (unlikely(mythr->work_restart)) {
  4930. /* Apart from device_thread 0, we stagger the
  4931. * starting of every next thread to try and get
  4932. * all devices busy before worrying about
  4933. * getting work for their extra threads */
  4934. if (!primary) {
  4935. struct timespec rgtp;
  4936. rgtp.tv_sec = 0;
  4937. rgtp.tv_nsec = 250 * mythr->device_thread * 1000000;
  4938. nanosleep(&rgtp, NULL);
  4939. }
  4940. break;
  4941. }
  4942. if (unlikely(mythr->pause || cgpu->deven != DEV_ENABLED))
  4943. mt_disable(mythr, thr_id, drv);
  4944. sdiff.tv_sec = sdiff.tv_usec = 0;
  4945. } while (!abandon_work(work, &wdiff, cgpu->max_hashes));
  4946. free_work(work);
  4947. }
  4948. }
  4949. /* Create a hashtable of work items for devices with a queue. The device
  4950. * driver must have a custom queue_full function or it will default to true
  4951. * and put only one work item in the queue. Work items should not be removed
  4952. * from this hashtable until they are no longer in use anywhere. Once a work
  4953. * item is physically queued on the device itself, the work->queued flag
  4954. * should be set under cgpu->qlock write lock to prevent it being dereferenced
  4955. * while still in use. */
  4956. static void fill_queue(struct thr_info *mythr, struct cgpu_info *cgpu, struct device_drv *drv, const int thr_id)
  4957. {
  4958. thread_reportout(mythr);
  4959. do {
  4960. struct work *work = get_work(mythr, thr_id);
  4961. work->device_diff = MIN(drv->max_diff, work->work_difficulty);
  4962. wr_lock(&cgpu->qlock);
  4963. HASH_ADD_INT(cgpu->queued_work, id, work);
  4964. wr_unlock(&cgpu->qlock);
  4965. /* The queue_full function should be used by the driver to
  4966. * actually place work items on the physical device if it
  4967. * does have a queue. */
  4968. } while (!drv->queue_full(cgpu));
  4969. }
  4970. /* This function is for retrieving one work item from the queued hashtable of
  4971. * available work items that are not yet physically on a device (which is
  4972. * flagged with the work->queued bool). Code using this function must be able
  4973. * to handle NULL as a return which implies there is no work available. */
  4974. struct work *get_queued(struct cgpu_info *cgpu)
  4975. {
  4976. struct work *work, *tmp, *ret = NULL;
  4977. wr_lock(&cgpu->qlock);
  4978. HASH_ITER(hh, cgpu->queued_work, work, tmp) {
  4979. if (!work->queued) {
  4980. work->queued = true;
  4981. ret = work;
  4982. break;
  4983. }
  4984. }
  4985. wr_unlock(&cgpu->qlock);
  4986. return ret;
  4987. }
  4988. /* This function should be used by queued device drivers when they're sure
  4989. * the work struct is no longer in use. */
  4990. void work_completed(struct cgpu_info *cgpu, struct work *work)
  4991. {
  4992. wr_lock(&cgpu->qlock);
  4993. HASH_DEL(cgpu->queued_work, work);
  4994. wr_unlock(&cgpu->qlock);
  4995. free_work(work);
  4996. }
  4997. static void flush_queue(struct cgpu_info *cgpu)
  4998. {
  4999. struct work *work, *tmp;
  5000. int discarded = 0;
  5001. wr_lock(&cgpu->qlock);
  5002. HASH_ITER(hh, cgpu->queued_work, work, tmp) {
  5003. /* Can only discard the work items if they're not physically
  5004. * queued on the device. */
  5005. if (!work->queued) {
  5006. HASH_DEL(cgpu->queued_work, work);
  5007. discard_work(work);
  5008. discarded++;
  5009. }
  5010. }
  5011. wr_unlock(&cgpu->qlock);
  5012. if (discarded)
  5013. applog(LOG_DEBUG, "Discarded %d queued work items", discarded);
  5014. }
  5015. /* This version of hash work is for devices that are fast enough to always
  5016. * perform a full nonce range and need a queue to maintain the device busy.
  5017. * Work creation and destruction is not done from within this function
  5018. * directly. */
  5019. void hash_queued_work(struct thr_info *mythr)
  5020. {
  5021. const long cycle = opt_log_interval / 5 ? : 1;
  5022. struct timeval tv_start = {0, 0}, tv_end;
  5023. struct cgpu_info *cgpu = mythr->cgpu;
  5024. struct device_drv *drv = cgpu->drv;
  5025. const int thr_id = mythr->id;
  5026. int64_t hashes_done = 0;
  5027. while (42) {
  5028. struct timeval diff;
  5029. int64_t hashes;
  5030. mythr->work_restart = false;
  5031. fill_queue(mythr, cgpu, drv, thr_id);
  5032. thread_reportin(mythr);
  5033. hashes = drv->scanwork(mythr);
  5034. if (unlikely(hashes == -1 )) {
  5035. applog(LOG_ERR, "%s %d failure, disabling!", drv->name, cgpu->device_id);
  5036. cgpu->deven = DEV_DISABLED;
  5037. dev_error(cgpu, REASON_THREAD_ZERO_HASH);
  5038. mt_disable(mythr, thr_id, drv);
  5039. }
  5040. hashes_done += hashes;
  5041. gettimeofday(&tv_end, NULL);
  5042. timersub(&tv_end, &tv_start, &diff);
  5043. if (diff.tv_sec >= cycle) {
  5044. hashmeter(thr_id, &diff, hashes_done);
  5045. hashes_done = 0;
  5046. memcpy(&tv_start, &tv_end, sizeof(struct timeval));
  5047. }
  5048. if (unlikely(mythr->work_restart)) {
  5049. flush_queue(cgpu);
  5050. drv->flush_work(cgpu);
  5051. }
  5052. if (unlikely(mythr->pause || cgpu->deven != DEV_ENABLED))
  5053. mt_disable(mythr, thr_id, drv);
  5054. }
  5055. }
  5056. void *miner_thread(void *userdata)
  5057. {
  5058. struct thr_info *mythr = userdata;
  5059. const int thr_id = mythr->id;
  5060. struct cgpu_info *cgpu = mythr->cgpu;
  5061. struct device_drv *drv = cgpu->drv;
  5062. char threadname[24];
  5063. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  5064. snprintf(threadname, 24, "miner/%d", thr_id);
  5065. RenameThread(threadname);
  5066. if (!drv->thread_init(mythr)) {
  5067. dev_error(cgpu, REASON_THREAD_FAIL_INIT);
  5068. goto out;
  5069. }
  5070. thread_reportout(mythr);
  5071. applog(LOG_DEBUG, "Popping ping in miner thread");
  5072. tq_pop(mythr->q, NULL); /* Wait for a ping to start */
  5073. drv->hash_work(mythr);
  5074. out:
  5075. drv->thread_shutdown(mythr);
  5076. thread_reportin(mythr);
  5077. applog(LOG_ERR, "Thread %d failure, exiting", thr_id);
  5078. tq_freeze(mythr->q);
  5079. return NULL;
  5080. }
  5081. enum {
  5082. STAT_SLEEP_INTERVAL = 1,
  5083. STAT_CTR_INTERVAL = 10000000,
  5084. FAILURE_INTERVAL = 30,
  5085. };
  5086. /* Stage another work item from the work returned in a longpoll */
  5087. static void convert_to_work(json_t *val, int rolltime, struct pool *pool, struct timeval *tv_lp, struct timeval *tv_lp_reply)
  5088. {
  5089. struct work *work;
  5090. bool rc;
  5091. work = make_work();
  5092. rc = work_decode(pool, work, val);
  5093. if (unlikely(!rc)) {
  5094. applog(LOG_ERR, "Could not convert longpoll data to work");
  5095. free_work(work);
  5096. return;
  5097. }
  5098. total_getworks++;
  5099. pool->getwork_requested++;
  5100. work->pool = pool;
  5101. work->rolltime = rolltime;
  5102. memcpy(&(work->tv_getwork), tv_lp, sizeof(struct timeval));
  5103. memcpy(&(work->tv_getwork_reply), tv_lp_reply, sizeof(struct timeval));
  5104. calc_diff(work, 0);
  5105. if (pool->enabled == POOL_REJECTING)
  5106. work->mandatory = true;
  5107. if (pool->has_gbt)
  5108. gen_gbt_work(pool, work);
  5109. work->longpoll = true;
  5110. work->getwork_mode = GETWORK_MODE_LP;
  5111. /* We'll be checking this work item twice, but we already know it's
  5112. * from a new block so explicitly force the new block detection now
  5113. * rather than waiting for it to hit the stage thread. This also
  5114. * allows testwork to know whether LP discovered the block or not. */
  5115. test_work_current(work);
  5116. /* Don't use backup LPs as work if we have failover-only enabled. Use
  5117. * the longpoll work from a pool that has been rejecting shares as a
  5118. * way to detect when the pool has recovered.
  5119. */
  5120. if (pool != current_pool() && opt_fail_only && pool->enabled != POOL_REJECTING) {
  5121. free_work(work);
  5122. return;
  5123. }
  5124. work = clone_work(work);
  5125. applog(LOG_DEBUG, "Pushing converted work to stage thread");
  5126. stage_work(work);
  5127. applog(LOG_DEBUG, "Converted longpoll data to work");
  5128. }
  5129. /* If we want longpoll, enable it for the chosen default pool, or, if
  5130. * the pool does not support longpoll, find the first one that does
  5131. * and use its longpoll support */
  5132. static struct pool *select_longpoll_pool(struct pool *cp)
  5133. {
  5134. int i;
  5135. if (cp->hdr_path || cp->has_gbt)
  5136. return cp;
  5137. for (i = 0; i < total_pools; i++) {
  5138. struct pool *pool = pools[i];
  5139. if (pool->has_stratum || pool->hdr_path)
  5140. return pool;
  5141. }
  5142. return NULL;
  5143. }
  5144. /* This will make the longpoll thread wait till it's the current pool, or it
  5145. * has been flagged as rejecting, before attempting to open any connections.
  5146. */
  5147. static void wait_lpcurrent(struct pool *pool)
  5148. {
  5149. if (cnx_needed(pool))
  5150. return;
  5151. while (pool != current_pool() && pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  5152. mutex_lock(&lp_lock);
  5153. pthread_cond_wait(&lp_cond, &lp_lock);
  5154. mutex_unlock(&lp_lock);
  5155. }
  5156. }
  5157. static void *longpoll_thread(void *userdata)
  5158. {
  5159. struct pool *cp = (struct pool *)userdata;
  5160. /* This *pool is the source of the actual longpoll, not the pool we've
  5161. * tied it to */
  5162. struct timeval start, reply, end;
  5163. struct pool *pool = NULL;
  5164. char threadname[16];
  5165. CURL *curl = NULL;
  5166. int failures = 0;
  5167. char lpreq[1024];
  5168. char *lp_url;
  5169. int rolltime;
  5170. snprintf(threadname, 16, "longpoll/%d", cp->pool_no);
  5171. RenameThread(threadname);
  5172. curl = curl_easy_init();
  5173. if (unlikely(!curl)) {
  5174. applog(LOG_ERR, "CURL initialisation failed");
  5175. return NULL;
  5176. }
  5177. retry_pool:
  5178. pool = select_longpoll_pool(cp);
  5179. if (!pool) {
  5180. applog(LOG_WARNING, "No suitable long-poll found for %s", cp->rpc_url);
  5181. while (!pool) {
  5182. nmsleep(60000);
  5183. pool = select_longpoll_pool(cp);
  5184. }
  5185. }
  5186. if (pool->has_stratum) {
  5187. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  5188. cp->rpc_url, pool->rpc_url);
  5189. goto out;
  5190. }
  5191. /* Any longpoll from any pool is enough for this to be true */
  5192. have_longpoll = true;
  5193. wait_lpcurrent(cp);
  5194. if (pool->has_gbt) {
  5195. lp_url = pool->rpc_url;
  5196. applog(LOG_WARNING, "GBT longpoll ID activated for %s", lp_url);
  5197. } else {
  5198. strcpy(lpreq, getwork_req);
  5199. lp_url = pool->lp_url;
  5200. if (cp == pool)
  5201. applog(LOG_WARNING, "Long-polling activated for %s", lp_url);
  5202. else
  5203. applog(LOG_WARNING, "Long-polling activated for %s via %s", cp->rpc_url, lp_url);
  5204. }
  5205. while (42) {
  5206. json_t *val, *soval;
  5207. wait_lpcurrent(cp);
  5208. gettimeofday(&start, NULL);
  5209. /* Update the longpollid every time, but do it under lock to
  5210. * avoid races */
  5211. if (pool->has_gbt) {
  5212. cg_rlock(&pool->gbt_lock);
  5213. sprintf(lpreq, "{\"id\": 0, \"method\": \"getblocktemplate\", \"params\": "
  5214. "[{\"capabilities\": [\"coinbasetxn\", \"workid\", \"coinbase/append\"], "
  5215. "\"longpollid\": \"%s\"}]}\n", pool->longpollid);
  5216. cg_runlock(&pool->gbt_lock);
  5217. }
  5218. /* Longpoll connections can be persistent for a very long time
  5219. * and any number of issues could have come up in the meantime
  5220. * so always establish a fresh connection instead of relying on
  5221. * a persistent one. */
  5222. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  5223. val = json_rpc_call(curl, lp_url, pool->rpc_userpass,
  5224. lpreq, false, true, &rolltime, pool, false);
  5225. gettimeofday(&reply, NULL);
  5226. if (likely(val)) {
  5227. soval = json_object_get(json_object_get(val, "result"), "submitold");
  5228. if (soval)
  5229. pool->submit_old = json_is_true(soval);
  5230. else
  5231. pool->submit_old = false;
  5232. convert_to_work(val, rolltime, pool, &start, &reply);
  5233. failures = 0;
  5234. json_decref(val);
  5235. } else {
  5236. /* Some pools regularly drop the longpoll request so
  5237. * only see this as longpoll failure if it happens
  5238. * immediately and just restart it the rest of the
  5239. * time. */
  5240. gettimeofday(&end, NULL);
  5241. if (end.tv_sec - start.tv_sec > 30)
  5242. continue;
  5243. if (failures == 1)
  5244. applog(LOG_WARNING, "longpoll failed for %s, retrying every 30s", lp_url);
  5245. nmsleep(30000);
  5246. }
  5247. if (pool != cp) {
  5248. pool = select_longpoll_pool(cp);
  5249. if (pool->has_stratum) {
  5250. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  5251. cp->rpc_url, pool->rpc_url);
  5252. break;
  5253. }
  5254. if (unlikely(!pool))
  5255. goto retry_pool;
  5256. }
  5257. if (unlikely(pool->removed))
  5258. break;
  5259. }
  5260. out:
  5261. curl_easy_cleanup(curl);
  5262. return NULL;
  5263. }
  5264. void reinit_device(struct cgpu_info *cgpu)
  5265. {
  5266. cgpu->drv->reinit_device(cgpu);
  5267. }
  5268. static struct timeval rotate_tv;
  5269. /* We reap curls if they are unused for over a minute */
  5270. static void reap_curl(struct pool *pool)
  5271. {
  5272. struct curl_ent *ent, *iter;
  5273. struct timeval now;
  5274. int reaped = 0;
  5275. gettimeofday(&now, NULL);
  5276. mutex_lock(&pool->pool_lock);
  5277. list_for_each_entry_safe(ent, iter, &pool->curlring, node) {
  5278. if (pool->curls < 2)
  5279. break;
  5280. if (now.tv_sec - ent->tv.tv_sec > 300) {
  5281. reaped++;
  5282. pool->curls--;
  5283. list_del(&ent->node);
  5284. curl_easy_cleanup(ent->curl);
  5285. free(ent);
  5286. }
  5287. }
  5288. mutex_unlock(&pool->pool_lock);
  5289. if (reaped)
  5290. applog(LOG_DEBUG, "Reaped %d curl%s from pool %d", reaped, reaped > 1 ? "s" : "", pool->pool_no);
  5291. }
  5292. static void *watchpool_thread(void __maybe_unused *userdata)
  5293. {
  5294. int intervals = 0;
  5295. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  5296. RenameThread("watchpool");
  5297. while (42) {
  5298. struct timeval now;
  5299. int i;
  5300. if (++intervals > 20)
  5301. intervals = 0;
  5302. gettimeofday(&now, NULL);
  5303. for (i = 0; i < total_pools; i++) {
  5304. struct pool *pool = pools[i];
  5305. if (!opt_benchmark)
  5306. reap_curl(pool);
  5307. /* Get a rolling utility per pool over 10 mins */
  5308. if (intervals > 19) {
  5309. int shares = pool->diff1 - pool->last_shares;
  5310. pool->last_shares = pool->diff1;
  5311. pool->utility = (pool->utility + (double)shares * 0.63) / 1.63;
  5312. pool->shares = pool->utility;
  5313. }
  5314. if (pool->enabled == POOL_DISABLED)
  5315. continue;
  5316. /* Don't start testing any pools if the test threads
  5317. * from startup are still doing their first attempt. */
  5318. if (unlikely(pool->testing)) {
  5319. pthread_join(pool->test_thread, NULL);
  5320. pool->testing = false;
  5321. }
  5322. /* Test pool is idle once every minute */
  5323. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 30) {
  5324. gettimeofday(&pool->tv_idle, NULL);
  5325. if (pool_active(pool, true) && pool_tclear(pool, &pool->idle))
  5326. pool_resus(pool);
  5327. }
  5328. }
  5329. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  5330. gettimeofday(&rotate_tv, NULL);
  5331. switch_pools(NULL);
  5332. }
  5333. nmsleep(30000);
  5334. }
  5335. return NULL;
  5336. }
  5337. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  5338. * the screen at regular intervals, and restarts threads if they appear to have
  5339. * died. */
  5340. #define WATCHDOG_INTERVAL 2
  5341. #define WATCHDOG_SICK_TIME 60
  5342. #define WATCHDOG_DEAD_TIME 600
  5343. #define WATCHDOG_SICK_COUNT (WATCHDOG_SICK_TIME/WATCHDOG_INTERVAL)
  5344. #define WATCHDOG_DEAD_COUNT (WATCHDOG_DEAD_TIME/WATCHDOG_INTERVAL)
  5345. static void *watchdog_thread(void __maybe_unused *userdata)
  5346. {
  5347. const unsigned int interval = WATCHDOG_INTERVAL;
  5348. struct timeval zero_tv;
  5349. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  5350. RenameThread("watchdog");
  5351. memset(&zero_tv, 0, sizeof(struct timeval));
  5352. gettimeofday(&rotate_tv, NULL);
  5353. while (1) {
  5354. int i;
  5355. struct timeval now;
  5356. sleep(interval);
  5357. discard_stale();
  5358. hashmeter(-1, &zero_tv, 0);
  5359. #ifdef HAVE_CURSES
  5360. if (curses_active_locked()) {
  5361. change_logwinsize();
  5362. curses_print_status();
  5363. for (i = 0; i < mining_threads; i++)
  5364. curses_print_devstatus(i);
  5365. touchwin(statuswin);
  5366. wrefresh(statuswin);
  5367. touchwin(logwin);
  5368. wrefresh(logwin);
  5369. unlock_curses();
  5370. }
  5371. #endif
  5372. gettimeofday(&now, NULL);
  5373. if (!sched_paused && !should_run()) {
  5374. applog(LOG_WARNING, "Pausing execution as per stop time %02d:%02d scheduled",
  5375. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  5376. if (!schedstart.enable) {
  5377. quit(0, "Terminating execution as planned");
  5378. break;
  5379. }
  5380. applog(LOG_WARNING, "Will restart execution as scheduled at %02d:%02d",
  5381. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  5382. sched_paused = true;
  5383. rd_lock(&mining_thr_lock);
  5384. for (i = 0; i < mining_threads; i++)
  5385. mining_thr[i]->pause = true;
  5386. rd_unlock(&mining_thr_lock);
  5387. } else if (sched_paused && should_run()) {
  5388. applog(LOG_WARNING, "Restarting execution as per start time %02d:%02d scheduled",
  5389. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  5390. if (schedstop.enable)
  5391. applog(LOG_WARNING, "Will pause execution as scheduled at %02d:%02d",
  5392. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  5393. sched_paused = false;
  5394. for (i = 0; i < mining_threads; i++) {
  5395. struct thr_info *thr;
  5396. thr = get_thread(i);
  5397. /* Don't touch disabled devices */
  5398. if (thr->cgpu->deven == DEV_DISABLED)
  5399. continue;
  5400. thr->pause = false;
  5401. tq_push(thr->q, &ping);
  5402. }
  5403. }
  5404. for (i = 0; i < total_devices; ++i) {
  5405. struct cgpu_info *cgpu = get_devices(i);
  5406. struct thr_info *thr = cgpu->thr[0];
  5407. enum dev_enable *denable;
  5408. char dev_str[8];
  5409. int gpu;
  5410. cgpu->drv->get_stats(cgpu);
  5411. gpu = cgpu->device_id;
  5412. denable = &cgpu->deven;
  5413. sprintf(dev_str, "%s%d", cgpu->drv->name, gpu);
  5414. #ifdef HAVE_ADL
  5415. if (adl_active && cgpu->has_adl)
  5416. gpu_autotune(gpu, denable);
  5417. if (opt_debug && cgpu->has_adl) {
  5418. int engineclock = 0, memclock = 0, activity = 0, fanspeed = 0, fanpercent = 0, powertune = 0;
  5419. float temp = 0, vddc = 0;
  5420. if (gpu_stats(gpu, &temp, &engineclock, &memclock, &vddc, &activity, &fanspeed, &fanpercent, &powertune))
  5421. applog(LOG_DEBUG, "%.1f C F: %d%%(%dRPM) E: %dMHz M: %dMhz V: %.3fV A: %d%% P: %d%%",
  5422. temp, fanpercent, fanspeed, engineclock, memclock, vddc, activity, powertune);
  5423. }
  5424. #endif
  5425. /* Thread is waiting on getwork or disabled */
  5426. if (thr->getwork || *denable == DEV_DISABLED)
  5427. continue;
  5428. #ifdef WANT_CPUMINE
  5429. if (cgpu->drv->drv_id == DRIVER_CPU)
  5430. continue;
  5431. #endif
  5432. if (cgpu->status != LIFE_WELL && (now.tv_sec - thr->last.tv_sec < WATCHDOG_SICK_TIME)) {
  5433. if (cgpu->status != LIFE_INIT)
  5434. applog(LOG_ERR, "%s: Recovered, declaring WELL!", dev_str);
  5435. cgpu->status = LIFE_WELL;
  5436. cgpu->device_last_well = time(NULL);
  5437. } else if (cgpu->status == LIFE_WELL && (now.tv_sec - thr->last.tv_sec > WATCHDOG_SICK_TIME)) {
  5438. thr->rolling = cgpu->rolling = 0;
  5439. cgpu->status = LIFE_SICK;
  5440. applog(LOG_ERR, "%s: Idle for more than 60 seconds, declaring SICK!", dev_str);
  5441. gettimeofday(&thr->sick, NULL);
  5442. dev_error(cgpu, REASON_DEV_SICK_IDLE_60);
  5443. #ifdef HAVE_ADL
  5444. if (adl_active && cgpu->has_adl && gpu_activity(gpu) > 50) {
  5445. applog(LOG_ERR, "GPU still showing activity suggesting a hard hang.");
  5446. applog(LOG_ERR, "Will not attempt to auto-restart it.");
  5447. } else
  5448. #endif
  5449. if (opt_restart) {
  5450. applog(LOG_ERR, "%s: Attempting to restart", dev_str);
  5451. reinit_device(cgpu);
  5452. }
  5453. } else if (cgpu->status == LIFE_SICK && (now.tv_sec - thr->last.tv_sec > WATCHDOG_DEAD_TIME)) {
  5454. cgpu->status = LIFE_DEAD;
  5455. applog(LOG_ERR, "%s: Not responded for more than 10 minutes, declaring DEAD!", dev_str);
  5456. gettimeofday(&thr->sick, NULL);
  5457. dev_error(cgpu, REASON_DEV_DEAD_IDLE_600);
  5458. } else if (now.tv_sec - thr->sick.tv_sec > 60 &&
  5459. (cgpu->status == LIFE_SICK || cgpu->status == LIFE_DEAD)) {
  5460. /* Attempt to restart a GPU that's sick or dead once every minute */
  5461. gettimeofday(&thr->sick, NULL);
  5462. #ifdef HAVE_ADL
  5463. if (adl_active && cgpu->has_adl && gpu_activity(gpu) > 50) {
  5464. /* Again do not attempt to restart a device that may have hard hung */
  5465. } else
  5466. #endif
  5467. if (opt_restart)
  5468. reinit_device(cgpu);
  5469. }
  5470. }
  5471. }
  5472. return NULL;
  5473. }
  5474. static void log_print_status(struct cgpu_info *cgpu)
  5475. {
  5476. char logline[255];
  5477. get_statline(logline, cgpu);
  5478. applog(LOG_WARNING, "%s", logline);
  5479. }
  5480. void print_summary(void)
  5481. {
  5482. struct timeval diff;
  5483. int hours, mins, secs, i;
  5484. double utility, displayed_hashes, work_util;
  5485. bool mhash_base = true;
  5486. timersub(&total_tv_end, &total_tv_start, &diff);
  5487. hours = diff.tv_sec / 3600;
  5488. mins = (diff.tv_sec % 3600) / 60;
  5489. secs = diff.tv_sec % 60;
  5490. utility = total_accepted / total_secs * 60;
  5491. work_util = total_diff1 / total_secs * 60;
  5492. applog(LOG_WARNING, "\nSummary of runtime statistics:\n");
  5493. applog(LOG_WARNING, "Started at %s", datestamp);
  5494. if (total_pools == 1)
  5495. applog(LOG_WARNING, "Pool: %s", pools[0]->rpc_url);
  5496. #ifdef WANT_CPUMINE
  5497. if (opt_n_threads)
  5498. applog(LOG_WARNING, "CPU hasher algorithm used: %s", algo_names[opt_algo]);
  5499. #endif
  5500. applog(LOG_WARNING, "Runtime: %d hrs : %d mins : %d secs", hours, mins, secs);
  5501. displayed_hashes = total_mhashes_done / total_secs;
  5502. if (displayed_hashes < 1) {
  5503. displayed_hashes *= 1000;
  5504. mhash_base = false;
  5505. }
  5506. applog(LOG_WARNING, "Average hashrate: %.1f %shash/s", displayed_hashes, mhash_base? "Mega" : "Kilo");
  5507. applog(LOG_WARNING, "Solved blocks: %d", found_blocks);
  5508. applog(LOG_WARNING, "Best share difficulty: %s", best_share);
  5509. applog(LOG_WARNING, "Share submissions: %d", total_accepted + total_rejected);
  5510. applog(LOG_WARNING, "Accepted shares: %d", total_accepted);
  5511. applog(LOG_WARNING, "Rejected shares: %d", total_rejected);
  5512. applog(LOG_WARNING, "Accepted difficulty shares: %1.f", total_diff_accepted);
  5513. applog(LOG_WARNING, "Rejected difficulty shares: %1.f", total_diff_rejected);
  5514. if (total_accepted || total_rejected)
  5515. applog(LOG_WARNING, "Reject ratio: %.1f%%", (double)(total_rejected * 100) / (double)(total_accepted + total_rejected));
  5516. applog(LOG_WARNING, "Hardware errors: %d", hw_errors);
  5517. applog(LOG_WARNING, "Utility (accepted shares / min): %.2f/min", utility);
  5518. applog(LOG_WARNING, "Work Utility (diff1 shares solved / min): %.2f/min\n", work_util);
  5519. applog(LOG_WARNING, "Stale submissions discarded due to new blocks: %d", total_stale);
  5520. applog(LOG_WARNING, "Unable to get work from server occasions: %d", total_go);
  5521. applog(LOG_WARNING, "Work items generated locally: %d", local_work);
  5522. applog(LOG_WARNING, "Submitting work remotely delay occasions: %d", total_ro);
  5523. applog(LOG_WARNING, "New blocks detected on network: %d\n", new_blocks);
  5524. if (total_pools > 1) {
  5525. for (i = 0; i < total_pools; i++) {
  5526. struct pool *pool = pools[i];
  5527. applog(LOG_WARNING, "Pool: %s", pool->rpc_url);
  5528. if (pool->solved)
  5529. applog(LOG_WARNING, "SOLVED %d BLOCK%s!", pool->solved, pool->solved > 1 ? "S" : "");
  5530. applog(LOG_WARNING, " Share submissions: %d", pool->accepted + pool->rejected);
  5531. applog(LOG_WARNING, " Accepted shares: %d", pool->accepted);
  5532. applog(LOG_WARNING, " Rejected shares: %d", pool->rejected);
  5533. applog(LOG_WARNING, " Accepted difficulty shares: %1.f", pool->diff_accepted);
  5534. applog(LOG_WARNING, " Rejected difficulty shares: %1.f", pool->diff_rejected);
  5535. if (pool->accepted || pool->rejected)
  5536. applog(LOG_WARNING, " Reject ratio: %.1f%%", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  5537. applog(LOG_WARNING, " Stale submissions discarded due to new blocks: %d", pool->stale_shares);
  5538. applog(LOG_WARNING, " Unable to get work from server occasions: %d", pool->getfail_occasions);
  5539. applog(LOG_WARNING, " Submitting work remotely delay occasions: %d\n", pool->remotefail_occasions);
  5540. }
  5541. }
  5542. applog(LOG_WARNING, "Summary of per device statistics:\n");
  5543. for (i = 0; i < total_devices; ++i) {
  5544. struct cgpu_info *cgpu = get_devices(i);
  5545. log_print_status(cgpu);
  5546. }
  5547. if (opt_shares)
  5548. applog(LOG_WARNING, "Mined %d accepted shares of %d requested\n", total_accepted, opt_shares);
  5549. fflush(stdout);
  5550. fflush(stderr);
  5551. if (opt_shares > total_accepted)
  5552. applog(LOG_WARNING, "WARNING - Mined only %d shares of %d requested.", total_accepted, opt_shares);
  5553. }
  5554. static void clean_up(void)
  5555. {
  5556. #ifdef HAVE_OPENCL
  5557. clear_adl(nDevs);
  5558. #endif
  5559. #ifdef HAVE_LIBUSB
  5560. libusb_exit(NULL);
  5561. #endif
  5562. gettimeofday(&total_tv_end, NULL);
  5563. #ifdef HAVE_CURSES
  5564. disable_curses();
  5565. #endif
  5566. if (!opt_realquiet && successful_connect)
  5567. print_summary();
  5568. if (opt_n_threads)
  5569. free(cpus);
  5570. curl_global_cleanup();
  5571. }
  5572. void quit(int status, const char *format, ...)
  5573. {
  5574. va_list ap;
  5575. clean_up();
  5576. if (format) {
  5577. va_start(ap, format);
  5578. vfprintf(stderr, format, ap);
  5579. va_end(ap);
  5580. }
  5581. fprintf(stderr, "\n");
  5582. fflush(stderr);
  5583. #if defined(unix)
  5584. if (forkpid > 0) {
  5585. kill(forkpid, SIGTERM);
  5586. forkpid = 0;
  5587. }
  5588. #endif
  5589. exit(status);
  5590. }
  5591. #ifdef HAVE_CURSES
  5592. char *curses_input(const char *query)
  5593. {
  5594. char *input;
  5595. echo();
  5596. input = malloc(255);
  5597. if (!input)
  5598. quit(1, "Failed to malloc input");
  5599. leaveok(logwin, false);
  5600. wlogprint("%s:\n", query);
  5601. wgetnstr(logwin, input, 255);
  5602. if (!strlen(input))
  5603. strcpy(input, "-1");
  5604. leaveok(logwin, true);
  5605. noecho();
  5606. return input;
  5607. }
  5608. #endif
  5609. static bool pools_active = false;
  5610. static void *test_pool_thread(void *arg)
  5611. {
  5612. struct pool *pool = (struct pool *)arg;
  5613. if (pool_active(pool, false)) {
  5614. pool_tset(pool, &pool->lagging);
  5615. pool_tclear(pool, &pool->idle);
  5616. cg_wlock(&control_lock);
  5617. if (!pools_active) {
  5618. currentpool = pool;
  5619. if (pool->pool_no != 0)
  5620. applog(LOG_NOTICE, "Switching to pool %d %s - first alive pool", pool->pool_no, pool->rpc_url);
  5621. pools_active = true;
  5622. }
  5623. cg_wunlock(&control_lock);
  5624. pool_resus(pool);
  5625. } else
  5626. pool_died(pool);
  5627. return NULL;
  5628. }
  5629. /* Always returns true that the pool details were added unless we are not
  5630. * live, implying this is the only pool being added, so if no pools are
  5631. * active it returns false. */
  5632. bool add_pool_details(struct pool *pool, bool live, char *url, char *user, char *pass)
  5633. {
  5634. url = get_proxy(url, pool);
  5635. pool->rpc_url = url;
  5636. pool->rpc_user = user;
  5637. pool->rpc_pass = pass;
  5638. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  5639. if (!pool->rpc_userpass)
  5640. quit(1, "Failed to malloc userpass");
  5641. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  5642. pool->testing = true;
  5643. pool->idle = true;
  5644. enable_pool(pool);
  5645. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  5646. if (!live) {
  5647. pthread_join(pool->test_thread, NULL);
  5648. pool->testing = false;
  5649. return pools_active;
  5650. }
  5651. return true;
  5652. }
  5653. #ifdef HAVE_CURSES
  5654. static bool input_pool(bool live)
  5655. {
  5656. char *url = NULL, *user = NULL, *pass = NULL;
  5657. struct pool *pool;
  5658. bool ret = false;
  5659. immedok(logwin, true);
  5660. wlogprint("Input server details.\n");
  5661. url = curses_input("URL");
  5662. if (!url)
  5663. goto out;
  5664. user = curses_input("Username");
  5665. if (!user)
  5666. goto out;
  5667. pass = curses_input("Password");
  5668. if (!pass)
  5669. goto out;
  5670. pool = add_pool();
  5671. if (!detect_stratum(pool, url) && strncmp(url, "http://", 7) &&
  5672. strncmp(url, "https://", 8)) {
  5673. char *httpinput;
  5674. httpinput = malloc(256);
  5675. if (!httpinput)
  5676. quit(1, "Failed to malloc httpinput");
  5677. strcpy(httpinput, "http://");
  5678. strncat(httpinput, url, 248);
  5679. free(url);
  5680. url = httpinput;
  5681. }
  5682. ret = add_pool_details(pool, live, url, user, pass);
  5683. out:
  5684. immedok(logwin, false);
  5685. if (!ret) {
  5686. if (url)
  5687. free(url);
  5688. if (user)
  5689. free(user);
  5690. if (pass)
  5691. free(pass);
  5692. }
  5693. return ret;
  5694. }
  5695. #endif
  5696. #if defined(unix)
  5697. static void fork_monitor()
  5698. {
  5699. // Make a pipe: [readFD, writeFD]
  5700. int pfd[2];
  5701. int r = pipe(pfd);
  5702. if (r < 0) {
  5703. perror("pipe - failed to create pipe for --monitor");
  5704. exit(1);
  5705. }
  5706. // Make stderr write end of pipe
  5707. fflush(stderr);
  5708. r = dup2(pfd[1], 2);
  5709. if (r < 0) {
  5710. perror("dup2 - failed to alias stderr to write end of pipe for --monitor");
  5711. exit(1);
  5712. }
  5713. r = close(pfd[1]);
  5714. if (r < 0) {
  5715. perror("close - failed to close write end of pipe for --monitor");
  5716. exit(1);
  5717. }
  5718. // Don't allow a dying monitor to kill the main process
  5719. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  5720. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  5721. if (SIG_ERR == sr0 || SIG_ERR == sr1) {
  5722. perror("signal - failed to edit signal mask for --monitor");
  5723. exit(1);
  5724. }
  5725. // Fork a child process
  5726. forkpid = fork();
  5727. if (forkpid < 0) {
  5728. perror("fork - failed to fork child process for --monitor");
  5729. exit(1);
  5730. }
  5731. // Child: launch monitor command
  5732. if (0 == forkpid) {
  5733. // Make stdin read end of pipe
  5734. r = dup2(pfd[0], 0);
  5735. if (r < 0) {
  5736. perror("dup2 - in child, failed to alias read end of pipe to stdin for --monitor");
  5737. exit(1);
  5738. }
  5739. close(pfd[0]);
  5740. if (r < 0) {
  5741. perror("close - in child, failed to close read end of pipe for --monitor");
  5742. exit(1);
  5743. }
  5744. // Launch user specified command
  5745. execl("/bin/bash", "/bin/bash", "-c", opt_stderr_cmd, (char*)NULL);
  5746. perror("execl - in child failed to exec user specified command for --monitor");
  5747. exit(1);
  5748. }
  5749. // Parent: clean up unused fds and bail
  5750. r = close(pfd[0]);
  5751. if (r < 0) {
  5752. perror("close - failed to close read end of pipe for --monitor");
  5753. exit(1);
  5754. }
  5755. }
  5756. #endif // defined(unix)
  5757. #ifdef HAVE_CURSES
  5758. void enable_curses(void) {
  5759. int x,y;
  5760. lock_curses();
  5761. if (curses_active) {
  5762. unlock_curses();
  5763. return;
  5764. }
  5765. mainwin = initscr();
  5766. getmaxyx(mainwin, y, x);
  5767. statuswin = newwin(logstart, x, 0, 0);
  5768. leaveok(statuswin, true);
  5769. logwin = newwin(y - logcursor, 0, logcursor, 0);
  5770. idlok(logwin, true);
  5771. scrollok(logwin, true);
  5772. leaveok(logwin, true);
  5773. cbreak();
  5774. noecho();
  5775. curses_active = true;
  5776. statusy = logstart;
  5777. unlock_curses();
  5778. }
  5779. #endif
  5780. /* TODO: fix need a dummy CPU device_drv even if no support for CPU mining */
  5781. #ifndef WANT_CPUMINE
  5782. struct device_drv cpu_drv;
  5783. struct device_drv cpu_drv = {
  5784. .drv_id = DRIVER_CPU,
  5785. .name = "CPU",
  5786. };
  5787. #endif
  5788. #ifdef USE_BFLSC
  5789. extern struct device_drv bflsc_drv;
  5790. #endif
  5791. #ifdef USE_BITFORCE
  5792. extern struct device_drv bitforce_drv;
  5793. #endif
  5794. #ifdef USE_ICARUS
  5795. extern struct device_drv icarus_drv;
  5796. #endif
  5797. #ifdef USE_MODMINER
  5798. extern struct device_drv modminer_drv;
  5799. #endif
  5800. #ifdef USE_ZTEX
  5801. extern struct device_drv ztex_drv;
  5802. #endif
  5803. static int cgminer_id_count = 0;
  5804. /* Various noop functions for drivers that don't support or need their
  5805. * variants. */
  5806. static void noop_reinit_device(struct cgpu_info __maybe_unused *cgpu)
  5807. {
  5808. }
  5809. void blank_get_statline_before(char *buf, struct cgpu_info __maybe_unused *cgpu)
  5810. {
  5811. tailsprintf(buf, " | ");
  5812. }
  5813. static void noop_get_statline(char __maybe_unused *buf, struct cgpu_info __maybe_unused *cgpu)
  5814. {
  5815. }
  5816. static bool noop_get_stats(struct cgpu_info __maybe_unused *cgpu)
  5817. {
  5818. return true;
  5819. }
  5820. static bool noop_thread_prepare(struct thr_info __maybe_unused *thr)
  5821. {
  5822. return true;
  5823. }
  5824. static uint64_t noop_can_limit_work(struct thr_info __maybe_unused *thr)
  5825. {
  5826. return 0xffffffff;
  5827. }
  5828. static bool noop_thread_init(struct thr_info __maybe_unused *thr)
  5829. {
  5830. return true;
  5831. }
  5832. static bool noop_prepare_work(struct thr_info __maybe_unused *thr, struct work __maybe_unused *work)
  5833. {
  5834. return true;
  5835. }
  5836. static void noop_hw_error(struct thr_info __maybe_unused *thr)
  5837. {
  5838. }
  5839. static void noop_thread_shutdown(struct thr_info __maybe_unused *thr)
  5840. {
  5841. }
  5842. static void noop_thread_enable(struct thr_info __maybe_unused *thr)
  5843. {
  5844. }
  5845. #define noop_flush_work noop_reinit_device
  5846. #define noop_queue_full noop_get_stats
  5847. /* Fill missing driver drv functions with noops */
  5848. void fill_device_drv(struct cgpu_info *cgpu)
  5849. {
  5850. struct device_drv *drv = cgpu->drv;
  5851. if (!drv->reinit_device)
  5852. drv->reinit_device = &noop_reinit_device;
  5853. if (!drv->get_statline_before)
  5854. drv->get_statline_before = &blank_get_statline_before;
  5855. if (!drv->get_statline)
  5856. drv->get_statline = &noop_get_statline;
  5857. if (!drv->get_stats)
  5858. drv->get_stats = &noop_get_stats;
  5859. if (!drv->thread_prepare)
  5860. drv->thread_prepare = &noop_thread_prepare;
  5861. if (!drv->can_limit_work)
  5862. drv->can_limit_work = &noop_can_limit_work;
  5863. if (!drv->thread_init)
  5864. drv->thread_init = &noop_thread_init;
  5865. if (!drv->prepare_work)
  5866. drv->prepare_work = &noop_prepare_work;
  5867. if (!drv->hw_error)
  5868. drv->hw_error = &noop_hw_error;
  5869. if (!drv->thread_shutdown)
  5870. drv->thread_shutdown = &noop_thread_shutdown;
  5871. if (!drv->thread_enable)
  5872. drv->thread_enable = &noop_thread_enable;
  5873. if (!drv->hash_work)
  5874. drv->hash_work = &hash_sole_work;
  5875. if (!drv->flush_work)
  5876. drv->flush_work = &noop_flush_work;
  5877. if (!drv->queue_full)
  5878. drv->queue_full = &noop_queue_full;
  5879. if (!drv->max_diff)
  5880. drv->max_diff = 1;
  5881. }
  5882. void enable_device(struct cgpu_info *cgpu)
  5883. {
  5884. cgpu->deven = DEV_ENABLED;
  5885. wr_lock(&devices_lock);
  5886. devices[cgpu->cgminer_id = cgminer_id_count++] = cgpu;
  5887. wr_unlock(&devices_lock);
  5888. if (hotplug_mode) {
  5889. new_threads += cgpu->threads;
  5890. #ifdef HAVE_CURSES
  5891. adj_width(mining_threads + new_threads, &dev_width);
  5892. #endif
  5893. } else {
  5894. mining_threads += cgpu->threads;
  5895. #ifdef HAVE_CURSES
  5896. adj_width(mining_threads, &dev_width);
  5897. #endif
  5898. }
  5899. #ifdef HAVE_OPENCL
  5900. if (cgpu->drv->drv_id == DRIVER_OPENCL) {
  5901. gpu_threads += cgpu->threads;
  5902. }
  5903. #endif
  5904. fill_device_drv(cgpu);
  5905. rwlock_init(&cgpu->qlock);
  5906. cgpu->queued_work = NULL;
  5907. }
  5908. struct _cgpu_devid_counter {
  5909. char name[4];
  5910. int lastid;
  5911. UT_hash_handle hh;
  5912. };
  5913. bool add_cgpu(struct cgpu_info*cgpu)
  5914. {
  5915. static struct _cgpu_devid_counter *devids = NULL;
  5916. struct _cgpu_devid_counter *d;
  5917. HASH_FIND_STR(devids, cgpu->drv->name, d);
  5918. if (d)
  5919. cgpu->device_id = ++d->lastid;
  5920. else {
  5921. d = malloc(sizeof(*d));
  5922. memcpy(d->name, cgpu->drv->name, sizeof(d->name));
  5923. cgpu->device_id = d->lastid = 0;
  5924. HASH_ADD_STR(devids, name, d);
  5925. }
  5926. wr_lock(&devices_lock);
  5927. devices = realloc(devices, sizeof(struct cgpu_info *) * (total_devices + new_devices + 2));
  5928. wr_unlock(&devices_lock);
  5929. if (hotplug_mode)
  5930. devices[total_devices + new_devices++] = cgpu;
  5931. else
  5932. devices[total_devices++] = cgpu;
  5933. return true;
  5934. }
  5935. struct device_drv *copy_drv(struct device_drv *drv)
  5936. {
  5937. struct device_drv *copy;
  5938. char buf[100];
  5939. if (unlikely(!(copy = malloc(sizeof(*copy))))) {
  5940. sprintf(buf, "Failed to allocate device_drv copy of %s (%s)",
  5941. drv->name, drv->copy ? "copy" : "original");
  5942. quit(1, buf);
  5943. }
  5944. memcpy(copy, drv, sizeof(*copy));
  5945. copy->copy = true;
  5946. return copy;
  5947. }
  5948. #ifdef USE_USBUTILS
  5949. static void hotplug_process()
  5950. {
  5951. struct thr_info *thr;
  5952. int i, j;
  5953. for (i = 0; i < new_devices; i++) {
  5954. struct cgpu_info *cgpu = devices[total_devices + i];
  5955. enable_device(cgpu);
  5956. cgpu->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  5957. cgpu->rolling = cgpu->total_mhashes = 0;
  5958. }
  5959. wr_lock(&mining_thr_lock);
  5960. mining_thr = realloc(mining_thr, sizeof(thr) * (mining_threads + new_threads + 1));
  5961. wr_unlock(&mining_thr_lock);
  5962. if (!mining_thr)
  5963. quit(1, "Failed to hotplug realloc mining_thr");
  5964. for (i = 0; i < new_threads; i++) {
  5965. mining_thr[mining_threads + i] = calloc(1, sizeof(*thr));
  5966. if (!mining_thr[mining_threads + i])
  5967. quit(1, "Failed to hotplug calloc mining_thr[%d]", i);
  5968. }
  5969. // Start threads
  5970. for (i = 0; i < new_devices; ++i) {
  5971. struct cgpu_info *cgpu = devices[total_devices];
  5972. cgpu->thr = malloc(sizeof(*cgpu->thr) * (cgpu->threads+1));
  5973. cgpu->thr[cgpu->threads] = NULL;
  5974. cgpu->status = LIFE_INIT;
  5975. for (j = 0; j < cgpu->threads; ++j) {
  5976. thr = get_thread(mining_threads);
  5977. thr->id = mining_threads;
  5978. thr->cgpu = cgpu;
  5979. thr->device_thread = j;
  5980. thr->q = tq_new();
  5981. if (!thr->q)
  5982. quit(1, "tq_new hotplug failed in starting %s%d mining thread (#%d)", cgpu->drv->name, cgpu->device_id, total_devices);
  5983. /* Enable threads for devices set not to mine but disable
  5984. * their queue in case we wish to enable them later */
  5985. if (cgpu->deven != DEV_DISABLED) {
  5986. applog(LOG_DEBUG, "Pushing hotplug ping to thread %d", thr->id);
  5987. tq_push(thr->q, &ping);
  5988. }
  5989. if (cgpu->drv->thread_prepare && !cgpu->drv->thread_prepare(thr))
  5990. continue;
  5991. thread_reportout(thr);
  5992. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  5993. quit(1, "hotplug thread %d create failed", thr->id);
  5994. cgpu->thr[j] = thr;
  5995. mining_threads++;
  5996. }
  5997. total_devices++;
  5998. applog(LOG_WARNING, "Hotplug: %s added %s %i", cgpu->drv->dname, cgpu->drv->name, cgpu->device_id);
  5999. }
  6000. }
  6001. static void *hotplug_thread(void __maybe_unused *userdata)
  6002. {
  6003. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  6004. RenameThread("hotplug");
  6005. hotplug_mode = true;
  6006. nmsleep(5000);
  6007. while (0x2a) {
  6008. // Version 0.1 just add the devices on - worry about using nodev later
  6009. if (hotplug_time == 0)
  6010. nmsleep(5000);
  6011. else {
  6012. new_devices = 0;
  6013. new_threads = 0;
  6014. #ifdef USE_BFLSC
  6015. bflsc_drv.drv_detect();
  6016. #endif
  6017. #ifdef USE_BITFORCE
  6018. bitforce_drv.drv_detect();
  6019. #endif
  6020. #ifdef USE_MODMINER
  6021. modminer_drv.drv_detect();
  6022. #endif
  6023. if (new_devices)
  6024. hotplug_process();
  6025. // hotplug_time >0 && <=9999
  6026. nmsleep(hotplug_time * 1000);
  6027. }
  6028. }
  6029. return NULL;
  6030. }
  6031. #endif
  6032. static void probe_pools(void)
  6033. {
  6034. int i;
  6035. for (i = 0; i < total_pools; i++) {
  6036. struct pool *pool = pools[i];
  6037. pool->testing = true;
  6038. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  6039. }
  6040. }
  6041. int main(int argc, char *argv[])
  6042. {
  6043. struct sigaction handler;
  6044. struct thr_info *thr;
  6045. struct block *block;
  6046. unsigned int k;
  6047. int i, j;
  6048. char *s;
  6049. /* This dangerous functions tramples random dynamically allocated
  6050. * variables so do it before anything at all */
  6051. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  6052. quit(1, "Failed to curl_global_init");
  6053. initial_args = malloc(sizeof(char *) * (argc + 1));
  6054. for (i = 0; i < argc; i++)
  6055. initial_args[i] = strdup(argv[i]);
  6056. initial_args[argc] = NULL;
  6057. #ifdef HAVE_LIBUSB
  6058. int err = libusb_init(NULL);
  6059. if (err) {
  6060. fprintf(stderr, "libusb_init() failed err %d", err);
  6061. fflush(stderr);
  6062. quit(1, "libusb_init() failed");
  6063. }
  6064. #ifdef USE_USBUTILS
  6065. mutex_init(&cgusb_lock);
  6066. #endif
  6067. #endif
  6068. mutex_init(&hash_lock);
  6069. mutex_init(&console_lock);
  6070. cglock_init(&control_lock);
  6071. mutex_init(&stats_lock);
  6072. mutex_init(&sharelog_lock);
  6073. cglock_init(&ch_lock);
  6074. mutex_init(&sshare_lock);
  6075. rwlock_init(&blk_lock);
  6076. rwlock_init(&netacc_lock);
  6077. rwlock_init(&mining_thr_lock);
  6078. rwlock_init(&devices_lock);
  6079. mutex_init(&lp_lock);
  6080. if (unlikely(pthread_cond_init(&lp_cond, NULL)))
  6081. quit(1, "Failed to pthread_cond_init lp_cond");
  6082. mutex_init(&restart_lock);
  6083. if (unlikely(pthread_cond_init(&restart_cond, NULL)))
  6084. quit(1, "Failed to pthread_cond_init restart_cond");
  6085. if (unlikely(pthread_cond_init(&gws_cond, NULL)))
  6086. quit(1, "Failed to pthread_cond_init gws_cond");
  6087. sprintf(packagename, "%s %s", PACKAGE, VERSION);
  6088. #ifdef WANT_CPUMINE
  6089. init_max_name_len();
  6090. #endif
  6091. handler.sa_handler = &sighandler;
  6092. handler.sa_flags = 0;
  6093. sigemptyset(&handler.sa_mask);
  6094. sigaction(SIGTERM, &handler, &termhandler);
  6095. sigaction(SIGINT, &handler, &inthandler);
  6096. #ifndef WIN32
  6097. signal(SIGPIPE, SIG_IGN);
  6098. #endif
  6099. opt_kernel_path = alloca(PATH_MAX);
  6100. strcpy(opt_kernel_path, CGMINER_PREFIX);
  6101. cgminer_path = alloca(PATH_MAX);
  6102. s = strdup(argv[0]);
  6103. strcpy(cgminer_path, dirname(s));
  6104. free(s);
  6105. strcat(cgminer_path, "/");
  6106. #ifdef WANT_CPUMINE
  6107. // Hack to make cgminer silent when called recursively on WIN32
  6108. int skip_to_bench = 0;
  6109. #if defined(WIN32)
  6110. char buf[32];
  6111. if (GetEnvironmentVariable("CGMINER_BENCH_ALGO", buf, 16))
  6112. skip_to_bench = 1;
  6113. #endif // defined(WIN32)
  6114. #endif
  6115. devcursor = 8;
  6116. logstart = devcursor + 1;
  6117. logcursor = logstart + 1;
  6118. block = calloc(sizeof(struct block), 1);
  6119. if (unlikely(!block))
  6120. quit (1, "main OOM");
  6121. for (i = 0; i < 36; i++)
  6122. strcat(block->hash, "0");
  6123. HASH_ADD_STR(blocks, hash, block);
  6124. strcpy(current_block, block->hash);
  6125. INIT_LIST_HEAD(&scan_devices);
  6126. #ifdef HAVE_OPENCL
  6127. memset(gpus, 0, sizeof(gpus));
  6128. for (i = 0; i < MAX_GPUDEVICES; i++)
  6129. gpus[i].dynamic = true;
  6130. #endif
  6131. /* parse command line */
  6132. opt_register_table(opt_config_table,
  6133. "Options for both config file and command line");
  6134. opt_register_table(opt_cmdline_table,
  6135. "Options for command line only");
  6136. opt_parse(&argc, argv, applog_and_exit);
  6137. if (argc != 1)
  6138. quit(1, "Unexpected extra commandline arguments");
  6139. if (!config_loaded)
  6140. load_default_config();
  6141. if (opt_benchmark) {
  6142. struct pool *pool;
  6143. pool = add_pool();
  6144. pool->rpc_url = malloc(255);
  6145. strcpy(pool->rpc_url, "Benchmark");
  6146. pool->rpc_user = pool->rpc_url;
  6147. pool->rpc_pass = pool->rpc_url;
  6148. enable_pool(pool);
  6149. pool->idle = false;
  6150. successful_connect = true;
  6151. }
  6152. #ifdef HAVE_CURSES
  6153. if (opt_realquiet || devices_enabled == -1)
  6154. use_curses = false;
  6155. if (use_curses)
  6156. enable_curses();
  6157. #endif
  6158. applog(LOG_WARNING, "Started %s", packagename);
  6159. if (cnfbuf) {
  6160. applog(LOG_NOTICE, "Loaded configuration file %s", cnfbuf);
  6161. switch (fileconf_load) {
  6162. case 0:
  6163. applog(LOG_WARNING, "Fatal JSON error in configuration file.");
  6164. applog(LOG_WARNING, "Configuration file could not be used.");
  6165. break;
  6166. case -1:
  6167. applog(LOG_WARNING, "Error in configuration file, partially loaded.");
  6168. if (use_curses)
  6169. applog(LOG_WARNING, "Start cgminer with -T to see what failed to load.");
  6170. break;
  6171. default:
  6172. break;
  6173. }
  6174. free(cnfbuf);
  6175. cnfbuf = NULL;
  6176. }
  6177. strcat(opt_kernel_path, "/");
  6178. if (want_per_device_stats)
  6179. opt_log_output = true;
  6180. #ifdef USE_USBUTILS
  6181. usb_initialise();
  6182. #endif
  6183. #ifdef WANT_CPUMINE
  6184. #ifdef USE_SCRYPT
  6185. if (opt_scrypt)
  6186. set_scrypt_algo(&opt_algo);
  6187. else
  6188. #endif
  6189. if (0 <= opt_bench_algo) {
  6190. double rate = bench_algo_stage3(opt_bench_algo);
  6191. if (!skip_to_bench)
  6192. printf("%.5f (%s)\n", rate, algo_names[opt_bench_algo]);
  6193. else {
  6194. // Write result to shared memory for parent
  6195. #if defined(WIN32)
  6196. char unique_name[64];
  6197. if (GetEnvironmentVariable("CGMINER_SHARED_MEM", unique_name, 32)) {
  6198. HANDLE map_handle = CreateFileMapping(
  6199. INVALID_HANDLE_VALUE, // use paging file
  6200. NULL, // default security attributes
  6201. PAGE_READWRITE, // read/write access
  6202. 0, // size: high 32-bits
  6203. 4096, // size: low 32-bits
  6204. unique_name // name of map object
  6205. );
  6206. if (NULL != map_handle) {
  6207. void *shared_mem = MapViewOfFile(
  6208. map_handle, // object to map view of
  6209. FILE_MAP_WRITE, // read/write access
  6210. 0, // high offset: map from
  6211. 0, // low offset: beginning
  6212. 0 // default: map entire file
  6213. );
  6214. if (NULL != shared_mem)
  6215. CopyMemory(shared_mem, &rate, sizeof(rate));
  6216. (void)UnmapViewOfFile(shared_mem);
  6217. }
  6218. (void)CloseHandle(map_handle);
  6219. }
  6220. #endif
  6221. }
  6222. exit(0);
  6223. }
  6224. #endif
  6225. #ifdef HAVE_OPENCL
  6226. if (!opt_nogpu)
  6227. opencl_drv.drv_detect();
  6228. gpu_threads = 0;
  6229. #endif
  6230. #ifdef USE_ICARUS
  6231. if (!opt_scrypt)
  6232. icarus_drv.drv_detect();
  6233. #endif
  6234. #ifdef USE_BFLSC
  6235. if (!opt_scrypt)
  6236. bflsc_drv.drv_detect();
  6237. #endif
  6238. #ifdef USE_BITFORCE
  6239. if (!opt_scrypt)
  6240. bitforce_drv.drv_detect();
  6241. #endif
  6242. #ifdef USE_MODMINER
  6243. if (!opt_scrypt)
  6244. modminer_drv.drv_detect();
  6245. #endif
  6246. #ifdef USE_ZTEX
  6247. if (!opt_scrypt)
  6248. ztex_drv.drv_detect();
  6249. #endif
  6250. #ifdef WANT_CPUMINE
  6251. cpu_drv.drv_detect();
  6252. #endif
  6253. if (devices_enabled == -1) {
  6254. applog(LOG_ERR, "Devices detected:");
  6255. for (i = 0; i < total_devices; ++i) {
  6256. struct cgpu_info *cgpu = devices[i];
  6257. if (cgpu->name)
  6258. applog(LOG_ERR, " %2d. %s %d: %s (driver: %s)", i, cgpu->drv->name, cgpu->device_id, cgpu->name, cgpu->drv->dname);
  6259. else
  6260. applog(LOG_ERR, " %2d. %s %d (driver: %s)", i, cgpu->drv->name, cgpu->device_id, cgpu->drv->dname);
  6261. }
  6262. quit(0, "%d devices listed", total_devices);
  6263. }
  6264. mining_threads = 0;
  6265. if (devices_enabled) {
  6266. for (i = 0; i < (int)(sizeof(devices_enabled) * 8) - 1; ++i) {
  6267. if (devices_enabled & (1 << i)) {
  6268. if (i >= total_devices)
  6269. quit (1, "Command line options set a device that doesn't exist");
  6270. enable_device(devices[i]);
  6271. } else if (i < total_devices) {
  6272. if (opt_removedisabled) {
  6273. if (devices[i]->drv->drv_id == DRIVER_CPU)
  6274. --opt_n_threads;
  6275. } else {
  6276. enable_device(devices[i]);
  6277. }
  6278. devices[i]->deven = DEV_DISABLED;
  6279. }
  6280. }
  6281. total_devices = cgminer_id_count;
  6282. } else {
  6283. for (i = 0; i < total_devices; ++i)
  6284. enable_device(devices[i]);
  6285. }
  6286. #ifdef USE_USBUTILS
  6287. if (!total_devices) {
  6288. applog(LOG_WARNING, "No devices detected!");
  6289. applog(LOG_WARNING, "Waiting for USB hotplug devices or press q to quit");
  6290. }
  6291. #else
  6292. if (!total_devices)
  6293. quit(1, "All devices disabled, cannot mine!");
  6294. #endif
  6295. start_devices = total_devices;
  6296. load_temp_cutoffs();
  6297. for (i = 0; i < total_devices; ++i)
  6298. devices[i]->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6299. if (!opt_compact) {
  6300. logstart += total_devices;
  6301. logcursor = logstart + 1;
  6302. #ifdef HAVE_CURSES
  6303. check_winsizes();
  6304. #endif
  6305. }
  6306. if (!total_pools) {
  6307. applog(LOG_WARNING, "Need to specify at least one pool server.");
  6308. #ifdef HAVE_CURSES
  6309. if (!use_curses || !input_pool(false))
  6310. #endif
  6311. quit(1, "Pool setup failed");
  6312. }
  6313. for (i = 0; i < total_pools; i++) {
  6314. struct pool *pool = pools[i];
  6315. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6316. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6317. if (!pool->rpc_userpass) {
  6318. if (!pool->rpc_user || !pool->rpc_pass)
  6319. quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  6320. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  6321. if (!pool->rpc_userpass)
  6322. quit(1, "Failed to malloc userpass");
  6323. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  6324. }
  6325. }
  6326. /* Set the currentpool to pool 0 */
  6327. currentpool = pools[0];
  6328. #ifdef HAVE_SYSLOG_H
  6329. if (use_syslog)
  6330. openlog(PACKAGE, LOG_PID, LOG_USER);
  6331. #endif
  6332. #if defined(unix)
  6333. if (opt_stderr_cmd)
  6334. fork_monitor();
  6335. #endif // defined(unix)
  6336. mining_thr = calloc(mining_threads, sizeof(thr));
  6337. if (!mining_thr)
  6338. quit(1, "Failed to calloc mining_thr");
  6339. for (i = 0; i < mining_threads; i++) {
  6340. mining_thr[i] = calloc(1, sizeof(*thr));
  6341. if (!mining_thr[i])
  6342. quit(1, "Failed to calloc mining_thr[%d]", i);
  6343. }
  6344. total_control_threads = 8;
  6345. control_thr = calloc(total_control_threads, sizeof(*thr));
  6346. if (!control_thr)
  6347. quit(1, "Failed to calloc control_thr");
  6348. gwsched_thr_id = 0;
  6349. stage_thr_id = 1;
  6350. thr = &control_thr[stage_thr_id];
  6351. thr->q = tq_new();
  6352. if (!thr->q)
  6353. quit(1, "Failed to tq_new");
  6354. /* start stage thread */
  6355. if (thr_info_create(thr, NULL, stage_thread, thr))
  6356. quit(1, "stage thread create failed");
  6357. pthread_detach(thr->pth);
  6358. /* Create a unique get work queue */
  6359. getq = tq_new();
  6360. if (!getq)
  6361. quit(1, "Failed to create getq");
  6362. /* We use the getq mutex as the staged lock */
  6363. stgd_lock = &getq->mutex;
  6364. if (opt_benchmark)
  6365. goto begin_bench;
  6366. for (i = 0; i < total_pools; i++) {
  6367. struct pool *pool = pools[i];
  6368. enable_pool(pool);
  6369. pool->idle = true;
  6370. }
  6371. applog(LOG_NOTICE, "Probing for an alive pool");
  6372. do {
  6373. int slept = 0;
  6374. /* Look for at least one active pool before starting */
  6375. probe_pools();
  6376. do {
  6377. sleep(1);
  6378. slept++;
  6379. } while (!pools_active && slept < 60);
  6380. if (!pools_active) {
  6381. applog(LOG_ERR, "No servers were found that could be used to get work from.");
  6382. applog(LOG_ERR, "Please check the details from the list below of the servers you have input");
  6383. applog(LOG_ERR, "Most likely you have input the wrong URL, forgotten to add a port, or have not set up workers");
  6384. for (i = 0; i < total_pools; i++) {
  6385. struct pool *pool;
  6386. pool = pools[i];
  6387. applog(LOG_WARNING, "Pool: %d URL: %s User: %s Password: %s",
  6388. i, pool->rpc_url, pool->rpc_user, pool->rpc_pass);
  6389. }
  6390. #ifdef HAVE_CURSES
  6391. if (use_curses) {
  6392. halfdelay(150);
  6393. applog(LOG_ERR, "Press any key to exit, or cgminer will try again in 15s.");
  6394. if (getch() != ERR)
  6395. quit(0, "No servers could be used! Exiting.");
  6396. cbreak();
  6397. } else
  6398. #endif
  6399. quit(0, "No servers could be used! Exiting.");
  6400. }
  6401. } while (!pools_active);
  6402. begin_bench:
  6403. total_mhashes_done = 0;
  6404. for (i = 0; i < total_devices; i++) {
  6405. struct cgpu_info *cgpu = devices[i];
  6406. cgpu->rolling = cgpu->total_mhashes = 0;
  6407. }
  6408. gettimeofday(&total_tv_start, NULL);
  6409. gettimeofday(&total_tv_end, NULL);
  6410. get_datestamp(datestamp, &total_tv_start);
  6411. // Start threads
  6412. k = 0;
  6413. for (i = 0; i < total_devices; ++i) {
  6414. struct cgpu_info *cgpu = devices[i];
  6415. cgpu->thr = malloc(sizeof(*cgpu->thr) * (cgpu->threads+1));
  6416. cgpu->thr[cgpu->threads] = NULL;
  6417. cgpu->status = LIFE_INIT;
  6418. for (j = 0; j < cgpu->threads; ++j, ++k) {
  6419. thr = get_thread(k);
  6420. thr->id = k;
  6421. thr->cgpu = cgpu;
  6422. thr->device_thread = j;
  6423. thr->q = tq_new();
  6424. if (!thr->q)
  6425. quit(1, "tq_new failed in starting %s%d mining thread (#%d)", cgpu->drv->name, cgpu->device_id, i);
  6426. /* Enable threads for devices set not to mine but disable
  6427. * their queue in case we wish to enable them later */
  6428. if (cgpu->deven != DEV_DISABLED) {
  6429. applog(LOG_DEBUG, "Pushing ping to thread %d", thr->id);
  6430. tq_push(thr->q, &ping);
  6431. }
  6432. if (!cgpu->drv->thread_prepare(thr))
  6433. continue;
  6434. thread_reportout(thr);
  6435. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  6436. quit(1, "thread %d create failed", thr->id);
  6437. cgpu->thr[j] = thr;
  6438. }
  6439. }
  6440. #ifdef HAVE_OPENCL
  6441. applog(LOG_INFO, "%d gpu miner threads started", gpu_threads);
  6442. for (i = 0; i < nDevs; i++)
  6443. pause_dynamic_threads(i);
  6444. #endif
  6445. #ifdef WANT_CPUMINE
  6446. applog(LOG_INFO, "%d cpu miner threads started, "
  6447. "using SHA256 '%s' algorithm.",
  6448. opt_n_threads,
  6449. algo_names[opt_algo]);
  6450. #endif
  6451. gettimeofday(&total_tv_start, NULL);
  6452. gettimeofday(&total_tv_end, NULL);
  6453. watchpool_thr_id = 2;
  6454. thr = &control_thr[watchpool_thr_id];
  6455. /* start watchpool thread */
  6456. if (thr_info_create(thr, NULL, watchpool_thread, NULL))
  6457. quit(1, "watchpool thread create failed");
  6458. pthread_detach(thr->pth);
  6459. watchdog_thr_id = 3;
  6460. thr = &control_thr[watchdog_thr_id];
  6461. /* start watchdog thread */
  6462. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  6463. quit(1, "watchdog thread create failed");
  6464. pthread_detach(thr->pth);
  6465. #ifdef HAVE_OPENCL
  6466. /* Create reinit gpu thread */
  6467. gpur_thr_id = 4;
  6468. thr = &control_thr[gpur_thr_id];
  6469. thr->q = tq_new();
  6470. if (!thr->q)
  6471. quit(1, "tq_new failed for gpur_thr_id");
  6472. if (thr_info_create(thr, NULL, reinit_gpu, thr))
  6473. quit(1, "reinit_gpu thread create failed");
  6474. #endif
  6475. /* Create API socket thread */
  6476. api_thr_id = 5;
  6477. thr = &control_thr[api_thr_id];
  6478. if (thr_info_create(thr, NULL, api_thread, thr))
  6479. quit(1, "API thread create failed");
  6480. #ifdef USE_USBUTILS
  6481. if (!opt_scrypt) {
  6482. hotplug_thr_id = 6;
  6483. thr = &control_thr[hotplug_thr_id];
  6484. if (thr_info_create(thr, NULL, hotplug_thread, thr))
  6485. quit(1, "hotplug thread create failed");
  6486. pthread_detach(thr->pth);
  6487. }
  6488. #endif
  6489. #ifdef HAVE_CURSES
  6490. /* Create curses input thread for keyboard input. Create this last so
  6491. * that we know all threads are created since this can call kill_work
  6492. * to try and shut down all previous threads. */
  6493. input_thr_id = 7;
  6494. thr = &control_thr[input_thr_id];
  6495. if (thr_info_create(thr, NULL, input_thread, thr))
  6496. quit(1, "input thread create failed");
  6497. pthread_detach(thr->pth);
  6498. #endif
  6499. /* Just to be sure */
  6500. if (total_control_threads != 8)
  6501. quit(1, "incorrect total_control_threads (%d) should be 8", total_control_threads);
  6502. /* Once everything is set up, main() becomes the getwork scheduler */
  6503. while (42) {
  6504. int ts, max_staged = opt_queue;
  6505. struct pool *pool, *cp;
  6506. bool lagging = false;
  6507. struct curl_ent *ce;
  6508. struct work *work;
  6509. cp = current_pool();
  6510. /* If the primary pool is a getwork pool and cannot roll work,
  6511. * try to stage one extra work per mining thread */
  6512. if (!cp->has_stratum && !cp->has_gbt && !staged_rollable)
  6513. max_staged += mining_threads;
  6514. mutex_lock(stgd_lock);
  6515. ts = __total_staged();
  6516. if (!cp->has_stratum && !cp->has_gbt && !ts && !opt_fail_only)
  6517. lagging = true;
  6518. /* Wait until hash_pop tells us we need to create more work */
  6519. if (ts > max_staged) {
  6520. pthread_cond_wait(&gws_cond, stgd_lock);
  6521. ts = __total_staged();
  6522. }
  6523. mutex_unlock(stgd_lock);
  6524. if (ts > max_staged)
  6525. continue;
  6526. work = make_work();
  6527. if (lagging && !pool_tset(cp, &cp->lagging)) {
  6528. applog(LOG_WARNING, "Pool %d not providing work fast enough", cp->pool_no);
  6529. cp->getfail_occasions++;
  6530. total_go++;
  6531. }
  6532. pool = select_pool(lagging);
  6533. retry:
  6534. if (pool->has_stratum) {
  6535. while (!pool->stratum_active || !pool->stratum_notify) {
  6536. struct pool *altpool = select_pool(true);
  6537. nmsleep(5000);
  6538. if (altpool != pool) {
  6539. pool = altpool;
  6540. goto retry;
  6541. }
  6542. }
  6543. gen_stratum_work(pool, work);
  6544. applog(LOG_DEBUG, "Generated stratum work");
  6545. stage_work(work);
  6546. continue;
  6547. }
  6548. if (pool->has_gbt) {
  6549. while (pool->idle) {
  6550. struct pool *altpool = select_pool(true);
  6551. nmsleep(5000);
  6552. if (altpool != pool) {
  6553. pool = altpool;
  6554. goto retry;
  6555. }
  6556. }
  6557. gen_gbt_work(pool, work);
  6558. applog(LOG_DEBUG, "Generated GBT work");
  6559. stage_work(work);
  6560. continue;
  6561. }
  6562. if (clone_available()) {
  6563. applog(LOG_DEBUG, "Cloned getwork work");
  6564. free_work(work);
  6565. continue;
  6566. }
  6567. if (opt_benchmark) {
  6568. get_benchmark_work(work);
  6569. applog(LOG_DEBUG, "Generated benchmark work");
  6570. stage_work(work);
  6571. continue;
  6572. }
  6573. work->pool = pool;
  6574. ce = pop_curl_entry(pool);
  6575. /* obtain new work from bitcoin via JSON-RPC */
  6576. if (!get_upstream_work(work, ce->curl)) {
  6577. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, retrying in 5s", pool->pool_no);
  6578. /* Make sure the pool just hasn't stopped serving
  6579. * requests but is up as we'll keep hammering it */
  6580. if (++pool->seq_getfails > mining_threads + opt_queue)
  6581. pool_died(pool);
  6582. nmsleep(5000);
  6583. push_curl_entry(ce, pool);
  6584. pool = select_pool(!opt_fail_only);
  6585. goto retry;
  6586. }
  6587. if (ts >= max_staged)
  6588. pool_tclear(pool, &pool->lagging);
  6589. if (pool_tclear(pool, &pool->idle))
  6590. pool_resus(pool);
  6591. applog(LOG_DEBUG, "Generated getwork work");
  6592. stage_work(work);
  6593. push_curl_entry(ce, pool);
  6594. }
  6595. return 0;
  6596. }