cgminer.c 197 KB

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