main.c 160 KB

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