cgminer.c 199 KB

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