cgminer.c 261 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953
  1. /*
  2. * Copyright 2011-2014 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 <limits.h>
  28. #include <sha2.h>
  29. #ifdef USE_USBUTILS
  30. #include <semaphore.h>
  31. #endif
  32. #include <sys/stat.h>
  33. #include <sys/types.h>
  34. #ifndef WIN32
  35. #include <sys/resource.h>
  36. #else
  37. #define WIN32_LEAN_AND_MEAN
  38. #include <windows.h>
  39. #undef WIN32_LEAN_AND_MEAN
  40. #endif
  41. #include <ccan/opt/opt.h>
  42. #include <jansson.h>
  43. #ifdef HAVE_LIBCURL
  44. #include <curl/curl.h>
  45. #else
  46. char *curly = ":D";
  47. #endif
  48. #include <libgen.h>
  49. #include "compat.h"
  50. #include "miner.h"
  51. #include "bench_block.h"
  52. #include "scrypt.h"
  53. #ifdef USE_USBUTILS
  54. #include "usbutils.h"
  55. #endif
  56. #if defined(unix) || defined(__APPLE__)
  57. #include <errno.h>
  58. #include <fcntl.h>
  59. #include <sys/wait.h>
  60. #endif
  61. #ifdef USE_AVALON
  62. #include "driver-avalon.h"
  63. #endif
  64. #ifdef USE_AVALON2
  65. #include "driver-avalon2.h"
  66. #endif
  67. #ifdef USE_BFLSC
  68. #include "driver-bflsc.h"
  69. #endif
  70. #ifdef USE_SPONDOOLIES
  71. #include "driver-spondoolies.h"
  72. #endif
  73. #ifdef USE_BITFURY
  74. #include "driver-bitfury.h"
  75. #endif
  76. #ifdef USE_COINTERRA
  77. #include "driver-cointerra.h"
  78. #endif
  79. #ifdef USE_HASHFAST
  80. #include "driver-hashfast.h"
  81. #endif
  82. #if defined(USE_ANT_S1) || defined(USE_ANT_S2)
  83. #include "driver-bitmain.h"
  84. #endif
  85. #ifdef USE_GRIDSEED
  86. #include "driver-gridseed.h"
  87. #endif
  88. #ifdef USE_ZEUS
  89. #include "driver-zeus.h"
  90. #endif
  91. #ifdef USE_LKETC
  92. #include "driver-lketc.h"
  93. #endif
  94. #if defined(USE_BITFORCE) || defined(USE_ICARUS) || defined(USE_AVALON) || defined(USE_AVALON2) || defined(USE_MODMINER)
  95. # define USE_FPGA
  96. #endif
  97. struct strategies strategies[] = {
  98. { "Failover" },
  99. { "Round Robin" },
  100. { "Rotate" },
  101. { "Load Balance" },
  102. { "Balance" },
  103. };
  104. static char packagename[256];
  105. bool opt_work_update;
  106. bool opt_protocol;
  107. static struct benchfile_layout {
  108. int length;
  109. char *name;
  110. } benchfile_data[] = {
  111. { 1, "Version" },
  112. { 64, "MerkleRoot" },
  113. { 64, "PrevHash" },
  114. { 8, "DifficultyBits" },
  115. { 10, "NonceTime" } // 10 digits
  116. };
  117. enum benchwork {
  118. BENCHWORK_VERSION = 0,
  119. BENCHWORK_MERKLEROOT,
  120. BENCHWORK_PREVHASH,
  121. BENCHWORK_DIFFBITS,
  122. BENCHWORK_NONCETIME,
  123. BENCHWORK_COUNT
  124. };
  125. #ifdef HAVE_LIBCURL
  126. static char *opt_btc_address;
  127. static char *opt_btc_sig;
  128. #endif
  129. static char *opt_benchfile;
  130. static bool opt_benchfile_display;
  131. static FILE *benchfile_in;
  132. static int benchfile_line;
  133. static int benchfile_work;
  134. static bool opt_benchmark;
  135. bool have_longpoll;
  136. bool want_per_device_stats;
  137. bool use_syslog;
  138. bool opt_quiet;
  139. bool opt_realquiet;
  140. bool opt_loginput;
  141. bool opt_compact;
  142. const int opt_cutofftemp = 95;
  143. int opt_log_interval = 5;
  144. int opt_queue = -1;
  145. static int max_queue = 1;
  146. int opt_scantime = -1;
  147. int opt_expiry = 120;
  148. static const bool opt_time = true;
  149. unsigned long long global_hashrate;
  150. unsigned long global_quota_gcd = 1;
  151. time_t last_getwork;
  152. #if defined(USE_USBUTILS)
  153. int nDevs;
  154. #endif
  155. bool opt_sha256;
  156. #ifdef USE_SCRYPT
  157. bool opt_scrypt;
  158. #endif
  159. bool opt_restart = true;
  160. bool opt_nogpu;
  161. struct list_head scan_devices;
  162. static bool opt_display_devs;
  163. int total_devices;
  164. int zombie_devs;
  165. static int most_devices;
  166. struct cgpu_info **devices;
  167. int mining_threads;
  168. int num_processors;
  169. #ifdef HAVE_CURSES
  170. bool use_curses = true;
  171. #else
  172. bool use_curses;
  173. #endif
  174. static bool opt_widescreen;
  175. static bool alt_status;
  176. static bool switch_status;
  177. static bool opt_submit_stale = true;
  178. static int opt_shares;
  179. bool opt_fail_only;
  180. static int opt_fail_switch_delay = 300;
  181. static bool opt_fix_protocol;
  182. bool opt_lowmem;
  183. bool opt_autofan;
  184. bool opt_autoengine;
  185. bool opt_noadl;
  186. char *opt_api_allow = NULL;
  187. char *opt_api_groups;
  188. char *opt_api_description = PACKAGE_STRING;
  189. int opt_api_port = 4028;
  190. bool opt_api_listen;
  191. bool opt_api_mcast;
  192. char *opt_api_mcast_addr = API_MCAST_ADDR;
  193. char *opt_api_mcast_code = API_MCAST_CODE;
  194. char *opt_api_mcast_des = "";
  195. int opt_api_mcast_port = 4028;
  196. bool opt_api_network;
  197. bool opt_delaynet;
  198. bool opt_disable_pool;
  199. static bool no_work;
  200. #ifdef USE_ICARUS
  201. char *opt_icarus_options = NULL;
  202. char *opt_icarus_timing = NULL;
  203. float opt_anu_freq = 200;
  204. #endif
  205. bool opt_worktime;
  206. #ifdef USE_AVALON
  207. char *opt_avalon_options;
  208. char *opt_bitburner_fury_options;
  209. static char *opt_set_avalon_fan;
  210. static char *opt_set_avalon_freq;
  211. #endif
  212. #ifdef USE_AVALON2
  213. static char *opt_set_avalon2_freq;
  214. static char *opt_set_avalon2_fan;
  215. static char *opt_set_avalon2_voltage;
  216. #endif
  217. #ifdef USE_KLONDIKE
  218. char *opt_klondike_options = NULL;
  219. #endif
  220. #ifdef USE_DRILLBIT
  221. char *opt_drillbit_options = NULL;
  222. char *opt_drillbit_auto = NULL;
  223. #endif
  224. char *opt_bab_options = NULL;
  225. #ifdef USE_BITMINE_A1
  226. char *opt_bitmine_a1_options = NULL;
  227. #endif
  228. #if defined(USE_ANT_S1) || defined(USE_ANT_S2)
  229. char *opt_bitmain_options;
  230. static char *opt_set_bitmain_fan;
  231. static char *opt_set_bitmain_freq;
  232. #endif
  233. #ifdef USE_ANT_S2
  234. char *opt_bitmain_dev;
  235. #endif
  236. #ifdef USE_HASHFAST
  237. static char *opt_set_hfa_fan;
  238. #endif
  239. #ifdef USE_GRIDSEED
  240. char *opt_gridseed_options = NULL;
  241. char *opt_gridseed_freq = NULL;
  242. char *opt_gridseed_override = NULL;
  243. #endif
  244. #ifdef USE_LKETC
  245. bool opt_lketc_debug;
  246. int opt_lketc_chips_count;
  247. int opt_lketc_chip_clk;
  248. bool opt_lketc_nocheck_golden;
  249. char *opt_lketc_options;
  250. #endif
  251. #ifdef USE_ZEUS
  252. bool opt_zeus_debug;
  253. int opt_zeus_chips_count;
  254. int opt_zeus_chip_clk;
  255. bool opt_zeus_nocheck_golden;
  256. char *opt_zeus_options;
  257. #endif
  258. static char *opt_set_null;
  259. #ifdef USE_MINION
  260. int opt_minion_chipreport;
  261. char *opt_minion_cores;
  262. char *opt_minion_freq;
  263. bool opt_minion_idlecount;
  264. bool opt_minion_overheat;
  265. char *opt_minion_temp;
  266. #endif
  267. #ifdef USE_USBUTILS
  268. char *opt_usb_select = NULL;
  269. int opt_usbdump = -1;
  270. bool opt_usb_list_all;
  271. cgsem_t usb_resource_sem;
  272. static pthread_t usb_poll_thread;
  273. static bool usb_polling;
  274. #endif
  275. char *opt_kernel_path;
  276. char *cgminer_path;
  277. #if defined(USE_BITFORCE)
  278. bool opt_bfl_noncerange;
  279. #endif
  280. #define QUIET (opt_quiet || opt_realquiet)
  281. struct thr_info *control_thr;
  282. struct thr_info **mining_thr;
  283. static int gwsched_thr_id;
  284. static int watchpool_thr_id;
  285. static int watchdog_thr_id;
  286. #ifdef HAVE_CURSES
  287. static int input_thr_id;
  288. #endif
  289. int gpur_thr_id;
  290. static int api_thr_id;
  291. #ifdef USE_USBUTILS
  292. static int usbres_thr_id;
  293. static int hotplug_thr_id;
  294. #endif
  295. static int total_control_threads;
  296. bool hotplug_mode;
  297. static int new_devices;
  298. static int new_threads;
  299. int hotplug_time = 5;
  300. #if LOCK_TRACKING
  301. pthread_mutex_t lockstat_lock;
  302. #endif
  303. pthread_mutex_t hash_lock;
  304. static pthread_mutex_t *stgd_lock;
  305. pthread_mutex_t console_lock;
  306. cglock_t ch_lock;
  307. static pthread_rwlock_t blk_lock;
  308. static pthread_mutex_t sshare_lock;
  309. pthread_rwlock_t netacc_lock;
  310. pthread_rwlock_t mining_thr_lock;
  311. pthread_rwlock_t devices_lock;
  312. static pthread_mutex_t lp_lock;
  313. static pthread_cond_t lp_cond;
  314. pthread_mutex_t restart_lock;
  315. pthread_cond_t restart_cond;
  316. pthread_cond_t gws_cond;
  317. double rolling1, rolling5, rolling15;
  318. double total_rolling;
  319. double total_mhashes_done;
  320. static struct timeval total_tv_start, total_tv_end;
  321. static struct timeval restart_tv_start, update_tv_start;
  322. cglock_t control_lock;
  323. pthread_mutex_t stats_lock;
  324. int hw_errors;
  325. int64_t total_accepted, total_rejected, total_diff1;
  326. int64_t total_getworks, total_stale, total_discarded;
  327. double total_diff_accepted, total_diff_rejected, total_diff_stale;
  328. static int staged_rollable;
  329. unsigned int new_blocks;
  330. static unsigned int work_block;
  331. unsigned int found_blocks;
  332. unsigned int local_work;
  333. unsigned int total_go, total_ro;
  334. struct pool **pools;
  335. static struct pool *currentpool = NULL;
  336. int total_pools, enabled_pools;
  337. enum pool_strategy pool_strategy = POOL_FAILOVER;
  338. int opt_rotate_period;
  339. static int total_urls, total_users, total_passes, total_userpasses;
  340. static
  341. #ifndef HAVE_CURSES
  342. const
  343. #endif
  344. bool curses_active;
  345. /* Protected by ch_lock */
  346. char current_hash[68];
  347. static char prev_block[12];
  348. static char current_block[32];
  349. static char datestamp[40];
  350. static char blocktime[32];
  351. struct timeval block_timeval;
  352. static char best_share[8] = "0";
  353. double current_diff = 0xFFFFFFFFFFFFFFFFULL;
  354. static char block_diff[8];
  355. uint64_t best_diff = 0;
  356. struct block {
  357. char hash[68];
  358. UT_hash_handle hh;
  359. int block_no;
  360. };
  361. static struct block *blocks = NULL;
  362. int swork_id;
  363. /* For creating a hash database of stratum shares submitted that have not had
  364. * a response yet */
  365. struct stratum_share {
  366. UT_hash_handle hh;
  367. bool block;
  368. struct work *work;
  369. int id;
  370. time_t sshare_time;
  371. time_t sshare_sent;
  372. };
  373. static struct stratum_share *stratum_shares = NULL;
  374. char *opt_socks_proxy = NULL;
  375. static const char def_conf[] = "cgminer.conf";
  376. static char *default_config;
  377. static bool config_loaded;
  378. static int include_count;
  379. #define JSON_INCLUDE_CONF "include"
  380. #define JSON_LOAD_ERROR "JSON decode of file '%s' failed\n %s"
  381. #define JSON_LOAD_ERROR_LEN strlen(JSON_LOAD_ERROR)
  382. #define JSON_MAX_DEPTH 10
  383. #define JSON_MAX_DEPTH_ERR "Too many levels of JSON includes (limit 10) or a loop"
  384. #define JSON_WEB_ERROR "WEB config err"
  385. #if defined(unix) || defined(__APPLE__)
  386. static char *opt_stderr_cmd = NULL;
  387. static int forkpid;
  388. #endif // defined(unix)
  389. struct sigaction termhandler, inthandler;
  390. struct thread_q *getq;
  391. static uint32_t total_work;
  392. struct work *staged_work = NULL;
  393. struct schedtime {
  394. bool enable;
  395. struct tm tm;
  396. };
  397. struct schedtime schedstart;
  398. struct schedtime schedstop;
  399. bool sched_paused;
  400. static bool time_before(struct tm *tm1, struct tm *tm2)
  401. {
  402. if (tm1->tm_hour < tm2->tm_hour)
  403. return true;
  404. if (tm1->tm_hour == tm2->tm_hour && tm1->tm_min < tm2->tm_min)
  405. return true;
  406. return false;
  407. }
  408. static bool should_run(void)
  409. {
  410. struct timeval tv;
  411. struct tm *tm;
  412. if (!schedstart.enable && !schedstop.enable)
  413. return true;
  414. cgtime(&tv);
  415. const time_t tmp_time = tv.tv_sec;
  416. tm = localtime(&tmp_time);
  417. if (schedstart.enable) {
  418. if (!schedstop.enable) {
  419. if (time_before(tm, &schedstart.tm))
  420. return false;
  421. /* This is a once off event with no stop time set */
  422. schedstart.enable = false;
  423. return true;
  424. }
  425. if (time_before(&schedstart.tm, &schedstop.tm)) {
  426. if (time_before(tm, &schedstop.tm) && !time_before(tm, &schedstart.tm))
  427. return true;
  428. return false;
  429. } /* Times are reversed */
  430. if (time_before(tm, &schedstart.tm)) {
  431. if (time_before(tm, &schedstop.tm))
  432. return true;
  433. return false;
  434. }
  435. return true;
  436. }
  437. /* only schedstop.enable == true */
  438. if (!time_before(tm, &schedstop.tm))
  439. return false;
  440. return true;
  441. }
  442. void get_datestamp(char *f, size_t fsiz, struct timeval *tv)
  443. {
  444. struct tm *tm;
  445. const time_t tmp_time = tv->tv_sec;
  446. tm = localtime(&tmp_time);
  447. snprintf(f, fsiz, "[%d-%02d-%02d %02d:%02d:%02d]",
  448. tm->tm_year + 1900,
  449. tm->tm_mon + 1,
  450. tm->tm_mday,
  451. tm->tm_hour,
  452. tm->tm_min,
  453. tm->tm_sec);
  454. }
  455. static void get_timestamp(char *f, size_t fsiz, struct timeval *tv)
  456. {
  457. struct tm *tm;
  458. const time_t tmp_time = tv->tv_sec;
  459. tm = localtime(&tmp_time);
  460. snprintf(f, fsiz, "[%02d:%02d:%02d]",
  461. tm->tm_hour,
  462. tm->tm_min,
  463. tm->tm_sec);
  464. }
  465. static char exit_buf[512];
  466. static void applog_and_exit(const char *fmt, ...)
  467. {
  468. va_list ap;
  469. va_start(ap, fmt);
  470. vsnprintf(exit_buf, sizeof(exit_buf), fmt, ap);
  471. va_end(ap);
  472. _applog(LOG_ERR, exit_buf, true);
  473. exit(1);
  474. }
  475. static pthread_mutex_t sharelog_lock;
  476. static FILE *sharelog_file = NULL;
  477. static struct thr_info *__get_thread(int thr_id)
  478. {
  479. return mining_thr[thr_id];
  480. }
  481. struct thr_info *get_thread(int thr_id)
  482. {
  483. struct thr_info *thr;
  484. rd_lock(&mining_thr_lock);
  485. thr = __get_thread(thr_id);
  486. rd_unlock(&mining_thr_lock);
  487. return thr;
  488. }
  489. static struct cgpu_info *get_thr_cgpu(int thr_id)
  490. {
  491. struct thr_info *thr = get_thread(thr_id);
  492. return thr->cgpu;
  493. }
  494. struct cgpu_info *get_devices(int id)
  495. {
  496. struct cgpu_info *cgpu;
  497. rd_lock(&devices_lock);
  498. cgpu = devices[id];
  499. rd_unlock(&devices_lock);
  500. return cgpu;
  501. }
  502. static void sharelog(const char*disposition, const struct work*work)
  503. {
  504. char *target, *hash, *data;
  505. struct cgpu_info *cgpu;
  506. unsigned long int t;
  507. struct pool *pool;
  508. int thr_id, rv;
  509. char s[1024];
  510. size_t ret;
  511. if (!sharelog_file)
  512. return;
  513. thr_id = work->thr_id;
  514. cgpu = get_thr_cgpu(thr_id);
  515. pool = work->pool;
  516. t = (unsigned long int)(work->tv_work_found.tv_sec);
  517. target = bin2hex(work->target, sizeof(work->target));
  518. hash = bin2hex(work->hash, sizeof(work->hash));
  519. data = bin2hex(work->data, sizeof(work->data));
  520. // timestamp,disposition,target,pool,dev,thr,sharehash,sharedata
  521. 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);
  522. free(target);
  523. free(hash);
  524. free(data);
  525. if (rv >= (int)(sizeof(s)))
  526. s[sizeof(s) - 1] = '\0';
  527. else if (rv < 0) {
  528. applog(LOG_ERR, "sharelog printf error");
  529. return;
  530. }
  531. mutex_lock(&sharelog_lock);
  532. ret = fwrite(s, rv, 1, sharelog_file);
  533. fflush(sharelog_file);
  534. mutex_unlock(&sharelog_lock);
  535. if (ret != 1)
  536. applog(LOG_ERR, "sharelog fwrite error");
  537. }
  538. static char *getwork_req = "{\"method\": \"getwork\", \"params\": [], \"id\":0}\n";
  539. static char *gbt_req = "{\"id\": 0, \"method\": \"getblocktemplate\", \"params\": [{\"capabilities\": [\"coinbasetxn\", \"workid\", \"coinbase/append\"]}]}\n";
  540. static char *gbt_solo_req = "{\"id\": 0, \"method\": \"getblocktemplate\"}\n";
  541. /* Adjust all the pools' quota to the greatest common denominator after a pool
  542. * has been added or the quotas changed. */
  543. void adjust_quota_gcd(void)
  544. {
  545. unsigned long gcd, lowest_quota = ~0UL, quota;
  546. struct pool *pool;
  547. int i;
  548. for (i = 0; i < total_pools; i++) {
  549. pool = pools[i];
  550. quota = pool->quota;
  551. if (!quota)
  552. continue;
  553. if (quota < lowest_quota)
  554. lowest_quota = quota;
  555. }
  556. if (likely(lowest_quota < ~0UL)) {
  557. gcd = lowest_quota;
  558. for (i = 0; i < total_pools; i++) {
  559. pool = pools[i];
  560. quota = pool->quota;
  561. if (!quota)
  562. continue;
  563. while (quota % gcd)
  564. gcd--;
  565. }
  566. } else
  567. gcd = 1;
  568. for (i = 0; i < total_pools; i++) {
  569. pool = pools[i];
  570. pool->quota_used *= global_quota_gcd;
  571. pool->quota_used /= gcd;
  572. pool->quota_gcd = pool->quota / gcd;
  573. }
  574. global_quota_gcd = gcd;
  575. applog(LOG_DEBUG, "Global quota greatest common denominator set to %lu", gcd);
  576. }
  577. /* Return value is ignored if not called from add_pool_details */
  578. struct pool *add_pool(void)
  579. {
  580. struct pool *pool;
  581. pool = calloc(sizeof(struct pool), 1);
  582. if (!pool)
  583. quit(1, "Failed to malloc pool in add_pool");
  584. pool->pool_no = pool->prio = total_pools;
  585. pools = realloc(pools, sizeof(struct pool *) * (total_pools + 2));
  586. pools[total_pools++] = pool;
  587. mutex_init(&pool->pool_lock);
  588. if (unlikely(pthread_cond_init(&pool->cr_cond, NULL)))
  589. quit(1, "Failed to pthread_cond_init in add_pool");
  590. cglock_init(&pool->data_lock);
  591. mutex_init(&pool->stratum_lock);
  592. cglock_init(&pool->gbt_lock);
  593. INIT_LIST_HEAD(&pool->curlring);
  594. /* Make sure the pool doesn't think we've been idle since time 0 */
  595. pool->tv_idle.tv_sec = ~0UL;
  596. pool->rpc_req = getwork_req;
  597. pool->rpc_proxy = NULL;
  598. pool->quota = 1;
  599. adjust_quota_gcd();
  600. return pool;
  601. }
  602. /* Pool variant of test and set */
  603. static bool pool_tset(struct pool *pool, bool *var)
  604. {
  605. bool ret;
  606. mutex_lock(&pool->pool_lock);
  607. ret = *var;
  608. *var = true;
  609. mutex_unlock(&pool->pool_lock);
  610. return ret;
  611. }
  612. bool pool_tclear(struct pool *pool, bool *var)
  613. {
  614. bool ret;
  615. mutex_lock(&pool->pool_lock);
  616. ret = *var;
  617. *var = false;
  618. mutex_unlock(&pool->pool_lock);
  619. return ret;
  620. }
  621. struct pool *current_pool(void)
  622. {
  623. struct pool *pool;
  624. cg_rlock(&control_lock);
  625. pool = currentpool;
  626. cg_runlock(&control_lock);
  627. return pool;
  628. }
  629. char *set_int_range(const char *arg, int *i, int min, int max)
  630. {
  631. char *err = opt_set_intval(arg, i);
  632. if (err)
  633. return err;
  634. if (*i < min || *i > max)
  635. return "Value out of range";
  636. return NULL;
  637. }
  638. static char *set_int_0_to_9999(const char *arg, int *i)
  639. {
  640. return set_int_range(arg, i, 0, 9999);
  641. }
  642. static char *set_int_1_to_65535(const char *arg, int *i)
  643. {
  644. return set_int_range(arg, i, 1, 65535);
  645. }
  646. static char *set_int_0_to_10(const char *arg, int *i)
  647. {
  648. return set_int_range(arg, i, 0, 10);
  649. }
  650. static char *set_int_0_to_100(const char *arg, int *i)
  651. {
  652. return set_int_range(arg, i, 0, 100);
  653. }
  654. static char *set_int_0_to_255(const char *arg, int *i)
  655. {
  656. return set_int_range(arg, i, 0, 255);
  657. }
  658. static char *set_int_0_to_200(const char *arg, int *i)
  659. {
  660. return set_int_range(arg, i, 0, 200);
  661. }
  662. static char *set_int_32_to_63(const char *arg, int *i)
  663. {
  664. return set_int_range(arg, i, 32, 63);
  665. }
  666. static char *set_int_1_to_10(const char *arg, int *i)
  667. {
  668. return set_int_range(arg, i, 1, 10);
  669. }
  670. static char __maybe_unused *set_int_0_to_4(const char *arg, int *i)
  671. {
  672. return set_int_range(arg, i, 0, 4);
  673. }
  674. static char *set_int_1_to_1024(const char *arg, int *i)
  675. {
  676. return set_int_range(arg, i, 1, 1024);
  677. }
  678. #ifdef USE_FPGA_SERIAL
  679. static char *opt_add_serial;
  680. static char *add_serial(char *arg)
  681. {
  682. string_elist_add(arg, &scan_devices);
  683. return NULL;
  684. }
  685. #endif
  686. void get_intrange(char *arg, int *val1, int *val2)
  687. {
  688. if (sscanf(arg, "%d-%d", val1, val2) == 1)
  689. *val2 = *val1;
  690. }
  691. static char *set_balance(enum pool_strategy *strategy)
  692. {
  693. *strategy = POOL_BALANCE;
  694. return NULL;
  695. }
  696. static char *set_loadbalance(enum pool_strategy *strategy)
  697. {
  698. *strategy = POOL_LOADBALANCE;
  699. return NULL;
  700. }
  701. static char *set_rotate(const char *arg, char __maybe_unused *i)
  702. {
  703. pool_strategy = POOL_ROTATE;
  704. return set_int_range(arg, &opt_rotate_period, 0, 9999);
  705. }
  706. static char *set_rr(enum pool_strategy *strategy)
  707. {
  708. *strategy = POOL_ROUNDROBIN;
  709. return NULL;
  710. }
  711. /* Detect that url is for a stratum protocol either via the presence of
  712. * stratum+tcp or by detecting a stratum server response */
  713. bool detect_stratum(struct pool *pool, char *url)
  714. {
  715. check_extranonce_option(pool, url);
  716. if (!extract_sockaddr(url, &pool->sockaddr_url, &pool->stratum_port))
  717. return false;
  718. if (!strncasecmp(url, "stratum+tcp://", 14)) {
  719. pool->rpc_url = strdup(url);
  720. pool->has_stratum = true;
  721. pool->stratum_url = pool->sockaddr_url;
  722. return true;
  723. }
  724. return false;
  725. }
  726. static struct pool *add_url(void)
  727. {
  728. total_urls++;
  729. if (total_urls > total_pools)
  730. add_pool();
  731. return pools[total_urls - 1];
  732. }
  733. static void setup_url(struct pool *pool, char *arg)
  734. {
  735. arg = get_proxy(arg, pool);
  736. if (detect_stratum(pool, arg))
  737. return;
  738. opt_set_charp(arg, &pool->rpc_url);
  739. if (strncmp(arg, "http://", 7) &&
  740. strncmp(arg, "https://", 8)) {
  741. char *httpinput;
  742. httpinput = malloc(256);
  743. if (!httpinput)
  744. quit(1, "Failed to malloc httpinput");
  745. strcpy(httpinput, "stratum+tcp://");
  746. strncat(httpinput, arg, 242);
  747. detect_stratum(pool, httpinput);
  748. }
  749. }
  750. static char *set_url(char *arg)
  751. {
  752. struct pool *pool = add_url();
  753. setup_url(pool, arg);
  754. return NULL;
  755. }
  756. static char *set_quota(char *arg)
  757. {
  758. char *semicolon = strchr(arg, ';'), *url;
  759. int len, qlen, quota;
  760. struct pool *pool;
  761. if (!semicolon)
  762. return "No semicolon separated quota;URL pair found";
  763. len = strlen(arg);
  764. *semicolon = '\0';
  765. qlen = strlen(arg);
  766. if (!qlen)
  767. return "No parameter for quota found";
  768. len -= qlen + 1;
  769. if (len < 1)
  770. return "No parameter for URL found";
  771. quota = atoi(arg);
  772. if (quota < 0)
  773. return "Invalid negative parameter for quota set";
  774. url = arg + qlen + 1;
  775. pool = add_url();
  776. setup_url(pool, url);
  777. pool->quota = quota;
  778. applog(LOG_INFO, "Setting pool %d to quota %d", pool->pool_no, pool->quota);
  779. adjust_quota_gcd();
  780. return NULL;
  781. }
  782. static char *set_user(const char *arg)
  783. {
  784. struct pool *pool;
  785. if (total_userpasses)
  786. return "Use only user + pass or userpass, but not both";
  787. total_users++;
  788. if (total_users > total_pools)
  789. add_pool();
  790. pool = pools[total_users - 1];
  791. opt_set_charp(arg, &pool->rpc_user);
  792. return NULL;
  793. }
  794. static char *set_pass(const char *arg)
  795. {
  796. struct pool *pool;
  797. if (total_userpasses)
  798. return "Use only user + pass or userpass, but not both";
  799. total_passes++;
  800. if (total_passes > total_pools)
  801. add_pool();
  802. pool = pools[total_passes - 1];
  803. opt_set_charp(arg, &pool->rpc_pass);
  804. return NULL;
  805. }
  806. static char *set_userpass(const char *arg)
  807. {
  808. struct pool *pool;
  809. char *updup;
  810. if (total_users || total_passes)
  811. return "Use only user + pass or userpass, but not both";
  812. total_userpasses++;
  813. if (total_userpasses > total_pools)
  814. add_pool();
  815. pool = pools[total_userpasses - 1];
  816. updup = strdup(arg);
  817. opt_set_charp(arg, &pool->rpc_userpass);
  818. pool->rpc_user = strtok(updup, ":");
  819. if (!pool->rpc_user)
  820. return "Failed to find : delimited user info";
  821. pool->rpc_pass = strtok(NULL, ":");
  822. if (!pool->rpc_pass)
  823. return "Failed to find : delimited pass info";
  824. return NULL;
  825. }
  826. static char *enable_debug(bool *flag)
  827. {
  828. *flag = true;
  829. /* Turn on verbose output, too. */
  830. opt_log_output = true;
  831. return NULL;
  832. }
  833. static char *opt_set_sched_start;
  834. static char *opt_set_sched_stop;
  835. static char *set_schedtime(const char *arg, struct schedtime *st)
  836. {
  837. if (sscanf(arg, "%d:%d", &st->tm.tm_hour, &st->tm.tm_min) != 2)
  838. return "Invalid time set, should be HH:MM";
  839. if (st->tm.tm_hour > 23 || st->tm.tm_min > 59 || st->tm.tm_hour < 0 || st->tm.tm_min < 0)
  840. return "Invalid time set.";
  841. st->enable = true;
  842. return NULL;
  843. }
  844. static char *set_sched_start(const char *arg)
  845. {
  846. return set_schedtime(arg, &schedstart);
  847. }
  848. static char *set_sched_stop(const char *arg)
  849. {
  850. return set_schedtime(arg, &schedstop);
  851. }
  852. static char *opt_set_sharelog;
  853. static char* set_sharelog(char *arg)
  854. {
  855. char *r = "";
  856. long int i = strtol(arg, &r, 10);
  857. if ((!*r) && i >= 0 && i <= INT_MAX) {
  858. sharelog_file = fdopen((int)i, "a");
  859. if (!sharelog_file)
  860. applog(LOG_ERR, "Failed to open fd %u for share log", (unsigned int)i);
  861. } else if (!strcmp(arg, "-")) {
  862. sharelog_file = stdout;
  863. if (!sharelog_file)
  864. applog(LOG_ERR, "Standard output missing for share log");
  865. } else {
  866. sharelog_file = fopen(arg, "a");
  867. if (!sharelog_file)
  868. applog(LOG_ERR, "Failed to open %s for share log", arg);
  869. }
  870. return NULL;
  871. }
  872. static char *temp_cutoff_str = NULL;
  873. static char __maybe_unused *opt_set_temp_cutoff;
  874. char *set_temp_cutoff(char *arg)
  875. {
  876. int val;
  877. if (!(arg && arg[0]))
  878. return "Invalid parameters for set temp cutoff";
  879. val = atoi(arg);
  880. if (val < 0 || val > 200)
  881. return "Invalid value passed to set temp cutoff";
  882. temp_cutoff_str = arg;
  883. return NULL;
  884. }
  885. static void load_temp_cutoffs()
  886. {
  887. int i, val = 0, device = 0;
  888. char *nextptr;
  889. if (temp_cutoff_str) {
  890. for (device = 0, nextptr = strtok(temp_cutoff_str, ","); nextptr; ++device, nextptr = strtok(NULL, ",")) {
  891. if (device >= total_devices)
  892. quit(1, "Too many values passed to set temp cutoff");
  893. val = atoi(nextptr);
  894. if (val < 0 || val > 200)
  895. quit(1, "Invalid value passed to set temp cutoff");
  896. rd_lock(&devices_lock);
  897. devices[device]->cutofftemp = val;
  898. rd_unlock(&devices_lock);
  899. }
  900. } else {
  901. rd_lock(&devices_lock);
  902. for (i = device; i < total_devices; ++i) {
  903. if (!devices[i]->cutofftemp)
  904. devices[i]->cutofftemp = opt_cutofftemp;
  905. }
  906. rd_unlock(&devices_lock);
  907. return;
  908. }
  909. if (device <= 1) {
  910. rd_lock(&devices_lock);
  911. for (i = device; i < total_devices; ++i)
  912. devices[i]->cutofftemp = val;
  913. rd_unlock(&devices_lock);
  914. }
  915. }
  916. static char *set_float_125_to_500(const char *arg, float *i)
  917. {
  918. char *err = opt_set_floatval(arg, i);
  919. if (err)
  920. return err;
  921. if (*i < 125 || *i > 500)
  922. return "Value out of range";
  923. return NULL;
  924. }
  925. static char *set_null(const char __maybe_unused *arg)
  926. {
  927. return NULL;
  928. }
  929. /* These options are available from config file or commandline */
  930. static struct opt_table opt_config_table[] = {
  931. #ifdef USE_ICARUS
  932. OPT_WITH_ARG("--anu-freq",
  933. set_float_125_to_500, &opt_show_intval, &opt_anu_freq,
  934. "Set AntminerU1 frequency in MHz, range 125-500"),
  935. #endif
  936. OPT_WITH_ARG("--api-allow",
  937. opt_set_charp, NULL, &opt_api_allow,
  938. "Allow API access only to the given list of [G:]IP[/Prefix] addresses[/subnets]"),
  939. OPT_WITH_ARG("--api-description",
  940. opt_set_charp, NULL, &opt_api_description,
  941. "Description placed in the API status header, default: cgminer version"),
  942. OPT_WITH_ARG("--api-groups",
  943. opt_set_charp, NULL, &opt_api_groups,
  944. "API one letter groups G:cmd:cmd[,P:cmd:*...] defining the cmds a groups can use"),
  945. OPT_WITHOUT_ARG("--api-listen",
  946. opt_set_bool, &opt_api_listen,
  947. "Enable API, default: disabled"),
  948. OPT_WITHOUT_ARG("--api-mcast",
  949. opt_set_bool, &opt_api_mcast,
  950. "Enable API Multicast listener, default: disabled"),
  951. OPT_WITH_ARG("--api-mcast-addr",
  952. opt_set_charp, NULL, &opt_api_mcast_addr,
  953. "API Multicast listen address"),
  954. OPT_WITH_ARG("--api-mcast-code",
  955. opt_set_charp, NULL, &opt_api_mcast_code,
  956. "Code expected in the API Multicast message, don't use '-'"),
  957. OPT_WITH_ARG("--api-mcast-des",
  958. opt_set_charp, NULL, &opt_api_mcast_des,
  959. "Description appended to the API Multicast reply, default: ''"),
  960. OPT_WITH_ARG("--api-mcast-port",
  961. set_int_1_to_65535, opt_show_intval, &opt_api_mcast_port,
  962. "API Multicast listen port"),
  963. OPT_WITHOUT_ARG("--api-network",
  964. opt_set_bool, &opt_api_network,
  965. "Allow API (if enabled) to listen on/for any address, default: only 127.0.0.1"),
  966. OPT_WITH_ARG("--api-port",
  967. set_int_1_to_65535, opt_show_intval, &opt_api_port,
  968. "Port number of miner API"),
  969. #ifdef USE_AVALON
  970. OPT_WITHOUT_ARG("--avalon-auto",
  971. opt_set_bool, &opt_avalon_auto,
  972. "Adjust avalon overclock frequency dynamically for best hashrate"),
  973. OPT_WITH_ARG("--avalon-cutoff",
  974. set_int_0_to_100, opt_show_intval, &opt_avalon_overheat,
  975. "Set avalon overheat cut off temperature"),
  976. OPT_WITH_CBARG("--avalon-fan",
  977. set_avalon_fan, NULL, &opt_set_avalon_fan,
  978. "Set fanspeed percentage for avalon, single value or range (default: 20-100)"),
  979. OPT_WITH_CBARG("--avalon-freq",
  980. set_avalon_freq, NULL, &opt_set_avalon_freq,
  981. "Set frequency range for avalon-auto, single value or range"),
  982. OPT_WITH_ARG("--avalon-options",
  983. opt_set_charp, NULL, &opt_avalon_options,
  984. "Set avalon options baud:miners:asic:timeout:freq:tech"),
  985. OPT_WITH_ARG("--avalon-temp",
  986. set_int_0_to_100, opt_show_intval, &opt_avalon_temp,
  987. "Set avalon target temperature"),
  988. #endif
  989. #ifdef USE_AVALON2
  990. OPT_WITH_CBARG("--avalon2-freq",
  991. set_avalon2_freq, NULL, &opt_set_avalon2_freq,
  992. "Set frequency range for Avalon2, single value or range"),
  993. OPT_WITH_CBARG("--avalon2-fan",
  994. set_avalon2_fan, NULL, &opt_set_avalon2_fan,
  995. "Set Avalon2 target fan speed"),
  996. OPT_WITH_CBARG("--avalon2-voltage",
  997. set_avalon2_voltage, NULL, &opt_set_avalon2_voltage,
  998. "Set Avalon2 core voltage, in millivolts"),
  999. OPT_WITH_ARG("--avalon2-cutoff",
  1000. set_int_0_to_100, opt_show_intval, &opt_avalon2_overheat,
  1001. "Set Avalon2 overheat cut off temperature"),
  1002. #endif
  1003. #ifdef USE_BAB
  1004. OPT_WITH_ARG("--bab-options",
  1005. opt_set_charp, NULL, &opt_bab_options,
  1006. "Set bab options max:def:min:up:down:hz:delay:trf"),
  1007. #endif
  1008. OPT_WITHOUT_ARG("--balance",
  1009. set_balance, &pool_strategy,
  1010. "Change multipool strategy from failover to even share balance"),
  1011. OPT_WITH_ARG("--benchfile",
  1012. opt_set_charp, NULL, &opt_benchfile,
  1013. "Run cgminer in benchmark mode using a work file - produces no shares"),
  1014. OPT_WITHOUT_ARG("--benchfile-display",
  1015. opt_set_bool, &opt_benchfile_display,
  1016. "Display each benchfile nonce found"),
  1017. OPT_WITHOUT_ARG("--benchmark",
  1018. opt_set_bool, &opt_benchmark,
  1019. "Run cgminer in benchmark mode - produces no shares"),
  1020. #if defined(USE_BITFORCE)
  1021. OPT_WITHOUT_ARG("--bfl-range",
  1022. opt_set_bool, &opt_bfl_noncerange,
  1023. "Use nonce range on bitforce devices if supported"),
  1024. #endif
  1025. #ifdef USE_BFLSC
  1026. OPT_WITH_ARG("--bflsc-overheat",
  1027. set_int_0_to_200, opt_show_intval, &opt_bflsc_overheat,
  1028. "Set overheat temperature where BFLSC devices throttle, 0 to disable"),
  1029. #endif
  1030. #ifdef USE_AVALON
  1031. OPT_WITH_ARG("--bitburner-voltage",
  1032. opt_set_intval, NULL, &opt_bitburner_core_voltage,
  1033. "Set BitBurner (Avalon) core voltage, in millivolts"),
  1034. OPT_WITH_ARG("--bitburner-fury-voltage",
  1035. opt_set_intval, NULL, &opt_bitburner_fury_core_voltage,
  1036. "Set BitBurner Fury core voltage, in millivolts"),
  1037. OPT_WITH_ARG("--bitburner-fury-options",
  1038. opt_set_charp, NULL, &opt_bitburner_fury_options,
  1039. "Override avalon-options for BitBurner Fury boards baud:miners:asic:timeout:freq"),
  1040. #endif
  1041. #if defined(USE_ANT_S1) || defined(USE_ANT_S2)
  1042. OPT_WITHOUT_ARG("--bitmain-auto",
  1043. opt_set_bool, &opt_bitmain_auto,
  1044. "Adjust bitmain overclock frequency dynamically for best hashrate"),
  1045. OPT_WITH_ARG("--bitmain-cutoff",
  1046. set_int_0_to_100, opt_show_intval, &opt_bitmain_overheat,
  1047. "Set bitmain overheat cut off temperature"),
  1048. OPT_WITH_CBARG("--bitmain-fan",
  1049. set_bitmain_fan, NULL, &opt_set_bitmain_fan,
  1050. "Set fanspeed percentage for bitmain, single value or range (default: 20-100)"),
  1051. OPT_WITH_CBARG("--bitmain-freq",
  1052. set_bitmain_freq, NULL, &opt_set_bitmain_freq,
  1053. "Set frequency range for bitmain-auto, single value or range"),
  1054. OPT_WITHOUT_ARG("--bitmain-hwerror",
  1055. opt_set_bool, &opt_bitmain_hwerror,
  1056. "Set bitmain device detect hardware error"),
  1057. OPT_WITH_ARG("--bitmain-options",
  1058. opt_set_charp, NULL, &opt_bitmain_options,
  1059. "Set bitmain options baud:miners:asic:timeout:freq"),
  1060. OPT_WITH_ARG("--bitmain-temp",
  1061. set_int_0_to_100, opt_show_intval, &opt_bitmain_temp,
  1062. "Set bitmain target temperature"),
  1063. #endif
  1064. #ifdef USE_ANT_S2
  1065. OPT_WITH_ARG("--bitmain-dev",
  1066. opt_set_charp, NULL, &opt_bitmain_dev,
  1067. "Set bitmain device"),
  1068. OPT_WITHOUT_ARG("--bitmainbeeper",
  1069. opt_set_bool, &opt_bitmain_beeper,
  1070. "Set bitmain beeper ringing"),
  1071. OPT_WITHOUT_ARG("--bitmain-checkall",
  1072. opt_set_bool, &opt_bitmain_checkall,
  1073. opt_hidden),
  1074. OPT_WITHOUT_ARG("--bitmain-checkn2diff",
  1075. opt_set_bool, &opt_bitmain_checkn2diff,
  1076. opt_hidden),
  1077. OPT_WITHOUT_ARG("--bitmaintempoverctrl",
  1078. opt_set_bool, &opt_bitmain_tempoverctrl,
  1079. "Set bitmain stop runing when temprerature is over 80 degree Celsius"),
  1080. #endif
  1081. #ifdef USE_BITMINE_A1
  1082. OPT_WITH_ARG("--bitmine-a1-options",
  1083. opt_set_charp, NULL, &opt_bitmine_a1_options,
  1084. "Bitmine A1 options ref_clk_khz:sys_clk_khz:spi_clk_khz:override_chip_num"),
  1085. #endif
  1086. #ifdef USE_BITFURY
  1087. OPT_WITH_ARG("--bxf-bits",
  1088. set_int_32_to_63, opt_show_intval, &opt_bxf_bits,
  1089. "Set max BXF/HXF bits for overclocking"),
  1090. OPT_WITH_ARG("--bxf-debug",
  1091. set_int_0_to_4, opt_show_intval, &opt_bxf_debug,
  1092. "BXF: Debug all USB I/O, > is to the board(s), < is from the board(s)"),
  1093. OPT_WITH_ARG("--bxf-temp-target",
  1094. set_int_0_to_200, opt_show_intval, &opt_bxf_temp_target,
  1095. "Set target temperature for BXF/HXF devices"),
  1096. OPT_WITH_ARG("--bxm-bits",
  1097. set_int_0_to_100, opt_show_intval, &opt_bxm_bits,
  1098. "Set BXM bits for overclocking"),
  1099. #endif
  1100. #ifdef HAVE_LIBCURL
  1101. OPT_WITH_ARG("--btc-address",
  1102. opt_set_charp, NULL, &opt_btc_address,
  1103. "Set bitcoin target address when solo mining to bitcoind (optional)"),
  1104. OPT_WITH_ARG("--btc-sig",
  1105. opt_set_charp, NULL, &opt_btc_sig,
  1106. "Set signature to add to coinbase when solo mining (optional)"),
  1107. #endif
  1108. #ifdef HAVE_CURSES
  1109. OPT_WITHOUT_ARG("--compact",
  1110. opt_set_bool, &opt_compact,
  1111. "Use compact display without per device statistics"),
  1112. #endif
  1113. #ifdef USE_COINTERRA
  1114. OPT_WITH_ARG("--cta-load",
  1115. set_int_0_to_255, opt_show_intval, &opt_cta_load,
  1116. "Set load for CTA devices, 0-255 range"),
  1117. OPT_WITH_ARG("--ps-load",
  1118. set_int_0_to_100, opt_show_intval, &opt_ps_load,
  1119. "Set power supply load for CTA devices, 0-100 range"),
  1120. #endif
  1121. OPT_WITHOUT_ARG("--debug|-D",
  1122. enable_debug, &opt_debug,
  1123. "Enable debug output"),
  1124. OPT_WITHOUT_ARG("--disable-rejecting",
  1125. opt_set_bool, &opt_disable_pool,
  1126. "Automatically disable pools that continually reject shares"),
  1127. #ifdef USE_DRILLBIT
  1128. OPT_WITH_ARG("--drillbit-options",
  1129. opt_set_charp, NULL, &opt_drillbit_options,
  1130. "Set drillbit options <int|ext>:clock[:clock_divider][:voltage]"),
  1131. OPT_WITH_ARG("--drillbit-auto",
  1132. opt_set_charp, NULL, &opt_drillbit_auto,
  1133. "Enable drillbit automatic tuning <every>:[<gooderr>:<baderr>:<maxerr>]"),
  1134. #endif
  1135. OPT_WITH_ARG("--expiry|-E",
  1136. set_int_0_to_9999, opt_show_intval, &opt_expiry,
  1137. "Upper bound on how many seconds after getting work we consider a share from it stale"),
  1138. OPT_WITHOUT_ARG("--failover-only",
  1139. opt_set_bool, &opt_fail_only,
  1140. "Don't leak work to backup pools when primary pool is lagging"),
  1141. OPT_WITH_ARG("--failover-switch-delay",
  1142. set_int_1_to_65535, opt_show_intval, &opt_fail_switch_delay,
  1143. "Seconds that a failed pool must be alive again before switching back"),
  1144. OPT_WITHOUT_ARG("--fix-protocol",
  1145. opt_set_bool, &opt_fix_protocol,
  1146. "Do not redirect to a different getwork protocol (eg. stratum)"),
  1147. #ifdef USE_GRIDSEED
  1148. OPT_WITH_ARG("--gridseed-options",
  1149. opt_set_charp, NULL, &opt_gridseed_options,
  1150. "Set gridseed options: freq=N[,voltage=1][,led_off=1]"),
  1151. OPT_WITH_ARG("--gridseed-freq",
  1152. opt_set_charp, NULL, &opt_gridseed_freq,
  1153. "Set gridseed frequency per-device: serial=freq[,...]"),
  1154. OPT_WITH_ARG("--gridseed-override",
  1155. opt_set_charp, NULL, &opt_gridseed_override,
  1156. "Set any gridseed option per-device: serial:opt1=val1[,...][;serial=...]"),
  1157. #endif
  1158. #ifdef USE_HASHFAST
  1159. OPT_WITHOUT_ARG("--hfa-dfu-boot",
  1160. opt_set_bool, &opt_hfa_dfu_boot,
  1161. opt_hidden),
  1162. OPT_WITH_ARG("--hfa-hash-clock",
  1163. set_int_0_to_9999, opt_show_intval, &opt_hfa_hash_clock,
  1164. "Set hashfast clock speed"),
  1165. OPT_WITH_ARG("--hfa-fail-drop",
  1166. set_int_0_to_100, opt_show_intval, &opt_hfa_fail_drop,
  1167. "Set how many MHz to drop clockspeed each failure on an overlocked hashfast device"),
  1168. OPT_WITH_CBARG("--hfa-fan",
  1169. set_hfa_fan, NULL, &opt_set_hfa_fan,
  1170. "Set fanspeed percentage for hashfast, single value or range (default: 10-85)"),
  1171. OPT_WITH_ARG("--hfa-name",
  1172. opt_set_charp, NULL, &opt_hfa_name,
  1173. "Set a unique name for a single hashfast device specified with --usb or the first device found"),
  1174. OPT_WITHOUT_ARG("--hfa-noshed",
  1175. opt_set_bool, &opt_hfa_noshed,
  1176. "Disable hashfast dynamic core disabling feature"),
  1177. OPT_WITH_ARG("--hfa-ntime-roll",
  1178. opt_set_intval, NULL, &opt_hfa_ntime_roll,
  1179. opt_hidden),
  1180. OPT_WITH_ARG("--hfa-options",
  1181. opt_set_charp, NULL, &opt_hfa_options,
  1182. "Set hashfast options name:clock (comma separated)"),
  1183. OPT_WITHOUT_ARG("--hfa-pll-bypass",
  1184. opt_set_bool, &opt_hfa_pll_bypass,
  1185. opt_hidden),
  1186. OPT_WITH_ARG("--hfa-temp-overheat",
  1187. set_int_0_to_200, opt_show_intval, &opt_hfa_overheat,
  1188. "Set the hashfast overheat throttling temperature"),
  1189. OPT_WITH_ARG("--hfa-temp-target",
  1190. set_int_0_to_200, opt_show_intval, &opt_hfa_target,
  1191. "Set the hashfast target temperature (0 to disable)"),
  1192. #endif
  1193. OPT_WITH_ARG("--hotplug",
  1194. set_int_0_to_9999, NULL, &hotplug_time,
  1195. #ifdef USE_USBUTILS
  1196. "Seconds between hotplug checks (0 means never check)"
  1197. #else
  1198. opt_hidden
  1199. #endif
  1200. ),
  1201. #ifdef USE_ICARUS
  1202. OPT_WITH_ARG("--icarus-options",
  1203. opt_set_charp, NULL, &opt_icarus_options,
  1204. opt_hidden),
  1205. OPT_WITH_ARG("--icarus-timing",
  1206. opt_set_charp, NULL, &opt_icarus_timing,
  1207. opt_hidden),
  1208. #endif
  1209. #if defined(HAVE_MODMINER)
  1210. OPT_WITH_ARG("--kernel-path|-K",
  1211. opt_set_charp, opt_show_charp, &opt_kernel_path,
  1212. "Specify a path to where bitstream files are"),
  1213. #endif
  1214. #ifdef USE_KLONDIKE
  1215. OPT_WITH_ARG("--klondike-options",
  1216. opt_set_charp, NULL, &opt_klondike_options,
  1217. "Set klondike options clock:temptarget"),
  1218. #endif
  1219. OPT_WITHOUT_ARG("--load-balance",
  1220. set_loadbalance, &pool_strategy,
  1221. "Change multipool strategy from failover to quota based balance"),
  1222. OPT_WITH_ARG("--log|-l",
  1223. set_int_0_to_9999, opt_show_intval, &opt_log_interval,
  1224. "Interval in seconds between log output"),
  1225. OPT_WITHOUT_ARG("--lowmem",
  1226. opt_set_bool, &opt_lowmem,
  1227. "Minimise caching of shares for low memory applications"),
  1228. #ifdef USE_MINION
  1229. OPT_WITH_ARG("--minion-chipreport",
  1230. set_int_0_to_100, opt_show_intval, &opt_minion_chipreport,
  1231. "Seconds to report chip 5min hashrate, range 0-100 (default: 0=disabled)"),
  1232. OPT_WITH_ARG("--minion-freq",
  1233. opt_set_charp, NULL, &opt_minion_freq,
  1234. "Set minion chip frequencies in MHz, single value or comma list, range 100-1400 (default: 1000)"),
  1235. OPT_WITH_ARG("--minion-cores",
  1236. opt_set_charp, NULL, &opt_minion_cores,
  1237. opt_hidden),
  1238. OPT_WITHOUT_ARG("--minion-idlecount",
  1239. opt_set_bool, &opt_minion_idlecount,
  1240. "Report when IdleCount is >0 or changes"),
  1241. OPT_WITHOUT_ARG("--minion-overheat",
  1242. opt_set_bool, &opt_minion_overheat,
  1243. "Enable directly halting any chip when the status exceeds 100C"),
  1244. OPT_WITH_ARG("--minion-temp",
  1245. opt_set_charp, NULL, &opt_minion_temp,
  1246. "Set minion chip temperature threshold, single value or comma list, range 120-160 (default: 135C)"),
  1247. #endif
  1248. #if defined(unix) || defined(__APPLE__)
  1249. OPT_WITH_ARG("--monitor|-m",
  1250. opt_set_charp, NULL, &opt_stderr_cmd,
  1251. "Use custom pipe cmd for output messages"),
  1252. #endif // defined(unix)
  1253. #ifdef USE_BITFURY
  1254. OPT_WITH_ARG("--nfu-bits",
  1255. set_int_32_to_63, opt_show_intval, &opt_nfu_bits,
  1256. "Set nanofury bits for overclocking, range 32-63"),
  1257. #endif
  1258. OPT_WITHOUT_ARG("--net-delay",
  1259. opt_set_bool, &opt_delaynet,
  1260. "Impose small delays in networking to not overload slow routers"),
  1261. OPT_WITHOUT_ARG("--no-pool-disable",
  1262. opt_set_invbool, &opt_disable_pool,
  1263. opt_hidden),
  1264. OPT_WITHOUT_ARG("--no-submit-stale",
  1265. opt_set_invbool, &opt_submit_stale,
  1266. "Don't submit shares if they are detected as stale"),
  1267. #ifdef USE_BITFURY
  1268. OPT_WITH_ARG("--osm-led-mode",
  1269. set_int_0_to_4, opt_show_intval, &opt_osm_led_mode,
  1270. "Set LED mode for OneStringMiner devices"),
  1271. #endif
  1272. OPT_WITH_ARG("--pass|-p",
  1273. set_pass, NULL, &opt_set_null,
  1274. "Password for bitcoin JSON-RPC server"),
  1275. OPT_WITHOUT_ARG("--per-device-stats",
  1276. opt_set_bool, &want_per_device_stats,
  1277. "Force verbose mode and output per-device statistics"),
  1278. OPT_WITH_ARG("--pools",
  1279. opt_set_bool, NULL, &opt_set_null, opt_hidden),
  1280. OPT_WITHOUT_ARG("--protocol-dump|-P",
  1281. opt_set_bool, &opt_protocol,
  1282. "Verbose dump of protocol-level activities"),
  1283. OPT_WITH_ARG("--queue|-Q",
  1284. set_int_0_to_9999, opt_show_intval, &opt_queue,
  1285. "Maximum number of work items to have queued"),
  1286. OPT_WITHOUT_ARG("--quiet|-q",
  1287. opt_set_bool, &opt_quiet,
  1288. "Disable logging output, display status and errors"),
  1289. OPT_WITH_ARG("--quota|-U",
  1290. set_quota, NULL, &opt_set_null,
  1291. "quota;URL combination for server with load-balance strategy quotas"),
  1292. OPT_WITHOUT_ARG("--real-quiet",
  1293. opt_set_bool, &opt_realquiet,
  1294. "Disable all output"),
  1295. OPT_WITH_ARG("--retries",
  1296. set_null, NULL, &opt_set_null,
  1297. opt_hidden),
  1298. OPT_WITH_ARG("--retry-pause",
  1299. set_null, NULL, &opt_set_null,
  1300. opt_hidden),
  1301. OPT_WITH_ARG("--rotate",
  1302. set_rotate, NULL, &opt_set_null,
  1303. "Change multipool strategy from failover to regularly rotate at N minutes"),
  1304. OPT_WITHOUT_ARG("--round-robin",
  1305. set_rr, &pool_strategy,
  1306. "Change multipool strategy from failover to round robin on failure"),
  1307. #ifdef USE_FPGA_SERIAL
  1308. OPT_WITH_CBARG("--scan-serial|-S",
  1309. add_serial, NULL, &opt_add_serial,
  1310. "Serial port to probe for Serial FPGA Mining device"),
  1311. #endif
  1312. OPT_WITH_ARG("--scan-time|-s",
  1313. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  1314. "Upper bound on time spent scanning current work, in seconds"),
  1315. OPT_WITH_CBARG("--sched-start",
  1316. set_sched_start, NULL, &opt_set_sched_start,
  1317. "Set a time of day in HH:MM to start mining (a once off without a stop time)"),
  1318. OPT_WITH_CBARG("--sched-stop",
  1319. set_sched_stop, NULL, &opt_set_sched_stop,
  1320. "Set a time of day in HH:MM to stop mining (will quit without a start time)"),
  1321. OPT_WITHOUT_ARG("--sha256",
  1322. opt_set_bool, &opt_sha256,
  1323. "Use the SHA-256 algorithm for mining"),
  1324. #ifdef USE_SCRYPT
  1325. OPT_WITHOUT_ARG("--scrypt",
  1326. opt_set_bool, &opt_scrypt,
  1327. "Use the scrypt algorithm for mining"),
  1328. #endif
  1329. OPT_WITH_CBARG("--sharelog",
  1330. set_sharelog, NULL, &opt_set_sharelog,
  1331. "Append share log to file"),
  1332. OPT_WITH_ARG("--shares",
  1333. opt_set_intval, NULL, &opt_shares,
  1334. "Quit after mining N shares (default: unlimited)"),
  1335. OPT_WITH_ARG("--socks-proxy",
  1336. opt_set_charp, NULL, &opt_socks_proxy,
  1337. "Set socks4 proxy (host:port)"),
  1338. #ifdef HAVE_SYSLOG_H
  1339. OPT_WITHOUT_ARG("--syslog",
  1340. opt_set_bool, &use_syslog,
  1341. "Use system log for output messages (default: standard error)"),
  1342. #endif
  1343. #if defined(USE_BITFORCE) || defined(USE_MODMINER) || defined(USE_BFLSC)
  1344. OPT_WITH_CBARG("--temp-cutoff",
  1345. set_temp_cutoff, opt_show_intval, &opt_set_temp_cutoff,
  1346. "Temperature where a device will be automatically disabled, one value or comma separated list"),
  1347. #endif
  1348. OPT_WITHOUT_ARG("--text-only|-T",
  1349. opt_set_invbool, &use_curses,
  1350. #ifdef HAVE_CURSES
  1351. "Disable ncurses formatted screen output"
  1352. #else
  1353. opt_hidden
  1354. #endif
  1355. ),
  1356. OPT_WITH_ARG("--url|-o",
  1357. set_url, NULL, &opt_set_null,
  1358. "URL for bitcoin JSON-RPC server"),
  1359. #ifdef USE_USBUTILS
  1360. OPT_WITH_ARG("--usb",
  1361. opt_set_charp, NULL, &opt_usb_select,
  1362. "USB device selection"),
  1363. OPT_WITH_ARG("--usb-dump",
  1364. set_int_0_to_10, opt_show_intval, &opt_usbdump,
  1365. opt_hidden),
  1366. OPT_WITHOUT_ARG("--usb-list-all",
  1367. opt_set_bool, &opt_usb_list_all,
  1368. opt_hidden),
  1369. #endif
  1370. OPT_WITH_ARG("--user|-u",
  1371. set_user, NULL, &opt_set_null,
  1372. "Username for bitcoin JSON-RPC server"),
  1373. OPT_WITH_ARG("--userpass|-O",
  1374. set_userpass, NULL, &opt_set_null,
  1375. "Username:Password pair for bitcoin JSON-RPC server"),
  1376. OPT_WITHOUT_ARG("--verbose",
  1377. opt_set_bool, &opt_log_output,
  1378. "Log verbose output to stderr as well as status output"),
  1379. OPT_WITHOUT_ARG("--widescreen",
  1380. opt_set_bool, &opt_widescreen,
  1381. "Use extra wide display without toggling"),
  1382. OPT_WITHOUT_ARG("--worktime",
  1383. opt_set_bool, &opt_worktime,
  1384. "Display extra work time debug information"),
  1385. #ifdef USE_ZEUS
  1386. OPT_WITH_ARG("--zeus-chips",
  1387. set_int_1_to_1024, NULL, &opt_zeus_chips_count,
  1388. "Number of Zeus chips per device"),
  1389. OPT_WITH_ARG("--zeus-clock",
  1390. opt_set_intval, NULL, &opt_zeus_chip_clk,
  1391. "Zeus chip clock speed (MHz)"),
  1392. OPT_WITHOUT_ARG("--zeus-debug",
  1393. opt_set_bool, &opt_zeus_debug,
  1394. "Enable extra Zeus driver debugging output in verbose mode"),
  1395. OPT_WITHOUT_ARG("--zeus-nocheck-golden",
  1396. opt_set_bool, &opt_zeus_nocheck_golden,
  1397. "Skip golden nonce verification during initialization"),
  1398. OPT_WITH_ARG("--zeus-options",
  1399. opt_set_charp, NULL, &opt_zeus_options,
  1400. "Set individual Zeus device options: ID,chips,clock[;ID,chips,clock...]"),
  1401. #endif
  1402. #ifdef USE_LKETC
  1403. OPT_WITH_ARG("--lketc-chips",
  1404. set_int_1_to_1024, NULL, &opt_lketc_chips_count,
  1405. "Number of LKETC chips per device"),
  1406. OPT_WITH_ARG("--lketc-clock",
  1407. opt_set_intval, NULL, &opt_lketc_chip_clk,
  1408. "LKETC chip clock speed (MHz)"),
  1409. OPT_WITHOUT_ARG("--lketc-debug",
  1410. opt_set_bool, &opt_lketc_debug,
  1411. "Enable extra LKETC driver debugging output in verbose mode"),
  1412. OPT_WITHOUT_ARG("--lketc-nocheck-golden",
  1413. opt_set_bool, &opt_lketc_nocheck_golden,
  1414. "Skip golden nonce verification during initialization"),
  1415. OPT_WITH_ARG("--lketc-options",
  1416. opt_set_charp, NULL, &opt_lketc_options,
  1417. "Set individual LKETC device options: ID,chips,clock[;ID,chips,clock...]"),
  1418. #endif
  1419. OPT_ENDTABLE
  1420. };
  1421. static char *load_config(const char *arg, void __maybe_unused *unused);
  1422. static int fileconf_load;
  1423. static char *parse_config(json_t *config, bool fileconf)
  1424. {
  1425. static char err_buf[200];
  1426. struct opt_table *opt;
  1427. json_t *val;
  1428. if (fileconf && !fileconf_load)
  1429. fileconf_load = 1;
  1430. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  1431. char *p, *name;
  1432. /* We don't handle subtables. */
  1433. assert(!(opt->type & OPT_SUBTABLE));
  1434. if (!opt->names)
  1435. continue;
  1436. /* Pull apart the option name(s). */
  1437. name = strdup(opt->names);
  1438. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  1439. char *err = NULL;
  1440. /* Ignore short options. */
  1441. if (p[1] != '-')
  1442. continue;
  1443. val = json_object_get(config, p+2);
  1444. if (!val)
  1445. continue;
  1446. if ((opt->type & (OPT_HASARG | OPT_PROCESSARG)) && json_is_string(val)) {
  1447. err = opt->cb_arg(json_string_value(val),
  1448. opt->u.arg);
  1449. } else if ((opt->type & (OPT_HASARG | OPT_PROCESSARG)) && json_is_array(val)) {
  1450. int n, size = json_array_size(val);
  1451. for (n = 0; n < size && !err; n++) {
  1452. if (json_is_string(json_array_get(val, n)))
  1453. err = opt->cb_arg(json_string_value(json_array_get(val, n)), opt->u.arg);
  1454. else if (json_is_object(json_array_get(val, n)))
  1455. err = parse_config(json_array_get(val, n), false);
  1456. }
  1457. } else if ((opt->type & OPT_NOARG) && json_is_true(val))
  1458. err = opt->cb(opt->u.arg);
  1459. else
  1460. err = "Invalid value";
  1461. if (err) {
  1462. /* Allow invalid values to be in configuration
  1463. * file, just skipping over them provided the
  1464. * JSON is still valid after that. */
  1465. if (fileconf) {
  1466. applog(LOG_ERR, "Invalid config option %s: %s", p, err);
  1467. fileconf_load = -1;
  1468. } else {
  1469. snprintf(err_buf, sizeof(err_buf), "Parsing JSON option %s: %s",
  1470. p, err);
  1471. return err_buf;
  1472. }
  1473. }
  1474. }
  1475. free(name);
  1476. }
  1477. val = json_object_get(config, JSON_INCLUDE_CONF);
  1478. if (val && json_is_string(val))
  1479. return load_config(json_string_value(val), NULL);
  1480. return NULL;
  1481. }
  1482. char *cnfbuf = NULL;
  1483. #ifdef HAVE_LIBCURL
  1484. char conf_web1[] = "http://";
  1485. char conf_web2[] = "https://";
  1486. static char *load_web_config(const char *arg)
  1487. {
  1488. json_t *val = json_web_config(arg);
  1489. if (!val || !json_is_object(val))
  1490. return JSON_WEB_ERROR;
  1491. if (!cnfbuf)
  1492. cnfbuf = strdup(arg);
  1493. config_loaded = true;
  1494. return parse_config(val, true);
  1495. }
  1496. #endif
  1497. static char *load_config(const char *arg, void __maybe_unused *unused)
  1498. {
  1499. json_error_t err;
  1500. json_t *config;
  1501. char *json_error;
  1502. size_t siz;
  1503. #ifdef HAVE_LIBCURL
  1504. if (strncasecmp(arg, conf_web1, sizeof(conf_web1)-1) == 0 ||
  1505. strncasecmp(arg, conf_web2, sizeof(conf_web2)-1) == 0)
  1506. return load_web_config(arg);
  1507. #endif
  1508. if (!cnfbuf)
  1509. cnfbuf = strdup(arg);
  1510. if (++include_count > JSON_MAX_DEPTH)
  1511. return JSON_MAX_DEPTH_ERR;
  1512. #if JANSSON_MAJOR_VERSION > 1
  1513. config = json_load_file(arg, 0, &err);
  1514. #else
  1515. config = json_load_file(arg, &err);
  1516. #endif
  1517. if (!json_is_object(config)) {
  1518. siz = JSON_LOAD_ERROR_LEN + strlen(arg) + strlen(err.text);
  1519. json_error = malloc(siz);
  1520. if (!json_error)
  1521. quit(1, "Malloc failure in json error");
  1522. snprintf(json_error, siz, JSON_LOAD_ERROR, arg, err.text);
  1523. return json_error;
  1524. }
  1525. config_loaded = true;
  1526. /* Parse the config now, so we can override it. That can keep pointers
  1527. * so don't free config object. */
  1528. return parse_config(config, true);
  1529. }
  1530. static char *set_default_config(const char *arg)
  1531. {
  1532. opt_set_charp(arg, &default_config);
  1533. return NULL;
  1534. }
  1535. void default_save_file(char *filename);
  1536. static void load_default_config(void)
  1537. {
  1538. cnfbuf = malloc(PATH_MAX);
  1539. default_save_file(cnfbuf);
  1540. if (!access(cnfbuf, R_OK))
  1541. load_config(cnfbuf, NULL);
  1542. else {
  1543. free(cnfbuf);
  1544. cnfbuf = NULL;
  1545. }
  1546. }
  1547. extern const char *opt_argv0;
  1548. static char *opt_verusage_and_exit(const char *extra)
  1549. {
  1550. printf("%s\nBuilt with "
  1551. #ifdef USE_ANT_S1
  1552. "ant.S1 "
  1553. #endif
  1554. #ifdef USE_ANT_S2
  1555. "ant.S2 "
  1556. #endif
  1557. #ifdef USE_AVALON
  1558. "avalon "
  1559. #endif
  1560. #ifdef USE_AVALON2
  1561. "avalon2 "
  1562. #endif
  1563. #ifdef USE_BFLSC
  1564. "bflsc "
  1565. #endif
  1566. #ifdef USE_BITFORCE
  1567. "bitforce "
  1568. #endif
  1569. #ifdef USE_BITFURY
  1570. "bitfury "
  1571. #endif
  1572. #ifdef USE_COINTERRA
  1573. "cointerra "
  1574. #endif
  1575. #ifdef USE_DRILLBIT
  1576. "drillbit "
  1577. #endif
  1578. #ifdef USE_HASHFAST
  1579. "hashfast "
  1580. #endif
  1581. #ifdef USE_ICARUS
  1582. "icarus "
  1583. #endif
  1584. #ifdef USE_KLONDIKE
  1585. "klondike "
  1586. #endif
  1587. #ifdef USE_KNC
  1588. "KnC "
  1589. #endif
  1590. #ifdef USE_BAB
  1591. "BaB "
  1592. #endif
  1593. #ifdef USE_MINION
  1594. "minion "
  1595. #endif
  1596. #ifdef USE_MODMINER
  1597. "modminer "
  1598. #endif
  1599. #ifdef USE_BITMINE_A1
  1600. "Bitmine.A1 "
  1601. #endif
  1602. #ifdef USE_SPONDOOLIES
  1603. "spondoolies "
  1604. #endif
  1605. #ifdef USE_GRIDSEED
  1606. "GridSeed "
  1607. #endif
  1608. #ifdef USE_ZEUS
  1609. "Zeus "
  1610. #endif
  1611. #ifdef USE_LKETC
  1612. "Lketc "
  1613. #endif
  1614. #ifdef USE_SCRYPT
  1615. "scrypt "
  1616. #endif
  1617. "mining support.\n"
  1618. , packagename);
  1619. printf("%s", opt_usage(opt_argv0, extra));
  1620. fflush(stdout);
  1621. exit(0);
  1622. }
  1623. #if defined(USE_USBUTILS)
  1624. char *display_devs(int *ndevs)
  1625. {
  1626. *ndevs = 0;
  1627. usb_all(0);
  1628. exit(*ndevs);
  1629. }
  1630. #endif
  1631. /* These options are available from commandline only */
  1632. static struct opt_table opt_cmdline_table[] = {
  1633. OPT_WITH_ARG("--config|-c",
  1634. load_config, NULL, &opt_set_null,
  1635. "Load a JSON-format configuration file\n"
  1636. "See example.conf for an example configuration."),
  1637. OPT_WITH_ARG("--default-config",
  1638. set_default_config, NULL, &opt_set_null,
  1639. "Specify the filename of the default config file\n"
  1640. "Loaded at start and used when saving without a name."),
  1641. OPT_WITHOUT_ARG("--help|-h",
  1642. opt_verusage_and_exit, NULL,
  1643. "Print this message"),
  1644. #if defined(USE_USBUTILS)
  1645. OPT_WITHOUT_ARG("--ndevs|-n",
  1646. display_devs, &nDevs,
  1647. "Display all USB devices and exit"),
  1648. #endif
  1649. OPT_WITHOUT_ARG("--version|-V",
  1650. opt_version_and_exit, packagename,
  1651. "Display version and exit"),
  1652. OPT_ENDTABLE
  1653. };
  1654. #ifdef HAVE_LIBCURL
  1655. static bool jobj_binary(const json_t *obj, const char *key,
  1656. void *buf, size_t buflen, bool required)
  1657. {
  1658. const char *hexstr;
  1659. json_t *tmp;
  1660. tmp = json_object_get(obj, key);
  1661. if (unlikely(!tmp)) {
  1662. if (unlikely(required))
  1663. applog(LOG_ERR, "JSON key '%s' not found", key);
  1664. return false;
  1665. }
  1666. hexstr = json_string_value(tmp);
  1667. if (unlikely(!hexstr)) {
  1668. applog(LOG_ERR, "JSON key '%s' is not a string", key);
  1669. return false;
  1670. }
  1671. if (!hex2bin(buf, hexstr, buflen))
  1672. return false;
  1673. return true;
  1674. }
  1675. #endif
  1676. static void calc_midstate(struct work *work)
  1677. {
  1678. unsigned char data[64];
  1679. uint32_t *data32 = (uint32_t *)data;
  1680. sha256_ctx ctx;
  1681. flip64(data32, work->data);
  1682. sha256_init(&ctx);
  1683. sha256_update(&ctx, data, 64);
  1684. memcpy(work->midstate, ctx.h, 32);
  1685. endian_flip32(work->midstate, work->midstate);
  1686. }
  1687. /* Returns the current value of total_work and increments it */
  1688. static int total_work_inc(void)
  1689. {
  1690. int ret;
  1691. cg_wlock(&control_lock);
  1692. ret = total_work++;
  1693. cg_wunlock(&control_lock);
  1694. return ret;
  1695. }
  1696. static struct work *make_work(void)
  1697. {
  1698. struct work *work = calloc(1, sizeof(struct work));
  1699. if (unlikely(!work))
  1700. quit(1, "Failed to calloc work in make_work");
  1701. work->id = total_work_inc();
  1702. return work;
  1703. }
  1704. /* This is the central place all work that is about to be retired should be
  1705. * cleaned to remove any dynamically allocated arrays within the struct */
  1706. void clean_work(struct work *work)
  1707. {
  1708. free(work->job_id);
  1709. free(work->ntime);
  1710. free(work->coinbase);
  1711. free(work->nonce1);
  1712. memset(work, 0, sizeof(struct work));
  1713. }
  1714. /* All dynamically allocated work structs should be freed here to not leak any
  1715. * ram from arrays allocated within the work struct */
  1716. void _free_work(struct work *work)
  1717. {
  1718. clean_work(work);
  1719. free(work);
  1720. }
  1721. static void gen_hash(unsigned char *data, unsigned char *hash, int len);
  1722. static void calc_diff(struct work *work, double known);
  1723. char *workpadding = "000000800000000000000000000000000000000000000000000000000000000000000000000000000000000080020000";
  1724. #ifdef HAVE_LIBCURL
  1725. /* Process transactions with GBT by storing the binary value of the first
  1726. * transaction, and the hashes of the remaining transactions since these
  1727. * remain constant with an altered coinbase when generating work. Must be
  1728. * entered under gbt_lock */
  1729. static void gbt_merkle_bins(struct pool *pool, json_t *transaction_arr);
  1730. static void __build_gbt_txns(struct pool *pool, json_t *res_val)
  1731. {
  1732. json_t *txn_array;
  1733. txn_array = json_object_get(res_val, "transactions");
  1734. gbt_merkle_bins(pool, txn_array);
  1735. }
  1736. static void __gbt_merkleroot(struct pool *pool, unsigned char *merkle_root)
  1737. {
  1738. unsigned char merkle_sha[64];
  1739. int i;
  1740. gen_hash(pool->coinbase, merkle_root, pool->coinbase_len);
  1741. memcpy(merkle_sha, merkle_root, 32);
  1742. for (i = 0; i < pool->merkles; i++) {
  1743. memcpy(merkle_sha + 32, pool->merklebin + i * 32, 32);
  1744. gen_hash(merkle_sha, merkle_root, 64);
  1745. memcpy(merkle_sha, merkle_root, 32);
  1746. }
  1747. }
  1748. static bool work_decode(struct pool *pool, struct work *work, json_t *val);
  1749. static void update_gbt(struct pool *pool)
  1750. {
  1751. int rolltime;
  1752. json_t *val;
  1753. CURL *curl;
  1754. curl = curl_easy_init();
  1755. if (unlikely(!curl))
  1756. quit (1, "CURL initialisation failed in update_gbt");
  1757. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass,
  1758. pool->rpc_req, true, false, &rolltime, pool, false);
  1759. if (val) {
  1760. struct work *work = make_work();
  1761. bool rc = work_decode(pool, work, val);
  1762. total_getworks++;
  1763. pool->getwork_requested++;
  1764. if (rc) {
  1765. applog(LOG_DEBUG, "Successfully retrieved and updated GBT from pool %u %s",
  1766. pool->pool_no, pool->rpc_url);
  1767. cgtime(&pool->tv_idle);
  1768. if (pool == current_pool())
  1769. opt_work_update = true;
  1770. } else {
  1771. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher GBT from pool %u %s",
  1772. pool->pool_no, pool->rpc_url);
  1773. }
  1774. json_decref(val);
  1775. free_work(work);
  1776. } else {
  1777. applog(LOG_DEBUG, "FAILED to update GBT from pool %u %s",
  1778. pool->pool_no, pool->rpc_url);
  1779. }
  1780. curl_easy_cleanup(curl);
  1781. }
  1782. static void gen_gbt_work(struct pool *pool, struct work *work)
  1783. {
  1784. unsigned char merkleroot[32];
  1785. struct timeval now;
  1786. uint64_t nonce2le;
  1787. cgtime(&now);
  1788. if (now.tv_sec - pool->tv_lastwork.tv_sec > 60)
  1789. update_gbt(pool);
  1790. cg_wlock(&pool->gbt_lock);
  1791. nonce2le = htole64(pool->nonce2);
  1792. memcpy(pool->coinbase + pool->nonce2_offset, &nonce2le, pool->n2size);
  1793. pool->nonce2++;
  1794. cg_dwlock(&pool->gbt_lock);
  1795. __gbt_merkleroot(pool, merkleroot);
  1796. memcpy(work->data, &pool->gbt_version, 4);
  1797. memcpy(work->data + 4, pool->previousblockhash, 32);
  1798. memcpy(work->data + 4 + 32 + 32, &pool->curtime, 4);
  1799. memcpy(work->data + 4 + 32 + 32 + 4, &pool->gbt_bits, 4);
  1800. memcpy(work->target, pool->gbt_target, 32);
  1801. work->coinbase = bin2hex(pool->coinbase, pool->coinbase_len);
  1802. /* For encoding the block data on submission */
  1803. work->gbt_txns = pool->gbt_txns + 1;
  1804. if (pool->gbt_workid)
  1805. work->job_id = strdup(pool->gbt_workid);
  1806. cg_runlock(&pool->gbt_lock);
  1807. flip32(work->data + 4 + 32, merkleroot);
  1808. memset(work->data + 4 + 32 + 32 + 4 + 4, 0, 4); /* nonce */
  1809. hex2bin(work->data + 4 + 32 + 32 + 4 + 4 + 4, workpadding, 48);
  1810. if (opt_debug) {
  1811. char *header = bin2hex(work->data, 128);
  1812. applog(LOG_DEBUG, "Generated GBT header %s", header);
  1813. applog(LOG_DEBUG, "Work coinbase %s", work->coinbase);
  1814. free(header);
  1815. }
  1816. calc_midstate(work);
  1817. local_work++;
  1818. work->pool = pool;
  1819. work->gbt = true;
  1820. work->longpoll = false;
  1821. work->getwork_mode = GETWORK_MODE_GBT;
  1822. work->work_block = work_block;
  1823. /* Nominally allow a driver to ntime roll 60 seconds */
  1824. work->drv_rolllimit = 60;
  1825. calc_diff(work, 0);
  1826. cgtime(&work->tv_staged);
  1827. }
  1828. static bool gbt_decode(struct pool *pool, json_t *res_val)
  1829. {
  1830. const char *previousblockhash;
  1831. const char *target;
  1832. const char *coinbasetxn;
  1833. const char *longpollid;
  1834. unsigned char hash_swap[32];
  1835. int expires;
  1836. int version;
  1837. int curtime;
  1838. bool submitold;
  1839. const char *bits;
  1840. const char *workid;
  1841. int cbt_len, orig_len;
  1842. uint8_t *extra_len;
  1843. size_t cal_len;
  1844. previousblockhash = json_string_value(json_object_get(res_val, "previousblockhash"));
  1845. target = json_string_value(json_object_get(res_val, "target"));
  1846. coinbasetxn = json_string_value(json_object_get(json_object_get(res_val, "coinbasetxn"), "data"));
  1847. longpollid = json_string_value(json_object_get(res_val, "longpollid"));
  1848. expires = json_integer_value(json_object_get(res_val, "expires"));
  1849. version = json_integer_value(json_object_get(res_val, "version"));
  1850. curtime = json_integer_value(json_object_get(res_val, "curtime"));
  1851. submitold = json_is_true(json_object_get(res_val, "submitold"));
  1852. bits = json_string_value(json_object_get(res_val, "bits"));
  1853. workid = json_string_value(json_object_get(res_val, "workid"));
  1854. if (!previousblockhash || !target || !coinbasetxn || !longpollid ||
  1855. !expires || !version || !curtime || !bits) {
  1856. applog(LOG_ERR, "JSON failed to decode GBT");
  1857. return false;
  1858. }
  1859. applog(LOG_DEBUG, "previousblockhash: %s", previousblockhash);
  1860. applog(LOG_DEBUG, "target: %s", target);
  1861. applog(LOG_DEBUG, "coinbasetxn: %s", coinbasetxn);
  1862. applog(LOG_DEBUG, "longpollid: %s", longpollid);
  1863. applog(LOG_DEBUG, "expires: %d", expires);
  1864. applog(LOG_DEBUG, "version: %d", version);
  1865. applog(LOG_DEBUG, "curtime: %d", curtime);
  1866. applog(LOG_DEBUG, "submitold: %s", submitold ? "true" : "false");
  1867. applog(LOG_DEBUG, "bits: %s", bits);
  1868. if (workid)
  1869. applog(LOG_DEBUG, "workid: %s", workid);
  1870. cg_wlock(&pool->gbt_lock);
  1871. free(pool->coinbasetxn);
  1872. pool->coinbasetxn = strdup(coinbasetxn);
  1873. cbt_len = strlen(pool->coinbasetxn) / 2;
  1874. /* We add 8 bytes of extra data corresponding to nonce2 */
  1875. pool->n2size = 8;
  1876. pool->coinbase_len = cbt_len + pool->n2size;
  1877. cal_len = pool->coinbase_len + 1;
  1878. align_len(&cal_len);
  1879. free(pool->coinbase);
  1880. pool->coinbase = calloc(cal_len, 1);
  1881. if (unlikely(!pool->coinbase))
  1882. quit(1, "Failed to calloc pool coinbase in gbt_decode");
  1883. hex2bin(pool->coinbase, pool->coinbasetxn, 42);
  1884. extra_len = (uint8_t *)(pool->coinbase + 41);
  1885. orig_len = *extra_len;
  1886. hex2bin(pool->coinbase + 42, pool->coinbasetxn + 84, orig_len);
  1887. *extra_len += pool->n2size;
  1888. hex2bin(pool->coinbase + 42 + *extra_len, pool->coinbasetxn + 84 + (orig_len * 2),
  1889. cbt_len - orig_len - 42);
  1890. pool->nonce2_offset = orig_len + 42;
  1891. free(pool->longpollid);
  1892. pool->longpollid = strdup(longpollid);
  1893. free(pool->gbt_workid);
  1894. if (workid)
  1895. pool->gbt_workid = strdup(workid);
  1896. else
  1897. pool->gbt_workid = NULL;
  1898. hex2bin(hash_swap, previousblockhash, 32);
  1899. swap256(pool->previousblockhash, hash_swap);
  1900. hex2bin(hash_swap, target, 32);
  1901. swab256(pool->gbt_target, hash_swap);
  1902. pool->gbt_expires = expires;
  1903. pool->gbt_version = htobe32(version);
  1904. pool->curtime = htobe32(curtime);
  1905. pool->submit_old = submitold;
  1906. hex2bin((unsigned char *)&pool->gbt_bits, bits, 4);
  1907. __build_gbt_txns(pool, res_val);
  1908. cg_wunlock(&pool->gbt_lock);
  1909. return true;
  1910. }
  1911. static bool getwork_decode(json_t *res_val, struct work *work)
  1912. {
  1913. if (unlikely(!jobj_binary(res_val, "data", work->data, sizeof(work->data), true))) {
  1914. applog(LOG_ERR, "JSON inval data");
  1915. return false;
  1916. }
  1917. if (!jobj_binary(res_val, "midstate", work->midstate, sizeof(work->midstate), false)) {
  1918. // Calculate it ourselves
  1919. applog(LOG_DEBUG, "Calculating midstate locally");
  1920. calc_midstate(work);
  1921. }
  1922. if (unlikely(!jobj_binary(res_val, "target", work->target, sizeof(work->target), true))) {
  1923. applog(LOG_ERR, "JSON inval target");
  1924. return false;
  1925. }
  1926. return true;
  1927. }
  1928. /* Returns whether the pool supports local work generation or not. */
  1929. static bool pool_localgen(struct pool *pool)
  1930. {
  1931. return (pool->has_stratum || pool->has_gbt || pool->gbt_solo);
  1932. }
  1933. static void gbt_merkle_bins(struct pool *pool, json_t *transaction_arr)
  1934. {
  1935. unsigned char *hashbin;
  1936. json_t *arr_val;
  1937. int i, j, binleft, binlen;
  1938. free(pool->txn_data);
  1939. pool->txn_data = NULL;
  1940. pool->transactions = 0;
  1941. pool->merkles = 0;
  1942. pool->transactions = json_array_size(transaction_arr);
  1943. binlen = pool->transactions * 32 + 32;
  1944. hashbin = alloca(binlen + 32);
  1945. memset(hashbin, 0, 32);
  1946. binleft = binlen / 32;
  1947. if (pool->transactions) {
  1948. int len = 1, ofs = 0;
  1949. const char *txn;
  1950. for (i = 0; i < pool->transactions; i++) {
  1951. arr_val = json_array_get(transaction_arr, i);
  1952. txn = json_string_value(json_object_get(arr_val, "data"));
  1953. if (!txn) {
  1954. applog(LOG_ERR, "Pool %d json_string_value fail - cannot find transaction data",
  1955. pool->pool_no);
  1956. return;
  1957. }
  1958. len += strlen(txn);
  1959. }
  1960. pool->txn_data = malloc(len + 1);
  1961. if (unlikely(!pool->txn_data))
  1962. quit(1, "Failed to calloc txn_data in gbt_merkle_bins");
  1963. pool->txn_data[len] = '\0';
  1964. for (i = 0; i < pool->transactions; i++) {
  1965. unsigned char binswap[32];
  1966. const char *hash;
  1967. arr_val = json_array_get(transaction_arr, i);
  1968. hash = json_string_value(json_object_get(arr_val, "hash"));
  1969. txn = json_string_value(json_object_get(arr_val, "data"));
  1970. len = strlen(txn);
  1971. memcpy(pool->txn_data + ofs, txn, len);
  1972. ofs += len;
  1973. if (!hash) {
  1974. unsigned char *txn_bin;
  1975. int txn_len;
  1976. txn_len = len / 2;
  1977. txn_bin = malloc(txn_len);
  1978. if (!txn_bin)
  1979. quit(1, "Failed to malloc txn_bin in gbt_merkle_bins");
  1980. hex2bin(txn_bin, txn, txn_len);
  1981. /* This is needed for pooled mining since only
  1982. * transaction data and not hashes are sent */
  1983. gen_hash(txn_bin, hashbin + 32 + 32 * i, txn_len);
  1984. continue;
  1985. }
  1986. if (!hex2bin(binswap, hash, 32)) {
  1987. applog(LOG_ERR, "Failed to hex2bin hash in gbt_merkle_bins");
  1988. return;
  1989. }
  1990. swab256(hashbin + 32 + 32 * i, binswap);
  1991. }
  1992. }
  1993. if (binleft > 1) {
  1994. while (42) {
  1995. if (binleft == 1)
  1996. break;
  1997. memcpy(pool->merklebin + (pool->merkles * 32), hashbin + 32, 32);
  1998. pool->merkles++;
  1999. if (binleft % 2) {
  2000. memcpy(hashbin + binlen, hashbin + binlen - 32, 32);
  2001. binlen += 32;
  2002. binleft++;
  2003. }
  2004. for (i = 32, j = 64; j < binlen; i += 32, j += 64) {
  2005. gen_hash(hashbin + j, hashbin + i, 64);
  2006. }
  2007. binleft /= 2;
  2008. binlen = binleft * 32;
  2009. }
  2010. }
  2011. if (opt_debug) {
  2012. char hashhex[68];
  2013. for (i = 0; i < pool->merkles; i++) {
  2014. __bin2hex(hashhex, pool->merklebin + i * 32, 32);
  2015. applog(LOG_DEBUG, "MH%d %s",i, hashhex);
  2016. }
  2017. }
  2018. applog(LOG_INFO, "Stored %d transactions from pool %d", pool->transactions,
  2019. pool->pool_no);
  2020. }
  2021. static double diff_from_target(void *target);
  2022. static const char scriptsig_header[] = "01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff";
  2023. static unsigned char scriptsig_header_bin[41];
  2024. static bool gbt_solo_decode(struct pool *pool, json_t *res_val)
  2025. {
  2026. json_t *transaction_arr, *coinbase_aux;
  2027. const char *previousblockhash;
  2028. unsigned char hash_swap[32];
  2029. struct timeval now;
  2030. const char *target;
  2031. uint64_t coinbasevalue;
  2032. const char *flags;
  2033. const char *bits;
  2034. char header[228];
  2035. int ofs = 0, len;
  2036. uint64_t *u64;
  2037. uint32_t *u32;
  2038. int version;
  2039. int curtime;
  2040. int height;
  2041. previousblockhash = json_string_value(json_object_get(res_val, "previousblockhash"));
  2042. target = json_string_value(json_object_get(res_val, "target"));
  2043. transaction_arr = json_object_get(res_val, "transactions");
  2044. version = json_integer_value(json_object_get(res_val, "version"));
  2045. curtime = json_integer_value(json_object_get(res_val, "curtime"));
  2046. bits = json_string_value(json_object_get(res_val, "bits"));
  2047. height = json_integer_value(json_object_get(res_val, "height"));
  2048. coinbasevalue = json_integer_value(json_object_get(res_val, "coinbasevalue"));
  2049. coinbase_aux = json_object_get(res_val, "coinbaseaux");
  2050. flags = json_string_value(json_object_get(coinbase_aux, "flags"));
  2051. if (!previousblockhash || !target || !version || !curtime || !bits || !coinbase_aux || !flags) {
  2052. applog(LOG_ERR, "Pool %d JSON failed to decode GBT", pool->pool_no);
  2053. return false;
  2054. }
  2055. applog(LOG_DEBUG, "previousblockhash: %s", previousblockhash);
  2056. applog(LOG_DEBUG, "target: %s", target);
  2057. applog(LOG_DEBUG, "version: %d", version);
  2058. applog(LOG_DEBUG, "curtime: %d", curtime);
  2059. applog(LOG_DEBUG, "bits: %s", bits);
  2060. applog(LOG_DEBUG, "height: %d", height);
  2061. applog(LOG_DEBUG, "flags: %s", flags);
  2062. cg_wlock(&pool->gbt_lock);
  2063. hex2bin(hash_swap, previousblockhash, 32);
  2064. swap256(pool->previousblockhash, hash_swap);
  2065. __bin2hex(pool->prev_hash, pool->previousblockhash, 32);
  2066. hex2bin(hash_swap, target, 32);
  2067. swab256(pool->gbt_target, hash_swap);
  2068. pool->sdiff = diff_from_target(pool->gbt_target);
  2069. pool->gbt_version = htobe32(version);
  2070. pool->curtime = htobe32(curtime);
  2071. snprintf(pool->ntime, 9, "%08x", curtime);
  2072. snprintf(pool->bbversion, 9, "%08x", version);
  2073. snprintf(pool->nbit, 9, "%s", bits);
  2074. pool->nValue = coinbasevalue;
  2075. hex2bin((unsigned char *)&pool->gbt_bits, bits, 4);
  2076. gbt_merkle_bins(pool, transaction_arr);
  2077. pool->height = height;
  2078. memset(pool->scriptsig_base, 0, 42);
  2079. ofs++; // Leave room for template length
  2080. /* Put block height at start of template. */
  2081. ofs += ser_number(pool->scriptsig_base + ofs, height); // max 5
  2082. /* Followed by flags */
  2083. len = strlen(flags) / 2;
  2084. pool->scriptsig_base[ofs++] = len;
  2085. hex2bin(pool->scriptsig_base + ofs, flags, len);
  2086. ofs += len;
  2087. /* Followed by timestamp */
  2088. cgtime(&now);
  2089. pool->scriptsig_base[ofs++] = 0xfe; // Encode seconds as u32
  2090. u32 = (uint32_t *)&pool->scriptsig_base[ofs];
  2091. *u32 = htole32(now.tv_sec);
  2092. ofs += 4; // sizeof uint32_t
  2093. pool->scriptsig_base[ofs++] = 0xfe; // Encode usecs as u32
  2094. u32 = (uint32_t *)&pool->scriptsig_base[ofs];
  2095. *u32 = htole32(now.tv_usec);
  2096. ofs += 4; // sizeof uint32_t
  2097. memcpy(pool->scriptsig_base + ofs, "\x09\x63\x67\x6d\x69\x6e\x65\x72\x34\x32", 10);
  2098. ofs += 10;
  2099. /* Followed by extranonce size, fixed at 8 */
  2100. pool->scriptsig_base[ofs++] = 8;
  2101. pool->nonce2_offset = 41 + ofs;
  2102. ofs += 8;
  2103. if (opt_btc_sig) {
  2104. len = strlen(opt_btc_sig);
  2105. if (len > 32)
  2106. len = 32;
  2107. pool->scriptsig_base[ofs++] = len;
  2108. memcpy(pool->scriptsig_base + ofs, opt_btc_sig, len);
  2109. ofs += len;
  2110. }
  2111. pool->scriptsig_base[0] = ofs++; // Template length
  2112. pool->n1_len = ofs;
  2113. len = 41 // prefix
  2114. + ofs // Template length
  2115. + 4 // txin sequence no
  2116. + 1 // transactions
  2117. + 8 // value
  2118. + 1 + 25 // txout
  2119. + 4; // lock
  2120. free(pool->coinbase);
  2121. pool->coinbase = calloc(len, 1);
  2122. if (unlikely(!pool->coinbase))
  2123. quit(1, "Failed to calloc coinbase in gbt_solo_decode");
  2124. memcpy(pool->coinbase + 41, pool->scriptsig_base, ofs);
  2125. memcpy(pool->coinbase + 41 + ofs, "\xff\xff\xff\xff", 4);
  2126. pool->coinbase[41 + ofs + 4] = 1;
  2127. u64 = (uint64_t *)&(pool->coinbase[41 + ofs + 4 + 1]);
  2128. *u64 = htole64(coinbasevalue);
  2129. pool->nonce2 = 0;
  2130. pool->n2size = 4;
  2131. pool->coinbase_len = 41 + ofs + 4 + 1 + 8 + 1 + 25 + 4;
  2132. cg_wunlock(&pool->gbt_lock);
  2133. snprintf(header, 225, "%s%s%s%s%s%s%s",
  2134. pool->bbversion,
  2135. pool->prev_hash,
  2136. "0000000000000000000000000000000000000000000000000000000000000000",
  2137. pool->ntime,
  2138. pool->nbit,
  2139. "00000000", /* nonce */
  2140. workpadding);
  2141. if (unlikely(!hex2bin(pool->header_bin, header, 112)))
  2142. quit(1, "Failed to hex2bin header in gbt_solo_decode");
  2143. return true;
  2144. }
  2145. static bool work_decode(struct pool *pool, struct work *work, json_t *val)
  2146. {
  2147. json_t *res_val = json_object_get(val, "result");
  2148. bool ret = false;
  2149. cgtime(&pool->tv_lastwork);
  2150. if (!res_val || json_is_null(res_val)) {
  2151. applog(LOG_ERR, "JSON Failed to decode result");
  2152. goto out;
  2153. }
  2154. if (pool->gbt_solo) {
  2155. if (unlikely(!gbt_solo_decode(pool, res_val)))
  2156. goto out;
  2157. ret = true;
  2158. goto out;
  2159. } else if (pool->has_gbt) {
  2160. if (unlikely(!gbt_decode(pool, res_val)))
  2161. goto out;
  2162. work->gbt = true;
  2163. ret = true;
  2164. goto out;
  2165. } else if (unlikely(!getwork_decode(res_val, work)))
  2166. goto out;
  2167. memset(work->hash, 0, sizeof(work->hash));
  2168. cgtime(&work->tv_staged);
  2169. ret = true;
  2170. out:
  2171. return ret;
  2172. }
  2173. #else /* HAVE_LIBCURL */
  2174. /* Always true with stratum */
  2175. #define pool_localgen(pool) (true)
  2176. #define json_rpc_call(curl, url, userpass, rpc_req, probe, longpoll, rolltime, pool, share) (NULL)
  2177. #define work_decode(pool, work, val) (false)
  2178. #define gen_gbt_work(pool, work) {}
  2179. #endif /* HAVE_LIBCURL */
  2180. int dev_from_id(int thr_id)
  2181. {
  2182. struct cgpu_info *cgpu = get_thr_cgpu(thr_id);
  2183. return cgpu->device_id;
  2184. }
  2185. /* Create an exponentially decaying average over the opt_log_interval */
  2186. void decay_time(double *f, double fadd, double fsecs, double interval)
  2187. {
  2188. double ftotal, fprop;
  2189. if (fsecs <= 0)
  2190. return;
  2191. fprop = 1.0 - 1 / (exp(fsecs / interval));
  2192. ftotal = 1.0 + fprop;
  2193. *f += (fadd / fsecs * fprop);
  2194. *f /= ftotal;
  2195. }
  2196. static int __total_staged(void)
  2197. {
  2198. return HASH_COUNT(staged_work);
  2199. }
  2200. static int total_staged(void)
  2201. {
  2202. int ret;
  2203. mutex_lock(stgd_lock);
  2204. ret = __total_staged();
  2205. mutex_unlock(stgd_lock);
  2206. return ret;
  2207. }
  2208. #ifdef HAVE_CURSES
  2209. WINDOW *mainwin, *statuswin, *logwin;
  2210. #endif
  2211. double total_secs = 1.0;
  2212. static char statusline[256];
  2213. /* logstart is where the log window should start */
  2214. static int devcursor, logstart, logcursor;
  2215. #ifdef HAVE_CURSES
  2216. /* statusy is where the status window goes up to in cases where it won't fit at startup */
  2217. static int statusy;
  2218. #endif
  2219. #ifdef HAVE_CURSES
  2220. static inline void unlock_curses(void)
  2221. {
  2222. mutex_unlock(&console_lock);
  2223. }
  2224. static inline void lock_curses(void)
  2225. {
  2226. mutex_lock(&console_lock);
  2227. }
  2228. static bool curses_active_locked(void)
  2229. {
  2230. bool ret;
  2231. lock_curses();
  2232. ret = curses_active;
  2233. if (!ret)
  2234. unlock_curses();
  2235. return ret;
  2236. }
  2237. #endif
  2238. /* Convert a uint64_t value into a truncated string for displaying with its
  2239. * associated suitable for Mega, Giga etc. Buf array needs to be long enough */
  2240. static void suffix_string(uint64_t val, char *buf, size_t bufsiz, int sigdigits)
  2241. {
  2242. const double dkilo = 1000.0;
  2243. const uint64_t kilo = 1000ull;
  2244. const uint64_t mega = 1000000ull;
  2245. const uint64_t giga = 1000000000ull;
  2246. const uint64_t tera = 1000000000000ull;
  2247. const uint64_t peta = 1000000000000000ull;
  2248. const uint64_t exa = 1000000000000000000ull;
  2249. char suffix[2] = "";
  2250. bool decimal = true;
  2251. double dval;
  2252. if (val >= exa) {
  2253. val /= peta;
  2254. dval = (double)val / dkilo;
  2255. strcpy(suffix, "E");
  2256. } else if (val >= peta) {
  2257. val /= tera;
  2258. dval = (double)val / dkilo;
  2259. strcpy(suffix, "P");
  2260. } else if (val >= tera) {
  2261. val /= giga;
  2262. dval = (double)val / dkilo;
  2263. strcpy(suffix, "T");
  2264. } else if (val >= giga) {
  2265. val /= mega;
  2266. dval = (double)val / dkilo;
  2267. strcpy(suffix, "G");
  2268. } else if (val >= mega) {
  2269. val /= kilo;
  2270. dval = (double)val / dkilo;
  2271. strcpy(suffix, "M");
  2272. } else if (val >= kilo) {
  2273. dval = (double)val / dkilo;
  2274. strcpy(suffix, "K");
  2275. } else {
  2276. dval = val;
  2277. decimal = false;
  2278. }
  2279. if (!sigdigits) {
  2280. if (decimal)
  2281. snprintf(buf, bufsiz, "%.3g%s", dval, suffix);
  2282. else
  2283. snprintf(buf, bufsiz, "%d%s", (unsigned int)dval, suffix);
  2284. } else {
  2285. /* Always show sigdigits + 1, padded on right with zeroes
  2286. * followed by suffix */
  2287. int ndigits = sigdigits - 1 - (dval > 0.0 ? floor(log10(dval)) : 0);
  2288. snprintf(buf, bufsiz, "%*.*f%s", sigdigits + 1, ndigits, dval, suffix);
  2289. }
  2290. }
  2291. double cgpu_runtime(struct cgpu_info *cgpu)
  2292. {
  2293. struct timeval now;
  2294. double dev_runtime;
  2295. if (cgpu->dev_start_tv.tv_sec == 0)
  2296. dev_runtime = total_secs;
  2297. else {
  2298. cgtime(&now);
  2299. dev_runtime = tdiff(&now, &(cgpu->dev_start_tv));
  2300. }
  2301. if (dev_runtime < 1.0)
  2302. dev_runtime = 1.0;
  2303. return dev_runtime;
  2304. }
  2305. double tsince_restart(void)
  2306. {
  2307. struct timeval now;
  2308. cgtime(&now);
  2309. return tdiff(&now, &restart_tv_start);
  2310. }
  2311. double tsince_update(void)
  2312. {
  2313. struct timeval now;
  2314. cgtime(&now);
  2315. return tdiff(&now, &update_tv_start);
  2316. }
  2317. static void get_statline(char *buf, size_t bufsiz, struct cgpu_info *cgpu)
  2318. {
  2319. char displayed_hashes[16], displayed_rolling[16];
  2320. double dev_runtime, wu;
  2321. uint64_t dh64, dr64;
  2322. dev_runtime = cgpu_runtime(cgpu);
  2323. wu = cgpu->diff1 / dev_runtime * 60.0;
  2324. dh64 = (double)cgpu->total_mhashes / dev_runtime * 1000000ull;
  2325. dr64 = (double)cgpu->rolling * 1000000ull;
  2326. suffix_string(dh64, displayed_hashes, sizeof(displayed_hashes), 4);
  2327. suffix_string(dr64, displayed_rolling, sizeof(displayed_rolling), 4);
  2328. snprintf(buf, bufsiz, "%s%d ", cgpu->drv->name, cgpu->device_id);
  2329. cgpu->drv->get_statline_before(buf, bufsiz, cgpu);
  2330. tailsprintf(buf, bufsiz, "(%ds):%s (avg):%sh/s | A:%.0f R:%.0f HW:%d WU:%.1f/m",
  2331. opt_log_interval,
  2332. displayed_rolling,
  2333. displayed_hashes,
  2334. cgpu->diff_accepted,
  2335. cgpu->diff_rejected,
  2336. cgpu->hw_errors,
  2337. wu);
  2338. cgpu->drv->get_statline(buf, bufsiz, cgpu);
  2339. }
  2340. static bool shared_strategy(void)
  2341. {
  2342. return (pool_strategy == POOL_LOADBALANCE || pool_strategy == POOL_BALANCE);
  2343. }
  2344. #ifdef HAVE_CURSES
  2345. #define CURBUFSIZ 256
  2346. #define cg_mvwprintw(win, y, x, fmt, ...) do { \
  2347. char tmp42[CURBUFSIZ]; \
  2348. snprintf(tmp42, sizeof(tmp42), fmt, ##__VA_ARGS__); \
  2349. mvwprintw(win, y, x, "%s", tmp42); \
  2350. } while (0)
  2351. #define cg_wprintw(win, fmt, ...) do { \
  2352. char tmp42[CURBUFSIZ]; \
  2353. snprintf(tmp42, sizeof(tmp42), fmt, ##__VA_ARGS__); \
  2354. wprintw(win, "%s", tmp42); \
  2355. } while (0)
  2356. /* Must be called with curses mutex lock held and curses_active */
  2357. static void curses_print_status(void)
  2358. {
  2359. struct pool *pool = current_pool();
  2360. int linewidth = opt_widescreen ? 100 : 80;
  2361. wattron(statuswin, A_BOLD);
  2362. cg_mvwprintw(statuswin, 0, 0, " " PACKAGE " version " VERSION " - Started: %s", datestamp);
  2363. wattroff(statuswin, A_BOLD);
  2364. mvwhline(statuswin, 1, 0, '-', linewidth);
  2365. cg_mvwprintw(statuswin, 2, 0, " %s", statusline);
  2366. wclrtoeol(statuswin);
  2367. if (opt_widescreen) {
  2368. cg_mvwprintw(statuswin, 3, 0, " A:%.0f R:%.0f HW:%d WU:%.1f/m |"
  2369. " ST: %d SS: %"PRId64" NB: %d LW: %d GF: %d RF: %d",
  2370. total_diff_accepted, total_diff_rejected, hw_errors,
  2371. total_diff1 / total_secs * 60,
  2372. total_staged(), total_stale, new_blocks, local_work, total_go, total_ro);
  2373. } else if (alt_status) {
  2374. cg_mvwprintw(statuswin, 3, 0, " ST: %d SS: %"PRId64" NB: %d LW: %d GF: %d RF: %d",
  2375. total_staged(), total_stale, new_blocks, local_work, total_go, total_ro);
  2376. } else {
  2377. cg_mvwprintw(statuswin, 3, 0, " A:%.0f R:%.0f HW:%d WU:%.1f/m",
  2378. total_diff_accepted, total_diff_rejected, hw_errors,
  2379. total_diff1 / total_secs * 60);
  2380. }
  2381. wclrtoeol(statuswin);
  2382. if (shared_strategy() && total_pools > 1) {
  2383. cg_mvwprintw(statuswin, 4, 0, " Connected to multiple pools with%s block change notify",
  2384. have_longpoll ? "": "out");
  2385. } else if (pool->has_stratum) {
  2386. cg_mvwprintw(statuswin, 4, 0, " Connected to %s diff %s with stratum as user %s",
  2387. pool->sockaddr_url, pool->diff, pool->rpc_user);
  2388. } else {
  2389. cg_mvwprintw(statuswin, 4, 0, " Connected to %s diff %s with%s %s as user %s",
  2390. pool->sockaddr_url, pool->diff, have_longpoll ? "": "out",
  2391. pool->has_gbt ? "GBT" : "LP", pool->rpc_user);
  2392. }
  2393. wclrtoeol(statuswin);
  2394. cg_mvwprintw(statuswin, 5, 0, " Block: %s... Diff:%s Started: %s Best share: %s ",
  2395. prev_block, block_diff, blocktime, best_share);
  2396. mvwhline(statuswin, 6, 0, '-', linewidth);
  2397. mvwhline(statuswin, statusy - 1, 0, '-', linewidth);
  2398. #ifdef USE_USBUTILS
  2399. cg_mvwprintw(statuswin, devcursor - 1, 1, "[U]SB management [P]ool management [S]ettings [D]isplay options [Q]uit");
  2400. #else
  2401. cg_mvwprintw(statuswin, devcursor - 1, 1, "[P]ool management [S]ettings [D]isplay options [Q]uit");
  2402. #endif
  2403. }
  2404. static void adj_width(int var, int *length)
  2405. {
  2406. if ((int)(log10(var) + 1) > *length)
  2407. (*length)++;
  2408. }
  2409. static void adj_fwidth(float var, int *length)
  2410. {
  2411. if ((int)(log10(var) + 1) > *length)
  2412. (*length)++;
  2413. }
  2414. #define STATBEFORELEN 23
  2415. const char blanks[] = " ";
  2416. static void curses_print_devstatus(struct cgpu_info *cgpu, int devno, int count)
  2417. {
  2418. static int devno_width = 1, uid_width = 4, dawidth = 1, drwidth = 1, hwwidth = 1, wuwidth = 1;
  2419. char logline[256], unique_id[16];
  2420. struct timeval now;
  2421. double dev_runtime, wu;
  2422. unsigned int devstatlen;
  2423. if (opt_compact)
  2424. return;
  2425. if (devcursor + count > LINES - 2)
  2426. return;
  2427. if (count >= most_devices)
  2428. return;
  2429. if (cgpu->dev_start_tv.tv_sec == 0)
  2430. dev_runtime = total_secs;
  2431. else {
  2432. cgtime(&now);
  2433. dev_runtime = tdiff(&now, &(cgpu->dev_start_tv));
  2434. }
  2435. if (dev_runtime < 1.0)
  2436. dev_runtime = 1.0;
  2437. cgpu->utility = cgpu->accepted / dev_runtime * 60;
  2438. wu = cgpu->diff1 / dev_runtime * 60;
  2439. wmove(statuswin,devcursor + count, 0);
  2440. adj_width(devno, &devno_width);
  2441. if (cgpu->unique_id) {
  2442. if (uid_width < 12 && (int)strlen(cgpu->unique_id) > uid_width)
  2443. uid_width = MIN(strlen(cgpu->unique_id), 12); // maximum length 12
  2444. unique_id[4] = '\0';
  2445. memcpy(unique_id, blanks, 4); // minimum length 4
  2446. strncpy(unique_id, cgpu->unique_id, uid_width);
  2447. unique_id[uid_width] = '\0';
  2448. } else {
  2449. adj_width(cgpu->device_id, &uid_width);
  2450. if (uid_width < 4)
  2451. uid_width = 4;
  2452. if (uid_width > 12)
  2453. uid_width = 12;
  2454. sprintf(unique_id, "%-*d", uid_width, cgpu->device_id);
  2455. }
  2456. cg_wprintw(statuswin, " %*d: %s %-*s: ", devno_width, devno, cgpu->drv->name,
  2457. uid_width, unique_id);
  2458. logline[0] = '\0';
  2459. cgpu->drv->get_statline_before(logline, sizeof(logline), cgpu);
  2460. devstatlen = strlen(logline);
  2461. if (devstatlen < STATBEFORELEN)
  2462. strncat(logline, blanks, STATBEFORELEN - devstatlen);
  2463. cg_wprintw(statuswin, "%s | ", logline);
  2464. #ifdef USE_USBUTILS
  2465. if (cgpu->usbinfo.nodev)
  2466. cg_wprintw(statuswin, "ZOMBIE");
  2467. else
  2468. #endif
  2469. if (cgpu->status == LIFE_DEAD)
  2470. cg_wprintw(statuswin, "DEAD ");
  2471. else if (cgpu->status == LIFE_SICK)
  2472. cg_wprintw(statuswin, "SICK ");
  2473. else if (cgpu->deven == DEV_DISABLED)
  2474. cg_wprintw(statuswin, "OFF ");
  2475. else if (cgpu->deven == DEV_RECOVER)
  2476. cg_wprintw(statuswin, "REST ");
  2477. else if (opt_widescreen) {
  2478. char displayed_hashes[16], displayed_rolling[16];
  2479. uint64_t d64;
  2480. d64 = (double)cgpu->total_mhashes / dev_runtime * 1000000ull;
  2481. suffix_string(d64, displayed_hashes, sizeof(displayed_hashes), 4);
  2482. d64 = (double)cgpu->rolling * 1000000ull;
  2483. suffix_string(d64, displayed_rolling, sizeof(displayed_rolling), 4);
  2484. adj_width(wu, &wuwidth);
  2485. adj_fwidth(cgpu->diff_accepted, &dawidth);
  2486. adj_fwidth(cgpu->diff_rejected, &drwidth);
  2487. adj_width(cgpu->hw_errors, &hwwidth);
  2488. cg_wprintw(statuswin, "%6s / %6sh/s WU:%*.1f/m "
  2489. "A:%*.0f R:%*.0f HW:%*d",
  2490. displayed_rolling,
  2491. displayed_hashes, wuwidth + 2, wu,
  2492. dawidth, cgpu->diff_accepted,
  2493. drwidth, cgpu->diff_rejected,
  2494. hwwidth, cgpu->hw_errors);
  2495. } else if (!alt_status) {
  2496. char displayed_hashes[16], displayed_rolling[16];
  2497. uint64_t d64;
  2498. d64 = (double)cgpu->total_mhashes / dev_runtime * 1000000ull;
  2499. suffix_string(d64, displayed_hashes, sizeof(displayed_hashes), 4);
  2500. d64 = (double)cgpu->rolling * 1000000ull;
  2501. suffix_string(d64, displayed_rolling, sizeof(displayed_rolling), 4);
  2502. adj_width(wu, &wuwidth);
  2503. cg_wprintw(statuswin, "%6s / %6sh/s WU:%*.1f/m", displayed_rolling,
  2504. displayed_hashes, wuwidth + 2, wu);
  2505. } else {
  2506. adj_fwidth(cgpu->diff_accepted, &dawidth);
  2507. adj_fwidth(cgpu->diff_rejected, &drwidth);
  2508. adj_width(cgpu->hw_errors, &hwwidth);
  2509. cg_wprintw(statuswin, "A:%*.0f R:%*.0f HW:%*d",
  2510. dawidth, cgpu->diff_accepted,
  2511. drwidth, cgpu->diff_rejected,
  2512. hwwidth, cgpu->hw_errors);
  2513. }
  2514. logline[0] = '\0';
  2515. cgpu->drv->get_statline(logline, sizeof(logline), cgpu);
  2516. cg_wprintw(statuswin, "%s", logline);
  2517. wclrtoeol(statuswin);
  2518. }
  2519. #endif
  2520. #ifdef HAVE_CURSES
  2521. /* Check for window resize. Called with curses mutex locked */
  2522. static inline void change_logwinsize(void)
  2523. {
  2524. int x, y, logx, logy;
  2525. getmaxyx(mainwin, y, x);
  2526. if (x < 80 || y < 25)
  2527. return;
  2528. if (y > statusy + 2 && statusy < logstart) {
  2529. if (y - 2 < logstart)
  2530. statusy = y - 2;
  2531. else
  2532. statusy = logstart;
  2533. logcursor = statusy + 1;
  2534. mvwin(logwin, logcursor, 0);
  2535. wresize(statuswin, statusy, x);
  2536. }
  2537. y -= logcursor;
  2538. getmaxyx(logwin, logy, logx);
  2539. /* Detect screen size change */
  2540. if (x != logx || y != logy)
  2541. wresize(logwin, y, x);
  2542. }
  2543. static void check_winsizes(void)
  2544. {
  2545. if (!use_curses)
  2546. return;
  2547. if (curses_active_locked()) {
  2548. int y, x;
  2549. erase();
  2550. x = getmaxx(statuswin);
  2551. if (logstart > LINES - 2)
  2552. statusy = LINES - 2;
  2553. else
  2554. statusy = logstart;
  2555. logcursor = statusy;
  2556. wresize(statuswin, statusy, x);
  2557. getmaxyx(mainwin, y, x);
  2558. y -= logcursor;
  2559. wresize(logwin, y, x);
  2560. mvwin(logwin, logcursor, 0);
  2561. unlock_curses();
  2562. }
  2563. }
  2564. static void disable_curses_windows(void);
  2565. static void enable_curses_windows(void);
  2566. static void switch_logsize(bool __maybe_unused newdevs)
  2567. {
  2568. if (curses_active_locked()) {
  2569. #ifdef WIN32
  2570. if (newdevs)
  2571. disable_curses_windows();
  2572. #endif
  2573. if (opt_compact) {
  2574. logstart = devcursor + 1;
  2575. logcursor = logstart + 1;
  2576. } else {
  2577. logstart = devcursor + most_devices + 1;
  2578. logcursor = logstart + 1;
  2579. }
  2580. #ifdef WIN32
  2581. if (newdevs)
  2582. enable_curses_windows();
  2583. #endif
  2584. unlock_curses();
  2585. check_winsizes();
  2586. }
  2587. }
  2588. /* For mandatory printing when mutex is already locked */
  2589. void _wlog(const char *str)
  2590. {
  2591. wprintw(logwin, "%s", str);
  2592. }
  2593. /* Mandatory printing */
  2594. void _wlogprint(const char *str)
  2595. {
  2596. if (curses_active_locked()) {
  2597. wprintw(logwin, "%s", str);
  2598. unlock_curses();
  2599. }
  2600. }
  2601. #endif
  2602. #ifdef HAVE_CURSES
  2603. bool log_curses_only(int prio, const char *datetime, const char *str)
  2604. {
  2605. bool high_prio;
  2606. high_prio = (prio == LOG_WARNING || prio == LOG_ERR);
  2607. if (curses_active_locked()) {
  2608. if (!opt_loginput || high_prio) {
  2609. wprintw(logwin, "%s%s\n", datetime, str);
  2610. if (high_prio) {
  2611. touchwin(logwin);
  2612. wrefresh(logwin);
  2613. }
  2614. }
  2615. unlock_curses();
  2616. return true;
  2617. }
  2618. return false;
  2619. }
  2620. void clear_logwin(void)
  2621. {
  2622. if (curses_active_locked()) {
  2623. erase();
  2624. wclear(logwin);
  2625. unlock_curses();
  2626. }
  2627. }
  2628. void logwin_update(void)
  2629. {
  2630. if (curses_active_locked()) {
  2631. touchwin(logwin);
  2632. wrefresh(logwin);
  2633. unlock_curses();
  2634. }
  2635. }
  2636. #endif
  2637. static void enable_pool(struct pool *pool)
  2638. {
  2639. if (pool->enabled != POOL_ENABLED) {
  2640. enabled_pools++;
  2641. pool->enabled = POOL_ENABLED;
  2642. }
  2643. }
  2644. #ifdef HAVE_CURSES
  2645. static void disable_pool(struct pool *pool)
  2646. {
  2647. if (pool->enabled == POOL_ENABLED)
  2648. enabled_pools--;
  2649. pool->enabled = POOL_DISABLED;
  2650. }
  2651. #endif
  2652. static void reject_pool(struct pool *pool)
  2653. {
  2654. if (pool->enabled == POOL_ENABLED)
  2655. enabled_pools--;
  2656. pool->enabled = POOL_REJECTING;
  2657. }
  2658. static void restart_threads(void);
  2659. /* Theoretically threads could race when modifying accepted and
  2660. * rejected values but the chance of two submits completing at the
  2661. * same time is zero so there is no point adding extra locking */
  2662. static void
  2663. share_result(json_t *val, json_t *res, json_t *err, const struct work *work,
  2664. char *hashshow, bool resubmit, char *worktime)
  2665. {
  2666. struct pool *pool = work->pool;
  2667. struct cgpu_info *cgpu;
  2668. cgpu = get_thr_cgpu(work->thr_id);
  2669. if (json_is_true(res) || (work->gbt && json_is_null(res))) {
  2670. mutex_lock(&stats_lock);
  2671. cgpu->accepted++;
  2672. total_accepted++;
  2673. pool->accepted++;
  2674. cgpu->diff_accepted += work->work_difficulty;
  2675. total_diff_accepted += work->work_difficulty;
  2676. pool->diff_accepted += work->work_difficulty;
  2677. mutex_unlock(&stats_lock);
  2678. pool->seq_rejects = 0;
  2679. cgpu->last_share_pool = pool->pool_no;
  2680. cgpu->last_share_pool_time = time(NULL);
  2681. cgpu->last_share_diff = work->work_difficulty;
  2682. pool->last_share_time = cgpu->last_share_pool_time;
  2683. pool->last_share_diff = work->work_difficulty;
  2684. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  2685. if (!QUIET) {
  2686. if (total_pools > 1)
  2687. applog(LOG_NOTICE, "Accepted %s %s %d pool %d %s%s",
  2688. hashshow, cgpu->drv->name, cgpu->device_id, work->pool->pool_no, resubmit ? "(resubmit)" : "", worktime);
  2689. else
  2690. applog(LOG_NOTICE, "Accepted %s %s %d %s%s",
  2691. hashshow, cgpu->drv->name, cgpu->device_id, resubmit ? "(resubmit)" : "", worktime);
  2692. }
  2693. sharelog("accept", work);
  2694. if (opt_shares && total_diff_accepted >= opt_shares) {
  2695. applog(LOG_WARNING, "Successfully mined %d accepted shares as requested and exiting.", opt_shares);
  2696. kill_work();
  2697. return;
  2698. }
  2699. /* Detect if a pool that has been temporarily disabled for
  2700. * continually rejecting shares has started accepting shares.
  2701. * This will only happen with the work returned from a
  2702. * longpoll */
  2703. if (unlikely(pool->enabled == POOL_REJECTING)) {
  2704. applog(LOG_WARNING, "Rejecting pool %d now accepting shares, re-enabling!", pool->pool_no);
  2705. enable_pool(pool);
  2706. switch_pools(NULL);
  2707. }
  2708. /* If we know we found the block we know better than anyone
  2709. * that new work is needed. */
  2710. if (unlikely(work->block))
  2711. restart_threads();
  2712. } else {
  2713. mutex_lock(&stats_lock);
  2714. cgpu->rejected++;
  2715. total_rejected++;
  2716. pool->rejected++;
  2717. cgpu->diff_rejected += work->work_difficulty;
  2718. total_diff_rejected += work->work_difficulty;
  2719. pool->diff_rejected += work->work_difficulty;
  2720. pool->seq_rejects++;
  2721. mutex_unlock(&stats_lock);
  2722. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  2723. if (!QUIET) {
  2724. char where[20];
  2725. char disposition[36] = "reject";
  2726. char reason[32];
  2727. strcpy(reason, "");
  2728. if (total_pools > 1)
  2729. snprintf(where, sizeof(where), "pool %d", work->pool->pool_no);
  2730. else
  2731. strcpy(where, "");
  2732. if (!work->gbt)
  2733. res = json_object_get(val, "reject-reason");
  2734. if (res) {
  2735. const char *reasontmp = json_string_value(res);
  2736. size_t reasonLen = strlen(reasontmp);
  2737. if (reasonLen > 28)
  2738. reasonLen = 28;
  2739. reason[0] = ' '; reason[1] = '(';
  2740. memcpy(2 + reason, reasontmp, reasonLen);
  2741. reason[reasonLen + 2] = ')'; reason[reasonLen + 3] = '\0';
  2742. memcpy(disposition + 7, reasontmp, reasonLen);
  2743. disposition[6] = ':'; disposition[reasonLen + 7] = '\0';
  2744. } else if (work->stratum && err && json_is_array(err)) {
  2745. json_t *reason_val = json_array_get(err, 1);
  2746. char *reason_str;
  2747. if (reason_val && json_is_string(reason_val)) {
  2748. reason_str = (char *)json_string_value(reason_val);
  2749. snprintf(reason, 31, " (%s)", reason_str);
  2750. }
  2751. }
  2752. applog(LOG_NOTICE, "Rejected %s %s %d %s%s %s%s",
  2753. hashshow, cgpu->drv->name, cgpu->device_id, where, reason, resubmit ? "(resubmit)" : "", worktime);
  2754. sharelog(disposition, work);
  2755. }
  2756. /* Once we have more than a nominal amount of sequential rejects,
  2757. * at least 10 and more than 3 mins at the current utility,
  2758. * disable the pool because some pool error is likely to have
  2759. * ensued. Do not do this if we know the share just happened to
  2760. * be stale due to networking delays.
  2761. */
  2762. if (pool->seq_rejects > 10 && !work->stale && opt_disable_pool && enabled_pools > 1) {
  2763. double utility = total_accepted / total_secs * 60;
  2764. if (pool->seq_rejects > utility * 3) {
  2765. applog(LOG_WARNING, "Pool %d rejected %d sequential shares, disabling!",
  2766. pool->pool_no, pool->seq_rejects);
  2767. reject_pool(pool);
  2768. if (pool == current_pool())
  2769. switch_pools(NULL);
  2770. pool->seq_rejects = 0;
  2771. }
  2772. }
  2773. }
  2774. }
  2775. static void show_hash(struct work *work, char *hashshow)
  2776. {
  2777. unsigned char rhash[32];
  2778. char diffdisp[16];
  2779. unsigned long h32;
  2780. uint32_t *hash32;
  2781. uint64_t uintdiff;
  2782. int ofs;
  2783. swab256(rhash, work->hash);
  2784. for (ofs = 0; ofs <= 28; ofs ++) {
  2785. if (rhash[ofs])
  2786. break;
  2787. }
  2788. hash32 = (uint32_t *)(rhash + ofs);
  2789. h32 = be32toh(*hash32);
  2790. uintdiff = round(work->work_difficulty);
  2791. suffix_string(work->share_diff, diffdisp, sizeof (diffdisp), 0);
  2792. snprintf(hashshow, 64, "%08lx Diff %s/%"PRIu64"%s", h32, diffdisp, uintdiff,
  2793. work->block? " BLOCK!" : "");
  2794. }
  2795. #ifdef HAVE_LIBCURL
  2796. static void text_print_status(int thr_id)
  2797. {
  2798. struct cgpu_info *cgpu;
  2799. char logline[256];
  2800. cgpu = get_thr_cgpu(thr_id);
  2801. if (cgpu) {
  2802. get_statline(logline, sizeof(logline), cgpu);
  2803. printf("%s\n", logline);
  2804. }
  2805. }
  2806. static void print_status(int thr_id)
  2807. {
  2808. if (!curses_active)
  2809. text_print_status(thr_id);
  2810. }
  2811. static bool submit_upstream_work(struct work *work, CURL *curl, bool resubmit)
  2812. {
  2813. json_t *val, *res, *err;
  2814. char *s;
  2815. bool rc = false;
  2816. int thr_id = work->thr_id;
  2817. struct cgpu_info *cgpu;
  2818. struct pool *pool = work->pool;
  2819. int rolltime;
  2820. struct timeval tv_submit, tv_submit_reply;
  2821. char hashshow[64 + 4] = "";
  2822. char worktime[200] = "";
  2823. struct timeval now;
  2824. double dev_runtime;
  2825. cgpu = get_thr_cgpu(thr_id);
  2826. /* build JSON-RPC request */
  2827. if (work->gbt) {
  2828. char gbt_block[1024], varint[12];
  2829. unsigned char data[80];
  2830. flip80(data, work->data);
  2831. __bin2hex(gbt_block, data, 80); // 160 length
  2832. if (work->gbt_txns < 0xfd) {
  2833. uint8_t val8 = work->gbt_txns;
  2834. __bin2hex(varint, (const unsigned char *)&val8, 1);
  2835. } else if (work->gbt_txns <= 0xffff) {
  2836. uint16_t val16 = htole16(work->gbt_txns);
  2837. strcat(gbt_block, "fd"); // +2
  2838. __bin2hex(varint, (const unsigned char *)&val16, 2);
  2839. } else {
  2840. uint32_t val32 = htole32(work->gbt_txns);
  2841. strcat(gbt_block, "fe"); // +2
  2842. __bin2hex(varint, (const unsigned char *)&val32, 4);
  2843. }
  2844. strcat(gbt_block, varint); // +8 max
  2845. strcat(gbt_block, work->coinbase);
  2846. s = malloc(1024);
  2847. if (unlikely(!s))
  2848. quit(1, "Failed to malloc s in submit_upstream_work");
  2849. sprintf(s, "{\"id\": 0, \"method\": \"submitblock\", \"params\": [\"%s", gbt_block);
  2850. /* Has submit/coinbase support */
  2851. if (!pool->has_gbt) {
  2852. cg_rlock(&pool->gbt_lock);
  2853. if (pool->txn_data)
  2854. s = realloc_strcat(s, pool->txn_data);
  2855. cg_runlock(&pool->gbt_lock);
  2856. }
  2857. if (work->job_id) {
  2858. s = realloc_strcat(s, "\", {\"workid\": \"");
  2859. s = realloc_strcat(s, work->job_id);
  2860. s = realloc_strcat(s, "\"}]}");
  2861. } else
  2862. s = realloc_strcat(s, "\"]}");
  2863. } else {
  2864. char *hexstr;
  2865. endian_flip128(work->data, work->data);
  2866. /* build hex string */
  2867. /* only 118 bytes are used, but *coind servers expect 128 byte hex strings */
  2868. hexstr = bin2hex(work->data, 128);
  2869. s = strdup("{\"method\": \"getwork\", \"params\": [ \"");
  2870. s = realloc_strcat(s, hexstr);
  2871. s = realloc_strcat(s, "\" ], \"id\":1}");
  2872. free(hexstr);
  2873. }
  2874. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->rpc_url, s);
  2875. s = realloc_strcat(s, "\n");
  2876. cgtime(&tv_submit);
  2877. /* issue JSON-RPC request */
  2878. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, s, false, false, &rolltime, pool, true);
  2879. cgtime(&tv_submit_reply);
  2880. free(s);
  2881. if (unlikely(!val)) {
  2882. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  2883. if (!pool_tset(pool, &pool->submit_fail)) {
  2884. total_ro++;
  2885. pool->remotefail_occasions++;
  2886. if (opt_lowmem) {
  2887. applog(LOG_WARNING, "Pool %d communication failure, discarding shares", pool->pool_no);
  2888. goto out;
  2889. }
  2890. applog(LOG_WARNING, "Pool %d communication failure, caching submissions", pool->pool_no);
  2891. }
  2892. cgsleep_ms(5000);
  2893. goto out;
  2894. } else if (pool_tclear(pool, &pool->submit_fail))
  2895. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  2896. res = json_object_get(val, "result");
  2897. err = json_object_get(val, "error");
  2898. if (!QUIET) {
  2899. show_hash(work, hashshow);
  2900. if (opt_worktime) {
  2901. char workclone[20];
  2902. struct tm *tm, tm_getwork, tm_submit_reply;
  2903. double getwork_time = tdiff((struct timeval *)&(work->tv_getwork_reply),
  2904. (struct timeval *)&(work->tv_getwork));
  2905. double getwork_to_work = tdiff((struct timeval *)&(work->tv_work_start),
  2906. (struct timeval *)&(work->tv_getwork_reply));
  2907. double work_time = tdiff((struct timeval *)&(work->tv_work_found),
  2908. (struct timeval *)&(work->tv_work_start));
  2909. double work_to_submit = tdiff(&tv_submit,
  2910. (struct timeval *)&(work->tv_work_found));
  2911. double submit_time = tdiff(&tv_submit_reply, &tv_submit);
  2912. int diffplaces = 3;
  2913. time_t tmp_time = work->tv_getwork.tv_sec;
  2914. tm = localtime(&tmp_time);
  2915. memcpy(&tm_getwork, tm, sizeof(struct tm));
  2916. tmp_time = tv_submit_reply.tv_sec;
  2917. tm = localtime(&tmp_time);
  2918. memcpy(&tm_submit_reply, tm, sizeof(struct tm));
  2919. if (work->clone) {
  2920. snprintf(workclone, sizeof(workclone), "C:%1.3f",
  2921. tdiff((struct timeval *)&(work->tv_cloned),
  2922. (struct timeval *)&(work->tv_getwork_reply)));
  2923. }
  2924. else
  2925. strcpy(workclone, "O");
  2926. if (work->work_difficulty < 1)
  2927. diffplaces = 6;
  2928. snprintf(worktime, sizeof(worktime),
  2929. " <-%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",
  2930. (unsigned long)be32toh(*(uint32_t *)&(work->data[opt_scrypt ? 32 : 28])),
  2931. (unsigned long)be32toh(*(uint32_t *)&(work->data[opt_scrypt ? 28 : 24])),
  2932. work->getwork_mode, diffplaces, work->work_difficulty,
  2933. tm_getwork.tm_hour, tm_getwork.tm_min,
  2934. tm_getwork.tm_sec, getwork_time, workclone,
  2935. getwork_to_work, work_time, work_to_submit, submit_time,
  2936. tm_submit_reply.tm_hour, tm_submit_reply.tm_min,
  2937. tm_submit_reply.tm_sec);
  2938. }
  2939. }
  2940. share_result(val, res, err, work, hashshow, resubmit, worktime);
  2941. if (cgpu->dev_start_tv.tv_sec == 0)
  2942. dev_runtime = total_secs;
  2943. else {
  2944. cgtime(&now);
  2945. dev_runtime = tdiff(&now, &(cgpu->dev_start_tv));
  2946. }
  2947. if (dev_runtime < 1.0)
  2948. dev_runtime = 1.0;
  2949. cgpu->utility = cgpu->accepted / dev_runtime * 60;
  2950. if (!opt_realquiet)
  2951. print_status(thr_id);
  2952. if (!want_per_device_stats) {
  2953. char logline[256];
  2954. get_statline(logline, sizeof(logline), cgpu);
  2955. applog(LOG_INFO, "%s", logline);
  2956. }
  2957. json_decref(val);
  2958. rc = true;
  2959. out:
  2960. return rc;
  2961. }
  2962. static bool get_upstream_work(struct work *work, CURL *curl)
  2963. {
  2964. struct pool *pool = work->pool;
  2965. struct cgminer_pool_stats *pool_stats = &(pool->cgminer_pool_stats);
  2966. struct timeval tv_elapsed;
  2967. json_t *val = NULL;
  2968. bool rc = false;
  2969. char *url;
  2970. url = pool->rpc_url;
  2971. applog(LOG_DEBUG, "DBG: sending %s get RPC call: %s", url, pool->rpc_req);
  2972. cgtime(&work->tv_getwork);
  2973. val = json_rpc_call(curl, url, pool->rpc_userpass, pool->rpc_req, false,
  2974. false, &work->rolltime, pool, false);
  2975. pool_stats->getwork_attempts++;
  2976. if (likely(val)) {
  2977. rc = work_decode(pool, work, val);
  2978. if (unlikely(!rc))
  2979. applog(LOG_DEBUG, "Failed to decode work in get_upstream_work");
  2980. } else
  2981. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  2982. cgtime(&work->tv_getwork_reply);
  2983. timersub(&(work->tv_getwork_reply), &(work->tv_getwork), &tv_elapsed);
  2984. pool_stats->getwork_wait_rolling += ((double)tv_elapsed.tv_sec + ((double)tv_elapsed.tv_usec / 1000000)) * 0.63;
  2985. pool_stats->getwork_wait_rolling /= 1.63;
  2986. timeradd(&tv_elapsed, &(pool_stats->getwork_wait), &(pool_stats->getwork_wait));
  2987. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_max), >)) {
  2988. pool_stats->getwork_wait_max.tv_sec = tv_elapsed.tv_sec;
  2989. pool_stats->getwork_wait_max.tv_usec = tv_elapsed.tv_usec;
  2990. }
  2991. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_min), <)) {
  2992. pool_stats->getwork_wait_min.tv_sec = tv_elapsed.tv_sec;
  2993. pool_stats->getwork_wait_min.tv_usec = tv_elapsed.tv_usec;
  2994. }
  2995. pool_stats->getwork_calls++;
  2996. work->pool = pool;
  2997. work->longpoll = false;
  2998. work->getwork_mode = GETWORK_MODE_POOL;
  2999. calc_diff(work, 0);
  3000. total_getworks++;
  3001. pool->getwork_requested++;
  3002. if (likely(val))
  3003. json_decref(val);
  3004. return rc;
  3005. }
  3006. #endif /* HAVE_LIBCURL */
  3007. /* Specifies whether we can use this pool for work or not. */
  3008. static bool pool_unworkable(struct pool *pool)
  3009. {
  3010. if (pool->idle)
  3011. return true;
  3012. if (pool->enabled != POOL_ENABLED)
  3013. return true;
  3014. if (pool->has_stratum && !pool->stratum_active)
  3015. return true;
  3016. return false;
  3017. }
  3018. /* In balanced mode, the amount of diff1 solutions per pool is monitored as a
  3019. * rolling average per 10 minutes and if pools start getting more, it biases
  3020. * away from them to distribute work evenly. The share count is reset to the
  3021. * rolling average every 10 minutes to not send all work to one pool after it
  3022. * has been disabled/out for an extended period. */
  3023. static struct pool *select_balanced(struct pool *cp)
  3024. {
  3025. int i, lowest = cp->shares;
  3026. struct pool *ret = cp;
  3027. for (i = 0; i < total_pools; i++) {
  3028. struct pool *pool = pools[i];
  3029. if (pool_unworkable(pool))
  3030. continue;
  3031. if (pool->shares < lowest) {
  3032. lowest = pool->shares;
  3033. ret = pool;
  3034. }
  3035. }
  3036. ret->shares++;
  3037. return ret;
  3038. }
  3039. static struct pool *priority_pool(int choice);
  3040. static bool pool_unusable(struct pool *pool);
  3041. /* Select any active pool in a rotating fashion when loadbalance is chosen if
  3042. * it has any quota left. */
  3043. static inline struct pool *select_pool(bool lagging)
  3044. {
  3045. static int rotating_pool = 0;
  3046. struct pool *pool, *cp;
  3047. bool avail = false;
  3048. int tested, i;
  3049. cp = current_pool();
  3050. if (pool_strategy == POOL_BALANCE) {
  3051. pool = select_balanced(cp);
  3052. goto out;
  3053. }
  3054. if (pool_strategy != POOL_LOADBALANCE && (!lagging || opt_fail_only)) {
  3055. pool = cp;
  3056. goto out;
  3057. } else
  3058. pool = NULL;
  3059. for (i = 0; i < total_pools; i++) {
  3060. struct pool *tp = pools[i];
  3061. if (tp->quota_used < tp->quota_gcd) {
  3062. avail = true;
  3063. break;
  3064. }
  3065. }
  3066. /* There are no pools with quota, so reset them. */
  3067. if (!avail) {
  3068. for (i = 0; i < total_pools; i++)
  3069. pools[i]->quota_used = 0;
  3070. if (++rotating_pool >= total_pools)
  3071. rotating_pool = 0;
  3072. }
  3073. /* Try to find the first pool in the rotation that is usable */
  3074. tested = 0;
  3075. while (!pool && tested++ < total_pools) {
  3076. pool = pools[rotating_pool];
  3077. if (pool->quota_used++ < pool->quota_gcd) {
  3078. if (!pool_unworkable(pool))
  3079. break;
  3080. /* Failover-only flag for load-balance means distribute
  3081. * unused quota to priority pool 0. */
  3082. if (opt_fail_only)
  3083. priority_pool(0)->quota_used--;
  3084. }
  3085. pool = NULL;
  3086. if (++rotating_pool >= total_pools)
  3087. rotating_pool = 0;
  3088. }
  3089. /* If there are no alive pools with quota, choose according to
  3090. * priority. */
  3091. if (!pool) {
  3092. for (i = 0; i < total_pools; i++) {
  3093. struct pool *tp = priority_pool(i);
  3094. if (!pool_unusable(tp)) {
  3095. pool = tp;
  3096. break;
  3097. }
  3098. }
  3099. }
  3100. /* If still nothing is usable, use the current pool */
  3101. if (!pool)
  3102. pool = cp;
  3103. out:
  3104. applog(LOG_DEBUG, "Selecting pool %d for work", pool->pool_no);
  3105. return pool;
  3106. }
  3107. /* truediffone == 0x00000000FFFF0000000000000000000000000000000000000000000000000000
  3108. * Generate a 256 bit binary LE target by cutting up diff into 64 bit sized
  3109. * portions or vice versa. */
  3110. static const double truediffone = 26959535291011309493156476344723991336010898738574164086137773096960.0;
  3111. static const double bits192 = 6277101735386680763835789423207666416102355444464034512896.0;
  3112. static const double bits128 = 340282366920938463463374607431768211456.0;
  3113. static const double bits64 = 18446744073709551616.0;
  3114. /* Converts a little endian 256 bit value to a double */
  3115. static double le256todouble(const void *target)
  3116. {
  3117. uint64_t *data64;
  3118. double dcut64;
  3119. data64 = (uint64_t *)(target + 24);
  3120. dcut64 = le64toh(*data64) * bits192;
  3121. data64 = (uint64_t *)(target + 16);
  3122. dcut64 += le64toh(*data64) * bits128;
  3123. data64 = (uint64_t *)(target + 8);
  3124. dcut64 += le64toh(*data64) * bits64;
  3125. data64 = (uint64_t *)(target);
  3126. dcut64 += le64toh(*data64);
  3127. return dcut64;
  3128. }
  3129. static double diff_from_target(void *target)
  3130. {
  3131. double d64, dcut64;
  3132. d64 = truediffone;
  3133. if (opt_scrypt)
  3134. d64 *= (double)65536;
  3135. dcut64 = le256todouble(target);
  3136. if (unlikely(!dcut64))
  3137. dcut64 = 1;
  3138. return d64 / dcut64;
  3139. }
  3140. /*
  3141. * Calculate the work->work_difficulty based on the work->target
  3142. */
  3143. static void calc_diff(struct work *work, double known)
  3144. {
  3145. struct cgminer_pool_stats *pool_stats = &(work->pool->cgminer_pool_stats);
  3146. double difficulty;
  3147. uint64_t uintdiff;
  3148. if (known)
  3149. work->work_difficulty = known;
  3150. else
  3151. work->work_difficulty = diff_from_target(work->target);
  3152. difficulty = work->work_difficulty;
  3153. pool_stats->last_diff = difficulty;
  3154. uintdiff = round(difficulty);
  3155. suffix_string(uintdiff, work->pool->diff, sizeof(work->pool->diff), 0);
  3156. if (difficulty == pool_stats->min_diff)
  3157. pool_stats->min_diff_count++;
  3158. else if (difficulty < pool_stats->min_diff || pool_stats->min_diff == 0) {
  3159. pool_stats->min_diff = difficulty;
  3160. pool_stats->min_diff_count = 1;
  3161. }
  3162. if (difficulty == pool_stats->max_diff)
  3163. pool_stats->max_diff_count++;
  3164. else if (difficulty > pool_stats->max_diff) {
  3165. pool_stats->max_diff = difficulty;
  3166. pool_stats->max_diff_count = 1;
  3167. }
  3168. }
  3169. static unsigned char bench_hidiff_bins[16][160];
  3170. static unsigned char bench_lodiff_bins[16][160];
  3171. static unsigned char bench_target[32];
  3172. /* Iterate over the lo and hi diff benchmark work items such that we find one
  3173. * diff 32+ share every 32 work items. */
  3174. static void get_benchmark_work(struct work *work)
  3175. {
  3176. work->work_difficulty = 32;
  3177. memcpy(work->target, bench_target, 32);
  3178. work->drv_rolllimit = 0;
  3179. work->mandatory = true;
  3180. work->pool = pools[0];
  3181. cgtime(&work->tv_getwork);
  3182. copy_time(&work->tv_getwork_reply, &work->tv_getwork);
  3183. work->getwork_mode = GETWORK_MODE_BENCHMARK;
  3184. }
  3185. static void benchfile_dspwork(struct work *work, uint32_t nonce)
  3186. {
  3187. char buf[1024];
  3188. uint32_t dn;
  3189. int i;
  3190. dn = 0;
  3191. for (i = 0; i < 4; i++) {
  3192. dn *= 0x100;
  3193. dn += nonce & 0xff;
  3194. nonce /= 0x100;
  3195. }
  3196. if ((sizeof(work->data) * 2 + 1) > sizeof(buf))
  3197. quithere(1, "BENCHFILE Invalid buf size");
  3198. __bin2hex(buf, work->data, sizeof(work->data));
  3199. applog(LOG_ERR, "BENCHFILE nonce %u=0x%08x for work=%s",
  3200. (unsigned int)dn, (unsigned int)dn, buf);
  3201. }
  3202. static bool benchfile_get_work(struct work *work)
  3203. {
  3204. char buf[1024];
  3205. char item[1024];
  3206. bool got = false;
  3207. if (!benchfile_in) {
  3208. if (opt_benchfile)
  3209. benchfile_in = fopen(opt_benchfile, "r");
  3210. else
  3211. quit(1, "BENCHFILE Invalid benchfile NULL");
  3212. if (!benchfile_in)
  3213. quit(1, "BENCHFILE Failed to open benchfile '%s'", opt_benchfile);
  3214. benchfile_line = 0;
  3215. if (!fgets(buf, 1024, benchfile_in))
  3216. quit(1, "BENCHFILE Failed to read benchfile '%s'", opt_benchfile);
  3217. got = true;
  3218. benchfile_work = 0;
  3219. }
  3220. if (!got) {
  3221. if (!fgets(buf, 1024, benchfile_in)) {
  3222. if (benchfile_work == 0)
  3223. quit(1, "BENCHFILE No work in benchfile '%s'", opt_benchfile);
  3224. fclose(benchfile_in);
  3225. benchfile_in = NULL;
  3226. return benchfile_get_work(work);
  3227. }
  3228. }
  3229. do {
  3230. benchfile_line++;
  3231. // Empty lines and lines starting with '#' or '/' are ignored
  3232. if (*buf != '\0' && *buf != '#' && *buf != '/') {
  3233. char *commas[BENCHWORK_COUNT];
  3234. int i, j, len;
  3235. long nonce_time;
  3236. commas[0] = buf;
  3237. for (i = 1; i < BENCHWORK_COUNT; i++) {
  3238. commas[i] = strchr(commas[i-1], ',');
  3239. if (!commas[i]) {
  3240. quit(1, "BENCHFILE Invalid input file line %d"
  3241. " - field count is %d but should be %d",
  3242. benchfile_line, i, BENCHWORK_COUNT);
  3243. }
  3244. len = commas[i] - commas[i-1];
  3245. if (benchfile_data[i-1].length &&
  3246. (len != benchfile_data[i-1].length)) {
  3247. quit(1, "BENCHFILE Invalid input file line %d "
  3248. "field %d (%s) length is %d but should be %d",
  3249. benchfile_line, i,
  3250. benchfile_data[i-1].name,
  3251. len, benchfile_data[i-1].length);
  3252. }
  3253. *(commas[i]++) = '\0';
  3254. }
  3255. // NonceTime may have LF's etc
  3256. len = strlen(commas[BENCHWORK_NONCETIME]);
  3257. if (len < benchfile_data[BENCHWORK_NONCETIME].length) {
  3258. quit(1, "BENCHFILE Invalid input file line %d field %d"
  3259. " (%s) length is %d but should be least %d",
  3260. benchfile_line, BENCHWORK_NONCETIME+1,
  3261. benchfile_data[BENCHWORK_NONCETIME].name, len,
  3262. benchfile_data[BENCHWORK_NONCETIME].length);
  3263. }
  3264. sprintf(item, "0000000%c", commas[BENCHWORK_VERSION][0]);
  3265. j = strlen(item);
  3266. for (i = benchfile_data[BENCHWORK_PREVHASH].length-8; i >= 0; i -= 8) {
  3267. sprintf(&(item[j]), "%.8s", &commas[BENCHWORK_PREVHASH][i]);
  3268. j += 8;
  3269. }
  3270. for (i = benchfile_data[BENCHWORK_MERKLEROOT].length-8; i >= 0; i -= 8) {
  3271. sprintf(&(item[j]), "%.8s", &commas[BENCHWORK_MERKLEROOT][i]);
  3272. j += 8;
  3273. }
  3274. nonce_time = atol(commas[BENCHWORK_NONCETIME]);
  3275. sprintf(&(item[j]), "%08lx", nonce_time);
  3276. j += 8;
  3277. strcpy(&(item[j]), commas[BENCHWORK_DIFFBITS]);
  3278. j += benchfile_data[BENCHWORK_DIFFBITS].length;
  3279. memset(work, 0, sizeof(*work));
  3280. hex2bin(work->data, item, j >> 1);
  3281. calc_midstate(work);
  3282. benchfile_work++;
  3283. return true;
  3284. }
  3285. } while (fgets(buf, 1024, benchfile_in));
  3286. if (benchfile_work == 0)
  3287. quit(1, "BENCHFILE No work in benchfile '%s'", opt_benchfile);
  3288. fclose(benchfile_in);
  3289. benchfile_in = NULL;
  3290. return benchfile_get_work(work);
  3291. }
  3292. static void get_benchfile_work(struct work *work)
  3293. {
  3294. benchfile_get_work(work);
  3295. work->mandatory = true;
  3296. work->pool = pools[0];
  3297. cgtime(&work->tv_getwork);
  3298. copy_time(&work->tv_getwork_reply, &work->tv_getwork);
  3299. work->getwork_mode = GETWORK_MODE_BENCHMARK;
  3300. calc_diff(work, 0);
  3301. }
  3302. #ifdef HAVE_CURSES
  3303. static void disable_curses_windows(void)
  3304. {
  3305. leaveok(logwin, false);
  3306. leaveok(statuswin, false);
  3307. leaveok(mainwin, false);
  3308. nocbreak();
  3309. echo();
  3310. delwin(logwin);
  3311. delwin(statuswin);
  3312. }
  3313. /* Force locking of curses console_lock on shutdown since a dead thread might
  3314. * have grabbed the lock. */
  3315. static bool curses_active_forcelocked(void)
  3316. {
  3317. bool ret;
  3318. mutex_trylock(&console_lock);
  3319. ret = curses_active;
  3320. if (!ret)
  3321. unlock_curses();
  3322. return ret;
  3323. }
  3324. static void disable_curses(void)
  3325. {
  3326. if (curses_active_forcelocked()) {
  3327. use_curses = false;
  3328. curses_active = false;
  3329. disable_curses_windows();
  3330. delwin(mainwin);
  3331. endwin();
  3332. #ifdef WIN32
  3333. // Move the cursor to after curses output.
  3334. HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
  3335. CONSOLE_SCREEN_BUFFER_INFO csbi;
  3336. COORD coord;
  3337. if (GetConsoleScreenBufferInfo(hout, &csbi)) {
  3338. coord.X = 0;
  3339. coord.Y = csbi.dwSize.Y - 1;
  3340. SetConsoleCursorPosition(hout, coord);
  3341. }
  3342. #endif
  3343. unlock_curses();
  3344. }
  3345. }
  3346. #endif
  3347. static void kill_timeout(struct thr_info *thr)
  3348. {
  3349. cg_completion_timeout(&thr_info_cancel, thr, 1000);
  3350. }
  3351. static void kill_mining(void)
  3352. {
  3353. struct thr_info *thr;
  3354. int i;
  3355. forcelog(LOG_DEBUG, "Killing off mining threads");
  3356. /* Kill the mining threads*/
  3357. for (i = 0; i < mining_threads; i++) {
  3358. pthread_t *pth = NULL;
  3359. thr = get_thread(i);
  3360. if (thr && PTH(thr) != 0L)
  3361. pth = &thr->pth;
  3362. thr_info_cancel(thr);
  3363. #ifndef WIN32
  3364. if (pth && *pth)
  3365. pthread_join(*pth, NULL);
  3366. #else
  3367. if (pth && pth->p)
  3368. pthread_join(*pth, NULL);
  3369. #endif
  3370. }
  3371. }
  3372. static void __kill_work(void)
  3373. {
  3374. struct thr_info *thr;
  3375. int i;
  3376. if (!successful_connect)
  3377. return;
  3378. forcelog(LOG_INFO, "Received kill message");
  3379. #ifdef USE_USBUTILS
  3380. /* Best to get rid of it first so it doesn't
  3381. * try to create any new devices */
  3382. forcelog(LOG_DEBUG, "Killing off HotPlug thread");
  3383. thr = &control_thr[hotplug_thr_id];
  3384. kill_timeout(thr);
  3385. #endif
  3386. forcelog(LOG_DEBUG, "Killing off watchpool thread");
  3387. /* Kill the watchpool thread */
  3388. thr = &control_thr[watchpool_thr_id];
  3389. kill_timeout(thr);
  3390. forcelog(LOG_DEBUG, "Killing off watchdog thread");
  3391. /* Kill the watchdog thread */
  3392. thr = &control_thr[watchdog_thr_id];
  3393. kill_timeout(thr);
  3394. forcelog(LOG_DEBUG, "Shutting down mining threads");
  3395. for (i = 0; i < mining_threads; i++) {
  3396. struct cgpu_info *cgpu;
  3397. thr = get_thread(i);
  3398. if (!thr)
  3399. continue;
  3400. cgpu = thr->cgpu;
  3401. if (!cgpu)
  3402. continue;
  3403. cgpu->shutdown = true;
  3404. }
  3405. sleep(1);
  3406. cg_completion_timeout(&kill_mining, NULL, 3000);
  3407. /* Stop the others */
  3408. forcelog(LOG_DEBUG, "Killing off API thread");
  3409. thr = &control_thr[api_thr_id];
  3410. kill_timeout(thr);
  3411. #ifdef USE_USBUTILS
  3412. /* Release USB resources in case it's a restart
  3413. * and not a QUIT */
  3414. forcelog(LOG_DEBUG, "Releasing all USB devices");
  3415. cg_completion_timeout(&usb_cleanup, NULL, 1000);
  3416. forcelog(LOG_DEBUG, "Killing off usbres thread");
  3417. thr = &control_thr[usbres_thr_id];
  3418. kill_timeout(thr);
  3419. #endif
  3420. }
  3421. /* This should be the common exit path */
  3422. void kill_work(void)
  3423. {
  3424. cg_completion_timeout(&__kill_work, NULL, 5000);
  3425. quit(0, "Shutdown signal received.");
  3426. }
  3427. static
  3428. #ifdef WIN32
  3429. const
  3430. #endif
  3431. char **initial_args;
  3432. static void clean_up(bool restarting);
  3433. void app_restart(void)
  3434. {
  3435. applog(LOG_WARNING, "Attempting to restart %s", packagename);
  3436. cg_completion_timeout(&__kill_work, NULL, 5000);
  3437. clean_up(true);
  3438. #if defined(unix) || defined(__APPLE__)
  3439. if (forkpid > 0) {
  3440. kill(forkpid, SIGTERM);
  3441. forkpid = 0;
  3442. }
  3443. #endif
  3444. execv(initial_args[0], (EXECV_2ND_ARG_TYPE)initial_args);
  3445. applog(LOG_WARNING, "Failed to restart application");
  3446. }
  3447. static void sighandler(int __maybe_unused sig)
  3448. {
  3449. /* Restore signal handlers so we can still quit if kill_work fails */
  3450. sigaction(SIGTERM, &termhandler, NULL);
  3451. sigaction(SIGINT, &inthandler, NULL);
  3452. kill_work();
  3453. }
  3454. static void _stage_work(struct work *work);
  3455. #define stage_work(WORK) do { \
  3456. _stage_work(WORK); \
  3457. WORK = NULL; \
  3458. } while (0)
  3459. #ifdef HAVE_LIBCURL
  3460. /* Called with pool_lock held. Recruit an extra curl if none are available for
  3461. * this pool. */
  3462. static void recruit_curl(struct pool *pool)
  3463. {
  3464. struct curl_ent *ce = calloc(sizeof(struct curl_ent), 1);
  3465. if (unlikely(!ce))
  3466. quit(1, "Failed to calloc in recruit_curl");
  3467. ce->curl = curl_easy_init();
  3468. if (unlikely(!ce->curl))
  3469. quit(1, "Failed to init in recruit_curl");
  3470. list_add(&ce->node, &pool->curlring);
  3471. pool->curls++;
  3472. }
  3473. /* Grab an available curl if there is one. If not, then recruit extra curls
  3474. * unless we are in a submit_fail situation, or we have opt_delaynet enabled
  3475. * and there are already 5 curls in circulation. Limit total number to the
  3476. * number of mining threads per pool as well to prevent blasting a pool during
  3477. * network delays/outages. */
  3478. static struct curl_ent *pop_curl_entry(struct pool *pool)
  3479. {
  3480. int curl_limit = opt_delaynet ? 5 : (mining_threads + opt_queue) * 2;
  3481. bool recruited = false;
  3482. struct curl_ent *ce;
  3483. mutex_lock(&pool->pool_lock);
  3484. retry:
  3485. if (!pool->curls) {
  3486. recruit_curl(pool);
  3487. recruited = true;
  3488. } else if (list_empty(&pool->curlring)) {
  3489. if (pool->curls >= curl_limit) {
  3490. pthread_cond_wait(&pool->cr_cond, &pool->pool_lock);
  3491. goto retry;
  3492. } else {
  3493. recruit_curl(pool);
  3494. recruited = true;
  3495. }
  3496. }
  3497. ce = list_entry(pool->curlring.next, struct curl_ent, node);
  3498. list_del(&ce->node);
  3499. mutex_unlock(&pool->pool_lock);
  3500. if (recruited)
  3501. applog(LOG_DEBUG, "Recruited curl for pool %d", pool->pool_no);
  3502. return ce;
  3503. }
  3504. static void push_curl_entry(struct curl_ent *ce, struct pool *pool)
  3505. {
  3506. mutex_lock(&pool->pool_lock);
  3507. list_add_tail(&ce->node, &pool->curlring);
  3508. cgtime(&ce->tv);
  3509. pthread_cond_broadcast(&pool->cr_cond);
  3510. mutex_unlock(&pool->pool_lock);
  3511. }
  3512. static bool stale_work(struct work *work, bool share);
  3513. static inline bool should_roll(struct work *work)
  3514. {
  3515. struct timeval now;
  3516. time_t expiry;
  3517. if (work->pool != current_pool() && pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE)
  3518. return false;
  3519. if (work->rolltime > opt_scantime)
  3520. expiry = work->rolltime;
  3521. else
  3522. expiry = opt_scantime;
  3523. expiry = expiry * 2 / 3;
  3524. /* We shouldn't roll if we're unlikely to get one shares' duration
  3525. * work out of doing so */
  3526. cgtime(&now);
  3527. if (now.tv_sec - work->tv_staged.tv_sec > expiry)
  3528. return false;
  3529. return true;
  3530. }
  3531. /* Limit rolls to 7000 to not beyond 2 hours in the future where bitcoind will
  3532. * reject blocks as invalid. */
  3533. static inline bool can_roll(struct work *work)
  3534. {
  3535. return (!work->stratum && work->pool && work->rolltime && !work->clone &&
  3536. work->rolls < 7000 && !stale_work(work, false));
  3537. }
  3538. /* Adjust an existing char ntime field with a relative noffset */
  3539. static void modify_ntime(char *ntime, int noffset)
  3540. {
  3541. unsigned char bin[4];
  3542. uint32_t h32, *be32 = (uint32_t *)bin;
  3543. hex2bin(bin, ntime, 4);
  3544. h32 = be32toh(*be32) + noffset;
  3545. *be32 = htobe32(h32);
  3546. __bin2hex(ntime, bin, 4);
  3547. }
  3548. void roll_work(struct work *work)
  3549. {
  3550. uint32_t *work_ntime;
  3551. uint32_t ntime;
  3552. work_ntime = (uint32_t *)(work->data + 68);
  3553. ntime = be32toh(*work_ntime);
  3554. ntime++;
  3555. *work_ntime = htobe32(ntime);
  3556. local_work++;
  3557. work->rolls++;
  3558. work->nonce = 0;
  3559. applog(LOG_DEBUG, "Successfully rolled work");
  3560. /* Change the ntime field if this is stratum work */
  3561. if (work->ntime)
  3562. modify_ntime(work->ntime, 1);
  3563. /* This is now a different work item so it needs a different ID for the
  3564. * hashtable */
  3565. work->id = total_work_inc();
  3566. }
  3567. static void *submit_work_thread(void *userdata)
  3568. {
  3569. struct work *work = (struct work *)userdata;
  3570. struct pool *pool = work->pool;
  3571. bool resubmit = false;
  3572. struct curl_ent *ce;
  3573. pthread_detach(pthread_self());
  3574. RenameThread("SubmitWork");
  3575. applog(LOG_DEBUG, "Creating extra submit work thread");
  3576. ce = pop_curl_entry(pool);
  3577. /* submit solution to bitcoin via JSON-RPC */
  3578. while (!submit_upstream_work(work, ce->curl, resubmit)) {
  3579. if (opt_lowmem) {
  3580. applog(LOG_NOTICE, "Pool %d share being discarded to minimise memory cache", pool->pool_no);
  3581. break;
  3582. }
  3583. resubmit = true;
  3584. if (stale_work(work, true)) {
  3585. applog(LOG_NOTICE, "Pool %d share became stale while retrying submit, discarding", pool->pool_no);
  3586. mutex_lock(&stats_lock);
  3587. total_stale++;
  3588. pool->stale_shares++;
  3589. total_diff_stale += work->work_difficulty;
  3590. pool->diff_stale += work->work_difficulty;
  3591. mutex_unlock(&stats_lock);
  3592. free_work(work);
  3593. break;
  3594. }
  3595. /* pause, then restart work-request loop */
  3596. applog(LOG_INFO, "json_rpc_call failed on submit_work, retrying");
  3597. }
  3598. push_curl_entry(ce, pool);
  3599. return NULL;
  3600. }
  3601. struct work *make_clone(struct work *work)
  3602. {
  3603. struct work *work_clone = copy_work(work);
  3604. work_clone->clone = true;
  3605. cgtime((struct timeval *)&(work_clone->tv_cloned));
  3606. work_clone->longpoll = false;
  3607. work_clone->mandatory = false;
  3608. /* Make cloned work appear slightly older to bias towards keeping the
  3609. * master work item which can be further rolled */
  3610. work_clone->tv_staged.tv_sec -= 1;
  3611. return work_clone;
  3612. }
  3613. static bool clone_available(void)
  3614. {
  3615. struct work *work_clone = NULL, *work, *tmp;
  3616. bool cloned = false;
  3617. mutex_lock(stgd_lock);
  3618. if (!staged_rollable)
  3619. goto out_unlock;
  3620. HASH_ITER(hh, staged_work, work, tmp) {
  3621. if (can_roll(work) && should_roll(work)) {
  3622. roll_work(work);
  3623. work_clone = make_clone(work);
  3624. roll_work(work);
  3625. cloned = true;
  3626. break;
  3627. }
  3628. }
  3629. out_unlock:
  3630. mutex_unlock(stgd_lock);
  3631. if (cloned) {
  3632. applog(LOG_DEBUG, "Pushing cloned available work to stage thread");
  3633. stage_work(work_clone);
  3634. }
  3635. return cloned;
  3636. }
  3637. /* Clones work by rolling it if possible, and returning a clone instead of the
  3638. * original work item which gets staged again to possibly be rolled again in
  3639. * the future */
  3640. static struct work *clone_work(struct work *work)
  3641. {
  3642. int mrs = mining_threads + opt_queue - total_staged();
  3643. struct work *work_clone;
  3644. bool cloned;
  3645. if (mrs < 1)
  3646. return work;
  3647. cloned = false;
  3648. work_clone = make_clone(work);
  3649. while (mrs-- > 0 && can_roll(work) && should_roll(work)) {
  3650. applog(LOG_DEBUG, "Pushing rolled converted work to stage thread");
  3651. stage_work(work_clone);
  3652. roll_work(work);
  3653. work_clone = make_clone(work);
  3654. /* Roll it again to prevent duplicates should this be used
  3655. * directly later on */
  3656. roll_work(work);
  3657. cloned = true;
  3658. }
  3659. if (cloned) {
  3660. stage_work(work);
  3661. return work_clone;
  3662. }
  3663. free_work(work_clone);
  3664. return work;
  3665. }
  3666. #else /* HAVE_LIBCURL */
  3667. static void *submit_work_thread(void __maybe_unused *userdata)
  3668. {
  3669. pthread_detach(pthread_self());
  3670. return NULL;
  3671. }
  3672. #endif /* HAVE_LIBCURL */
  3673. /* Return an adjusted ntime if we're submitting work that a device has
  3674. * internally offset the ntime. */
  3675. static char *offset_ntime(const char *ntime, int noffset)
  3676. {
  3677. unsigned char bin[4];
  3678. uint32_t h32, *be32 = (uint32_t *)bin;
  3679. hex2bin(bin, ntime, 4);
  3680. h32 = be32toh(*be32) + noffset;
  3681. *be32 = htobe32(h32);
  3682. return bin2hex(bin, 4);
  3683. }
  3684. /* Duplicates any dynamically allocated arrays within the work struct to
  3685. * prevent a copied work struct from freeing ram belonging to another struct */
  3686. static void _copy_work(struct work *work, const struct work *base_work, int noffset)
  3687. {
  3688. uint32_t id = work->id;
  3689. clean_work(work);
  3690. memcpy(work, base_work, sizeof(struct work));
  3691. /* Keep the unique new id assigned during make_work to prevent copied
  3692. * work from having the same id. */
  3693. work->id = id;
  3694. if (base_work->job_id)
  3695. work->job_id = strdup(base_work->job_id);
  3696. if (base_work->nonce1)
  3697. work->nonce1 = strdup(base_work->nonce1);
  3698. if (base_work->ntime) {
  3699. /* If we are passed an noffset the binary work->data ntime and
  3700. * the work->ntime hex string need to be adjusted. */
  3701. if (noffset) {
  3702. uint32_t *work_ntime = (uint32_t *)(work->data + 68);
  3703. uint32_t ntime = be32toh(*work_ntime);
  3704. ntime += noffset;
  3705. *work_ntime = htobe32(ntime);
  3706. work->ntime = offset_ntime(base_work->ntime, noffset);
  3707. } else
  3708. work->ntime = strdup(base_work->ntime);
  3709. } else if (noffset) {
  3710. uint32_t *work_ntime = (uint32_t *)(work->data + 68);
  3711. uint32_t ntime = be32toh(*work_ntime);
  3712. ntime += noffset;
  3713. *work_ntime = htobe32(ntime);
  3714. }
  3715. if (base_work->coinbase)
  3716. work->coinbase = strdup(base_work->coinbase);
  3717. }
  3718. void set_work_ntime(struct work *work, int ntime)
  3719. {
  3720. uint32_t *work_ntime = (uint32_t *)(work->data + 68);
  3721. *work_ntime = htobe32(ntime);
  3722. if (work->ntime) {
  3723. free(work->ntime);
  3724. work->ntime = bin2hex((unsigned char *)work_ntime, 4);
  3725. }
  3726. }
  3727. /* Generates a copy of an existing work struct, creating fresh heap allocations
  3728. * for all dynamically allocated arrays within the struct. noffset is used for
  3729. * when a driver has internally rolled the ntime, noffset is a relative value.
  3730. * The macro copy_work() calls this function with an noffset of 0. */
  3731. struct work *copy_work_noffset(struct work *base_work, int noffset)
  3732. {
  3733. struct work *work = make_work();
  3734. _copy_work(work, base_work, noffset);
  3735. return work;
  3736. }
  3737. void pool_failed(struct pool *pool)
  3738. {
  3739. if (!pool_tset(pool, &pool->idle)) {
  3740. cgtime(&pool->tv_idle);
  3741. if (pool == current_pool()) {
  3742. switch_pools(NULL);
  3743. }
  3744. }
  3745. }
  3746. static void pool_died(struct pool *pool)
  3747. {
  3748. if (!pool_tset(pool, &pool->idle)) {
  3749. cgtime(&pool->tv_idle);
  3750. if (pool == current_pool()) {
  3751. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  3752. switch_pools(NULL);
  3753. } else
  3754. applog(LOG_INFO, "Pool %d %s failed to return work", pool->pool_no, pool->rpc_url);
  3755. }
  3756. }
  3757. static bool stale_work(struct work *work, bool share)
  3758. {
  3759. struct timeval now;
  3760. time_t work_expiry;
  3761. struct pool *pool;
  3762. int getwork_delay;
  3763. if (opt_benchmark || opt_benchfile)
  3764. return false;
  3765. if (work->work_block != work_block) {
  3766. applog(LOG_DEBUG, "Work stale due to block mismatch");
  3767. return true;
  3768. }
  3769. /* Technically the rolltime should be correct but some pools
  3770. * advertise a broken expire= that is lower than a meaningful
  3771. * scantime */
  3772. if (work->rolltime > opt_scantime)
  3773. work_expiry = work->rolltime;
  3774. else
  3775. work_expiry = opt_expiry;
  3776. pool = work->pool;
  3777. if (!share && pool->has_stratum) {
  3778. bool same_job;
  3779. if (!pool->stratum_active || !pool->stratum_notify) {
  3780. applog(LOG_DEBUG, "Work stale due to stratum inactive");
  3781. return true;
  3782. }
  3783. same_job = true;
  3784. cg_rlock(&pool->data_lock);
  3785. if (strcmp(work->job_id, pool->swork.job_id))
  3786. same_job = false;
  3787. cg_runlock(&pool->data_lock);
  3788. if (!same_job) {
  3789. applog(LOG_DEBUG, "Work stale due to stratum job_id mismatch");
  3790. return true;
  3791. }
  3792. }
  3793. /* Factor in the average getwork delay of this pool, rounding it up to
  3794. * the nearest second */
  3795. getwork_delay = pool->cgminer_pool_stats.getwork_wait_rolling * 5 + 1;
  3796. work_expiry -= getwork_delay;
  3797. if (unlikely(work_expiry < 5))
  3798. work_expiry = 5;
  3799. cgtime(&now);
  3800. if ((now.tv_sec - work->tv_staged.tv_sec) >= work_expiry) {
  3801. applog(LOG_DEBUG, "Work stale due to expiry");
  3802. return true;
  3803. }
  3804. if (opt_fail_only && !share && pool != current_pool() && !work->mandatory &&
  3805. pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  3806. applog(LOG_DEBUG, "Work stale due to fail only pool mismatch");
  3807. return true;
  3808. }
  3809. return false;
  3810. }
  3811. uint64_t share_diff(const struct work *work)
  3812. {
  3813. bool new_best = false;
  3814. double d64, s64;
  3815. uint64_t ret;
  3816. d64 = truediffone;
  3817. if (opt_scrypt)
  3818. d64 *= (double)65536;
  3819. s64 = le256todouble(work->hash);
  3820. if (unlikely(!s64))
  3821. s64 = 0;
  3822. ret = round(d64 / s64);
  3823. cg_wlock(&control_lock);
  3824. if (unlikely(ret > best_diff)) {
  3825. new_best = true;
  3826. best_diff = ret;
  3827. suffix_string(best_diff, best_share, sizeof(best_share), 0);
  3828. }
  3829. if (unlikely(ret > work->pool->best_diff))
  3830. work->pool->best_diff = ret;
  3831. cg_wunlock(&control_lock);
  3832. if (unlikely(new_best))
  3833. applog(LOG_INFO, "New best share: %s", best_share);
  3834. return ret;
  3835. }
  3836. static void regen_hash(struct work *work)
  3837. {
  3838. uint32_t *data32 = (uint32_t *)(work->data);
  3839. unsigned char swap[80];
  3840. uint32_t *swap32 = (uint32_t *)swap;
  3841. unsigned char hash1[32];
  3842. flip80(swap32, data32);
  3843. sha256(swap, 80, hash1);
  3844. sha256(hash1, 32, (unsigned char *)(work->hash));
  3845. }
  3846. static void rebuild_hash(struct work *work)
  3847. {
  3848. if (opt_scrypt)
  3849. scrypt_regenhash(work);
  3850. else
  3851. regen_hash(work);
  3852. }
  3853. static bool cnx_needed(struct pool *pool);
  3854. /* Find the pool that currently has the highest priority */
  3855. static struct pool *priority_pool(int choice)
  3856. {
  3857. struct pool *ret = NULL;
  3858. int i;
  3859. for (i = 0; i < total_pools; i++) {
  3860. struct pool *pool = pools[i];
  3861. if (pool->prio == choice) {
  3862. ret = pool;
  3863. break;
  3864. }
  3865. }
  3866. if (unlikely(!ret)) {
  3867. applog(LOG_ERR, "WTF No pool %d found!", choice);
  3868. return pools[choice];
  3869. }
  3870. return ret;
  3871. }
  3872. /* Specifies whether we can switch to this pool or not. */
  3873. static bool pool_unusable(struct pool *pool)
  3874. {
  3875. if (pool->idle)
  3876. return true;
  3877. if (pool->enabled != POOL_ENABLED)
  3878. return true;
  3879. return false;
  3880. }
  3881. void switch_pools(struct pool *selected)
  3882. {
  3883. struct pool *pool, *last_pool;
  3884. int i, pool_no, next_pool;
  3885. cg_wlock(&control_lock);
  3886. last_pool = currentpool;
  3887. pool_no = currentpool->pool_no;
  3888. /* Switch selected to pool number 0 and move the rest down */
  3889. if (selected) {
  3890. if (selected->prio != 0) {
  3891. for (i = 0; i < total_pools; i++) {
  3892. pool = pools[i];
  3893. if (pool->prio < selected->prio)
  3894. pool->prio++;
  3895. }
  3896. selected->prio = 0;
  3897. }
  3898. }
  3899. switch (pool_strategy) {
  3900. /* All of these set to the master pool */
  3901. case POOL_BALANCE:
  3902. case POOL_FAILOVER:
  3903. case POOL_LOADBALANCE:
  3904. for (i = 0; i < total_pools; i++) {
  3905. pool = priority_pool(i);
  3906. if (pool_unusable(pool))
  3907. continue;
  3908. pool_no = pool->pool_no;
  3909. break;
  3910. }
  3911. break;
  3912. /* Both of these simply increment and cycle */
  3913. case POOL_ROUNDROBIN:
  3914. case POOL_ROTATE:
  3915. if (selected && !selected->idle) {
  3916. pool_no = selected->pool_no;
  3917. break;
  3918. }
  3919. next_pool = pool_no;
  3920. /* Select the next alive pool */
  3921. for (i = 1; i < total_pools; i++) {
  3922. next_pool++;
  3923. if (next_pool >= total_pools)
  3924. next_pool = 0;
  3925. pool = pools[next_pool];
  3926. if (pool_unusable(pool))
  3927. continue;
  3928. pool_no = next_pool;
  3929. break;
  3930. }
  3931. break;
  3932. default:
  3933. break;
  3934. }
  3935. currentpool = pools[pool_no];
  3936. pool = currentpool;
  3937. cg_wunlock(&control_lock);
  3938. /* Set the lagging flag to avoid pool not providing work fast enough
  3939. * messages in failover only mode since we have to get all fresh work
  3940. * as in restart_threads */
  3941. if (opt_fail_only)
  3942. pool_tset(pool, &pool->lagging);
  3943. if (pool != last_pool && pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  3944. applog(LOG_WARNING, "Switching to pool %d %s", pool->pool_no, pool->rpc_url);
  3945. if (pool_localgen(pool) || opt_fail_only)
  3946. clear_pool_work(last_pool);
  3947. }
  3948. mutex_lock(&lp_lock);
  3949. pthread_cond_broadcast(&lp_cond);
  3950. mutex_unlock(&lp_lock);
  3951. }
  3952. void _discard_work(struct work *work)
  3953. {
  3954. if (!work->clone && !work->rolls && !work->mined) {
  3955. if (work->pool) {
  3956. work->pool->discarded_work++;
  3957. work->pool->quota_used--;
  3958. work->pool->works--;
  3959. }
  3960. total_discarded++;
  3961. applog(LOG_DEBUG, "Discarded work");
  3962. } else
  3963. applog(LOG_DEBUG, "Discarded cloned or rolled work");
  3964. free_work(work);
  3965. }
  3966. static void wake_gws(void)
  3967. {
  3968. mutex_lock(stgd_lock);
  3969. pthread_cond_signal(&gws_cond);
  3970. mutex_unlock(stgd_lock);
  3971. }
  3972. static void discard_stale(void)
  3973. {
  3974. struct work *work, *tmp;
  3975. int stale = 0;
  3976. mutex_lock(stgd_lock);
  3977. HASH_ITER(hh, staged_work, work, tmp) {
  3978. if (stale_work(work, false)) {
  3979. HASH_DEL(staged_work, work);
  3980. discard_work(work);
  3981. stale++;
  3982. }
  3983. }
  3984. pthread_cond_signal(&gws_cond);
  3985. mutex_unlock(stgd_lock);
  3986. if (stale)
  3987. applog(LOG_DEBUG, "Discarded %d stales that didn't match current hash", stale);
  3988. }
  3989. /* A generic wait function for threads that poll that will wait a specified
  3990. * time tdiff waiting on the pthread conditional that is broadcast when a
  3991. * work restart is required. Returns the value of pthread_cond_timedwait
  3992. * which is zero if the condition was met or ETIMEDOUT if not.
  3993. */
  3994. int restart_wait(struct thr_info *thr, unsigned int mstime)
  3995. {
  3996. struct timeval now, then, tdiff;
  3997. struct timespec abstime;
  3998. int rc;
  3999. tdiff.tv_sec = mstime / 1000;
  4000. tdiff.tv_usec = mstime * 1000 - (tdiff.tv_sec * 1000000);
  4001. cgtime(&now);
  4002. timeradd(&now, &tdiff, &then);
  4003. abstime.tv_sec = then.tv_sec;
  4004. abstime.tv_nsec = then.tv_usec * 1000;
  4005. mutex_lock(&restart_lock);
  4006. if (thr->work_restart)
  4007. rc = 0;
  4008. else
  4009. rc = pthread_cond_timedwait(&restart_cond, &restart_lock, &abstime);
  4010. mutex_unlock(&restart_lock);
  4011. return rc;
  4012. }
  4013. static void *restart_thread(void __maybe_unused *arg)
  4014. {
  4015. struct pool *cp = current_pool();
  4016. struct cgpu_info *cgpu;
  4017. int i, mt;
  4018. pthread_detach(pthread_self());
  4019. /* Artificially set the lagging flag to avoid pool not providing work
  4020. * fast enough messages after every long poll */
  4021. pool_tset(cp, &cp->lagging);
  4022. /* Discard staged work that is now stale */
  4023. discard_stale();
  4024. rd_lock(&mining_thr_lock);
  4025. mt = mining_threads;
  4026. rd_unlock(&mining_thr_lock);
  4027. for (i = 0; i < mt; i++) {
  4028. cgpu = mining_thr[i]->cgpu;
  4029. if (unlikely(!cgpu))
  4030. continue;
  4031. if (cgpu->deven != DEV_ENABLED)
  4032. continue;
  4033. mining_thr[i]->work_restart = true;
  4034. flush_queue(cgpu);
  4035. cgpu->drv->flush_work(cgpu);
  4036. }
  4037. mutex_lock(&restart_lock);
  4038. pthread_cond_broadcast(&restart_cond);
  4039. mutex_unlock(&restart_lock);
  4040. #ifdef USE_USBUTILS
  4041. /* Cancels any cancellable usb transfers. Flagged as such it means they
  4042. * are usualy waiting on a read result and it's safe to abort the read
  4043. * early. */
  4044. cancel_usb_transfers();
  4045. #endif
  4046. return NULL;
  4047. }
  4048. /* In order to prevent a deadlock via the various drv->flush_work
  4049. * implementations we send the restart messages via a separate thread. */
  4050. static void restart_threads(void)
  4051. {
  4052. pthread_t rthread;
  4053. cgtime(&restart_tv_start);
  4054. if (unlikely(pthread_create(&rthread, NULL, restart_thread, NULL)))
  4055. quit(1, "Failed to create restart thread");
  4056. }
  4057. static void signal_work_update(void)
  4058. {
  4059. int i;
  4060. applog(LOG_INFO, "Work update message received");
  4061. cgtime(&update_tv_start);
  4062. rd_lock(&mining_thr_lock);
  4063. for (i = 0; i < mining_threads; i++)
  4064. mining_thr[i]->work_update = true;
  4065. rd_unlock(&mining_thr_lock);
  4066. }
  4067. static void set_curblock(char *hexstr, unsigned char *bedata)
  4068. {
  4069. int ofs;
  4070. cg_wlock(&ch_lock);
  4071. cgtime(&block_timeval);
  4072. strcpy(current_hash, hexstr);
  4073. memcpy(current_block, bedata, 32);
  4074. get_timestamp(blocktime, sizeof(blocktime), &block_timeval);
  4075. cg_wunlock(&ch_lock);
  4076. for (ofs = 0; ofs <= 56; ofs++) {
  4077. if (memcmp(&current_hash[ofs], "0", 1))
  4078. break;
  4079. }
  4080. strncpy(prev_block, &current_hash[ofs], 8);
  4081. prev_block[8] = '\0';
  4082. applog(LOG_INFO, "New block: %s... diff %s", current_hash, block_diff);
  4083. }
  4084. /* Search to see if this string is from a block that has been seen before */
  4085. static bool block_exists(char *hexstr)
  4086. {
  4087. struct block *s;
  4088. rd_lock(&blk_lock);
  4089. HASH_FIND_STR(blocks, hexstr, s);
  4090. rd_unlock(&blk_lock);
  4091. if (s)
  4092. return true;
  4093. return false;
  4094. }
  4095. /* Tests if this work is from a block that has been seen before */
  4096. static inline bool from_existing_block(struct work *work)
  4097. {
  4098. char *hexstr = bin2hex(work->data + 8, 18);
  4099. bool ret;
  4100. ret = block_exists(hexstr);
  4101. free(hexstr);
  4102. return ret;
  4103. }
  4104. static int block_sort(struct block *blocka, struct block *blockb)
  4105. {
  4106. return blocka->block_no - blockb->block_no;
  4107. }
  4108. /* Decode the current block difficulty which is in packed form */
  4109. static void set_blockdiff(const struct work *work)
  4110. {
  4111. uint8_t pow = work->data[72];
  4112. int powdiff = (8 * (0x1d - 3)) - (8 * (pow - 3));
  4113. uint32_t diff32 = be32toh(*((uint32_t *)(work->data + 72))) & 0x00FFFFFF;
  4114. double numerator = 0xFFFFULL << powdiff;
  4115. double ddiff = numerator / (double)diff32;
  4116. if (unlikely(current_diff != ddiff)) {
  4117. suffix_string(ddiff, block_diff, sizeof(block_diff), 0);
  4118. current_diff = ddiff;
  4119. applog(LOG_NOTICE, "Network diff set to %s", block_diff);
  4120. }
  4121. }
  4122. static bool test_work_current(struct work *work)
  4123. {
  4124. struct pool *pool = work->pool;
  4125. unsigned char bedata[32];
  4126. char hexstr[68];
  4127. bool ret = true;
  4128. if (work->mandatory)
  4129. return ret;
  4130. swap256(bedata, work->data + 4);
  4131. __bin2hex(hexstr, bedata, 32);
  4132. /* Search to see if this block exists yet and if not, consider it a
  4133. * new block and set the current block details to this one */
  4134. if (!block_exists(hexstr)) {
  4135. struct block *s = calloc(sizeof(struct block), 1);
  4136. int deleted_block = 0;
  4137. if (unlikely(!s))
  4138. quit (1, "test_work_current OOM");
  4139. strcpy(s->hash, hexstr);
  4140. s->block_no = new_blocks++;
  4141. wr_lock(&blk_lock);
  4142. /* Only keep the last hour's worth of blocks in memory since
  4143. * work from blocks before this is virtually impossible and we
  4144. * want to prevent memory usage from continually rising */
  4145. if (HASH_COUNT(blocks) > 6) {
  4146. struct block *oldblock;
  4147. HASH_SORT(blocks, block_sort);
  4148. oldblock = blocks;
  4149. deleted_block = oldblock->block_no;
  4150. HASH_DEL(blocks, oldblock);
  4151. free(oldblock);
  4152. }
  4153. HASH_ADD_STR(blocks, hash, s);
  4154. set_blockdiff(work);
  4155. wr_unlock(&blk_lock);
  4156. if (deleted_block)
  4157. applog(LOG_DEBUG, "Deleted block %d from database", deleted_block);
  4158. set_curblock(hexstr, bedata);
  4159. /* Copy the information to this pool's prev_block since it
  4160. * knows the new block exists. */
  4161. memcpy(pool->prev_block, bedata, 32);
  4162. if (unlikely(new_blocks == 1)) {
  4163. ret = false;
  4164. goto out;
  4165. }
  4166. work->work_block = ++work_block;
  4167. if (work->longpoll) {
  4168. if (work->stratum) {
  4169. applog(LOG_NOTICE, "Stratum from pool %d detected new block",
  4170. pool->pool_no);
  4171. } else {
  4172. applog(LOG_NOTICE, "%sLONGPOLL from pool %d detected new block",
  4173. work->gbt ? "GBT " : "", work->pool->pool_no);
  4174. }
  4175. } else if (have_longpoll && !pool->gbt_solo)
  4176. applog(LOG_NOTICE, "New block detected on network before pool notification");
  4177. else if (!pool->gbt_solo)
  4178. applog(LOG_NOTICE, "New block detected on network");
  4179. restart_threads();
  4180. } else {
  4181. if (memcmp(pool->prev_block, bedata, 32)) {
  4182. /* Work doesn't match what this pool has stored as
  4183. * prev_block. Let's see if the work is from an old
  4184. * block or the pool is just learning about a new
  4185. * block. */
  4186. if (memcmp(bedata, current_block, 32)) {
  4187. /* Doesn't match current block. It's stale */
  4188. applog(LOG_DEBUG, "Stale data from pool %d", pool->pool_no);
  4189. ret = false;
  4190. } else {
  4191. /* Work is from new block and pool is up now
  4192. * current. */
  4193. applog(LOG_INFO, "Pool %d now up to date", pool->pool_no);
  4194. memcpy(pool->prev_block, bedata, 32);
  4195. }
  4196. }
  4197. #if 0
  4198. /* This isn't ideal, this pool is still on an old block but
  4199. * accepting shares from it. To maintain fair work distribution
  4200. * we work on it anyway. */
  4201. if (memcmp(bedata, current_block, 32))
  4202. applog(LOG_DEBUG, "Pool %d still on old block", pool->pool_no);
  4203. #endif
  4204. if (work->longpoll) {
  4205. work->work_block = ++work_block;
  4206. if (shared_strategy() || work->pool == current_pool()) {
  4207. if (work->stratum) {
  4208. applog(LOG_NOTICE, "Stratum from pool %d requested work restart",
  4209. pool->pool_no);
  4210. } else {
  4211. applog(LOG_NOTICE, "%sLONGPOLL from pool %d requested work restart",
  4212. work->gbt ? "GBT " : "", work->pool->pool_no);
  4213. }
  4214. restart_threads();
  4215. }
  4216. }
  4217. }
  4218. out:
  4219. work->longpoll = false;
  4220. return ret;
  4221. }
  4222. static int tv_sort(struct work *worka, struct work *workb)
  4223. {
  4224. return worka->tv_staged.tv_sec - workb->tv_staged.tv_sec;
  4225. }
  4226. static bool work_rollable(struct work *work)
  4227. {
  4228. return (!work->clone && work->rolltime);
  4229. }
  4230. static bool hash_push(struct work *work)
  4231. {
  4232. bool rc = true;
  4233. mutex_lock(stgd_lock);
  4234. if (work_rollable(work))
  4235. staged_rollable++;
  4236. if (likely(!getq->frozen)) {
  4237. HASH_ADD_INT(staged_work, id, work);
  4238. HASH_SORT(staged_work, tv_sort);
  4239. } else
  4240. rc = false;
  4241. pthread_cond_broadcast(&getq->cond);
  4242. mutex_unlock(stgd_lock);
  4243. return rc;
  4244. }
  4245. static void _stage_work(struct work *work)
  4246. {
  4247. applog(LOG_DEBUG, "Pushing work from pool %d to hash queue", work->pool->pool_no);
  4248. work->work_block = work_block;
  4249. test_work_current(work);
  4250. work->pool->works++;
  4251. hash_push(work);
  4252. }
  4253. #ifdef HAVE_CURSES
  4254. int curses_int(const char *query)
  4255. {
  4256. int ret;
  4257. char *cvar;
  4258. cvar = curses_input(query);
  4259. ret = atoi(cvar);
  4260. free(cvar);
  4261. return ret;
  4262. }
  4263. #endif
  4264. #ifdef HAVE_CURSES
  4265. static bool input_pool(bool live);
  4266. #endif
  4267. #ifdef HAVE_CURSES
  4268. static void display_pool_summary(struct pool *pool)
  4269. {
  4270. double efficiency = 0.0;
  4271. if (curses_active_locked()) {
  4272. wlog("Pool: %s\n", pool->rpc_url);
  4273. if (pool->solved)
  4274. wlog("SOLVED %d BLOCK%s!\n", pool->solved, pool->solved > 1 ? "S" : "");
  4275. if (!pool->has_stratum)
  4276. wlog("%s own long-poll support\n", pool->hdr_path ? "Has" : "Does not have");
  4277. wlog(" Queued work requests: %d\n", pool->getwork_requested);
  4278. wlog(" Share submissions: %"PRId64"\n", pool->accepted + pool->rejected);
  4279. wlog(" Accepted shares: %"PRId64"\n", pool->accepted);
  4280. wlog(" Rejected shares: %"PRId64"\n", pool->rejected);
  4281. wlog(" Accepted difficulty shares: %1.f\n", pool->diff_accepted);
  4282. wlog(" Rejected difficulty shares: %1.f\n", pool->diff_rejected);
  4283. if (pool->accepted || pool->rejected)
  4284. wlog(" Reject ratio: %.1f%%\n", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  4285. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  4286. if (!pool_localgen(pool))
  4287. wlog(" Efficiency (accepted / queued): %.0f%%\n", efficiency);
  4288. wlog(" Items worked on: %d\n", pool->works);
  4289. wlog(" Discarded work due to new blocks: %d\n", pool->discarded_work);
  4290. wlog(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  4291. wlog(" Unable to get work from server occasions: %d\n", pool->getfail_occasions);
  4292. wlog(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  4293. unlock_curses();
  4294. }
  4295. }
  4296. #endif
  4297. /* We can't remove the memory used for this struct pool because there may
  4298. * still be work referencing it. We just remove it from the pools list */
  4299. void remove_pool(struct pool *pool)
  4300. {
  4301. int i, last_pool = total_pools - 1;
  4302. struct pool *other;
  4303. /* Boost priority of any lower prio than this one */
  4304. for (i = 0; i < total_pools; i++) {
  4305. other = pools[i];
  4306. if (other->prio > pool->prio)
  4307. other->prio--;
  4308. }
  4309. if (pool->pool_no < last_pool) {
  4310. /* Swap the last pool for this one */
  4311. (pools[last_pool])->pool_no = pool->pool_no;
  4312. pools[pool->pool_no] = pools[last_pool];
  4313. }
  4314. /* Give it an invalid number */
  4315. pool->pool_no = total_pools;
  4316. pool->removed = true;
  4317. total_pools--;
  4318. }
  4319. /* add a mutex if this needs to be thread safe in the future */
  4320. static struct JE {
  4321. char *buf;
  4322. struct JE *next;
  4323. } *jedata = NULL;
  4324. static void json_escape_free()
  4325. {
  4326. struct JE *jeptr = jedata;
  4327. struct JE *jenext;
  4328. jedata = NULL;
  4329. while (jeptr) {
  4330. jenext = jeptr->next;
  4331. free(jeptr->buf);
  4332. free(jeptr);
  4333. jeptr = jenext;
  4334. }
  4335. }
  4336. static char *json_escape(char *str)
  4337. {
  4338. struct JE *jeptr;
  4339. char *buf, *ptr;
  4340. /* 2x is the max, may as well just allocate that */
  4341. ptr = buf = malloc(strlen(str) * 2 + 1);
  4342. jeptr = malloc(sizeof(*jeptr));
  4343. jeptr->buf = buf;
  4344. jeptr->next = jedata;
  4345. jedata = jeptr;
  4346. while (*str) {
  4347. if (*str == '\\' || *str == '"')
  4348. *(ptr++) = '\\';
  4349. *(ptr++) = *(str++);
  4350. }
  4351. *ptr = '\0';
  4352. return buf;
  4353. }
  4354. void write_config(FILE *fcfg)
  4355. {
  4356. struct opt_table *opt;
  4357. int i;
  4358. /* Write pool values */
  4359. fputs("{\n\"pools\" : [", fcfg);
  4360. for(i = 0; i < total_pools; i++) {
  4361. struct pool *pool = pools[i];
  4362. if (pool->quota != 1) {
  4363. fprintf(fcfg, "%s\n\t{\n\t\t\"quota\" : \"%s%s%s%d;%s\",", i > 0 ? "," : "",
  4364. pool->rpc_proxy ? json_escape((char *)proxytype(pool->rpc_proxytype)) : "",
  4365. pool->rpc_proxy ? json_escape(pool->rpc_proxy) : "",
  4366. pool->rpc_proxy ? "|" : "",
  4367. pool->quota,
  4368. json_escape(pool->rpc_url));
  4369. } else {
  4370. fprintf(fcfg, "%s\n\t{\n\t\t\"url\" : \"%s%s%s%s\",", i > 0 ? "," : "",
  4371. pool->rpc_proxy ? json_escape((char *)proxytype(pool->rpc_proxytype)) : "",
  4372. pool->rpc_proxy ? json_escape(pool->rpc_proxy) : "",
  4373. pool->rpc_proxy ? "|" : "",
  4374. json_escape(pool->rpc_url));
  4375. }
  4376. fprintf(fcfg, "\n\t\t\"user\" : \"%s\",", json_escape(pool->rpc_user));
  4377. fprintf(fcfg, "\n\t\t\"pass\" : \"%s\"\n\t}", json_escape(pool->rpc_pass));
  4378. }
  4379. fputs("\n]\n", fcfg);
  4380. /* Simple bool,int and char options */
  4381. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  4382. char *p, *name = strdup(opt->names);
  4383. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  4384. if (p[1] != '-')
  4385. continue;
  4386. if (opt->desc == opt_hidden)
  4387. continue;
  4388. if (opt->type & OPT_NOARG &&
  4389. ((void *)opt->cb == (void *)opt_set_bool || (void *)opt->cb == (void *)opt_set_invbool) &&
  4390. (*(bool *)opt->u.arg == ((void *)opt->cb == (void *)opt_set_bool))) {
  4391. fprintf(fcfg, ",\n\"%s\" : true", p+2);
  4392. continue;
  4393. }
  4394. if (opt->type & OPT_HASARG &&
  4395. ((void *)opt->cb_arg == (void *)opt_set_intval ||
  4396. (void *)opt->cb_arg == (void *)set_int_0_to_9999 ||
  4397. (void *)opt->cb_arg == (void *)set_int_1_to_65535 ||
  4398. (void *)opt->cb_arg == (void *)set_int_0_to_10 ||
  4399. (void *)opt->cb_arg == (void *)set_int_1_to_10 ||
  4400. (void *)opt->cb_arg == (void *)set_int_0_to_100 ||
  4401. (void *)opt->cb_arg == (void *)set_int_0_to_255 ||
  4402. (void *)opt->cb_arg == (void *)set_int_0_to_200 ||
  4403. (void *)opt->cb_arg == (void *)set_int_32_to_63 ||
  4404. (void *)opt->cb_arg == (void *)set_int_1_to_1024)) {
  4405. fprintf(fcfg, ",\n\"%s\" : \"%d\"", p+2, *(int *)opt->u.arg);
  4406. continue;
  4407. }
  4408. if (opt->type & OPT_HASARG &&
  4409. ((void *)opt->cb_arg == (void *)set_float_125_to_500)) {
  4410. fprintf(fcfg, ",\n\"%s\" : \"%.1f\"", p+2, *(float *)opt->u.arg);
  4411. continue;
  4412. }
  4413. if (opt->type & (OPT_HASARG | OPT_PROCESSARG) &&
  4414. (opt->u.arg != &opt_set_null)) {
  4415. char *carg = *(char **)opt->u.arg;
  4416. if (carg)
  4417. fprintf(fcfg, ",\n\"%s\" : \"%s\"", p+2, json_escape(carg));
  4418. continue;
  4419. }
  4420. }
  4421. free(name);
  4422. }
  4423. /* Special case options */
  4424. if (pool_strategy == POOL_BALANCE)
  4425. fputs(",\n\"balance\" : true", fcfg);
  4426. if (pool_strategy == POOL_LOADBALANCE)
  4427. fputs(",\n\"load-balance\" : true", fcfg);
  4428. if (pool_strategy == POOL_ROUNDROBIN)
  4429. fputs(",\n\"round-robin\" : true", fcfg);
  4430. if (pool_strategy == POOL_ROTATE)
  4431. fprintf(fcfg, ",\n\"rotate\" : \"%d\"", opt_rotate_period);
  4432. fputs("\n}\n", fcfg);
  4433. json_escape_free();
  4434. }
  4435. void zero_bestshare(void)
  4436. {
  4437. int i;
  4438. best_diff = 0;
  4439. memset(best_share, 0, 8);
  4440. suffix_string(best_diff, best_share, sizeof(best_share), 0);
  4441. for (i = 0; i < total_pools; i++) {
  4442. struct pool *pool = pools[i];
  4443. pool->best_diff = 0;
  4444. }
  4445. }
  4446. static struct timeval tv_hashmeter;
  4447. static time_t hashdisplay_t;
  4448. void zero_stats(void)
  4449. {
  4450. int i;
  4451. cgtime(&total_tv_start);
  4452. copy_time(&tv_hashmeter, &total_tv_start);
  4453. total_rolling = 0;
  4454. rolling1 = 0;
  4455. rolling5 = 0;
  4456. rolling15 = 0;
  4457. total_mhashes_done = 0;
  4458. total_getworks = 0;
  4459. total_accepted = 0;
  4460. total_rejected = 0;
  4461. hw_errors = 0;
  4462. total_stale = 0;
  4463. total_discarded = 0;
  4464. local_work = 0;
  4465. total_go = 0;
  4466. total_ro = 0;
  4467. total_secs = 1.0;
  4468. total_diff1 = 0;
  4469. found_blocks = 0;
  4470. total_diff_accepted = 0;
  4471. total_diff_rejected = 0;
  4472. total_diff_stale = 0;
  4473. for (i = 0; i < total_pools; i++) {
  4474. struct pool *pool = pools[i];
  4475. pool->getwork_requested = 0;
  4476. pool->accepted = 0;
  4477. pool->rejected = 0;
  4478. pool->stale_shares = 0;
  4479. pool->discarded_work = 0;
  4480. pool->getfail_occasions = 0;
  4481. pool->remotefail_occasions = 0;
  4482. pool->last_share_time = 0;
  4483. pool->diff1 = 0;
  4484. pool->diff_accepted = 0;
  4485. pool->diff_rejected = 0;
  4486. pool->diff_stale = 0;
  4487. pool->last_share_diff = 0;
  4488. }
  4489. zero_bestshare();
  4490. for (i = 0; i < total_devices; ++i) {
  4491. struct cgpu_info *cgpu = get_devices(i);
  4492. copy_time(&cgpu->dev_start_tv, &total_tv_start);
  4493. mutex_lock(&hash_lock);
  4494. cgpu->total_mhashes = 0;
  4495. cgpu->accepted = 0;
  4496. cgpu->rejected = 0;
  4497. cgpu->hw_errors = 0;
  4498. cgpu->utility = 0.0;
  4499. cgpu->last_share_pool_time = 0;
  4500. cgpu->diff1 = 0;
  4501. cgpu->diff_accepted = 0;
  4502. cgpu->diff_rejected = 0;
  4503. cgpu->last_share_diff = 0;
  4504. mutex_unlock(&hash_lock);
  4505. /* Don't take any locks in the driver zero stats function, as
  4506. * it's called async from everything else and we don't want to
  4507. * deadlock. */
  4508. cgpu->drv->zero_stats(cgpu);
  4509. }
  4510. }
  4511. static void set_highprio(void)
  4512. {
  4513. #ifndef WIN32
  4514. int ret = nice(-10);
  4515. if (!ret)
  4516. applog(LOG_DEBUG, "Unable to set thread to high priority");
  4517. #else
  4518. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST);
  4519. #endif
  4520. }
  4521. static void set_lowprio(void)
  4522. {
  4523. #ifndef WIN32
  4524. int ret = nice(10);
  4525. if (!ret)
  4526. applog(LOG_INFO, "Unable to set thread to low priority");
  4527. #else
  4528. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST);
  4529. #endif
  4530. }
  4531. #ifdef HAVE_CURSES
  4532. static void display_pools(void)
  4533. {
  4534. struct pool *pool;
  4535. int selected, i;
  4536. char input;
  4537. opt_loginput = true;
  4538. immedok(logwin, true);
  4539. clear_logwin();
  4540. updated:
  4541. for (i = 0; i < total_pools; i++) {
  4542. pool = pools[i];
  4543. if (pool == current_pool())
  4544. wattron(logwin, A_BOLD);
  4545. if (pool->enabled != POOL_ENABLED)
  4546. wattron(logwin, A_DIM);
  4547. wlogprint("%d: ", pool->pool_no);
  4548. switch (pool->enabled) {
  4549. case POOL_ENABLED:
  4550. wlogprint("Enabled ");
  4551. break;
  4552. case POOL_DISABLED:
  4553. wlogprint("Disabled ");
  4554. break;
  4555. case POOL_REJECTING:
  4556. wlogprint("Rejecting ");
  4557. break;
  4558. }
  4559. wlogprint("%s Quota %d Prio %d: %s User:%s\n",
  4560. pool->idle? "Dead" : "Alive",
  4561. pool->quota,
  4562. pool->prio,
  4563. pool->rpc_url, pool->rpc_user);
  4564. wattroff(logwin, A_BOLD | A_DIM);
  4565. }
  4566. retry:
  4567. wlogprint("\nCurrent pool management strategy: %s\n",
  4568. strategies[pool_strategy].s);
  4569. if (pool_strategy == POOL_ROTATE)
  4570. wlogprint("Set to rotate every %d minutes\n", opt_rotate_period);
  4571. wlogprint("[F]ailover only %s\n", opt_fail_only ? "enabled" : "disabled");
  4572. wlogprint("Pool [A]dd [R]emove [D]isable [E]nable [Q]uota change\n");
  4573. wlogprint("[C]hange management strategy [S]witch pool [I]nformation\n");
  4574. wlogprint("Or press any other key to continue\n");
  4575. logwin_update();
  4576. input = getch();
  4577. if (!strncasecmp(&input, "a", 1)) {
  4578. input_pool(true);
  4579. goto updated;
  4580. } else if (!strncasecmp(&input, "r", 1)) {
  4581. if (total_pools <= 1) {
  4582. wlogprint("Cannot remove last pool");
  4583. goto retry;
  4584. }
  4585. selected = curses_int("Select pool number");
  4586. if (selected < 0 || selected >= total_pools) {
  4587. wlogprint("Invalid selection\n");
  4588. goto retry;
  4589. }
  4590. pool = pools[selected];
  4591. if (pool == current_pool())
  4592. switch_pools(NULL);
  4593. if (pool == current_pool()) {
  4594. wlogprint("Unable to remove pool due to activity\n");
  4595. goto retry;
  4596. }
  4597. disable_pool(pool);
  4598. remove_pool(pool);
  4599. goto updated;
  4600. } else if (!strncasecmp(&input, "s", 1)) {
  4601. selected = curses_int("Select pool number");
  4602. if (selected < 0 || selected >= total_pools) {
  4603. wlogprint("Invalid selection\n");
  4604. goto retry;
  4605. }
  4606. pool = pools[selected];
  4607. enable_pool(pool);
  4608. switch_pools(pool);
  4609. goto updated;
  4610. } else if (!strncasecmp(&input, "d", 1)) {
  4611. if (enabled_pools <= 1) {
  4612. wlogprint("Cannot disable last pool");
  4613. goto retry;
  4614. }
  4615. selected = curses_int("Select pool number");
  4616. if (selected < 0 || selected >= total_pools) {
  4617. wlogprint("Invalid selection\n");
  4618. goto retry;
  4619. }
  4620. pool = pools[selected];
  4621. disable_pool(pool);
  4622. if (pool == current_pool())
  4623. switch_pools(NULL);
  4624. goto updated;
  4625. } else if (!strncasecmp(&input, "e", 1)) {
  4626. selected = curses_int("Select pool number");
  4627. if (selected < 0 || selected >= total_pools) {
  4628. wlogprint("Invalid selection\n");
  4629. goto retry;
  4630. }
  4631. pool = pools[selected];
  4632. enable_pool(pool);
  4633. if (pool->prio < current_pool()->prio)
  4634. switch_pools(pool);
  4635. goto updated;
  4636. } else if (!strncasecmp(&input, "c", 1)) {
  4637. for (i = 0; i <= TOP_STRATEGY; i++)
  4638. wlogprint("%d: %s\n", i, strategies[i].s);
  4639. selected = curses_int("Select strategy number type");
  4640. if (selected < 0 || selected > TOP_STRATEGY) {
  4641. wlogprint("Invalid selection\n");
  4642. goto retry;
  4643. }
  4644. if (selected == POOL_ROTATE) {
  4645. opt_rotate_period = curses_int("Select interval in minutes");
  4646. if (opt_rotate_period < 0 || opt_rotate_period > 9999) {
  4647. opt_rotate_period = 0;
  4648. wlogprint("Invalid selection\n");
  4649. goto retry;
  4650. }
  4651. }
  4652. pool_strategy = selected;
  4653. switch_pools(NULL);
  4654. goto updated;
  4655. } else if (!strncasecmp(&input, "i", 1)) {
  4656. selected = curses_int("Select pool number");
  4657. if (selected < 0 || selected >= total_pools) {
  4658. wlogprint("Invalid selection\n");
  4659. goto retry;
  4660. }
  4661. pool = pools[selected];
  4662. display_pool_summary(pool);
  4663. goto retry;
  4664. } else if (!strncasecmp(&input, "q", 1)) {
  4665. selected = curses_int("Select pool number");
  4666. if (selected < 0 || selected >= total_pools) {
  4667. wlogprint("Invalid selection\n");
  4668. goto retry;
  4669. }
  4670. pool = pools[selected];
  4671. selected = curses_int("Set quota");
  4672. if (selected < 0) {
  4673. wlogprint("Invalid negative quota\n");
  4674. goto retry;
  4675. }
  4676. pool->quota = selected;
  4677. adjust_quota_gcd();
  4678. goto updated;
  4679. } else if (!strncasecmp(&input, "f", 1)) {
  4680. opt_fail_only ^= true;
  4681. goto updated;
  4682. } else
  4683. clear_logwin();
  4684. immedok(logwin, false);
  4685. opt_loginput = false;
  4686. }
  4687. static void display_options(void)
  4688. {
  4689. int selected;
  4690. char input;
  4691. opt_loginput = true;
  4692. immedok(logwin, true);
  4693. clear_logwin();
  4694. retry:
  4695. wlogprint("[N]ormal [C]lear [S]ilent mode (disable all output)\n");
  4696. wlogprint("[D]ebug:%s\n[P]er-device:%s\n[Q]uiet:%s\n[V]erbose:%s\n"
  4697. "[R]PC debug:%s\n[W]orkTime details:%s\nco[M]pact: %s\n"
  4698. "[T]oggle status switching:%s\n"
  4699. "w[I]descreen:%s\n"
  4700. "[Z]ero statistics\n"
  4701. "[L]og interval:%d\n",
  4702. opt_debug ? "on" : "off",
  4703. want_per_device_stats? "on" : "off",
  4704. opt_quiet ? "on" : "off",
  4705. opt_log_output ? "on" : "off",
  4706. opt_protocol ? "on" : "off",
  4707. opt_worktime ? "on" : "off",
  4708. opt_compact ? "on" : "off",
  4709. switch_status ? "enabled" : "disabled",
  4710. opt_widescreen ? "enabled" : "disabled",
  4711. opt_log_interval);
  4712. wlogprint("Select an option or any other key to return\n");
  4713. logwin_update();
  4714. input = getch();
  4715. if (!strncasecmp(&input, "q", 1)) {
  4716. opt_quiet ^= true;
  4717. wlogprint("Quiet mode %s\n", opt_quiet ? "enabled" : "disabled");
  4718. goto retry;
  4719. } else if (!strncasecmp(&input, "v", 1)) {
  4720. opt_log_output ^= true;
  4721. if (opt_log_output)
  4722. opt_quiet = false;
  4723. wlogprint("Verbose mode %s\n", opt_log_output ? "enabled" : "disabled");
  4724. goto retry;
  4725. } else if (!strncasecmp(&input, "n", 1)) {
  4726. opt_log_output = false;
  4727. opt_debug = false;
  4728. opt_quiet = false;
  4729. opt_protocol = false;
  4730. opt_compact = false;
  4731. want_per_device_stats = false;
  4732. wlogprint("Output mode reset to normal\n");
  4733. switch_logsize(false);
  4734. goto retry;
  4735. } else if (!strncasecmp(&input, "d", 1)) {
  4736. opt_debug ^= true;
  4737. opt_log_output = opt_debug;
  4738. if (opt_debug)
  4739. opt_quiet = false;
  4740. wlogprint("Debug mode %s\n", opt_debug ? "enabled" : "disabled");
  4741. goto retry;
  4742. } else if (!strncasecmp(&input, "m", 1)) {
  4743. opt_compact ^= true;
  4744. wlogprint("Compact mode %s\n", opt_compact ? "enabled" : "disabled");
  4745. switch_logsize(false);
  4746. goto retry;
  4747. } else if (!strncasecmp(&input, "p", 1)) {
  4748. want_per_device_stats ^= true;
  4749. opt_log_output = want_per_device_stats;
  4750. wlogprint("Per-device stats %s\n", want_per_device_stats ? "enabled" : "disabled");
  4751. goto retry;
  4752. } else if (!strncasecmp(&input, "r", 1)) {
  4753. opt_protocol ^= true;
  4754. if (opt_protocol)
  4755. opt_quiet = false;
  4756. wlogprint("RPC protocol debugging %s\n", opt_protocol ? "enabled" : "disabled");
  4757. goto retry;
  4758. } else if (!strncasecmp(&input, "c", 1))
  4759. clear_logwin();
  4760. else if (!strncasecmp(&input, "l", 1)) {
  4761. selected = curses_int("Interval in seconds");
  4762. if (selected < 0 || selected > 9999) {
  4763. wlogprint("Invalid selection\n");
  4764. goto retry;
  4765. }
  4766. opt_log_interval = selected;
  4767. wlogprint("Log interval set to %d seconds\n", opt_log_interval);
  4768. goto retry;
  4769. } else if (!strncasecmp(&input, "s", 1)) {
  4770. opt_realquiet = true;
  4771. } else if (!strncasecmp(&input, "w", 1)) {
  4772. opt_worktime ^= true;
  4773. wlogprint("WorkTime details %s\n", opt_worktime ? "enabled" : "disabled");
  4774. goto retry;
  4775. } else if (!strncasecmp(&input, "t", 1)) {
  4776. switch_status ^= true;
  4777. goto retry;
  4778. } else if (!strncasecmp(&input, "i", 1)) {
  4779. opt_widescreen ^= true;
  4780. goto retry;
  4781. } else if (!strncasecmp(&input, "z", 1)) {
  4782. zero_stats();
  4783. goto retry;
  4784. } else
  4785. clear_logwin();
  4786. immedok(logwin, false);
  4787. opt_loginput = false;
  4788. }
  4789. #endif
  4790. void default_save_file(char *filename)
  4791. {
  4792. if (default_config && *default_config) {
  4793. strcpy(filename, default_config);
  4794. return;
  4795. }
  4796. #if defined(unix) || defined(__APPLE__)
  4797. if (getenv("HOME") && *getenv("HOME")) {
  4798. strcpy(filename, getenv("HOME"));
  4799. strcat(filename, "/");
  4800. }
  4801. else
  4802. strcpy(filename, "");
  4803. strcat(filename, ".cgminer/");
  4804. mkdir(filename, 0777);
  4805. #else
  4806. strcpy(filename, "");
  4807. #endif
  4808. strcat(filename, def_conf);
  4809. }
  4810. #ifdef HAVE_CURSES
  4811. static void set_options(void)
  4812. {
  4813. int selected;
  4814. char input;
  4815. opt_loginput = true;
  4816. immedok(logwin, true);
  4817. clear_logwin();
  4818. retry:
  4819. wlogprint("[Q]ueue: %d\n[S]cantime: %d\n[E]xpiry: %d\n"
  4820. "[W]rite config file\n[C]gminer restart\n",
  4821. opt_queue, opt_scantime, opt_expiry);
  4822. wlogprint("Select an option or any other key to return\n");
  4823. logwin_update();
  4824. input = getch();
  4825. if (!strncasecmp(&input, "q", 1)) {
  4826. selected = curses_int("Extra work items to queue");
  4827. if (selected < 0 || selected > 9999) {
  4828. wlogprint("Invalid selection\n");
  4829. goto retry;
  4830. }
  4831. opt_queue = selected;
  4832. if (opt_queue < max_queue)
  4833. max_queue = opt_queue;
  4834. goto retry;
  4835. } else if (!strncasecmp(&input, "s", 1)) {
  4836. selected = curses_int("Set scantime in seconds");
  4837. if (selected < 0 || selected > 9999) {
  4838. wlogprint("Invalid selection\n");
  4839. goto retry;
  4840. }
  4841. opt_scantime = selected;
  4842. goto retry;
  4843. } else if (!strncasecmp(&input, "e", 1)) {
  4844. selected = curses_int("Set expiry time in seconds");
  4845. if (selected < 0 || selected > 9999) {
  4846. wlogprint("Invalid selection\n");
  4847. goto retry;
  4848. }
  4849. opt_expiry = selected;
  4850. goto retry;
  4851. } else if (!strncasecmp(&input, "w", 1)) {
  4852. FILE *fcfg;
  4853. char *str, filename[PATH_MAX], prompt[PATH_MAX + 50];
  4854. default_save_file(filename);
  4855. snprintf(prompt, sizeof(prompt), "Config filename to write (Enter for default) [%s]", filename);
  4856. str = curses_input(prompt);
  4857. if (strcmp(str, "-1")) {
  4858. struct stat statbuf;
  4859. strcpy(filename, str);
  4860. free(str);
  4861. if (!stat(filename, &statbuf)) {
  4862. wlogprint("File exists, overwrite?\n");
  4863. input = getch();
  4864. if (strncasecmp(&input, "y", 1))
  4865. goto retry;
  4866. }
  4867. }
  4868. else
  4869. free(str);
  4870. fcfg = fopen(filename, "w");
  4871. if (!fcfg) {
  4872. wlogprint("Cannot open or create file\n");
  4873. goto retry;
  4874. }
  4875. write_config(fcfg);
  4876. fclose(fcfg);
  4877. goto retry;
  4878. } else if (!strncasecmp(&input, "c", 1)) {
  4879. wlogprint("Are you sure?\n");
  4880. input = getch();
  4881. if (!strncasecmp(&input, "y", 1))
  4882. app_restart();
  4883. else
  4884. clear_logwin();
  4885. } else
  4886. clear_logwin();
  4887. immedok(logwin, false);
  4888. opt_loginput = false;
  4889. }
  4890. #ifdef USE_USBUTILS
  4891. static void mt_enable(struct thr_info *mythr)
  4892. {
  4893. cgsem_post(&mythr->sem);
  4894. }
  4895. static void set_usb(void)
  4896. {
  4897. int selected, i, mt, enabled, disabled, zombie, total, blacklisted;
  4898. struct cgpu_info *cgpu;
  4899. struct thr_info *thr;
  4900. double val;
  4901. char input;
  4902. opt_loginput = true;
  4903. immedok(logwin, true);
  4904. clear_logwin();
  4905. retry:
  4906. enabled = 0;
  4907. disabled = 0;
  4908. zombie = 0;
  4909. total = 0;
  4910. blacklisted = 0;
  4911. rd_lock(&mining_thr_lock);
  4912. mt = mining_threads;
  4913. rd_unlock(&mining_thr_lock);
  4914. for (i = 0; i < mt; i++) {
  4915. cgpu = mining_thr[i]->cgpu;
  4916. if (unlikely(!cgpu))
  4917. continue;
  4918. if (cgpu->usbinfo.nodev)
  4919. zombie++;
  4920. else if (cgpu->deven == DEV_DISABLED)
  4921. disabled++;
  4922. else
  4923. enabled++;
  4924. if (cgpu->blacklisted)
  4925. blacklisted++;
  4926. total++;
  4927. }
  4928. wlogprint("Hotplug interval:%d\n", hotplug_time);
  4929. wlogprint("%d USB devices, %d enabled, %d disabled, %d zombie\n",
  4930. total, enabled, disabled, zombie);
  4931. wlogprint("[S]ummary of device information\n");
  4932. wlogprint("[E]nable device\n");
  4933. wlogprint("[D]isable device\n");
  4934. wlogprint("[U]nplug to allow hotplug restart\n");
  4935. wlogprint("[R]eset device USB\n");
  4936. wlogprint("[L]ist all known devices\n");
  4937. wlogprint("[B]lacklist current device from current instance of cgminer\n");
  4938. wlogprint("[W]hitelist previously blacklisted device\n");
  4939. wlogprint("[H]otplug interval (0 to disable)\n");
  4940. wlogprint("Select an option or any other key to return\n");
  4941. logwin_update();
  4942. input = getch();
  4943. if (!strncasecmp(&input, "s", 1)) {
  4944. selected = curses_int("Select device number");
  4945. if (selected < 0 || selected >= mt) {
  4946. wlogprint("Invalid selection\n");
  4947. goto retry;
  4948. }
  4949. cgpu = mining_thr[selected]->cgpu;
  4950. wlogprint("Device %03u:%03u\n", cgpu->usbinfo.bus_number, cgpu->usbinfo.device_address);
  4951. wlogprint("Name %s\n", cgpu->drv->name);
  4952. wlogprint("ID %d\n", cgpu->device_id);
  4953. wlogprint("Enabled: %s\n", cgpu->deven != DEV_DISABLED ? "Yes" : "No");
  4954. wlogprint("Temperature %.1f\n", cgpu->temp);
  4955. wlogprint("MHS av %.0f\n", cgpu->total_mhashes / cgpu_runtime(cgpu));
  4956. wlogprint("Accepted %d\n", cgpu->accepted);
  4957. wlogprint("Rejected %d\n", cgpu->rejected);
  4958. wlogprint("Hardware Errors %d\n", cgpu->hw_errors);
  4959. wlogprint("Last Share Pool %d\n", cgpu->last_share_pool_time > 0 ? cgpu->last_share_pool : -1);
  4960. wlogprint("Total MH %.1f\n", cgpu->total_mhashes);
  4961. wlogprint("Diff1 Work %"PRId64"\n", cgpu->diff1);
  4962. wlogprint("Difficulty Accepted %.1f\n", cgpu->diff_accepted);
  4963. wlogprint("Difficulty Rejected %.1f\n", cgpu->diff_rejected);
  4964. wlogprint("Last Share Difficulty %.1f\n", cgpu->last_share_diff);
  4965. wlogprint("No Device: %s\n", cgpu->usbinfo.nodev ? "True" : "False");
  4966. wlogprint("Last Valid Work %"PRIu64"\n", (uint64_t)cgpu->last_device_valid_work);
  4967. val = 0;
  4968. if (cgpu->hw_errors + cgpu->diff1)
  4969. val = cgpu->hw_errors / (cgpu->hw_errors + cgpu->diff1);
  4970. wlogprint("Device Hardware %.1f%%\n", val);
  4971. val = 0;
  4972. if (cgpu->diff1)
  4973. val = cgpu->diff_rejected / cgpu->diff1;
  4974. wlogprint("Device Rejected %.1f%%\n", val);
  4975. goto retry;
  4976. } else if (!strncasecmp(&input, "e", 1)) {
  4977. selected = curses_int("Select device number");
  4978. if (selected < 0 || selected >= mt) {
  4979. wlogprint("Invalid selection\n");
  4980. goto retry;
  4981. }
  4982. cgpu = mining_thr[selected]->cgpu;
  4983. if (cgpu->usbinfo.nodev) {
  4984. wlogprint("Device removed, unable to re-enable!\n");
  4985. goto retry;
  4986. }
  4987. thr = get_thread(selected);
  4988. cgpu->deven = DEV_ENABLED;
  4989. mt_enable(thr);
  4990. goto retry;
  4991. } else if (!strncasecmp(&input, "d", 1)) {
  4992. selected = curses_int("Select device number");
  4993. if (selected < 0 || selected >= mt) {
  4994. wlogprint("Invalid selection\n");
  4995. goto retry;
  4996. }
  4997. cgpu = mining_thr[selected]->cgpu;
  4998. cgpu->deven = DEV_DISABLED;
  4999. goto retry;
  5000. } else if (!strncasecmp(&input, "u", 1)) {
  5001. selected = curses_int("Select device number");
  5002. if (selected < 0 || selected >= mt) {
  5003. wlogprint("Invalid selection\n");
  5004. goto retry;
  5005. }
  5006. cgpu = mining_thr[selected]->cgpu;
  5007. if (cgpu->usbinfo.nodev) {
  5008. wlogprint("Device already removed, unable to unplug!\n");
  5009. goto retry;
  5010. }
  5011. usb_nodev(cgpu);
  5012. goto retry;
  5013. } else if (!strncasecmp(&input, "r", 1)) {
  5014. selected = curses_int("Select device number");
  5015. if (selected < 0 || selected >= mt) {
  5016. wlogprint("Invalid selection\n");
  5017. goto retry;
  5018. }
  5019. cgpu = mining_thr[selected]->cgpu;
  5020. if (cgpu->usbinfo.nodev) {
  5021. wlogprint("Device already removed, unable to reset!\n");
  5022. goto retry;
  5023. }
  5024. usb_reset(cgpu);
  5025. goto retry;
  5026. } else if (!strncasecmp(&input, "b", 1)) {
  5027. selected = curses_int("Select device number");
  5028. if (selected < 0 || selected >= mt) {
  5029. wlogprint("Invalid selection\n");
  5030. goto retry;
  5031. }
  5032. cgpu = mining_thr[selected]->cgpu;
  5033. if (cgpu->usbinfo.nodev) {
  5034. wlogprint("Device already removed, unable to blacklist!\n");
  5035. goto retry;
  5036. }
  5037. blacklist_cgpu(cgpu);
  5038. goto retry;
  5039. } else if (!strncasecmp(&input, "w", 1)) {
  5040. if (!blacklisted) {
  5041. wlogprint("No blacklisted devices!\n");
  5042. goto retry;
  5043. }
  5044. wlogprint("Blacklisted devices:\n");
  5045. for (i = 0; i < mt; i++) {
  5046. cgpu = mining_thr[i]->cgpu;
  5047. if (unlikely(!cgpu))
  5048. continue;
  5049. if (cgpu->blacklisted) {
  5050. wlogprint("%d: %s %d %03u:%03u\n", i, cgpu->drv->name,
  5051. cgpu->device_id, cgpu->usbinfo.bus_number,
  5052. cgpu->usbinfo.device_address);
  5053. }
  5054. }
  5055. selected = curses_int("Select device number");
  5056. if (selected < 0 || selected >= mt) {
  5057. wlogprint("Invalid selection\n");
  5058. goto retry;
  5059. }
  5060. cgpu = mining_thr[selected]->cgpu;
  5061. if (!cgpu->blacklisted) {
  5062. wlogprint("Device not blacklisted, unable to whitelist\n");
  5063. goto retry;
  5064. }
  5065. whitelist_cgpu(cgpu);
  5066. goto retry;
  5067. } else if (!strncasecmp(&input, "h", 1)) {
  5068. selected = curses_int("Select hotplug interval in seconds (0 to disable)");
  5069. if (selected < 0 || selected > 9999) {
  5070. wlogprint("Invalid value\n");
  5071. goto retry;
  5072. }
  5073. hotplug_time = selected;
  5074. goto retry;
  5075. } else if (!strncasecmp(&input, "l", 1)) {
  5076. usb_list();
  5077. goto retry;
  5078. } else
  5079. clear_logwin();
  5080. immedok(logwin, false);
  5081. opt_loginput = false;
  5082. }
  5083. #endif
  5084. static void *input_thread(void __maybe_unused *userdata)
  5085. {
  5086. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  5087. RenameThread("Input");
  5088. if (!curses_active)
  5089. return NULL;
  5090. while (1) {
  5091. char input;
  5092. input = getch();
  5093. if (!strncasecmp(&input, "q", 1)) {
  5094. kill_work();
  5095. return NULL;
  5096. } else if (!strncasecmp(&input, "d", 1))
  5097. display_options();
  5098. else if (!strncasecmp(&input, "p", 1))
  5099. display_pools();
  5100. else if (!strncasecmp(&input, "s", 1))
  5101. set_options();
  5102. #ifdef USE_USBUTILS
  5103. else if (!strncasecmp(&input, "u", 1))
  5104. set_usb();
  5105. #endif
  5106. if (opt_realquiet) {
  5107. disable_curses();
  5108. break;
  5109. }
  5110. }
  5111. return NULL;
  5112. }
  5113. #endif
  5114. static void *api_thread(void *userdata)
  5115. {
  5116. struct thr_info *mythr = userdata;
  5117. pthread_detach(pthread_self());
  5118. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  5119. RenameThread("API");
  5120. set_lowprio();
  5121. api(api_thr_id);
  5122. PTH(mythr) = 0L;
  5123. return NULL;
  5124. }
  5125. /* Sole work devices are serialised wrt calling get_work so they report in on
  5126. * each pass through their scanhash function as well as in get_work whereas
  5127. * queued work devices work asynchronously so get them to report in and out
  5128. * only across get_work. */
  5129. static void thread_reportin(struct thr_info *thr)
  5130. {
  5131. thr->getwork = false;
  5132. cgtime(&thr->last);
  5133. thr->cgpu->status = LIFE_WELL;
  5134. thr->cgpu->device_last_well = time(NULL);
  5135. }
  5136. /* Tell the watchdog thread this thread is waiting on get work and should not
  5137. * be restarted */
  5138. static void thread_reportout(struct thr_info *thr)
  5139. {
  5140. thr->getwork = true;
  5141. cgtime(&thr->last);
  5142. thr->cgpu->status = LIFE_WELL;
  5143. thr->cgpu->device_last_well = time(NULL);
  5144. }
  5145. static void hashmeter(int thr_id, double hashes_done)
  5146. {
  5147. bool showlog = false;
  5148. double tv_tdiff;
  5149. time_t now_t;
  5150. int diff_t;
  5151. cgtime(&total_tv_end);
  5152. tv_tdiff = tdiff(&total_tv_end, &tv_hashmeter);
  5153. now_t = total_tv_end.tv_sec;
  5154. diff_t = now_t - hashdisplay_t;
  5155. if (diff_t >= opt_log_interval) {
  5156. alt_status ^= switch_status;
  5157. hashdisplay_t = now_t;
  5158. showlog = true;
  5159. } else if (thr_id < 0) {
  5160. /* hashmeter is called by non-mining threads in case nothing
  5161. * has reported in to allow hashrate to converge to zero , but
  5162. * we only update if it has been more than opt_log_interval */
  5163. return;
  5164. }
  5165. copy_time(&tv_hashmeter, &total_tv_end);
  5166. if (thr_id >= 0) {
  5167. struct thr_info *thr = get_thread(thr_id);
  5168. struct cgpu_info *cgpu = thr->cgpu;
  5169. double device_tdiff, thr_mhs;
  5170. /* Update the last time this thread reported in */
  5171. copy_time(&thr->last, &total_tv_end);
  5172. cgpu->device_last_well = now_t;
  5173. device_tdiff = tdiff(&total_tv_end, &cgpu->last_message_tv);
  5174. copy_time(&cgpu->last_message_tv, &total_tv_end);
  5175. thr_mhs = (double)hashes_done / device_tdiff / 1000000;
  5176. applog(LOG_DEBUG, "[thread %d: %.0f hashes, %.1f mhash/sec]",
  5177. thr_id, hashes_done, thr_mhs);
  5178. hashes_done /= 1000000;
  5179. mutex_lock(&hash_lock);
  5180. cgpu->total_mhashes += hashes_done;
  5181. decay_time(&cgpu->rolling, hashes_done, device_tdiff, opt_log_interval);
  5182. decay_time(&cgpu->rolling1, hashes_done, device_tdiff, 60.0);
  5183. decay_time(&cgpu->rolling5, hashes_done, device_tdiff, 300.0);
  5184. decay_time(&cgpu->rolling15, hashes_done, device_tdiff, 900.0);
  5185. mutex_unlock(&hash_lock);
  5186. if (want_per_device_stats && showlog) {
  5187. char logline[256];
  5188. get_statline(logline, sizeof(logline), cgpu);
  5189. if (!curses_active) {
  5190. printf("%s \r", logline);
  5191. fflush(stdout);
  5192. } else
  5193. applog(LOG_INFO, "%s", logline);
  5194. }
  5195. } else {
  5196. /* No device has reported in, we have been called from the
  5197. * watchdog thread so decay all the hashrates */
  5198. mutex_lock(&hash_lock);
  5199. for (thr_id = 0; thr_id < mining_threads; thr_id++) {
  5200. struct thr_info *thr = get_thread(thr_id);
  5201. struct cgpu_info *cgpu = thr->cgpu;
  5202. double device_tdiff = tdiff(&total_tv_end, &cgpu->last_message_tv);
  5203. copy_time(&cgpu->last_message_tv, &total_tv_end);
  5204. decay_time(&cgpu->rolling, 0, device_tdiff, opt_log_interval);
  5205. decay_time(&cgpu->rolling1, 0, device_tdiff, 60.0);
  5206. decay_time(&cgpu->rolling5, 0, device_tdiff, 300.0);
  5207. decay_time(&cgpu->rolling15, 0, device_tdiff, 900.0);
  5208. }
  5209. mutex_unlock(&hash_lock);
  5210. }
  5211. mutex_lock(&hash_lock);
  5212. total_mhashes_done += hashes_done;
  5213. decay_time(&total_rolling, hashes_done, tv_tdiff, opt_log_interval);
  5214. decay_time(&rolling1, hashes_done, tv_tdiff, 60.0);
  5215. decay_time(&rolling5, hashes_done, tv_tdiff, 300.0);
  5216. decay_time(&rolling15, hashes_done, tv_tdiff, 900.0);
  5217. #ifndef WIN32
  5218. global_hashrate = llround(total_rolling) * 1000000;
  5219. #else
  5220. global_hashrate = (unsigned long long)lround(total_rolling) * 1000000; // MinGW(non64) is missing llround
  5221. #endif
  5222. total_secs = tdiff(&total_tv_end, &total_tv_start);
  5223. if (showlog) {
  5224. char displayed_hashes[16], displayed_rolling[16];
  5225. char displayed_r1[16], displayed_r5[16], displayed_r15[16];
  5226. uint64_t d64;
  5227. d64 = (double)total_mhashes_done / total_secs * 1000000ull;
  5228. suffix_string(d64, displayed_hashes, sizeof(displayed_hashes), 4);
  5229. d64 = (double)total_rolling * 1000000ull;
  5230. suffix_string(d64, displayed_rolling, sizeof(displayed_rolling), 4);
  5231. d64 = (double)rolling1 * 1000000ull;
  5232. suffix_string(d64, displayed_r1, sizeof(displayed_rolling), 4);
  5233. d64 = (double)rolling5 * 1000000ull;
  5234. suffix_string(d64, displayed_r5, sizeof(displayed_rolling), 4);
  5235. d64 = (double)rolling15 * 1000000ull;
  5236. suffix_string(d64, displayed_r15, sizeof(displayed_rolling), 4);
  5237. snprintf(statusline, sizeof(statusline),
  5238. "(%ds):%s (1m):%s (5m):%s (15m):%s (avg):%sh/s",
  5239. opt_log_interval, displayed_rolling, displayed_r1, displayed_r5,
  5240. displayed_r15, displayed_hashes);
  5241. }
  5242. mutex_unlock(&hash_lock);
  5243. if (showlog) {
  5244. if (!curses_active) {
  5245. printf("%s \r", statusline);
  5246. fflush(stdout);
  5247. } else
  5248. applog(LOG_INFO, "%s", statusline);
  5249. }
  5250. }
  5251. static void stratum_share_result(json_t *val, json_t *res_val, json_t *err_val,
  5252. struct stratum_share *sshare)
  5253. {
  5254. struct work *work = sshare->work;
  5255. time_t now_t = time(NULL);
  5256. char hashshow[64];
  5257. int srdiff;
  5258. srdiff = now_t - sshare->sshare_sent;
  5259. if (opt_debug || srdiff > 0) {
  5260. applog(LOG_INFO, "Pool %d stratum share result lag time %d seconds",
  5261. work->pool->pool_no, srdiff);
  5262. }
  5263. show_hash(work, hashshow);
  5264. share_result(val, res_val, err_val, work, hashshow, false, "");
  5265. }
  5266. /* Parses stratum json responses and tries to find the id that the request
  5267. * matched to and treat it accordingly. */
  5268. static bool parse_stratum_response(struct pool *pool, char *s)
  5269. {
  5270. json_t *val = NULL, *err_val, *res_val, *id_val;
  5271. struct stratum_share *sshare;
  5272. json_error_t err;
  5273. bool ret = false;
  5274. int id;
  5275. val = JSON_LOADS(s, &err);
  5276. if (!val) {
  5277. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  5278. goto out;
  5279. }
  5280. res_val = json_object_get(val, "result");
  5281. err_val = json_object_get(val, "error");
  5282. id_val = json_object_get(val, "id");
  5283. if (json_is_null(id_val) || !id_val) {
  5284. char *ss;
  5285. if (err_val)
  5286. ss = json_dumps(err_val, JSON_INDENT(3));
  5287. else
  5288. ss = strdup("(unknown reason)");
  5289. applog(LOG_INFO, "JSON-RPC non method decode failed: %s", ss);
  5290. free(ss);
  5291. goto out;
  5292. }
  5293. id = json_integer_value(id_val);
  5294. mutex_lock(&sshare_lock);
  5295. HASH_FIND_INT(stratum_shares, &id, sshare);
  5296. if (sshare) {
  5297. HASH_DEL(stratum_shares, sshare);
  5298. pool->sshares--;
  5299. }
  5300. mutex_unlock(&sshare_lock);
  5301. if (!sshare) {
  5302. double pool_diff;
  5303. /* Since the share is untracked, we can only guess at what the
  5304. * work difficulty is based on the current pool diff. */
  5305. cg_rlock(&pool->data_lock);
  5306. pool_diff = pool->sdiff;
  5307. cg_runlock(&pool->data_lock);
  5308. if (json_is_true(res_val)) {
  5309. applog(LOG_NOTICE, "Accepted untracked stratum share from pool %d", pool->pool_no);
  5310. /* We don't know what device this came from so we can't
  5311. * attribute the work to the relevant cgpu */
  5312. mutex_lock(&stats_lock);
  5313. total_accepted++;
  5314. pool->accepted++;
  5315. total_diff_accepted += pool_diff;
  5316. pool->diff_accepted += pool_diff;
  5317. mutex_unlock(&stats_lock);
  5318. } else {
  5319. applog(LOG_NOTICE, "Rejected untracked stratum share from pool %d", pool->pool_no);
  5320. mutex_lock(&stats_lock);
  5321. total_rejected++;
  5322. pool->rejected++;
  5323. total_diff_rejected += pool_diff;
  5324. pool->diff_rejected += pool_diff;
  5325. mutex_unlock(&stats_lock);
  5326. }
  5327. goto out;
  5328. }
  5329. stratum_share_result(val, res_val, err_val, sshare);
  5330. free_work(sshare->work);
  5331. free(sshare);
  5332. ret = true;
  5333. out:
  5334. if (val)
  5335. json_decref(val);
  5336. return ret;
  5337. }
  5338. void clear_stratum_shares(struct pool *pool)
  5339. {
  5340. struct stratum_share *sshare, *tmpshare;
  5341. double diff_cleared = 0;
  5342. int cleared = 0;
  5343. mutex_lock(&sshare_lock);
  5344. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  5345. if (sshare->work->pool == pool) {
  5346. HASH_DEL(stratum_shares, sshare);
  5347. diff_cleared += sshare->work->work_difficulty;
  5348. free_work(sshare->work);
  5349. pool->sshares--;
  5350. free(sshare);
  5351. cleared++;
  5352. }
  5353. }
  5354. mutex_unlock(&sshare_lock);
  5355. if (cleared) {
  5356. applog(LOG_WARNING, "Lost %d shares due to stratum disconnect on pool %d", cleared, pool->pool_no);
  5357. pool->stale_shares += cleared;
  5358. total_stale += cleared;
  5359. pool->diff_stale += diff_cleared;
  5360. total_diff_stale += diff_cleared;
  5361. }
  5362. }
  5363. void clear_pool_work(struct pool *pool)
  5364. {
  5365. struct work *work, *tmp;
  5366. int cleared = 0;
  5367. mutex_lock(stgd_lock);
  5368. HASH_ITER(hh, staged_work, work, tmp) {
  5369. if (work->pool == pool) {
  5370. HASH_DEL(staged_work, work);
  5371. free_work(work);
  5372. cleared++;
  5373. }
  5374. }
  5375. mutex_unlock(stgd_lock);
  5376. if (cleared)
  5377. applog(LOG_INFO, "Cleared %d work items due to stratum disconnect on pool %d", cleared, pool->pool_no);
  5378. }
  5379. static int cp_prio(void)
  5380. {
  5381. int prio;
  5382. cg_rlock(&control_lock);
  5383. prio = currentpool->prio;
  5384. cg_runlock(&control_lock);
  5385. return prio;
  5386. }
  5387. /* We only need to maintain a secondary pool connection when we need the
  5388. * capacity to get work from the backup pools while still on the primary */
  5389. static bool cnx_needed(struct pool *pool)
  5390. {
  5391. struct pool *cp;
  5392. if (pool->enabled != POOL_ENABLED)
  5393. return false;
  5394. /* Balance strategies need all pools online */
  5395. if (pool_strategy == POOL_BALANCE)
  5396. return true;
  5397. if (pool_strategy == POOL_LOADBALANCE)
  5398. return true;
  5399. /* Idle stratum pool needs something to kick it alive again */
  5400. if (pool->has_stratum && pool->idle)
  5401. return true;
  5402. /* Getwork pools without opt_fail_only need backup pools up to be able
  5403. * to leak shares */
  5404. cp = current_pool();
  5405. if (cp == pool)
  5406. return true;
  5407. if (!pool_localgen(cp) && (!opt_fail_only || !cp->hdr_path))
  5408. return true;
  5409. /* If we're waiting for a response from shares submitted, keep the
  5410. * connection open. */
  5411. if (pool->sshares)
  5412. return true;
  5413. /* If the pool has only just come to life and is higher priority than
  5414. * the current pool keep the connection open so we can fail back to
  5415. * it. */
  5416. if (pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  5417. return true;
  5418. if (pool_unworkable(cp))
  5419. return true;
  5420. /* We've run out of work, bring anything back to life. */
  5421. if (no_work)
  5422. return true;
  5423. return false;
  5424. }
  5425. static void wait_lpcurrent(struct pool *pool);
  5426. static void pool_resus(struct pool *pool);
  5427. static void gen_stratum_work(struct pool *pool, struct work *work);
  5428. static void stratum_resumed(struct pool *pool)
  5429. {
  5430. if (!pool->stratum_notify)
  5431. return;
  5432. if (pool_tclear(pool, &pool->idle)) {
  5433. applog(LOG_INFO, "Stratum connection to pool %d resumed", pool->pool_no);
  5434. pool_resus(pool);
  5435. }
  5436. }
  5437. static bool supports_resume(struct pool *pool)
  5438. {
  5439. bool ret;
  5440. cg_rlock(&pool->data_lock);
  5441. ret = (pool->sessionid != NULL);
  5442. cg_runlock(&pool->data_lock);
  5443. return ret;
  5444. }
  5445. /* One stratum receive thread per pool that has stratum waits on the socket
  5446. * checking for new messages and for the integrity of the socket connection. We
  5447. * reset the connection based on the integrity of the receive side only as the
  5448. * send side will eventually expire data it fails to send. */
  5449. static void *stratum_rthread(void *userdata)
  5450. {
  5451. struct pool *pool = (struct pool *)userdata;
  5452. char threadname[16];
  5453. pthread_detach(pthread_self());
  5454. snprintf(threadname, sizeof(threadname), "%d/RStratum", pool->pool_no);
  5455. RenameThread(threadname);
  5456. while (42) {
  5457. struct timeval timeout;
  5458. int sel_ret;
  5459. fd_set rd;
  5460. char *s;
  5461. if (unlikely(pool->removed))
  5462. break;
  5463. /* Check to see whether we need to maintain this connection
  5464. * indefinitely or just bring it up when we switch to this
  5465. * pool */
  5466. if (!sock_full(pool) && !cnx_needed(pool)) {
  5467. suspend_stratum(pool);
  5468. clear_stratum_shares(pool);
  5469. clear_pool_work(pool);
  5470. wait_lpcurrent(pool);
  5471. if (!restart_stratum(pool)) {
  5472. pool_died(pool);
  5473. while (!restart_stratum(pool)) {
  5474. pool_failed(pool);
  5475. if (pool->removed)
  5476. goto out;
  5477. cgsleep_ms(30000);
  5478. }
  5479. }
  5480. }
  5481. FD_ZERO(&rd);
  5482. FD_SET(pool->sock, &rd);
  5483. timeout.tv_sec = 90;
  5484. timeout.tv_usec = 0;
  5485. /* The protocol specifies that notify messages should be sent
  5486. * every minute so if we fail to receive any for 90 seconds we
  5487. * assume the connection has been dropped and treat this pool
  5488. * as dead */
  5489. if (!sock_full(pool) && (sel_ret = select(pool->sock + 1, &rd, NULL, NULL, &timeout)) < 1) {
  5490. applog(LOG_DEBUG, "Stratum select failed on pool %d with value %d", pool->pool_no, sel_ret);
  5491. s = NULL;
  5492. } else
  5493. s = recv_line(pool);
  5494. if (!s) {
  5495. applog(LOG_NOTICE, "Stratum connection to pool %d interrupted", pool->pool_no);
  5496. pool->getfail_occasions++;
  5497. total_go++;
  5498. /* If the socket to our stratum pool disconnects, all
  5499. * tracked submitted shares are lost and we will leak
  5500. * the memory if we don't discard their records. */
  5501. if (!supports_resume(pool) || opt_lowmem)
  5502. clear_stratum_shares(pool);
  5503. clear_pool_work(pool);
  5504. if (pool == current_pool())
  5505. restart_threads();
  5506. if (restart_stratum(pool))
  5507. continue;
  5508. pool_died(pool);
  5509. while (!restart_stratum(pool)) {
  5510. pool_failed(pool);
  5511. if (pool->removed)
  5512. goto out;
  5513. cgsleep_ms(30000);
  5514. }
  5515. stratum_resumed(pool);
  5516. continue;
  5517. }
  5518. /* Check this pool hasn't died while being a backup pool and
  5519. * has not had its idle flag cleared */
  5520. stratum_resumed(pool);
  5521. if (!parse_method(pool, s) && !parse_stratum_response(pool, s))
  5522. applog(LOG_INFO, "Unknown stratum msg: %s", s);
  5523. else if (pool->swork.clean) {
  5524. struct work *work = make_work();
  5525. /* Generate a single work item to update the current
  5526. * block database */
  5527. pool->swork.clean = false;
  5528. gen_stratum_work(pool, work);
  5529. work->longpoll = true;
  5530. /* Return value doesn't matter. We're just informing
  5531. * that we may need to restart. */
  5532. test_work_current(work);
  5533. free_work(work);
  5534. }
  5535. free(s);
  5536. }
  5537. out:
  5538. return NULL;
  5539. }
  5540. /* Each pool has one stratum send thread for sending shares to avoid many
  5541. * threads being created for submission since all sends need to be serialised
  5542. * anyway. */
  5543. static void *stratum_sthread(void *userdata)
  5544. {
  5545. struct pool *pool = (struct pool *)userdata;
  5546. char threadname[16];
  5547. pthread_detach(pthread_self());
  5548. snprintf(threadname, sizeof(threadname), "%d/SStratum", pool->pool_no);
  5549. RenameThread(threadname);
  5550. pool->stratum_q = tq_new();
  5551. if (!pool->stratum_q)
  5552. quit(1, "Failed to create stratum_q in stratum_sthread");
  5553. while (42) {
  5554. char noncehex[12], nonce2hex[20], s[1024];
  5555. struct stratum_share *sshare;
  5556. uint32_t *hash32, nonce;
  5557. unsigned char nonce2[8];
  5558. uint64_t *nonce2_64;
  5559. struct work *work;
  5560. bool submitted;
  5561. if (unlikely(pool->removed))
  5562. break;
  5563. work = tq_pop(pool->stratum_q, NULL);
  5564. if (unlikely(!work))
  5565. quit(1, "Stratum q returned empty work");
  5566. if (unlikely(work->nonce2_len > 8)) {
  5567. applog(LOG_ERR, "Pool %d asking for inappropriately long nonce2 length %d",
  5568. pool->pool_no, (int)work->nonce2_len);
  5569. applog(LOG_ERR, "Not attempting to submit shares");
  5570. free_work(work);
  5571. continue;
  5572. }
  5573. sshare = calloc(sizeof(struct stratum_share), 1);
  5574. hash32 = (uint32_t *)work->hash;
  5575. submitted = false;
  5576. sshare->sshare_time = time(NULL);
  5577. /* This work item is freed in parse_stratum_response */
  5578. sshare->work = work;
  5579. nonce = *((uint32_t *)(work->data + 76));
  5580. __bin2hex(noncehex, (const unsigned char *)&nonce, 4);
  5581. memset(s, 0, 1024);
  5582. mutex_lock(&sshare_lock);
  5583. /* Give the stratum share a unique id */
  5584. sshare->id = swork_id++;
  5585. mutex_unlock(&sshare_lock);
  5586. nonce2_64 = (uint64_t *)nonce2;
  5587. *nonce2_64 = htole64(work->nonce2);
  5588. __bin2hex(nonce2hex, nonce2, work->nonce2_len);
  5589. snprintf(s, sizeof(s),
  5590. "{\"params\": [\"%s\", \"%s\", \"%s\", \"%s\", \"%s\"], \"id\": %d, \"method\": \"mining.submit\"}",
  5591. pool->rpc_user, work->job_id, nonce2hex, work->ntime, noncehex, sshare->id);
  5592. applog(LOG_INFO, "Submitting share %08lx to pool %d",
  5593. (long unsigned int)htole32(hash32[6]), pool->pool_no);
  5594. /* Try resubmitting for up to 2 minutes if we fail to submit
  5595. * once and the stratum pool nonce1 still matches suggesting
  5596. * we may be able to resume. */
  5597. while (time(NULL) < sshare->sshare_time + 120) {
  5598. bool sessionid_match;
  5599. if (likely(stratum_send(pool, s, strlen(s)))) {
  5600. if (pool_tclear(pool, &pool->submit_fail))
  5601. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  5602. mutex_lock(&sshare_lock);
  5603. HASH_ADD_INT(stratum_shares, id, sshare);
  5604. pool->sshares++;
  5605. mutex_unlock(&sshare_lock);
  5606. applog(LOG_DEBUG, "Successfully submitted, adding to stratum_shares db");
  5607. submitted = true;
  5608. break;
  5609. }
  5610. if (!pool_tset(pool, &pool->submit_fail) && cnx_needed(pool)) {
  5611. applog(LOG_WARNING, "Pool %d stratum share submission failure", pool->pool_no);
  5612. total_ro++;
  5613. pool->remotefail_occasions++;
  5614. }
  5615. if (opt_lowmem) {
  5616. applog(LOG_DEBUG, "Lowmem option prevents resubmitting stratum share");
  5617. break;
  5618. }
  5619. cg_rlock(&pool->data_lock);
  5620. sessionid_match = (pool->nonce1 && !strcmp(work->nonce1, pool->nonce1));
  5621. cg_runlock(&pool->data_lock);
  5622. if (!sessionid_match) {
  5623. applog(LOG_DEBUG, "No matching session id for resubmitting stratum share");
  5624. break;
  5625. }
  5626. /* Retry every 5 seconds */
  5627. sleep(5);
  5628. }
  5629. if (unlikely(!submitted)) {
  5630. applog(LOG_DEBUG, "Failed to submit stratum share, discarding");
  5631. free_work(work);
  5632. free(sshare);
  5633. pool->stale_shares++;
  5634. total_stale++;
  5635. } else {
  5636. int ssdiff;
  5637. sshare->sshare_sent = time(NULL);
  5638. ssdiff = sshare->sshare_sent - sshare->sshare_time;
  5639. if (opt_debug || ssdiff > 0) {
  5640. applog(LOG_INFO, "Pool %d stratum share submission lag time %d seconds",
  5641. pool->pool_no, ssdiff);
  5642. }
  5643. }
  5644. }
  5645. /* Freeze the work queue but don't free up its memory in case there is
  5646. * work still trying to be submitted to the removed pool. */
  5647. tq_freeze(pool->stratum_q);
  5648. return NULL;
  5649. }
  5650. static void init_stratum_threads(struct pool *pool)
  5651. {
  5652. have_longpoll = true;
  5653. if (unlikely(pthread_create(&pool->stratum_sthread, NULL, stratum_sthread, (void *)pool)))
  5654. quit(1, "Failed to create stratum sthread");
  5655. if (unlikely(pthread_create(&pool->stratum_rthread, NULL, stratum_rthread, (void *)pool)))
  5656. quit(1, "Failed to create stratum rthread");
  5657. }
  5658. static void *longpoll_thread(void *userdata);
  5659. static bool stratum_works(struct pool *pool)
  5660. {
  5661. applog(LOG_INFO, "Testing pool %d stratum %s", pool->pool_no, pool->stratum_url);
  5662. check_extranonce_option(pool, pool->stratum_url);
  5663. if (!extract_sockaddr(pool->stratum_url, &pool->sockaddr_url, &pool->stratum_port))
  5664. return false;
  5665. if (!initiate_stratum(pool))
  5666. return false;
  5667. return true;
  5668. }
  5669. #ifdef HAVE_LIBCURL
  5670. static void __setup_gbt_solo(struct pool *pool)
  5671. {
  5672. cg_wlock(&pool->gbt_lock);
  5673. memcpy(pool->coinbase, scriptsig_header_bin, 41);
  5674. pool->coinbase[41 + pool->n1_len + 4 + 1 + 8] = 25;
  5675. memcpy(pool->coinbase + 41 + pool->n1_len + 4 + 1 + 8 + 1, pool->script_pubkey, 25);
  5676. cg_wunlock(&pool->gbt_lock);
  5677. }
  5678. static bool setup_gbt_solo(CURL *curl, struct pool *pool)
  5679. {
  5680. char s[256];
  5681. int uninitialised_var(rolltime);
  5682. bool ret = false;
  5683. json_t *val = NULL, *res_val, *valid_val;
  5684. if (!opt_btc_address) {
  5685. applog(LOG_ERR, "No BTC address specified, unable to mine solo on %s",
  5686. pool->rpc_url);
  5687. goto out;
  5688. }
  5689. snprintf(s, 256, "{\"method\": \"validateaddress\", \"params\": [\"%s\"]}\n", opt_btc_address);
  5690. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, s, true,
  5691. false, &rolltime, pool, false);
  5692. if (!val)
  5693. goto out;
  5694. res_val = json_object_get(val, "result");
  5695. if (!res_val)
  5696. goto out;
  5697. valid_val = json_object_get(res_val, "isvalid");
  5698. if (!valid_val)
  5699. goto out;
  5700. if (!json_is_true(valid_val)) {
  5701. applog(LOG_ERR, "Bitcoin address %s is NOT valid", opt_btc_address);
  5702. goto out;
  5703. }
  5704. applog(LOG_NOTICE, "Solo mining to valid address: %s", opt_btc_address);
  5705. ret = true;
  5706. address_to_pubkeyhash(pool->script_pubkey, opt_btc_address);
  5707. hex2bin(scriptsig_header_bin, scriptsig_header, 41);
  5708. __setup_gbt_solo(pool);
  5709. if (opt_debug) {
  5710. char *cb = bin2hex(pool->coinbase, pool->coinbase_len);
  5711. applog(LOG_DEBUG, "Pool %d coinbase %s", pool->pool_no, cb);
  5712. free(cb);
  5713. }
  5714. pool->gbt_curl = curl_easy_init();
  5715. if (unlikely(!pool->gbt_curl))
  5716. quit(1, "GBT CURL initialisation failed");
  5717. out:
  5718. if (val)
  5719. json_decref(val);
  5720. return ret;
  5721. }
  5722. #else
  5723. static bool setup_gbt_solo(CURL __maybe_unused *curl, struct pool __maybe_unused *pool)
  5724. {
  5725. return false;
  5726. }
  5727. #endif
  5728. static void pool_start_lp(struct pool *pool)
  5729. {
  5730. if (!pool->lp_started) {
  5731. pool->lp_started = true;
  5732. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  5733. quit(1, "Failed to create pool longpoll thread");
  5734. }
  5735. }
  5736. static bool pool_active(struct pool *pool, bool pinging)
  5737. {
  5738. struct timeval tv_getwork, tv_getwork_reply;
  5739. json_t *val = NULL;
  5740. bool ret = false;
  5741. CURL *curl;
  5742. int uninitialised_var(rolltime);
  5743. if (pool->has_gbt)
  5744. applog(LOG_DEBUG, "Retrieving block template from pool %s", pool->rpc_url);
  5745. else
  5746. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  5747. /* This is the central point we activate stratum when we can */
  5748. retry_stratum:
  5749. if (pool->has_stratum) {
  5750. /* We create the stratum thread for each pool just after
  5751. * successful authorisation. Once the init flag has been set
  5752. * we never unset it and the stratum thread is responsible for
  5753. * setting/unsetting the active flag */
  5754. bool init = pool_tset(pool, &pool->stratum_init);
  5755. if (!init) {
  5756. bool ret = initiate_stratum(pool) && auth_stratum(pool);
  5757. extranonce_subscribe_stratum(pool);
  5758. if (ret)
  5759. init_stratum_threads(pool);
  5760. else
  5761. pool_tclear(pool, &pool->stratum_init);
  5762. return ret;
  5763. }
  5764. return pool->stratum_active;
  5765. }
  5766. curl = curl_easy_init();
  5767. if (unlikely(!curl)) {
  5768. applog(LOG_ERR, "CURL initialisation failed");
  5769. return false;
  5770. }
  5771. /* Probe for GBT support on first pass */
  5772. if (!pool->probed) {
  5773. bool append = false, submit = false, transactions = false;
  5774. applog(LOG_DEBUG, "Probing for GBT support");
  5775. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass,
  5776. gbt_req, true, false, &rolltime, pool, false);
  5777. if (val) {
  5778. json_t *res_val, *mutables;
  5779. int i, mutsize = 0;
  5780. res_val = json_object_get(val, "result");
  5781. if (res_val) {
  5782. mutables = json_object_get(res_val, "mutable");
  5783. mutsize = json_array_size(mutables);
  5784. }
  5785. for (i = 0; i < mutsize; i++) {
  5786. json_t *arrval = json_array_get(mutables, i);
  5787. if (json_is_string(arrval)) {
  5788. const char *mutable = json_string_value(arrval);
  5789. if (!strncasecmp(mutable, "coinbase/append", 15))
  5790. append = true;
  5791. else if (!strncasecmp(mutable, "submit/coinbase", 15))
  5792. submit = true;
  5793. else if (!strncasecmp(mutable, "transactions", 12))
  5794. transactions = true;
  5795. }
  5796. }
  5797. json_decref(val);
  5798. /* Only use GBT if it supports coinbase append and
  5799. * submit coinbase */
  5800. if (append && submit) {
  5801. pool->has_gbt = true;
  5802. pool->rpc_req = gbt_req;
  5803. } else if (transactions && opt_btc_address) {
  5804. pool->gbt_solo = true;
  5805. pool->rpc_req = gbt_solo_req;
  5806. }
  5807. }
  5808. /* Reset this so we can probe fully just after this. It will be
  5809. * set to true that time.*/
  5810. pool->probed = false;
  5811. if (pool->has_gbt)
  5812. applog(LOG_DEBUG, "GBT coinbase + append support found, switching to GBT protocol");
  5813. else if (pool->gbt_solo)
  5814. applog(LOG_DEBUG, "GBT coinbase without append found, switching to GBT solo protocol");
  5815. else if (transactions)
  5816. applog(LOG_DEBUG, "GBT found but no target address specified, falling back to getwork protocol");
  5817. else
  5818. applog(LOG_DEBUG, "No GBT coinbase + append support found, using getwork protocol");
  5819. }
  5820. cgtime(&tv_getwork);
  5821. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass,
  5822. pool->rpc_req, true, false, &rolltime, pool, false);
  5823. cgtime(&tv_getwork_reply);
  5824. /* Detect if a http getwork pool has an X-Stratum header at startup,
  5825. * and if so, switch to that in preference to getwork if it works */
  5826. if (pool->stratum_url && !opt_fix_protocol && stratum_works(pool)) {
  5827. applog(LOG_NOTICE, "Switching pool %d %s to %s", pool->pool_no, pool->rpc_url, pool->stratum_url);
  5828. if (!pool->rpc_url)
  5829. pool->rpc_url = strdup(pool->stratum_url);
  5830. pool->has_stratum = true;
  5831. curl_easy_cleanup(curl);
  5832. goto retry_stratum;
  5833. }
  5834. if (val) {
  5835. struct work *work = make_work();
  5836. bool rc;
  5837. rc = work_decode(pool, work, val);
  5838. if (rc) {
  5839. if (pool->gbt_solo) {
  5840. ret = setup_gbt_solo(curl, pool);
  5841. if (ret)
  5842. pool_start_lp(pool);
  5843. free_work(work);
  5844. goto out;
  5845. }
  5846. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  5847. pool->pool_no, pool->rpc_url);
  5848. work->pool = pool;
  5849. work->rolltime = rolltime;
  5850. copy_time(&work->tv_getwork, &tv_getwork);
  5851. copy_time(&work->tv_getwork_reply, &tv_getwork_reply);
  5852. work->getwork_mode = GETWORK_MODE_TESTPOOL;
  5853. calc_diff(work, 0);
  5854. applog(LOG_DEBUG, "Pushing pooltest work to base pool");
  5855. stage_work(work);
  5856. total_getworks++;
  5857. pool->getwork_requested++;
  5858. ret = true;
  5859. cgtime(&pool->tv_idle);
  5860. } else {
  5861. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher work from pool %u %s",
  5862. pool->pool_no, pool->rpc_url);
  5863. free_work(work);
  5864. }
  5865. if (pool->lp_url)
  5866. goto out;
  5867. /* Decipher the longpoll URL, if any, and store it in ->lp_url */
  5868. if (pool->hdr_path) {
  5869. char *copy_start, *hdr_path;
  5870. bool need_slash = false;
  5871. size_t siz;
  5872. hdr_path = pool->hdr_path;
  5873. if (strstr(hdr_path, "://")) {
  5874. pool->lp_url = hdr_path;
  5875. hdr_path = NULL;
  5876. } else {
  5877. /* absolute path, on current server */
  5878. copy_start = (*hdr_path == '/') ? (hdr_path + 1) : hdr_path;
  5879. if (pool->rpc_url[strlen(pool->rpc_url) - 1] != '/')
  5880. need_slash = true;
  5881. siz = strlen(pool->rpc_url) + strlen(copy_start) + 2;
  5882. pool->lp_url = malloc(siz);
  5883. if (!pool->lp_url) {
  5884. applog(LOG_ERR, "Malloc failure in pool_active");
  5885. return false;
  5886. }
  5887. snprintf(pool->lp_url, siz, "%s%s%s", pool->rpc_url, need_slash ? "/" : "", copy_start);
  5888. }
  5889. } else
  5890. pool->lp_url = NULL;
  5891. pool_start_lp(pool);
  5892. } else {
  5893. /* If we failed to parse a getwork, this could be a stratum
  5894. * url without the prefix stratum+tcp:// so let's check it */
  5895. if (initiate_stratum(pool)) {
  5896. pool->has_stratum = true;
  5897. goto retry_stratum;
  5898. }
  5899. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  5900. pool->pool_no, pool->rpc_url);
  5901. if (!pinging && !pool->idle)
  5902. applog(LOG_WARNING, "Pool %u slow/down or URL or credentials invalid", pool->pool_no);
  5903. }
  5904. out:
  5905. if (val)
  5906. json_decref(val);
  5907. curl_easy_cleanup(curl);
  5908. return ret;
  5909. }
  5910. static void pool_resus(struct pool *pool)
  5911. {
  5912. pool->seq_getfails = 0;
  5913. if (pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  5914. applog(LOG_WARNING, "Pool %d %s alive, testing stability", pool->pool_no, pool->rpc_url);
  5915. else
  5916. applog(LOG_INFO, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  5917. }
  5918. static bool work_filled;
  5919. static bool work_emptied;
  5920. /* If this is called non_blocking, it will return NULL for work so that must
  5921. * be handled. */
  5922. static struct work *hash_pop(bool blocking)
  5923. {
  5924. struct work *work = NULL, *tmp;
  5925. int hc;
  5926. mutex_lock(stgd_lock);
  5927. if (!HASH_COUNT(staged_work)) {
  5928. /* Increase the queue if we reach zero and we know we can reach
  5929. * the maximum we're asking for. */
  5930. if (work_filled && max_queue < opt_queue) {
  5931. max_queue++;
  5932. work_filled = false;
  5933. }
  5934. work_emptied = true;
  5935. if (!blocking)
  5936. goto out_unlock;
  5937. do {
  5938. struct timespec then;
  5939. struct timeval now;
  5940. int rc;
  5941. cgtime(&now);
  5942. then.tv_sec = now.tv_sec + 10;
  5943. then.tv_nsec = now.tv_usec * 1000;
  5944. pthread_cond_signal(&gws_cond);
  5945. rc = pthread_cond_timedwait(&getq->cond, stgd_lock, &then);
  5946. /* Check again for !no_work as multiple threads may be
  5947. * waiting on this condition and another may set the
  5948. * bool separately. */
  5949. if (rc && !no_work) {
  5950. no_work = true;
  5951. applog(LOG_WARNING, "Waiting for work to be available from pools.");
  5952. }
  5953. } while (!HASH_COUNT(staged_work));
  5954. }
  5955. if (no_work) {
  5956. applog(LOG_WARNING, "Work available from pools, resuming.");
  5957. no_work = false;
  5958. }
  5959. hc = HASH_COUNT(staged_work);
  5960. /* Find clone work if possible, to allow masters to be reused */
  5961. if (hc > staged_rollable) {
  5962. HASH_ITER(hh, staged_work, work, tmp) {
  5963. if (!work_rollable(work))
  5964. break;
  5965. }
  5966. } else
  5967. work = staged_work;
  5968. HASH_DEL(staged_work, work);
  5969. if (work_rollable(work))
  5970. staged_rollable--;
  5971. /* Signal the getwork scheduler to look for more work */
  5972. pthread_cond_signal(&gws_cond);
  5973. /* Signal hash_pop again in case there are mutliple hash_pop waiters */
  5974. pthread_cond_signal(&getq->cond);
  5975. /* Keep track of last getwork grabbed */
  5976. last_getwork = time(NULL);
  5977. out_unlock:
  5978. mutex_unlock(stgd_lock);
  5979. return work;
  5980. }
  5981. static void gen_hash(unsigned char *data, unsigned char *hash, int len)
  5982. {
  5983. unsigned char hash1[32];
  5984. sha256(data, len, hash1);
  5985. sha256(hash1, 32, hash);
  5986. }
  5987. void set_target(unsigned char *dest_target, double diff)
  5988. {
  5989. unsigned char target[32];
  5990. uint64_t *data64, h64;
  5991. double d64, dcut64;
  5992. if (unlikely(diff == 0.0)) {
  5993. /* This shouldn't happen but best we check to prevent a crash */
  5994. applog(LOG_ERR, "Diff zero passed to set_target");
  5995. diff = 1.0;
  5996. }
  5997. d64 = truediffone;
  5998. if (opt_scrypt)
  5999. d64 *= (double)65536;
  6000. d64 /= diff;
  6001. dcut64 = d64 / bits192;
  6002. h64 = dcut64;
  6003. data64 = (uint64_t *)(target + 24);
  6004. *data64 = htole64(h64);
  6005. dcut64 = h64;
  6006. dcut64 *= bits192;
  6007. d64 -= dcut64;
  6008. dcut64 = d64 / bits128;
  6009. h64 = dcut64;
  6010. data64 = (uint64_t *)(target + 16);
  6011. *data64 = htole64(h64);
  6012. dcut64 = h64;
  6013. dcut64 *= bits128;
  6014. d64 -= dcut64;
  6015. dcut64 = d64 / bits64;
  6016. h64 = dcut64;
  6017. data64 = (uint64_t *)(target + 8);
  6018. *data64 = htole64(h64);
  6019. dcut64 = h64;
  6020. dcut64 *= bits64;
  6021. d64 -= dcut64;
  6022. h64 = d64;
  6023. data64 = (uint64_t *)(target);
  6024. *data64 = htole64(h64);
  6025. if (opt_debug) {
  6026. char *htarget = bin2hex(target, 32);
  6027. applog(LOG_DEBUG, "Generated target %s", htarget);
  6028. free(htarget);
  6029. }
  6030. memcpy(dest_target, target, 32);
  6031. }
  6032. #ifdef USE_AVALON2
  6033. void submit_nonce2_nonce(struct thr_info *thr, uint32_t pool_no, uint32_t nonce2, uint32_t nonce)
  6034. {
  6035. struct cgpu_info *cgpu = thr->cgpu;
  6036. struct device_drv *drv = cgpu->drv;
  6037. struct pool *pool = pools[pool_no];
  6038. struct work *work = make_work();
  6039. pool->nonce2 = nonce2;
  6040. gen_stratum_work(pool, work);
  6041. submit_nonce(thr, work, nonce);
  6042. free_work(work);
  6043. }
  6044. #endif
  6045. /* Generates stratum based work based on the most recent notify information
  6046. * from the pool. This will keep generating work while a pool is down so we use
  6047. * other means to detect when the pool has died in stratum_thread */
  6048. static void gen_stratum_work(struct pool *pool, struct work *work)
  6049. {
  6050. unsigned char merkle_root[32], merkle_sha[64];
  6051. uint32_t *data32, *swap32;
  6052. uint64_t nonce2le;
  6053. int i;
  6054. cg_wlock(&pool->data_lock);
  6055. /* Update coinbase. Always use an LE encoded nonce2 to fill in values
  6056. * from left to right and prevent overflow errors with small n2sizes */
  6057. nonce2le = htole64(pool->nonce2);
  6058. memcpy(pool->coinbase + pool->nonce2_offset, &nonce2le, pool->n2size);
  6059. work->nonce2 = pool->nonce2++;
  6060. work->nonce2_len = pool->n2size;
  6061. /* Downgrade to a read lock to read off the pool variables */
  6062. cg_dwlock(&pool->data_lock);
  6063. /* Generate merkle root */
  6064. gen_hash(pool->coinbase, merkle_root, pool->coinbase_len);
  6065. memcpy(merkle_sha, merkle_root, 32);
  6066. for (i = 0; i < pool->merkles; i++) {
  6067. memcpy(merkle_sha + 32, pool->swork.merkle_bin[i], 32);
  6068. gen_hash(merkle_sha, merkle_root, 64);
  6069. memcpy(merkle_sha, merkle_root, 32);
  6070. }
  6071. data32 = (uint32_t *)merkle_sha;
  6072. swap32 = (uint32_t *)merkle_root;
  6073. flip32(swap32, data32);
  6074. /* Copy the data template from header_bin */
  6075. memcpy(work->data, pool->header_bin, 112);
  6076. memcpy(work->data + 36, merkle_root, 32);
  6077. /* Store the stratum work diff to check it still matches the pool's
  6078. * stratum diff when submitting shares */
  6079. work->sdiff = pool->sdiff;
  6080. /* Copy parameters required for share submission */
  6081. work->job_id = strdup(pool->swork.job_id);
  6082. work->nonce1 = strdup(pool->nonce1);
  6083. work->ntime = strdup(pool->ntime);
  6084. cg_runlock(&pool->data_lock);
  6085. if (opt_debug) {
  6086. char *header, *merkle_hash;
  6087. header = bin2hex(work->data, 112);
  6088. merkle_hash = bin2hex((const unsigned char *)merkle_root, 32);
  6089. applog(LOG_DEBUG, "Generated stratum merkle %s", merkle_hash);
  6090. applog(LOG_DEBUG, "Generated stratum header %s", header);
  6091. applog(LOG_DEBUG, "Work job_id %s nonce2 %"PRIu64" ntime %s", work->job_id,
  6092. work->nonce2, work->ntime);
  6093. free(header);
  6094. free(merkle_hash);
  6095. }
  6096. calc_midstate(work);
  6097. set_target(work->target, work->sdiff);
  6098. local_work++;
  6099. work->pool = pool;
  6100. work->stratum = true;
  6101. work->nonce = 0;
  6102. work->longpoll = false;
  6103. work->getwork_mode = GETWORK_MODE_STRATUM;
  6104. work->work_block = work_block;
  6105. /* Nominally allow a driver to ntime roll 60 seconds */
  6106. work->drv_rolllimit = 60;
  6107. calc_diff(work, work->sdiff);
  6108. cgtime(&work->tv_staged);
  6109. }
  6110. #ifdef HAVE_LIBCURL
  6111. static void gen_solo_work(struct pool *pool, struct work *work);
  6112. /* Use the one instance of gbt_curl, protecting the bool with the gbt_lock but
  6113. * avoiding holding the lock once we've set the bool. */
  6114. static void get_gbt_curl(struct pool *pool, int poll)
  6115. {
  6116. cg_ilock(&pool->gbt_lock);
  6117. while (pool->gbt_curl_inuse) {
  6118. cg_uilock(&pool->gbt_lock);
  6119. cgsleep_ms(poll);
  6120. cg_ilock(&pool->gbt_lock);
  6121. }
  6122. cg_ulock(&pool->gbt_lock);
  6123. pool->gbt_curl_inuse = true;
  6124. cg_wunlock(&pool->gbt_lock);
  6125. }
  6126. /* No need for locking here */
  6127. static inline void release_gbt_curl(struct pool *pool)
  6128. {
  6129. pool->gbt_curl_inuse = false;
  6130. }
  6131. static void update_gbt_solo(struct pool *pool)
  6132. {
  6133. struct work *work = make_work();
  6134. int rolltime;
  6135. json_t *val;
  6136. get_gbt_curl(pool, 10);
  6137. retry:
  6138. /* Bitcoind doesn't like many open RPC connections. */
  6139. curl_easy_setopt(pool->gbt_curl, CURLOPT_FORBID_REUSE, 1);
  6140. val = json_rpc_call(pool->gbt_curl, pool->rpc_url, pool->rpc_userpass, pool->rpc_req,
  6141. true, false, &rolltime, pool, false);
  6142. if (likely(val)) {
  6143. bool rc = work_decode(pool, work, val);
  6144. if (rc) {
  6145. __setup_gbt_solo(pool);
  6146. gen_solo_work(pool, work);
  6147. stage_work(work);
  6148. } else
  6149. free_work(work);
  6150. json_decref(val);
  6151. } else {
  6152. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get gbt, retrying in 5s",
  6153. pool->pool_no);
  6154. if (++pool->seq_getfails > 5) {
  6155. pool_died(pool);
  6156. goto out;
  6157. }
  6158. cgsleep_ms(5000);
  6159. goto retry;
  6160. }
  6161. out:
  6162. release_gbt_curl(pool);
  6163. }
  6164. static void gen_solo_work(struct pool *pool, struct work *work)
  6165. {
  6166. unsigned char merkle_root[32], merkle_sha[64];
  6167. uint32_t *data32, *swap32;
  6168. struct timeval now;
  6169. uint64_t nonce2le;
  6170. int i;
  6171. cgtime(&now);
  6172. if (now.tv_sec - pool->tv_lastwork.tv_sec > 60)
  6173. update_gbt_solo(pool);
  6174. cg_wlock(&pool->gbt_lock);
  6175. /* Update coinbase. Always use an LE encoded nonce2 to fill in values
  6176. * from left to right and prevent overflow errors with small n2sizes */
  6177. nonce2le = htole64(pool->nonce2);
  6178. memcpy(pool->coinbase + pool->nonce2_offset, &nonce2le, pool->n2size);
  6179. work->nonce2 = pool->nonce2++;
  6180. work->nonce2_len = pool->n2size;
  6181. work->gbt_txns = pool->transactions + 1;
  6182. /* Downgrade to a read lock to read off the pool variables */
  6183. cg_dwlock(&pool->gbt_lock);
  6184. work->coinbase = bin2hex(pool->coinbase, pool->coinbase_len);
  6185. /* Generate merkle root */
  6186. gen_hash(pool->coinbase, merkle_root, pool->coinbase_len);
  6187. memcpy(merkle_sha, merkle_root, 32);
  6188. for (i = 0; i < pool->merkles; i++) {
  6189. unsigned char *merkle_bin;
  6190. merkle_bin = pool->merklebin + (i * 32);
  6191. memcpy(merkle_sha + 32, merkle_bin, 32);
  6192. gen_hash(merkle_sha, merkle_root, 64);
  6193. memcpy(merkle_sha, merkle_root, 32);
  6194. }
  6195. data32 = (uint32_t *)merkle_sha;
  6196. swap32 = (uint32_t *)merkle_root;
  6197. flip32(swap32, data32);
  6198. /* Copy the data template from header_bin */
  6199. memcpy(work->data, pool->header_bin, 112);
  6200. memcpy(work->data + 36, merkle_root, 32);
  6201. work->sdiff = pool->sdiff;
  6202. /* Copy parameters required for share submission */
  6203. work->ntime = strdup(pool->ntime);
  6204. memcpy(work->target, pool->gbt_target, 32);
  6205. cg_runlock(&pool->gbt_lock);
  6206. if (opt_debug) {
  6207. char *header, *merkle_hash;
  6208. header = bin2hex(work->data, 112);
  6209. merkle_hash = bin2hex((const unsigned char *)merkle_root, 32);
  6210. applog(LOG_DEBUG, "Generated GBT solo merkle %s", merkle_hash);
  6211. applog(LOG_DEBUG, "Generated GBT solo header %s", header);
  6212. applog(LOG_DEBUG, "Work nonce2 %"PRIu64" ntime %s", work->nonce2,
  6213. work->ntime);
  6214. free(header);
  6215. free(merkle_hash);
  6216. }
  6217. calc_midstate(work);
  6218. local_work++;
  6219. work->gbt = true;
  6220. work->pool = pool;
  6221. work->nonce = 0;
  6222. work->longpoll = false;
  6223. work->getwork_mode = GETWORK_MODE_SOLO;
  6224. work->work_block = work_block;
  6225. /* Nominally allow a driver to ntime roll 60 seconds */
  6226. work->drv_rolllimit = 60;
  6227. calc_diff(work, work->sdiff);
  6228. cgtime(&work->tv_staged);
  6229. }
  6230. #endif
  6231. /* The time difference in seconds between when this device last got work via
  6232. * get_work() and generated a valid share. */
  6233. int share_work_tdiff(struct cgpu_info *cgpu)
  6234. {
  6235. return last_getwork - cgpu->last_device_valid_work;
  6236. }
  6237. static void set_benchmark_work(struct cgpu_info *cgpu, struct work *work)
  6238. {
  6239. cgpu->lodiff += cgpu->direction;
  6240. if (cgpu->lodiff < 1)
  6241. cgpu->direction = 1;
  6242. if (cgpu->lodiff > 15) {
  6243. cgpu->direction = -1;
  6244. if (++cgpu->hidiff > 15)
  6245. cgpu->hidiff = 0;
  6246. memcpy(work, &bench_hidiff_bins[cgpu->hidiff][0], 160);
  6247. } else
  6248. memcpy(work, &bench_lodiff_bins[cgpu->lodiff][0], 160);
  6249. }
  6250. struct work *get_work(struct thr_info *thr, const int thr_id)
  6251. {
  6252. struct cgpu_info *cgpu = thr->cgpu;
  6253. struct work *work = NULL;
  6254. time_t diff_t;
  6255. thread_reportout(thr);
  6256. applog(LOG_DEBUG, "Popping work from get queue to get work");
  6257. diff_t = time(NULL);
  6258. while (!work) {
  6259. work = hash_pop(true);
  6260. if (stale_work(work, false)) {
  6261. discard_work(work);
  6262. wake_gws();
  6263. }
  6264. }
  6265. diff_t = time(NULL) - diff_t;
  6266. /* Since this is a blocking function, we need to add grace time to
  6267. * the device's last valid work to not make outages appear to be
  6268. * device failures. */
  6269. if (diff_t > 0) {
  6270. applog(LOG_DEBUG, "Get work blocked for %d seconds", (int)diff_t);
  6271. cgpu->last_device_valid_work += diff_t;
  6272. }
  6273. applog(LOG_DEBUG, "Got work from get queue to get work for thread %d", thr_id);
  6274. work->thr_id = thr_id;
  6275. if (opt_benchmark)
  6276. set_benchmark_work(cgpu, work);
  6277. thread_reportin(thr);
  6278. work->mined = true;
  6279. work->device_diff = MIN(cgpu->drv->max_diff, work->work_difficulty);
  6280. return work;
  6281. }
  6282. /* Submit a copy of the tested, statistic recorded work item asynchronously */
  6283. static void submit_work_async(struct work *work)
  6284. {
  6285. struct pool *pool = work->pool;
  6286. pthread_t submit_thread;
  6287. cgtime(&work->tv_work_found);
  6288. if (opt_benchmark) {
  6289. struct cgpu_info *cgpu = get_thr_cgpu(work->thr_id);
  6290. mutex_lock(&stats_lock);
  6291. cgpu->accepted++;
  6292. total_accepted++;
  6293. pool->accepted++;
  6294. cgpu->diff_accepted += work->work_difficulty;
  6295. total_diff_accepted += work->work_difficulty;
  6296. pool->diff_accepted += work->work_difficulty;
  6297. mutex_unlock(&stats_lock);
  6298. applog(LOG_NOTICE, "Accepted %s %d benchmark share nonce %08x",
  6299. cgpu->drv->name, cgpu->device_id, *(uint32_t *)(work->data + 64 + 12));
  6300. return;
  6301. }
  6302. if (stale_work(work, true)) {
  6303. if (opt_submit_stale)
  6304. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as user requested", pool->pool_no);
  6305. else if (pool->submit_old)
  6306. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as pool requested", pool->pool_no);
  6307. else {
  6308. applog(LOG_NOTICE, "Pool %d stale share detected, discarding", pool->pool_no);
  6309. sharelog("discard", work);
  6310. mutex_lock(&stats_lock);
  6311. total_stale++;
  6312. pool->stale_shares++;
  6313. total_diff_stale += work->work_difficulty;
  6314. pool->diff_stale += work->work_difficulty;
  6315. mutex_unlock(&stats_lock);
  6316. free_work(work);
  6317. return;
  6318. }
  6319. work->stale = true;
  6320. }
  6321. if (work->stratum) {
  6322. applog(LOG_DEBUG, "Pushing pool %d work to stratum queue", pool->pool_no);
  6323. if (unlikely(!tq_push(pool->stratum_q, work))) {
  6324. applog(LOG_DEBUG, "Discarding work from removed pool");
  6325. free_work(work);
  6326. }
  6327. } else {
  6328. applog(LOG_DEBUG, "Pushing submit work to work thread");
  6329. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, (void *)work)))
  6330. quit(1, "Failed to create submit_work_thread");
  6331. }
  6332. }
  6333. void inc_hw_errors(struct thr_info *thr)
  6334. {
  6335. applog(LOG_INFO, "%s%d: invalid nonce - HW error", thr->cgpu->drv->name,
  6336. thr->cgpu->device_id);
  6337. mutex_lock(&stats_lock);
  6338. hw_errors++;
  6339. thr->cgpu->hw_errors++;
  6340. mutex_unlock(&stats_lock);
  6341. thr->cgpu->drv->hw_error(thr);
  6342. }
  6343. /* Fills in the work nonce and builds the output data in work->hash */
  6344. static void rebuild_nonce(struct work *work, uint32_t nonce)
  6345. {
  6346. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  6347. *work_nonce = htole32(nonce);
  6348. rebuild_hash(work);
  6349. }
  6350. /* For testing a nonce against diff 1 */
  6351. bool test_nonce(struct work *work, uint32_t nonce)
  6352. {
  6353. uint32_t *hash_32 = (uint32_t *)(work->hash + 28);
  6354. rebuild_nonce(work, nonce);
  6355. return (*hash_32 <= (opt_scrypt ? 0x0000ffffUL : 0));
  6356. }
  6357. /* For testing a nonce against an arbitrary diff */
  6358. bool test_nonce_diff(struct work *work, uint32_t nonce, double diff)
  6359. {
  6360. uint64_t *hash64 = (uint64_t *)(work->hash + 24), diff64;
  6361. rebuild_nonce(work, nonce);
  6362. diff64 = opt_scrypt ? 0x0000ffff00000000ULL : 0x00000000ffff0000ULL;
  6363. diff64 /= diff;
  6364. return (le64toh(*hash64) <= diff64);
  6365. }
  6366. static void update_work_stats(struct thr_info *thr, struct work *work)
  6367. {
  6368. double test_diff = current_diff;
  6369. work->share_diff = share_diff(work);
  6370. if (opt_scrypt)
  6371. test_diff *= (double)65536;
  6372. if (unlikely(work->share_diff >= test_diff)) {
  6373. work->block = true;
  6374. work->pool->solved++;
  6375. found_blocks++;
  6376. work->mandatory = true;
  6377. applog(LOG_NOTICE, "Found block for pool %d!", work->pool->pool_no);
  6378. }
  6379. mutex_lock(&stats_lock);
  6380. total_diff1 += work->device_diff;
  6381. thr->cgpu->diff1 += work->device_diff;
  6382. work->pool->diff1 += work->device_diff;
  6383. thr->cgpu->last_device_valid_work = time(NULL);
  6384. mutex_unlock(&stats_lock);
  6385. }
  6386. /* To be used once the work has been tested to be meet diff1 and has had its
  6387. * nonce adjusted. Returns true if the work target is met. */
  6388. bool submit_tested_work(struct thr_info *thr, struct work *work)
  6389. {
  6390. struct work *work_out;
  6391. update_work_stats(thr, work);
  6392. if (!fulltest(work->hash, work->target)) {
  6393. applog(LOG_INFO, "%s %d: Share above target", thr->cgpu->drv->name,
  6394. thr->cgpu->device_id);
  6395. return false;
  6396. }
  6397. work_out = copy_work(work);
  6398. submit_work_async(work_out);
  6399. return true;
  6400. }
  6401. /* Returns true if nonce for work was a valid share */
  6402. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  6403. {
  6404. if (test_nonce(work, nonce))
  6405. submit_tested_work(thr, work);
  6406. else {
  6407. inc_hw_errors(thr);
  6408. return false;
  6409. }
  6410. if (opt_benchfile && opt_benchfile_display)
  6411. benchfile_dspwork(work, nonce);
  6412. return true;
  6413. }
  6414. /* Allows drivers to submit work items where the driver has changed the ntime
  6415. * value by noffset. Must be only used with a work protocol that does not ntime
  6416. * roll itself intrinsically to generate work (eg stratum). We do not touch
  6417. * the original work struct, but the copy of it only. */
  6418. bool submit_noffset_nonce(struct thr_info *thr, struct work *work_in, uint32_t nonce,
  6419. int noffset)
  6420. {
  6421. struct work *work = make_work();
  6422. bool ret = false;
  6423. _copy_work(work, work_in, noffset);
  6424. if (!test_nonce(work, nonce)) {
  6425. free_work(work);
  6426. inc_hw_errors(thr);
  6427. goto out;
  6428. }
  6429. update_work_stats(thr, work);
  6430. if (opt_benchfile && opt_benchfile_display)
  6431. benchfile_dspwork(work, nonce);
  6432. ret = true;
  6433. if (!fulltest(work->hash, work->target)) {
  6434. free_work(work);
  6435. applog(LOG_INFO, "%s %d: Share above target", thr->cgpu->drv->name,
  6436. thr->cgpu->device_id);
  6437. goto out;
  6438. }
  6439. submit_work_async(work);
  6440. out:
  6441. return ret;
  6442. }
  6443. static inline bool abandon_work(struct work *work, struct timeval *wdiff, uint64_t hashes)
  6444. {
  6445. if (wdiff->tv_sec > opt_scantime || hashes >= 0xfffffffe ||
  6446. stale_work(work, false))
  6447. return true;
  6448. return false;
  6449. }
  6450. static void mt_disable(struct thr_info *mythr, const int thr_id,
  6451. struct device_drv *drv)
  6452. {
  6453. applog(LOG_WARNING, "Thread %d being disabled", thr_id);
  6454. mythr->cgpu->rolling = 0;
  6455. applog(LOG_DEBUG, "Waiting on sem in miner thread");
  6456. cgsem_wait(&mythr->sem);
  6457. applog(LOG_WARNING, "Thread %d being re-enabled", thr_id);
  6458. drv->thread_enable(mythr);
  6459. }
  6460. /* The main hashing loop for devices that are slow enough to work on one work
  6461. * item at a time, without a queue, aborting work before the entire nonce
  6462. * range has been hashed if needed. */
  6463. static void hash_sole_work(struct thr_info *mythr)
  6464. {
  6465. const int thr_id = mythr->id;
  6466. struct cgpu_info *cgpu = mythr->cgpu;
  6467. struct device_drv *drv = cgpu->drv;
  6468. struct timeval getwork_start, tv_start, *tv_end, tv_workstart, tv_lastupdate;
  6469. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  6470. struct cgminer_stats *pool_stats;
  6471. /* Try to cycle approximately 5 times before each log update */
  6472. const long cycle = opt_log_interval / 5 ? : 1;
  6473. const bool primary = (!mythr->device_thread) || mythr->primary_thread;
  6474. struct timeval diff, sdiff, wdiff = {0, 0};
  6475. uint32_t max_nonce = drv->can_limit_work(mythr);
  6476. int64_t hashes_done = 0;
  6477. tv_end = &getwork_start;
  6478. cgtime(&getwork_start);
  6479. sdiff.tv_sec = sdiff.tv_usec = 0;
  6480. cgtime(&tv_lastupdate);
  6481. while (likely(!cgpu->shutdown)) {
  6482. struct work *work = get_work(mythr, thr_id);
  6483. int64_t hashes;
  6484. mythr->work_restart = false;
  6485. cgpu->new_work = true;
  6486. cgtime(&tv_workstart);
  6487. work->nonce = 0;
  6488. cgpu->max_hashes = 0;
  6489. if (!drv->prepare_work(mythr, work)) {
  6490. applog(LOG_ERR, "work prepare failed, exiting "
  6491. "mining thread %d", thr_id);
  6492. break;
  6493. }
  6494. work->device_diff = MIN(drv->max_diff, work->work_difficulty);
  6495. do {
  6496. cgtime(&tv_start);
  6497. subtime(&tv_start, &getwork_start);
  6498. addtime(&getwork_start, &dev_stats->getwork_wait);
  6499. if (time_more(&getwork_start, &dev_stats->getwork_wait_max))
  6500. copy_time(&dev_stats->getwork_wait_max, &getwork_start);
  6501. if (time_less(&getwork_start, &dev_stats->getwork_wait_min))
  6502. copy_time(&dev_stats->getwork_wait_min, &getwork_start);
  6503. dev_stats->getwork_calls++;
  6504. pool_stats = &(work->pool->cgminer_stats);
  6505. addtime(&getwork_start, &pool_stats->getwork_wait);
  6506. if (time_more(&getwork_start, &pool_stats->getwork_wait_max))
  6507. copy_time(&pool_stats->getwork_wait_max, &getwork_start);
  6508. if (time_less(&getwork_start, &pool_stats->getwork_wait_min))
  6509. copy_time(&pool_stats->getwork_wait_min, &getwork_start);
  6510. pool_stats->getwork_calls++;
  6511. cgtime(&(work->tv_work_start));
  6512. /* Only allow the mining thread to be cancelled when
  6513. * it is not in the driver code. */
  6514. pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
  6515. thread_reportin(mythr);
  6516. hashes = drv->scanhash(mythr, work, work->nonce + max_nonce);
  6517. thread_reportout(mythr);
  6518. pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
  6519. pthread_testcancel();
  6520. /* tv_end is == &getwork_start */
  6521. cgtime(&getwork_start);
  6522. if (unlikely(hashes == -1)) {
  6523. applog(LOG_ERR, "%s %d failure, disabling!", drv->name, cgpu->device_id);
  6524. cgpu->deven = DEV_DISABLED;
  6525. dev_error(cgpu, REASON_THREAD_ZERO_HASH);
  6526. cgpu->shutdown = true;
  6527. break;
  6528. }
  6529. hashes_done += hashes;
  6530. if (hashes > cgpu->max_hashes)
  6531. cgpu->max_hashes = hashes;
  6532. timersub(tv_end, &tv_start, &diff);
  6533. sdiff.tv_sec += diff.tv_sec;
  6534. sdiff.tv_usec += diff.tv_usec;
  6535. if (sdiff.tv_usec > 1000000) {
  6536. ++sdiff.tv_sec;
  6537. sdiff.tv_usec -= 1000000;
  6538. }
  6539. timersub(tv_end, &tv_workstart, &wdiff);
  6540. if (unlikely((long)sdiff.tv_sec < cycle)) {
  6541. int mult;
  6542. if (likely(max_nonce == 0xffffffff))
  6543. continue;
  6544. mult = 1000000 / ((sdiff.tv_usec + 0x400) / 0x400) + 0x10;
  6545. mult *= cycle;
  6546. if (max_nonce > (0xffffffff * 0x400) / mult)
  6547. max_nonce = 0xffffffff;
  6548. else
  6549. max_nonce = (max_nonce * mult) / 0x400;
  6550. } else if (unlikely(sdiff.tv_sec > cycle))
  6551. max_nonce = max_nonce * cycle / sdiff.tv_sec;
  6552. else if (unlikely(sdiff.tv_usec > 100000))
  6553. max_nonce = max_nonce * 0x400 / (((cycle * 1000000) + sdiff.tv_usec) / (cycle * 1000000 / 0x400));
  6554. timersub(tv_end, &tv_lastupdate, &diff);
  6555. /* Update the hashmeter at most 5 times per second */
  6556. if ((hashes_done && (diff.tv_sec > 0 || diff.tv_usec > 200000)) ||
  6557. diff.tv_sec >= opt_log_interval) {
  6558. hashmeter(thr_id, hashes_done);
  6559. hashes_done = 0;
  6560. copy_time(&tv_lastupdate, tv_end);
  6561. }
  6562. if (unlikely(mythr->work_restart)) {
  6563. /* Apart from device_thread 0, we stagger the
  6564. * starting of every next thread to try and get
  6565. * all devices busy before worrying about
  6566. * getting work for their extra threads */
  6567. if (!primary) {
  6568. struct timespec rgtp;
  6569. rgtp.tv_sec = 0;
  6570. rgtp.tv_nsec = 250 * mythr->device_thread * 1000000;
  6571. nanosleep(&rgtp, NULL);
  6572. }
  6573. break;
  6574. }
  6575. if (unlikely(mythr->pause || cgpu->deven != DEV_ENABLED))
  6576. mt_disable(mythr, thr_id, drv);
  6577. sdiff.tv_sec = sdiff.tv_usec = 0;
  6578. } while (!abandon_work(work, &wdiff, cgpu->max_hashes));
  6579. free_work(work);
  6580. }
  6581. cgpu->deven = DEV_DISABLED;
  6582. }
  6583. /* Put a new unqueued work item in cgpu->unqueued_work under cgpu->qlock till
  6584. * the driver tells us it's full so that it may extract the work item using
  6585. * the get_queued() function which adds it to the hashtable on
  6586. * cgpu->queued_work. */
  6587. static void fill_queue(struct thr_info *mythr, struct cgpu_info *cgpu, struct device_drv *drv, const int thr_id)
  6588. {
  6589. do {
  6590. bool need_work;
  6591. /* Do this lockless just to know if we need more unqueued work. */
  6592. need_work = (!cgpu->unqueued_work);
  6593. /* get_work is a blocking function so do it outside of lock
  6594. * to prevent deadlocks with other locks. */
  6595. if (need_work) {
  6596. struct work *work = get_work(mythr, thr_id);
  6597. wr_lock(&cgpu->qlock);
  6598. /* Check we haven't grabbed work somehow between
  6599. * checking and picking up the lock. */
  6600. if (likely(!cgpu->unqueued_work))
  6601. cgpu->unqueued_work = work;
  6602. else
  6603. need_work = false;
  6604. wr_unlock(&cgpu->qlock);
  6605. if (unlikely(!need_work))
  6606. discard_work(work);
  6607. }
  6608. /* The queue_full function should be used by the driver to
  6609. * actually place work items on the physical device if it
  6610. * does have a queue. */
  6611. } while (!drv->queue_full(cgpu));
  6612. }
  6613. /* Add a work item to a cgpu's queued hashlist */
  6614. void __add_queued(struct cgpu_info *cgpu, struct work *work)
  6615. {
  6616. cgpu->queued_count++;
  6617. HASH_ADD_INT(cgpu->queued_work, id, work);
  6618. }
  6619. /* This function is for retrieving one work item from the unqueued pointer and
  6620. * adding it to the hashtable of queued work. Code using this function must be
  6621. * able to handle NULL as a return which implies there is no work available. */
  6622. struct work *get_queued(struct cgpu_info *cgpu)
  6623. {
  6624. struct work *work = NULL;
  6625. wr_lock(&cgpu->qlock);
  6626. if (cgpu->unqueued_work) {
  6627. work = cgpu->unqueued_work;
  6628. if (unlikely(stale_work(work, false))) {
  6629. discard_work(work);
  6630. wake_gws();
  6631. } else
  6632. __add_queued(cgpu, work);
  6633. cgpu->unqueued_work = NULL;
  6634. }
  6635. wr_unlock(&cgpu->qlock);
  6636. return work;
  6637. }
  6638. void add_queued(struct cgpu_info *cgpu, struct work *work)
  6639. {
  6640. wr_lock(&cgpu->qlock);
  6641. __add_queued(cgpu, work);
  6642. wr_unlock(&cgpu->qlock);
  6643. }
  6644. /* Get fresh work and add it to cgpu's queued hashlist */
  6645. struct work *get_queue_work(struct thr_info *thr, struct cgpu_info *cgpu, int thr_id)
  6646. {
  6647. struct work *work = get_work(thr, thr_id);
  6648. add_queued(cgpu, work);
  6649. return work;
  6650. }
  6651. /* This function is for finding an already queued work item in the
  6652. * given que hashtable. Code using this function must be able
  6653. * to handle NULL as a return which implies there is no matching work.
  6654. * The calling function must lock access to the que if it is required.
  6655. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  6656. struct work *__find_work_bymidstate(struct work *que, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  6657. {
  6658. struct work *work, *tmp, *ret = NULL;
  6659. HASH_ITER(hh, que, work, tmp) {
  6660. if (memcmp(work->midstate, midstate, midstatelen) == 0 &&
  6661. memcmp(work->data + offset, data, datalen) == 0) {
  6662. ret = work;
  6663. break;
  6664. }
  6665. }
  6666. return ret;
  6667. }
  6668. /* This function is for finding an already queued work item in the
  6669. * device's queued_work hashtable. Code using this function must be able
  6670. * to handle NULL as a return which implies there is no matching work.
  6671. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  6672. struct work *find_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  6673. {
  6674. struct work *ret;
  6675. rd_lock(&cgpu->qlock);
  6676. ret = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  6677. rd_unlock(&cgpu->qlock);
  6678. return ret;
  6679. }
  6680. struct work *clone_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  6681. {
  6682. struct work *work, *ret = NULL;
  6683. rd_lock(&cgpu->qlock);
  6684. work = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  6685. if (work)
  6686. ret = copy_work(work);
  6687. rd_unlock(&cgpu->qlock);
  6688. return ret;
  6689. }
  6690. /* This function is for finding an already queued work item in the
  6691. * given que hashtable. Code using this function must be able
  6692. * to handle NULL as a return which implies there is no matching work.
  6693. * The calling function must lock access to the que if it is required. */
  6694. struct work *__find_work_byid(struct work *que, uint32_t id)
  6695. {
  6696. struct work *work, *tmp, *ret = NULL;
  6697. HASH_ITER(hh, que, work, tmp) {
  6698. if (work->id == id) {
  6699. ret = work;
  6700. break;
  6701. }
  6702. }
  6703. return ret;
  6704. }
  6705. struct work *find_queued_work_byid(struct cgpu_info *cgpu, uint32_t id)
  6706. {
  6707. struct work *ret;
  6708. rd_lock(&cgpu->qlock);
  6709. ret = __find_work_byid(cgpu->queued_work, id);
  6710. rd_unlock(&cgpu->qlock);
  6711. return ret;
  6712. }
  6713. void __work_completed(struct cgpu_info *cgpu, struct work *work)
  6714. {
  6715. cgpu->queued_count--;
  6716. HASH_DEL(cgpu->queued_work, work);
  6717. }
  6718. /* This iterates over a queued hashlist finding work started more than secs
  6719. * seconds ago and discards the work as completed. The driver must set the
  6720. * work->tv_work_start value appropriately. Returns the number of items aged. */
  6721. int age_queued_work(struct cgpu_info *cgpu, double secs)
  6722. {
  6723. struct work *work, *tmp;
  6724. struct timeval tv_now;
  6725. int aged = 0;
  6726. cgtime(&tv_now);
  6727. wr_lock(&cgpu->qlock);
  6728. HASH_ITER(hh, cgpu->queued_work, work, tmp) {
  6729. if (tdiff(&tv_now, &work->tv_work_start) > secs) {
  6730. __work_completed(cgpu, work);
  6731. free_work(work);
  6732. aged++;
  6733. }
  6734. }
  6735. wr_unlock(&cgpu->qlock);
  6736. return aged;
  6737. }
  6738. /* This function should be used by queued device drivers when they're sure
  6739. * the work struct is no longer in use. */
  6740. void work_completed(struct cgpu_info *cgpu, struct work *work)
  6741. {
  6742. wr_lock(&cgpu->qlock);
  6743. __work_completed(cgpu, work);
  6744. wr_unlock(&cgpu->qlock);
  6745. free_work(work);
  6746. }
  6747. /* Combines find_queued_work_bymidstate and work_completed in one function
  6748. * withOUT destroying the work so the driver must free it. */
  6749. struct work *take_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  6750. {
  6751. struct work *work;
  6752. wr_lock(&cgpu->qlock);
  6753. work = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  6754. if (work)
  6755. __work_completed(cgpu, work);
  6756. wr_unlock(&cgpu->qlock);
  6757. return work;
  6758. }
  6759. void flush_queue(struct cgpu_info *cgpu)
  6760. {
  6761. struct work *work = NULL;
  6762. if (unlikely(!cgpu))
  6763. return;
  6764. /* Use only a trylock in case we get into a deadlock with a queueing
  6765. * function holding the read lock when we're called. */
  6766. if (wr_trylock(&cgpu->qlock))
  6767. return;
  6768. work = cgpu->unqueued_work;
  6769. cgpu->unqueued_work = NULL;
  6770. wr_unlock(&cgpu->qlock);
  6771. if (work) {
  6772. free_work(work);
  6773. applog(LOG_DEBUG, "Discarded queued work item");
  6774. }
  6775. }
  6776. /* This version of hash work is for devices that are fast enough to always
  6777. * perform a full nonce range and need a queue to maintain the device busy.
  6778. * Work creation and destruction is not done from within this function
  6779. * directly. */
  6780. void hash_queued_work(struct thr_info *mythr)
  6781. {
  6782. struct timeval tv_start = {0, 0}, tv_end;
  6783. struct cgpu_info *cgpu = mythr->cgpu;
  6784. struct device_drv *drv = cgpu->drv;
  6785. const int thr_id = mythr->id;
  6786. int64_t hashes_done = 0;
  6787. while (likely(!cgpu->shutdown)) {
  6788. struct timeval diff;
  6789. int64_t hashes;
  6790. mythr->work_update = false;
  6791. fill_queue(mythr, cgpu, drv, thr_id);
  6792. hashes = drv->scanwork(mythr);
  6793. /* Reset the bool here in case the driver looks for it
  6794. * synchronously in the scanwork loop. */
  6795. mythr->work_restart = false;
  6796. if (unlikely(hashes == -1 )) {
  6797. applog(LOG_ERR, "%s %d failure, disabling!", drv->name, cgpu->device_id);
  6798. cgpu->deven = DEV_DISABLED;
  6799. dev_error(cgpu, REASON_THREAD_ZERO_HASH);
  6800. break;
  6801. }
  6802. hashes_done += hashes;
  6803. cgtime(&tv_end);
  6804. timersub(&tv_end, &tv_start, &diff);
  6805. /* Update the hashmeter at most 5 times per second */
  6806. if ((hashes_done && (diff.tv_sec > 0 || diff.tv_usec > 200000)) ||
  6807. diff.tv_sec >= opt_log_interval) {
  6808. hashmeter(thr_id, hashes_done);
  6809. hashes_done = 0;
  6810. copy_time(&tv_start, &tv_end);
  6811. }
  6812. if (unlikely(mythr->pause || cgpu->deven != DEV_ENABLED))
  6813. mt_disable(mythr, thr_id, drv);
  6814. if (mythr->work_update)
  6815. drv->update_work(cgpu);
  6816. }
  6817. cgpu->deven = DEV_DISABLED;
  6818. }
  6819. /* This version of hash_work is for devices drivers that want to do their own
  6820. * work management entirely, usually by using get_work(). Note that get_work
  6821. * is a blocking function and will wait indefinitely if no work is available
  6822. * so this must be taken into consideration in the driver. */
  6823. void hash_driver_work(struct thr_info *mythr)
  6824. {
  6825. struct timeval tv_start = {0, 0}, tv_end;
  6826. struct cgpu_info *cgpu = mythr->cgpu;
  6827. struct device_drv *drv = cgpu->drv;
  6828. const int thr_id = mythr->id;
  6829. int64_t hashes_done = 0;
  6830. while (likely(!cgpu->shutdown)) {
  6831. struct timeval diff;
  6832. int64_t hashes;
  6833. #ifndef USE_AVALON2
  6834. mythr->work_update = false;
  6835. #endif
  6836. hashes = drv->scanwork(mythr);
  6837. #ifndef USE_AVALON2
  6838. /* Reset the bool here in case the driver looks for it
  6839. * synchronously in the scanwork loop. */
  6840. mythr->work_restart = false;
  6841. #endif
  6842. if (unlikely(hashes == -1 )) {
  6843. applog(LOG_ERR, "%s %d failure, disabling!", drv->name, cgpu->device_id);
  6844. cgpu->deven = DEV_DISABLED;
  6845. dev_error(cgpu, REASON_THREAD_ZERO_HASH);
  6846. break;
  6847. }
  6848. hashes_done += hashes;
  6849. cgtime(&tv_end);
  6850. timersub(&tv_end, &tv_start, &diff);
  6851. /* Update the hashmeter at most 5 times per second */
  6852. if ((hashes_done && (diff.tv_sec > 0 || diff.tv_usec > 200000)) ||
  6853. diff.tv_sec >= opt_log_interval) {
  6854. hashmeter(thr_id, hashes_done);
  6855. hashes_done = 0;
  6856. copy_time(&tv_start, &tv_end);
  6857. }
  6858. if (unlikely(mythr->pause || cgpu->deven != DEV_ENABLED))
  6859. mt_disable(mythr, thr_id, drv);
  6860. if (mythr->work_update)
  6861. drv->update_work(cgpu);
  6862. }
  6863. cgpu->deven = DEV_DISABLED;
  6864. }
  6865. void *miner_thread(void *userdata)
  6866. {
  6867. struct thr_info *mythr = userdata;
  6868. const int thr_id = mythr->id;
  6869. struct cgpu_info *cgpu = mythr->cgpu;
  6870. struct device_drv *drv = cgpu->drv;
  6871. char threadname[16];
  6872. snprintf(threadname, sizeof(threadname), "%d/Miner", thr_id);
  6873. RenameThread(threadname);
  6874. thread_reportout(mythr);
  6875. if (!drv->thread_init(mythr)) {
  6876. dev_error(cgpu, REASON_THREAD_FAIL_INIT);
  6877. goto out;
  6878. }
  6879. applog(LOG_DEBUG, "Waiting on sem in miner thread");
  6880. cgsem_wait(&mythr->sem);
  6881. cgpu->last_device_valid_work = time(NULL);
  6882. drv->hash_work(mythr);
  6883. drv->thread_shutdown(mythr);
  6884. out:
  6885. return NULL;
  6886. }
  6887. enum {
  6888. STAT_SLEEP_INTERVAL = 1,
  6889. STAT_CTR_INTERVAL = 10000000,
  6890. FAILURE_INTERVAL = 30,
  6891. };
  6892. #ifdef HAVE_LIBCURL
  6893. /* Stage another work item from the work returned in a longpoll */
  6894. static void convert_to_work(json_t *val, int rolltime, struct pool *pool, struct timeval *tv_lp, struct timeval *tv_lp_reply)
  6895. {
  6896. struct work *work;
  6897. bool rc;
  6898. work = make_work();
  6899. rc = work_decode(pool, work, val);
  6900. if (unlikely(!rc)) {
  6901. applog(LOG_ERR, "Could not convert longpoll data to work");
  6902. free_work(work);
  6903. return;
  6904. }
  6905. total_getworks++;
  6906. pool->getwork_requested++;
  6907. work->pool = pool;
  6908. work->rolltime = rolltime;
  6909. copy_time(&work->tv_getwork, tv_lp);
  6910. copy_time(&work->tv_getwork_reply, tv_lp_reply);
  6911. calc_diff(work, 0);
  6912. if (pool->enabled == POOL_REJECTING)
  6913. work->mandatory = true;
  6914. if (pool->has_gbt)
  6915. gen_gbt_work(pool, work);
  6916. work->longpoll = true;
  6917. work->getwork_mode = GETWORK_MODE_LP;
  6918. /* We'll be checking this work item twice, but we already know it's
  6919. * from a new block so explicitly force the new block detection now
  6920. * rather than waiting for it to hit the stage thread. This also
  6921. * allows testwork to know whether LP discovered the block or not. */
  6922. test_work_current(work);
  6923. /* Don't use backup LPs as work if we have failover-only enabled. Use
  6924. * the longpoll work from a pool that has been rejecting shares as a
  6925. * way to detect when the pool has recovered.
  6926. */
  6927. if (pool != current_pool() && opt_fail_only && pool->enabled != POOL_REJECTING) {
  6928. free_work(work);
  6929. return;
  6930. }
  6931. work = clone_work(work);
  6932. applog(LOG_DEBUG, "Pushing converted work to stage thread");
  6933. stage_work(work);
  6934. applog(LOG_DEBUG, "Converted longpoll data to work");
  6935. }
  6936. /* If we want longpoll, enable it for the chosen default pool, or, if
  6937. * the pool does not support longpoll, find the first one that does
  6938. * and use its longpoll support */
  6939. static struct pool *select_longpoll_pool(struct pool *cp)
  6940. {
  6941. int i;
  6942. if (cp->hdr_path || cp->has_gbt || cp->gbt_solo)
  6943. return cp;
  6944. for (i = 0; i < total_pools; i++) {
  6945. struct pool *pool = pools[i];
  6946. if (pool->has_stratum || pool->hdr_path)
  6947. return pool;
  6948. }
  6949. return NULL;
  6950. }
  6951. #endif /* HAVE_LIBCURL */
  6952. /* This will make the longpoll thread wait till it's the current pool, or it
  6953. * has been flagged as rejecting, before attempting to open any connections.
  6954. */
  6955. static void wait_lpcurrent(struct pool *pool)
  6956. {
  6957. while (!cnx_needed(pool) && (pool->enabled == POOL_DISABLED ||
  6958. (pool != current_pool() && pool_strategy != POOL_LOADBALANCE &&
  6959. pool_strategy != POOL_BALANCE))) {
  6960. mutex_lock(&lp_lock);
  6961. pthread_cond_wait(&lp_cond, &lp_lock);
  6962. mutex_unlock(&lp_lock);
  6963. }
  6964. }
  6965. #ifdef HAVE_LIBCURL
  6966. static void *longpoll_thread(void *userdata)
  6967. {
  6968. struct pool *cp = (struct pool *)userdata;
  6969. /* This *pool is the source of the actual longpoll, not the pool we've
  6970. * tied it to */
  6971. struct timeval start, reply, end;
  6972. struct pool *pool = NULL;
  6973. char threadname[16];
  6974. CURL *curl = NULL;
  6975. int failures = 0;
  6976. char lpreq[1024];
  6977. char *lp_url;
  6978. int rolltime;
  6979. snprintf(threadname, sizeof(threadname), "%d/Longpoll", cp->pool_no);
  6980. RenameThread(threadname);
  6981. retry_pool:
  6982. pool = select_longpoll_pool(cp);
  6983. if (!pool) {
  6984. applog(LOG_WARNING, "No suitable long-poll found for %s", cp->rpc_url);
  6985. while (!pool) {
  6986. cgsleep_ms(60000);
  6987. pool = select_longpoll_pool(cp);
  6988. }
  6989. }
  6990. if (pool->has_stratum) {
  6991. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  6992. cp->rpc_url, pool->rpc_url);
  6993. goto out;
  6994. }
  6995. if (pool->gbt_solo) {
  6996. applog(LOG_WARNING, "Block change for %s detection via getblockcount polling",
  6997. cp->rpc_url);
  6998. while (42) {
  6999. json_t *val, *res_val = NULL;
  7000. if (unlikely(pool->removed))
  7001. return NULL;
  7002. cgtime(&start);
  7003. wait_lpcurrent(cp);
  7004. sprintf(lpreq, "{\"id\": 0, \"method\": \"getblockcount\"}\n");
  7005. /* We will be making another call immediately after this
  7006. * one to get the height so allow this curl to be reused.*/
  7007. get_gbt_curl(pool, 500);
  7008. curl_easy_setopt(pool->gbt_curl, CURLOPT_FORBID_REUSE, 0);
  7009. val = json_rpc_call(pool->gbt_curl, pool->rpc_url, pool->rpc_userpass, lpreq, true,
  7010. false, &rolltime, pool, false);
  7011. release_gbt_curl(pool);
  7012. if (likely(val))
  7013. res_val = json_object_get(val, "result");
  7014. if (likely(res_val)) {
  7015. int height = json_integer_value(res_val);
  7016. const char *prev_hash;
  7017. failures = 0;
  7018. json_decref(val);
  7019. if (height >= cp->height) {
  7020. applog(LOG_WARNING, "Block height change to %d detected on pool %d",
  7021. height, cp->pool_no);
  7022. update_gbt_solo(pool);
  7023. continue;
  7024. }
  7025. sprintf(lpreq, "{\"id\": 0, \"method\": \"getblockhash\", \"params\": [%d]}\n", height);
  7026. get_gbt_curl(pool, 500);
  7027. curl_easy_setopt(pool->gbt_curl, CURLOPT_FORBID_REUSE, 1);
  7028. val = json_rpc_call(pool->gbt_curl, pool->rpc_url, pool->rpc_userpass,
  7029. lpreq, true, false, &rolltime, pool, false);
  7030. release_gbt_curl(pool);
  7031. if (val) {
  7032. /* Do a comparison on a short stretch of
  7033. * the hash to make sure it hasn't changed
  7034. * due to mining on an orphan branch. */
  7035. prev_hash = json_string_value(json_object_get(val, "result"));
  7036. if (unlikely(prev_hash && strncasecmp(prev_hash + 56, pool->prev_hash, 8))) {
  7037. applog(LOG_WARNING, "Mining on orphan branch detected, switching!");
  7038. update_gbt_solo(pool);
  7039. }
  7040. json_decref(val);
  7041. }
  7042. cgsleep_ms(500);
  7043. } else {
  7044. if (val)
  7045. json_decref(val);
  7046. cgtime(&end);
  7047. if (end.tv_sec - start.tv_sec > 30)
  7048. continue;
  7049. if (failures == 1)
  7050. applog(LOG_WARNING, "longpoll failed for %s, retrying every 30s", lp_url);
  7051. cgsleep_ms(30000);
  7052. }
  7053. }
  7054. }
  7055. curl = curl_easy_init();
  7056. if (unlikely(!curl))
  7057. quit (1, "Longpoll CURL initialisation failed");
  7058. /* Any longpoll from any pool is enough for this to be true */
  7059. have_longpoll = true;
  7060. wait_lpcurrent(cp);
  7061. if (pool->has_gbt) {
  7062. lp_url = pool->rpc_url;
  7063. applog(LOG_WARNING, "GBT longpoll ID activated for %s", lp_url);
  7064. } else {
  7065. strcpy(lpreq, getwork_req);
  7066. lp_url = pool->lp_url;
  7067. if (cp == pool)
  7068. applog(LOG_WARNING, "Long-polling activated for %s", lp_url);
  7069. else
  7070. applog(LOG_WARNING, "Long-polling activated for %s via %s", cp->rpc_url, lp_url);
  7071. }
  7072. while (42) {
  7073. json_t *val, *soval;
  7074. wait_lpcurrent(cp);
  7075. cgtime(&start);
  7076. /* Update the longpollid every time, but do it under lock to
  7077. * avoid races */
  7078. if (pool->has_gbt) {
  7079. cg_rlock(&pool->gbt_lock);
  7080. snprintf(lpreq, sizeof(lpreq),
  7081. "{\"id\": 0, \"method\": \"getblocktemplate\", \"params\": "
  7082. "[{\"capabilities\": [\"coinbasetxn\", \"workid\", \"coinbase/append\"], "
  7083. "\"longpollid\": \"%s\"}]}\n", pool->longpollid);
  7084. cg_runlock(&pool->gbt_lock);
  7085. }
  7086. /* Longpoll connections can be persistent for a very long time
  7087. * and any number of issues could have come up in the meantime
  7088. * so always establish a fresh connection instead of relying on
  7089. * a persistent one. */
  7090. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  7091. val = json_rpc_call(curl, lp_url, pool->rpc_userpass,
  7092. lpreq, false, true, &rolltime, pool, false);
  7093. cgtime(&reply);
  7094. if (likely(val)) {
  7095. soval = json_object_get(json_object_get(val, "result"), "submitold");
  7096. if (soval)
  7097. pool->submit_old = json_is_true(soval);
  7098. else
  7099. pool->submit_old = false;
  7100. convert_to_work(val, rolltime, pool, &start, &reply);
  7101. failures = 0;
  7102. json_decref(val);
  7103. } else {
  7104. /* Some pools regularly drop the longpoll request so
  7105. * only see this as longpoll failure if it happens
  7106. * immediately and just restart it the rest of the
  7107. * time. */
  7108. cgtime(&end);
  7109. if (end.tv_sec - start.tv_sec > 30)
  7110. continue;
  7111. if (failures == 1)
  7112. applog(LOG_WARNING, "longpoll failed for %s, retrying every 30s", lp_url);
  7113. cgsleep_ms(30000);
  7114. }
  7115. if (pool != cp) {
  7116. pool = select_longpoll_pool(cp);
  7117. if (pool->has_stratum) {
  7118. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  7119. cp->rpc_url, pool->rpc_url);
  7120. break;
  7121. }
  7122. if (unlikely(!pool))
  7123. goto retry_pool;
  7124. }
  7125. if (unlikely(pool->removed))
  7126. break;
  7127. }
  7128. out:
  7129. curl_easy_cleanup(curl);
  7130. return NULL;
  7131. }
  7132. #else /* HAVE_LIBCURL */
  7133. static void *longpoll_thread(void __maybe_unused *userdata)
  7134. {
  7135. pthread_detach(pthread_self());
  7136. return NULL;
  7137. }
  7138. #endif /* HAVE_LIBCURL */
  7139. void reinit_device(struct cgpu_info *cgpu)
  7140. {
  7141. if (cgpu->deven == DEV_DISABLED)
  7142. return;
  7143. #ifdef USE_USBUTILS
  7144. /* Attempt a usb device reset if the device has gone sick */
  7145. if (cgpu->usbdev && cgpu->usbdev->handle)
  7146. libusb_reset_device(cgpu->usbdev->handle);
  7147. #endif
  7148. cgpu->drv->reinit_device(cgpu);
  7149. }
  7150. static struct timeval rotate_tv;
  7151. /* We reap curls if they are unused for over a minute */
  7152. static void reap_curl(struct pool *pool)
  7153. {
  7154. struct curl_ent *ent, *iter;
  7155. struct timeval now;
  7156. int reaped = 0;
  7157. cgtime(&now);
  7158. mutex_lock(&pool->pool_lock);
  7159. list_for_each_entry_safe(ent, iter, &pool->curlring, node) {
  7160. if (pool->curls < 2)
  7161. break;
  7162. if (now.tv_sec - ent->tv.tv_sec > 300) {
  7163. reaped++;
  7164. pool->curls--;
  7165. list_del(&ent->node);
  7166. curl_easy_cleanup(ent->curl);
  7167. free(ent);
  7168. }
  7169. }
  7170. mutex_unlock(&pool->pool_lock);
  7171. if (reaped)
  7172. applog(LOG_DEBUG, "Reaped %d curl%s from pool %d", reaped, reaped > 1 ? "s" : "", pool->pool_no);
  7173. }
  7174. /* Prune old shares we haven't had a response about for over 2 minutes in case
  7175. * the pool never plans to respond and we're just leaking memory. If we get a
  7176. * response beyond that time they will be seen as untracked shares. */
  7177. static void prune_stratum_shares(struct pool *pool)
  7178. {
  7179. struct stratum_share *sshare, *tmpshare;
  7180. time_t current_time = time(NULL);
  7181. int cleared = 0;
  7182. mutex_lock(&sshare_lock);
  7183. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  7184. if (sshare->work->pool == pool && current_time > sshare->sshare_time + 120) {
  7185. HASH_DEL(stratum_shares, sshare);
  7186. free_work(sshare->work);
  7187. free(sshare);
  7188. cleared++;
  7189. }
  7190. }
  7191. mutex_unlock(&sshare_lock);
  7192. if (cleared) {
  7193. applog(LOG_WARNING, "Lost %d shares due to no stratum share response from pool %d",
  7194. cleared, pool->pool_no);
  7195. pool->stale_shares += cleared;
  7196. total_stale += cleared;
  7197. }
  7198. }
  7199. static void *watchpool_thread(void __maybe_unused *userdata)
  7200. {
  7201. int intervals = 0;
  7202. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  7203. RenameThread("Watchpool");
  7204. set_lowprio();
  7205. while (42) {
  7206. struct timeval now;
  7207. int i;
  7208. if (++intervals > 20)
  7209. intervals = 0;
  7210. cgtime(&now);
  7211. for (i = 0; i < total_pools; i++) {
  7212. struct pool *pool = pools[i];
  7213. if (!opt_benchmark && !opt_benchfile) {
  7214. reap_curl(pool);
  7215. prune_stratum_shares(pool);
  7216. }
  7217. /* Get a rolling utility per pool over 10 mins */
  7218. if (intervals > 19) {
  7219. double shares = pool->diff1 - pool->last_shares;
  7220. pool->last_shares = pool->diff1;
  7221. pool->utility = (pool->utility + shares * 0.63) / 1.63;
  7222. pool->shares = pool->utility;
  7223. }
  7224. if (pool->enabled == POOL_DISABLED)
  7225. continue;
  7226. /* Don't start testing any pools if the test threads
  7227. * from startup are still doing their first attempt. */
  7228. if (unlikely(pool->testing)) {
  7229. pthread_join(pool->test_thread, NULL);
  7230. pool->testing = false;
  7231. }
  7232. /* Test pool is idle once every minute */
  7233. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 30) {
  7234. cgtime(&pool->tv_idle);
  7235. if (pool_active(pool, true) && pool_tclear(pool, &pool->idle))
  7236. pool_resus(pool);
  7237. }
  7238. /* Only switch pools if the failback pool has been
  7239. * alive for more than 5 minutes (default) to prevent
  7240. * intermittently failing pools from being used. */
  7241. if (!pool->idle && pool_strategy == POOL_FAILOVER && pool->prio < cp_prio() &&
  7242. now.tv_sec - pool->tv_idle.tv_sec > opt_fail_switch_delay) {
  7243. applog(LOG_WARNING, "Pool %d %s stable for %d seconds",
  7244. pool->pool_no, pool->rpc_url, opt_fail_switch_delay);
  7245. switch_pools(NULL);
  7246. }
  7247. }
  7248. if (current_pool()->idle)
  7249. switch_pools(NULL);
  7250. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  7251. cgtime(&rotate_tv);
  7252. switch_pools(NULL);
  7253. }
  7254. cgsleep_ms(30000);
  7255. }
  7256. return NULL;
  7257. }
  7258. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  7259. * the screen at regular intervals, and restarts threads if they appear to have
  7260. * died. */
  7261. #define WATCHDOG_INTERVAL 2
  7262. #define WATCHDOG_SICK_TIME 120
  7263. #define WATCHDOG_DEAD_TIME 600
  7264. #define WATCHDOG_SICK_COUNT (WATCHDOG_SICK_TIME/WATCHDOG_INTERVAL)
  7265. #define WATCHDOG_DEAD_COUNT (WATCHDOG_DEAD_TIME/WATCHDOG_INTERVAL)
  7266. static void *watchdog_thread(void __maybe_unused *userdata)
  7267. {
  7268. const unsigned int interval = WATCHDOG_INTERVAL;
  7269. struct timeval zero_tv;
  7270. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  7271. RenameThread("Watchdog");
  7272. set_lowprio();
  7273. memset(&zero_tv, 0, sizeof(struct timeval));
  7274. cgtime(&rotate_tv);
  7275. while (1) {
  7276. int i;
  7277. struct timeval now;
  7278. sleep(interval);
  7279. discard_stale();
  7280. hashmeter(-1, 0);
  7281. #ifdef HAVE_CURSES
  7282. if (curses_active_locked()) {
  7283. struct cgpu_info *cgpu;
  7284. int count;
  7285. change_logwinsize();
  7286. curses_print_status();
  7287. count = 0;
  7288. for (i = 0; i < total_devices; i++) {
  7289. cgpu = get_devices(i);
  7290. #ifndef USE_USBUTILS
  7291. if (cgpu)
  7292. #else
  7293. if (cgpu && !cgpu->usbinfo.nodev)
  7294. #endif
  7295. curses_print_devstatus(cgpu, i, count++);
  7296. }
  7297. #ifdef USE_USBUTILS
  7298. for (i = 0; i < total_devices; i++) {
  7299. cgpu = get_devices(i);
  7300. if (cgpu && cgpu->usbinfo.nodev)
  7301. curses_print_devstatus(cgpu, i, count++);
  7302. }
  7303. #endif
  7304. touchwin(statuswin);
  7305. wrefresh(statuswin);
  7306. touchwin(logwin);
  7307. wrefresh(logwin);
  7308. unlock_curses();
  7309. }
  7310. #endif
  7311. cgtime(&now);
  7312. if (!sched_paused && !should_run()) {
  7313. applog(LOG_WARNING, "Pausing execution as per stop time %02d:%02d scheduled",
  7314. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  7315. if (!schedstart.enable) {
  7316. quit(0, "Terminating execution as planned");
  7317. break;
  7318. }
  7319. applog(LOG_WARNING, "Will restart execution as scheduled at %02d:%02d",
  7320. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  7321. sched_paused = true;
  7322. rd_lock(&mining_thr_lock);
  7323. for (i = 0; i < mining_threads; i++)
  7324. mining_thr[i]->pause = true;
  7325. rd_unlock(&mining_thr_lock);
  7326. } else if (sched_paused && should_run()) {
  7327. applog(LOG_WARNING, "Restarting execution as per start time %02d:%02d scheduled",
  7328. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  7329. if (schedstop.enable)
  7330. applog(LOG_WARNING, "Will pause execution as scheduled at %02d:%02d",
  7331. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  7332. sched_paused = false;
  7333. for (i = 0; i < mining_threads; i++) {
  7334. struct thr_info *thr;
  7335. thr = get_thread(i);
  7336. /* Don't touch disabled devices */
  7337. if (thr->cgpu->deven == DEV_DISABLED)
  7338. continue;
  7339. thr->pause = false;
  7340. applog(LOG_DEBUG, "Pushing sem post to thread %d", thr->id);
  7341. cgsem_post(&thr->sem);
  7342. }
  7343. }
  7344. for (i = 0; i < total_devices; ++i) {
  7345. struct cgpu_info *cgpu = get_devices(i);
  7346. struct thr_info *thr = cgpu->thr[0];
  7347. enum dev_enable *denable;
  7348. char dev_str[8];
  7349. int gpu;
  7350. if (!thr)
  7351. continue;
  7352. cgpu->drv->get_stats(cgpu);
  7353. gpu = cgpu->device_id;
  7354. denable = &cgpu->deven;
  7355. snprintf(dev_str, sizeof(dev_str), "%s%d", cgpu->drv->name, gpu);
  7356. /* Thread is waiting on getwork or disabled */
  7357. if (thr->getwork || *denable == DEV_DISABLED)
  7358. continue;
  7359. if (cgpu->status != LIFE_WELL && (now.tv_sec - thr->last.tv_sec < WATCHDOG_SICK_TIME)) {
  7360. if (cgpu->status != LIFE_INIT)
  7361. applog(LOG_ERR, "%s: Recovered, declaring WELL!", dev_str);
  7362. cgpu->status = LIFE_WELL;
  7363. cgpu->device_last_well = time(NULL);
  7364. } else if (cgpu->status == LIFE_WELL && (now.tv_sec - thr->last.tv_sec > WATCHDOG_SICK_TIME)) {
  7365. cgpu->rolling = 0;
  7366. cgpu->status = LIFE_SICK;
  7367. applog(LOG_ERR, "%s: Idle for more than 60 seconds, declaring SICK!", dev_str);
  7368. cgtime(&thr->sick);
  7369. dev_error(cgpu, REASON_DEV_SICK_IDLE_60);
  7370. if (opt_restart) {
  7371. applog(LOG_ERR, "%s: Attempting to restart", dev_str);
  7372. reinit_device(cgpu);
  7373. }
  7374. } else if (cgpu->status == LIFE_SICK && (now.tv_sec - thr->last.tv_sec > WATCHDOG_DEAD_TIME)) {
  7375. cgpu->status = LIFE_DEAD;
  7376. applog(LOG_ERR, "%s: Not responded for more than 10 minutes, declaring DEAD!", dev_str);
  7377. cgtime(&thr->sick);
  7378. dev_error(cgpu, REASON_DEV_DEAD_IDLE_600);
  7379. } else if (now.tv_sec - thr->sick.tv_sec > 60 &&
  7380. (cgpu->status == LIFE_SICK || cgpu->status == LIFE_DEAD)) {
  7381. /* Attempt to restart a GPU that's sick or dead once every minute */
  7382. cgtime(&thr->sick);
  7383. if (opt_restart)
  7384. reinit_device(cgpu);
  7385. }
  7386. }
  7387. }
  7388. return NULL;
  7389. }
  7390. static void log_print_status(struct cgpu_info *cgpu)
  7391. {
  7392. char logline[255];
  7393. get_statline(logline, sizeof(logline), cgpu);
  7394. applog(LOG_WARNING, "%s", logline);
  7395. }
  7396. static void noop_get_statline(char __maybe_unused *buf, size_t __maybe_unused bufsiz, struct cgpu_info __maybe_unused *cgpu);
  7397. void blank_get_statline_before(char *buf, size_t bufsiz, struct cgpu_info __maybe_unused *cgpu);
  7398. void print_summary(void)
  7399. {
  7400. struct timeval diff;
  7401. int hours, mins, secs, i;
  7402. double utility, displayed_hashes, work_util;
  7403. timersub(&total_tv_end, &total_tv_start, &diff);
  7404. hours = diff.tv_sec / 3600;
  7405. mins = (diff.tv_sec % 3600) / 60;
  7406. secs = diff.tv_sec % 60;
  7407. utility = total_accepted / total_secs * 60;
  7408. work_util = total_diff1 / total_secs * 60;
  7409. applog(LOG_WARNING, "\nSummary of runtime statistics:\n");
  7410. applog(LOG_WARNING, "Started at %s", datestamp);
  7411. if (total_pools == 1)
  7412. applog(LOG_WARNING, "Pool: %s", pools[0]->rpc_url);
  7413. applog(LOG_WARNING, "Runtime: %d hrs : %d mins : %d secs", hours, mins, secs);
  7414. displayed_hashes = total_mhashes_done / total_secs;
  7415. applog(LOG_WARNING, "Average hashrate: %.1f Mhash/s", displayed_hashes);
  7416. applog(LOG_WARNING, "Solved blocks: %d", found_blocks);
  7417. applog(LOG_WARNING, "Best share difficulty: %s", best_share);
  7418. applog(LOG_WARNING, "Share submissions: %"PRId64, total_accepted + total_rejected);
  7419. applog(LOG_WARNING, "Accepted shares: %"PRId64, total_accepted);
  7420. applog(LOG_WARNING, "Rejected shares: %"PRId64, total_rejected);
  7421. applog(LOG_WARNING, "Accepted difficulty shares: %1.f", total_diff_accepted);
  7422. applog(LOG_WARNING, "Rejected difficulty shares: %1.f", total_diff_rejected);
  7423. if (total_accepted || total_rejected)
  7424. applog(LOG_WARNING, "Reject ratio: %.1f%%", (double)(total_rejected * 100) / (double)(total_accepted + total_rejected));
  7425. applog(LOG_WARNING, "Hardware errors: %d", hw_errors);
  7426. applog(LOG_WARNING, "Utility (accepted shares / min): %.2f/min", utility);
  7427. applog(LOG_WARNING, "Work Utility (diff1 shares solved / min): %.2f/min\n", work_util);
  7428. applog(LOG_WARNING, "Stale submissions discarded due to new blocks: %"PRId64, total_stale);
  7429. applog(LOG_WARNING, "Unable to get work from server occasions: %d", total_go);
  7430. applog(LOG_WARNING, "Work items generated locally: %d", local_work);
  7431. applog(LOG_WARNING, "Submitting work remotely delay occasions: %d", total_ro);
  7432. applog(LOG_WARNING, "New blocks detected on network: %d\n", new_blocks);
  7433. if (total_pools > 1) {
  7434. for (i = 0; i < total_pools; i++) {
  7435. struct pool *pool = pools[i];
  7436. applog(LOG_WARNING, "Pool: %s", pool->rpc_url);
  7437. if (pool->solved)
  7438. applog(LOG_WARNING, "SOLVED %d BLOCK%s!", pool->solved, pool->solved > 1 ? "S" : "");
  7439. applog(LOG_WARNING, " Share submissions: %"PRId64, pool->accepted + pool->rejected);
  7440. applog(LOG_WARNING, " Accepted shares: %"PRId64, pool->accepted);
  7441. applog(LOG_WARNING, " Rejected shares: %"PRId64, pool->rejected);
  7442. applog(LOG_WARNING, " Accepted difficulty shares: %1.f", pool->diff_accepted);
  7443. applog(LOG_WARNING, " Rejected difficulty shares: %1.f", pool->diff_rejected);
  7444. if (pool->accepted || pool->rejected)
  7445. applog(LOG_WARNING, " Reject ratio: %.1f%%", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  7446. applog(LOG_WARNING, " Items worked on: %d", pool->works);
  7447. applog(LOG_WARNING, " Stale submissions discarded due to new blocks: %d", pool->stale_shares);
  7448. applog(LOG_WARNING, " Unable to get work from server occasions: %d", pool->getfail_occasions);
  7449. applog(LOG_WARNING, " Submitting work remotely delay occasions: %d\n", pool->remotefail_occasions);
  7450. }
  7451. }
  7452. applog(LOG_WARNING, "Summary of per device statistics:\n");
  7453. for (i = 0; i < total_devices; ++i) {
  7454. struct cgpu_info *cgpu = get_devices(i);
  7455. cgpu->drv->get_statline_before = &blank_get_statline_before;
  7456. cgpu->drv->get_statline = &noop_get_statline;
  7457. log_print_status(cgpu);
  7458. }
  7459. if (opt_shares) {
  7460. applog(LOG_WARNING, "Mined %.0f accepted shares of %d requested\n", total_diff_accepted, opt_shares);
  7461. if (opt_shares > total_diff_accepted)
  7462. applog(LOG_WARNING, "WARNING - Mined only %.0f shares of %d requested.", total_diff_accepted, opt_shares);
  7463. }
  7464. applog(LOG_WARNING, " ");
  7465. fflush(stderr);
  7466. fflush(stdout);
  7467. }
  7468. static void clean_up(bool restarting)
  7469. {
  7470. #ifdef USE_USBUTILS
  7471. usb_polling = false;
  7472. pthread_join(usb_poll_thread, NULL);
  7473. libusb_exit(NULL);
  7474. #endif
  7475. cgtime(&total_tv_end);
  7476. #ifdef WIN32
  7477. timeEndPeriod(1);
  7478. #endif
  7479. #ifdef HAVE_CURSES
  7480. disable_curses();
  7481. #endif
  7482. if (!restarting && !opt_realquiet && successful_connect)
  7483. print_summary();
  7484. curl_global_cleanup();
  7485. }
  7486. /* Should all else fail and we're unable to clean up threads due to locking
  7487. * issues etc, just silently exit. */
  7488. static void *killall_thread(void __maybe_unused *arg)
  7489. {
  7490. pthread_detach(pthread_self());
  7491. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  7492. sleep(5);
  7493. exit(1);
  7494. return NULL;
  7495. }
  7496. void __quit(int status, bool clean)
  7497. {
  7498. pthread_t killall_t;
  7499. if (unlikely(pthread_create(&killall_t, NULL, killall_thread, NULL)))
  7500. exit(1);
  7501. if (clean)
  7502. clean_up(false);
  7503. #ifdef HAVE_CURSES
  7504. else
  7505. disable_curses();
  7506. #endif
  7507. #if defined(unix) || defined(__APPLE__)
  7508. if (forkpid > 0) {
  7509. kill(forkpid, SIGTERM);
  7510. forkpid = 0;
  7511. }
  7512. #endif
  7513. pthread_cancel(killall_t);
  7514. exit(status);
  7515. }
  7516. void _quit(int status)
  7517. {
  7518. __quit(status, true);
  7519. }
  7520. #ifdef HAVE_CURSES
  7521. char *curses_input(const char *query)
  7522. {
  7523. char *input;
  7524. echo();
  7525. input = malloc(255);
  7526. if (!input)
  7527. quit(1, "Failed to malloc input");
  7528. leaveok(logwin, false);
  7529. wlogprint("%s:\n", query);
  7530. wgetnstr(logwin, input, 255);
  7531. if (!strlen(input))
  7532. strcpy(input, "-1");
  7533. leaveok(logwin, true);
  7534. noecho();
  7535. return input;
  7536. }
  7537. #endif
  7538. static bool pools_active = false;
  7539. static void *test_pool_thread(void *arg)
  7540. {
  7541. struct pool *pool = (struct pool *)arg;
  7542. retry:
  7543. if (pool_active(pool, false)) {
  7544. pool_tset(pool, &pool->lagging);
  7545. pool_tclear(pool, &pool->idle);
  7546. bool first_pool = false;
  7547. cg_wlock(&control_lock);
  7548. if (!pools_active) {
  7549. currentpool = pool;
  7550. if (pool->pool_no != 0)
  7551. first_pool = true;
  7552. pools_active = true;
  7553. }
  7554. cg_wunlock(&control_lock);
  7555. if (unlikely(first_pool))
  7556. applog(LOG_NOTICE, "Switching to pool %d %s - first alive pool", pool->pool_no, pool->rpc_url);
  7557. pool_resus(pool);
  7558. switch_pools(NULL);
  7559. } else {
  7560. pool_died(pool);
  7561. sleep(5);
  7562. goto retry;
  7563. }
  7564. return NULL;
  7565. }
  7566. /* Always returns true that the pool details were added unless we are not
  7567. * live, implying this is the only pool being added, so if no pools are
  7568. * active it returns false. */
  7569. bool add_pool_details(struct pool *pool, bool live, char *url, char *user, char *pass)
  7570. {
  7571. size_t siz;
  7572. url = get_proxy(url, pool);
  7573. pool->rpc_url = url;
  7574. pool->rpc_user = user;
  7575. pool->rpc_pass = pass;
  7576. siz = strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2;
  7577. pool->rpc_userpass = malloc(siz);
  7578. if (!pool->rpc_userpass)
  7579. quit(1, "Failed to malloc userpass");
  7580. snprintf(pool->rpc_userpass, siz, "%s:%s", pool->rpc_user, pool->rpc_pass);
  7581. pool->testing = true;
  7582. pool->idle = true;
  7583. enable_pool(pool);
  7584. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  7585. if (!live) {
  7586. pthread_join(pool->test_thread, NULL);
  7587. pool->testing = false;
  7588. return pools_active;
  7589. }
  7590. return true;
  7591. }
  7592. #ifdef HAVE_CURSES
  7593. static bool input_pool(bool live)
  7594. {
  7595. char *url = NULL, *user = NULL, *pass = NULL;
  7596. struct pool *pool;
  7597. bool ret = false;
  7598. immedok(logwin, true);
  7599. wlogprint("Input server details.\n");
  7600. url = curses_input("URL");
  7601. if (!url)
  7602. goto out;
  7603. user = curses_input("Username");
  7604. if (!user)
  7605. goto out;
  7606. pass = curses_input("Password");
  7607. if (!pass)
  7608. goto out;
  7609. pool = add_pool();
  7610. if (!detect_stratum(pool, url) && strncmp(url, "http://", 7) &&
  7611. strncmp(url, "https://", 8)) {
  7612. char *httpinput;
  7613. httpinput = malloc(256);
  7614. if (!httpinput)
  7615. quit(1, "Failed to malloc httpinput");
  7616. strcpy(httpinput, "http://");
  7617. strncat(httpinput, url, 248);
  7618. free(url);
  7619. url = httpinput;
  7620. }
  7621. ret = add_pool_details(pool, live, url, user, pass);
  7622. out:
  7623. immedok(logwin, false);
  7624. if (!ret) {
  7625. if (url)
  7626. free(url);
  7627. if (user)
  7628. free(user);
  7629. if (pass)
  7630. free(pass);
  7631. }
  7632. return ret;
  7633. }
  7634. #endif
  7635. #if defined(unix) || defined(__APPLE__)
  7636. static void fork_monitor()
  7637. {
  7638. // Make a pipe: [readFD, writeFD]
  7639. int pfd[2];
  7640. int r = pipe(pfd);
  7641. if (r < 0) {
  7642. perror("pipe - failed to create pipe for --monitor");
  7643. exit(1);
  7644. }
  7645. // Make stderr write end of pipe
  7646. fflush(stderr);
  7647. r = dup2(pfd[1], 2);
  7648. if (r < 0) {
  7649. perror("dup2 - failed to alias stderr to write end of pipe for --monitor");
  7650. exit(1);
  7651. }
  7652. r = close(pfd[1]);
  7653. if (r < 0) {
  7654. perror("close - failed to close write end of pipe for --monitor");
  7655. exit(1);
  7656. }
  7657. // Don't allow a dying monitor to kill the main process
  7658. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  7659. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  7660. if (SIG_ERR == sr0 || SIG_ERR == sr1) {
  7661. perror("signal - failed to edit signal mask for --monitor");
  7662. exit(1);
  7663. }
  7664. // Fork a child process
  7665. forkpid = fork();
  7666. if (forkpid < 0) {
  7667. perror("fork - failed to fork child process for --monitor");
  7668. exit(1);
  7669. }
  7670. // Child: launch monitor command
  7671. if (0 == forkpid) {
  7672. // Make stdin read end of pipe
  7673. r = dup2(pfd[0], 0);
  7674. if (r < 0) {
  7675. perror("dup2 - in child, failed to alias read end of pipe to stdin for --monitor");
  7676. exit(1);
  7677. }
  7678. close(pfd[0]);
  7679. if (r < 0) {
  7680. perror("close - in child, failed to close read end of pipe for --monitor");
  7681. exit(1);
  7682. }
  7683. // Launch user specified command
  7684. execl("/bin/bash", "/bin/bash", "-c", opt_stderr_cmd, (char*)NULL);
  7685. perror("execl - in child failed to exec user specified command for --monitor");
  7686. exit(1);
  7687. }
  7688. // Parent: clean up unused fds and bail
  7689. r = close(pfd[0]);
  7690. if (r < 0) {
  7691. perror("close - failed to close read end of pipe for --monitor");
  7692. exit(1);
  7693. }
  7694. }
  7695. #endif // defined(unix)
  7696. #ifdef HAVE_CURSES
  7697. static void enable_curses_windows(void)
  7698. {
  7699. int x,y;
  7700. getmaxyx(mainwin, y, x);
  7701. statuswin = newwin(logstart, x, 0, 0);
  7702. leaveok(statuswin, true);
  7703. logwin = newwin(y - logcursor, 0, logcursor, 0);
  7704. idlok(logwin, true);
  7705. scrollok(logwin, true);
  7706. leaveok(logwin, true);
  7707. cbreak();
  7708. noecho();
  7709. }
  7710. void enable_curses(void) {
  7711. lock_curses();
  7712. if (curses_active) {
  7713. unlock_curses();
  7714. return;
  7715. }
  7716. mainwin = initscr();
  7717. enable_curses_windows();
  7718. curses_active = true;
  7719. statusy = logstart;
  7720. unlock_curses();
  7721. }
  7722. #endif
  7723. static int cgminer_id_count = 0;
  7724. /* Various noop functions for drivers that don't support or need their
  7725. * variants. */
  7726. static void noop_reinit_device(struct cgpu_info __maybe_unused *cgpu)
  7727. {
  7728. }
  7729. void blank_get_statline_before(char __maybe_unused *buf,size_t __maybe_unused bufsiz, struct cgpu_info __maybe_unused *cgpu)
  7730. {
  7731. }
  7732. static void noop_get_statline(char __maybe_unused *buf, size_t __maybe_unused bufsiz, struct cgpu_info __maybe_unused *cgpu)
  7733. {
  7734. }
  7735. static bool noop_get_stats(struct cgpu_info __maybe_unused *cgpu)
  7736. {
  7737. return true;
  7738. }
  7739. static bool noop_thread_prepare(struct thr_info __maybe_unused *thr)
  7740. {
  7741. return true;
  7742. }
  7743. static uint64_t noop_can_limit_work(struct thr_info __maybe_unused *thr)
  7744. {
  7745. return 0xffffffff;
  7746. }
  7747. static bool noop_thread_init(struct thr_info __maybe_unused *thr)
  7748. {
  7749. return true;
  7750. }
  7751. static bool noop_prepare_work(struct thr_info __maybe_unused *thr, struct work __maybe_unused *work)
  7752. {
  7753. return true;
  7754. }
  7755. static void noop_hw_error(struct thr_info __maybe_unused *thr)
  7756. {
  7757. }
  7758. static void noop_thread_shutdown(struct thr_info __maybe_unused *thr)
  7759. {
  7760. }
  7761. static void noop_thread_enable(struct thr_info __maybe_unused *thr)
  7762. {
  7763. }
  7764. static void noop_detect(bool __maybe_unused hotplug)
  7765. {
  7766. }
  7767. static struct api_data *noop_get_api_stats(struct cgpu_info __maybe_unused *cgpu)
  7768. {
  7769. return NULL;
  7770. }
  7771. static void noop_hash_work(struct thr_info __maybe_unused *thr)
  7772. {
  7773. }
  7774. #define noop_flush_work noop_reinit_device
  7775. #define noop_update_work noop_reinit_device
  7776. #define noop_queue_full noop_get_stats
  7777. #define noop_zero_stats noop_reinit_device
  7778. #define noop_identify_device noop_reinit_device
  7779. /* Fill missing driver drv functions with noops */
  7780. void fill_device_drv(struct device_drv *drv)
  7781. {
  7782. if (!drv->drv_detect)
  7783. drv->drv_detect = &noop_detect;
  7784. if (!drv->reinit_device)
  7785. drv->reinit_device = &noop_reinit_device;
  7786. if (!drv->get_statline_before)
  7787. drv->get_statline_before = &blank_get_statline_before;
  7788. if (!drv->get_statline)
  7789. drv->get_statline = &noop_get_statline;
  7790. if (!drv->get_stats)
  7791. drv->get_stats = &noop_get_stats;
  7792. if (!drv->thread_prepare)
  7793. drv->thread_prepare = &noop_thread_prepare;
  7794. if (!drv->can_limit_work)
  7795. drv->can_limit_work = &noop_can_limit_work;
  7796. if (!drv->thread_init)
  7797. drv->thread_init = &noop_thread_init;
  7798. if (!drv->prepare_work)
  7799. drv->prepare_work = &noop_prepare_work;
  7800. if (!drv->hw_error)
  7801. drv->hw_error = &noop_hw_error;
  7802. if (!drv->thread_shutdown)
  7803. drv->thread_shutdown = &noop_thread_shutdown;
  7804. if (!drv->thread_enable)
  7805. drv->thread_enable = &noop_thread_enable;
  7806. if (!drv->hash_work)
  7807. drv->hash_work = &hash_sole_work;
  7808. if (!drv->flush_work)
  7809. drv->flush_work = &noop_flush_work;
  7810. if (!drv->update_work)
  7811. drv->update_work = &noop_update_work;
  7812. if (!drv->queue_full)
  7813. drv->queue_full = &noop_queue_full;
  7814. if (!drv->zero_stats)
  7815. drv->zero_stats = &noop_zero_stats;
  7816. if (!drv->max_diff)
  7817. drv->max_diff = 1;
  7818. }
  7819. void null_device_drv(struct device_drv *drv)
  7820. {
  7821. drv->drv_detect = &noop_detect;
  7822. drv->reinit_device = &noop_reinit_device;
  7823. drv->get_statline_before = &blank_get_statline_before;
  7824. drv->get_statline = &noop_get_statline;
  7825. drv->get_api_stats = &noop_get_api_stats;
  7826. drv->get_stats = &noop_get_stats;
  7827. drv->identify_device = &noop_identify_device;
  7828. drv->set_device = NULL;
  7829. drv->thread_prepare = &noop_thread_prepare;
  7830. drv->can_limit_work = &noop_can_limit_work;
  7831. drv->thread_init = &noop_thread_init;
  7832. drv->prepare_work = &noop_prepare_work;
  7833. /* This should make the miner thread just exit */
  7834. drv->hash_work = &noop_hash_work;
  7835. drv->hw_error = &noop_hw_error;
  7836. drv->thread_shutdown = &noop_thread_shutdown;
  7837. drv->thread_enable = &noop_thread_enable;
  7838. drv->zero_stats = &noop_zero_stats;
  7839. drv->hash_work = &noop_hash_work;
  7840. drv->queue_full = &noop_queue_full;
  7841. drv->flush_work = &noop_flush_work;
  7842. drv->update_work = &noop_update_work;
  7843. drv->zero_stats = &noop_zero_stats;
  7844. drv->max_diff = 1;
  7845. }
  7846. void enable_device(struct cgpu_info *cgpu)
  7847. {
  7848. cgpu->deven = DEV_ENABLED;
  7849. wr_lock(&devices_lock);
  7850. devices[cgpu->cgminer_id = cgminer_id_count++] = cgpu;
  7851. wr_unlock(&devices_lock);
  7852. if (hotplug_mode)
  7853. new_threads += cgpu->threads;
  7854. else
  7855. mining_threads += cgpu->threads;
  7856. rwlock_init(&cgpu->qlock);
  7857. cgpu->queued_work = NULL;
  7858. }
  7859. struct _cgpu_devid_counter {
  7860. char name[4];
  7861. int lastid;
  7862. UT_hash_handle hh;
  7863. };
  7864. static void adjust_mostdevs(void)
  7865. {
  7866. if (total_devices - zombie_devs > most_devices)
  7867. most_devices = total_devices - zombie_devs;
  7868. }
  7869. bool add_cgpu(struct cgpu_info *cgpu)
  7870. {
  7871. static struct _cgpu_devid_counter *devids = NULL;
  7872. struct _cgpu_devid_counter *d;
  7873. HASH_FIND_STR(devids, cgpu->drv->name, d);
  7874. if (d)
  7875. cgpu->device_id = ++d->lastid;
  7876. else {
  7877. d = malloc(sizeof(*d));
  7878. memcpy(d->name, cgpu->drv->name, sizeof(d->name));
  7879. cgpu->device_id = d->lastid = 0;
  7880. HASH_ADD_STR(devids, name, d);
  7881. }
  7882. wr_lock(&devices_lock);
  7883. devices = realloc(devices, sizeof(struct cgpu_info *) * (total_devices + new_devices + 2));
  7884. wr_unlock(&devices_lock);
  7885. mutex_lock(&stats_lock);
  7886. cgpu->last_device_valid_work = time(NULL);
  7887. mutex_unlock(&stats_lock);
  7888. if (hotplug_mode)
  7889. devices[total_devices + new_devices++] = cgpu;
  7890. else
  7891. devices[total_devices++] = cgpu;
  7892. adjust_mostdevs();
  7893. #ifdef USE_USBUTILS
  7894. if (cgpu->usbdev && !cgpu->unique_id && cgpu->usbdev->serial_string &&
  7895. strlen(cgpu->usbdev->serial_string) > 4)
  7896. cgpu->unique_id = str_text(cgpu->usbdev->serial_string);
  7897. #endif
  7898. return true;
  7899. }
  7900. struct device_drv *copy_drv(struct device_drv *drv)
  7901. {
  7902. struct device_drv *copy;
  7903. if (unlikely(!(copy = malloc(sizeof(*copy))))) {
  7904. quit(1, "Failed to allocate device_drv copy of %s (%s)",
  7905. drv->name, drv->copy ? "copy" : "original");
  7906. }
  7907. memcpy(copy, drv, sizeof(*copy));
  7908. copy->copy = true;
  7909. return copy;
  7910. }
  7911. #ifdef USE_USBUTILS
  7912. static void hotplug_process(void)
  7913. {
  7914. struct thr_info *thr;
  7915. int i, j;
  7916. for (i = 0; i < new_devices; i++) {
  7917. struct cgpu_info *cgpu;
  7918. int dev_no = total_devices + i;
  7919. cgpu = devices[dev_no];
  7920. enable_device(cgpu);
  7921. cgpu->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  7922. cgpu->rolling = cgpu->total_mhashes = 0;
  7923. }
  7924. wr_lock(&mining_thr_lock);
  7925. mining_thr = realloc(mining_thr, sizeof(thr) * (mining_threads + new_threads + 1));
  7926. if (!mining_thr)
  7927. quit(1, "Failed to hotplug realloc mining_thr");
  7928. for (i = 0; i < new_threads; i++) {
  7929. mining_thr[mining_threads + i] = calloc(1, sizeof(*thr));
  7930. if (!mining_thr[mining_threads + i])
  7931. quit(1, "Failed to hotplug calloc mining_thr[%d]", i);
  7932. }
  7933. // Start threads
  7934. for (i = 0; i < new_devices; ++i) {
  7935. struct cgpu_info *cgpu = devices[total_devices];
  7936. cgpu->thr = malloc(sizeof(*cgpu->thr) * (cgpu->threads+1));
  7937. cgpu->thr[cgpu->threads] = NULL;
  7938. cgpu->status = LIFE_INIT;
  7939. cgtime(&(cgpu->dev_start_tv));
  7940. for (j = 0; j < cgpu->threads; ++j) {
  7941. thr = __get_thread(mining_threads);
  7942. thr->id = mining_threads;
  7943. thr->cgpu = cgpu;
  7944. thr->device_thread = j;
  7945. if (!cgpu->drv->thread_prepare(thr)) {
  7946. null_device_drv(cgpu->drv);
  7947. cgpu->deven = DEV_DISABLED;
  7948. continue;
  7949. }
  7950. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  7951. quit(1, "hotplug thread %d create failed", thr->id);
  7952. cgpu->thr[j] = thr;
  7953. /* Enable threads for devices set not to mine but disable
  7954. * their queue in case we wish to enable them later */
  7955. if (cgpu->deven != DEV_DISABLED) {
  7956. applog(LOG_DEBUG, "Pushing sem post to thread %d", thr->id);
  7957. cgsem_post(&thr->sem);
  7958. }
  7959. mining_threads++;
  7960. }
  7961. total_devices++;
  7962. applog(LOG_WARNING, "Hotplug: %s added %s %i", cgpu->drv->dname, cgpu->drv->name, cgpu->device_id);
  7963. }
  7964. wr_unlock(&mining_thr_lock);
  7965. adjust_mostdevs();
  7966. #ifdef HAVE_CURSES
  7967. switch_logsize(true);
  7968. #endif
  7969. }
  7970. #define DRIVER_DRV_DETECT_HOTPLUG(X) X##_drv.drv_detect(true);
  7971. static void *hotplug_thread(void __maybe_unused *userdata)
  7972. {
  7973. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  7974. RenameThread("Hotplug");
  7975. hotplug_mode = true;
  7976. cgsleep_ms(5000);
  7977. while (0x2a) {
  7978. // Version 0.1 just add the devices on - worry about using nodev later
  7979. if (hotplug_time == 0)
  7980. cgsleep_ms(5000);
  7981. else {
  7982. new_devices = 0;
  7983. new_threads = 0;
  7984. /* Use the DRIVER_PARSE_COMMANDS macro to detect all
  7985. * devices */
  7986. DRIVER_PARSE_COMMANDS(DRIVER_DRV_DETECT_HOTPLUG)
  7987. if (new_devices)
  7988. hotplug_process();
  7989. // hotplug_time >0 && <=9999
  7990. cgsleep_ms(hotplug_time * 1000);
  7991. }
  7992. }
  7993. return NULL;
  7994. }
  7995. #endif
  7996. static void probe_pools(void)
  7997. {
  7998. int i;
  7999. for (i = 0; i < total_pools; i++) {
  8000. struct pool *pool = pools[i];
  8001. pool->testing = true;
  8002. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  8003. }
  8004. }
  8005. #define DRIVER_FILL_DEVICE_DRV(X) fill_device_drv(&X##_drv);
  8006. #define DRIVER_DRV_DETECT_ALL(X) X##_drv.drv_detect(false);
  8007. #ifdef USE_USBUTILS
  8008. static void *libusb_poll_thread(void __maybe_unused *arg)
  8009. {
  8010. struct timeval tv_end = {1, 0};
  8011. RenameThread("USBPoll");
  8012. while (usb_polling)
  8013. libusb_handle_events_timeout_completed(NULL, &tv_end, NULL);
  8014. /* Cancel any cancellable usb transfers */
  8015. cancel_usb_transfers();
  8016. /* Keep event handling going until there are no async transfers in
  8017. * flight. */
  8018. do {
  8019. libusb_handle_events_timeout_completed(NULL, &tv_end, NULL);
  8020. } while (async_usb_transfers());
  8021. return NULL;
  8022. }
  8023. static void initialise_usb(void) {
  8024. int err = libusb_init(NULL);
  8025. if (err) {
  8026. fprintf(stderr, "libusb_init() failed err %d", err);
  8027. fflush(stderr);
  8028. quit(1, "libusb_init() failed");
  8029. }
  8030. initialise_usblocks();
  8031. usb_polling = true;
  8032. pthread_create(&usb_poll_thread, NULL, libusb_poll_thread, NULL);
  8033. }
  8034. #else
  8035. #define initialise_usb() {}
  8036. #endif
  8037. int main(int argc, char *argv[])
  8038. {
  8039. struct sigaction handler;
  8040. struct work *work = NULL;
  8041. bool pool_msg = false;
  8042. struct thr_info *thr;
  8043. struct block *block;
  8044. int i, j, slept = 0;
  8045. unsigned int k;
  8046. char *s;
  8047. /* This dangerous functions tramples random dynamically allocated
  8048. * variables so do it before anything at all */
  8049. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  8050. early_quit(1, "Failed to curl_global_init");
  8051. #if LOCK_TRACKING
  8052. // Must be first
  8053. if (unlikely(pthread_mutex_init(&lockstat_lock, NULL)))
  8054. quithere(1, "Failed to pthread_mutex_init lockstat_lock errno=%d", errno);
  8055. #endif
  8056. initial_args = malloc(sizeof(char *) * (argc + 1));
  8057. for (i = 0; i < argc; i++)
  8058. initial_args[i] = strdup(argv[i]);
  8059. initial_args[argc] = NULL;
  8060. mutex_init(&hash_lock);
  8061. mutex_init(&console_lock);
  8062. cglock_init(&control_lock);
  8063. mutex_init(&stats_lock);
  8064. mutex_init(&sharelog_lock);
  8065. cglock_init(&ch_lock);
  8066. mutex_init(&sshare_lock);
  8067. rwlock_init(&blk_lock);
  8068. rwlock_init(&netacc_lock);
  8069. rwlock_init(&mining_thr_lock);
  8070. rwlock_init(&devices_lock);
  8071. mutex_init(&lp_lock);
  8072. if (unlikely(pthread_cond_init(&lp_cond, NULL)))
  8073. early_quit(1, "Failed to pthread_cond_init lp_cond");
  8074. mutex_init(&restart_lock);
  8075. if (unlikely(pthread_cond_init(&restart_cond, NULL)))
  8076. early_quit(1, "Failed to pthread_cond_init restart_cond");
  8077. if (unlikely(pthread_cond_init(&gws_cond, NULL)))
  8078. early_quit(1, "Failed to pthread_cond_init gws_cond");
  8079. /* Create a unique get work queue */
  8080. getq = tq_new();
  8081. if (!getq)
  8082. early_quit(1, "Failed to create getq");
  8083. /* We use the getq mutex as the staged lock */
  8084. stgd_lock = &getq->mutex;
  8085. initialise_usb();
  8086. snprintf(packagename, sizeof(packagename), "%s %s", PACKAGE, VERSION);
  8087. handler.sa_handler = &sighandler;
  8088. handler.sa_flags = 0;
  8089. sigemptyset(&handler.sa_mask);
  8090. sigaction(SIGTERM, &handler, &termhandler);
  8091. sigaction(SIGINT, &handler, &inthandler);
  8092. #ifndef WIN32
  8093. signal(SIGPIPE, SIG_IGN);
  8094. #else
  8095. timeBeginPeriod(1);
  8096. #endif
  8097. opt_kernel_path = alloca(PATH_MAX);
  8098. strcpy(opt_kernel_path, CGMINER_PREFIX);
  8099. cgminer_path = alloca(PATH_MAX);
  8100. s = strdup(argv[0]);
  8101. strcpy(cgminer_path, dirname(s));
  8102. free(s);
  8103. strcat(cgminer_path, "/");
  8104. devcursor = 8;
  8105. logstart = devcursor + 1;
  8106. logcursor = logstart + 1;
  8107. block = calloc(sizeof(struct block), 1);
  8108. if (unlikely(!block))
  8109. quit (1, "main OOM");
  8110. for (i = 0; i < 36; i++)
  8111. strcat(block->hash, "0");
  8112. HASH_ADD_STR(blocks, hash, block);
  8113. strcpy(current_hash, block->hash);
  8114. INIT_LIST_HEAD(&scan_devices);
  8115. /* parse command line */
  8116. opt_register_table(opt_config_table,
  8117. "Options for both config file and command line");
  8118. opt_register_table(opt_cmdline_table,
  8119. "Options for command line only");
  8120. opt_parse(&argc, argv, applog_and_exit);
  8121. if (argc != 1)
  8122. early_quit(1, "Unexpected extra commandline arguments");
  8123. if (!config_loaded)
  8124. load_default_config();
  8125. if (!opt_sha256 && !opt_scrypt)
  8126. early_quit(1, "Must explicitly specify mining algorithm (--sha256 or --scrypt)");
  8127. if (opt_benchmark || opt_benchfile) {
  8128. struct pool *pool;
  8129. if (opt_scrypt)
  8130. early_quit(1, "Cannot use benchmark mode with scrypt");
  8131. pool = add_pool();
  8132. pool->rpc_url = malloc(255);
  8133. if (opt_benchfile)
  8134. strcpy(pool->rpc_url, "Benchfile");
  8135. else
  8136. strcpy(pool->rpc_url, "Benchmark");
  8137. pool->rpc_user = pool->rpc_url;
  8138. pool->rpc_pass = pool->rpc_url;
  8139. enable_pool(pool);
  8140. pool->idle = false;
  8141. successful_connect = true;
  8142. for (i = 0; i < 16; i++) {
  8143. hex2bin(&bench_hidiff_bins[i][0], &bench_hidiffs[i][0], 160);
  8144. hex2bin(&bench_lodiff_bins[i][0], &bench_lodiffs[i][0], 160);
  8145. }
  8146. set_target(bench_target, 32);
  8147. }
  8148. #ifdef HAVE_CURSES
  8149. if (opt_realquiet || opt_display_devs)
  8150. use_curses = false;
  8151. if (use_curses)
  8152. enable_curses();
  8153. #endif
  8154. applog(LOG_WARNING, "Started %s", packagename);
  8155. if (cnfbuf) {
  8156. applog(LOG_NOTICE, "Loaded configuration file %s", cnfbuf);
  8157. switch (fileconf_load) {
  8158. case 0:
  8159. applog(LOG_WARNING, "Fatal JSON error in configuration file.");
  8160. applog(LOG_WARNING, "Configuration file could not be used.");
  8161. break;
  8162. case -1:
  8163. applog(LOG_WARNING, "Error in configuration file, partially loaded.");
  8164. if (use_curses)
  8165. applog(LOG_WARNING, "Start cgminer with -T to see what failed to load.");
  8166. break;
  8167. default:
  8168. break;
  8169. }
  8170. free(cnfbuf);
  8171. cnfbuf = NULL;
  8172. }
  8173. strcat(opt_kernel_path, "/");
  8174. if (want_per_device_stats)
  8175. opt_log_output = true;
  8176. /* Use a shorter scantime for scrypt */
  8177. if (opt_scantime < 0)
  8178. opt_scantime = opt_scrypt ? 30 : 60;
  8179. total_control_threads = 8;
  8180. control_thr = calloc(total_control_threads, sizeof(*thr));
  8181. if (!control_thr)
  8182. early_quit(1, "Failed to calloc control_thr");
  8183. gwsched_thr_id = 0;
  8184. #ifdef USE_USBUTILS
  8185. usb_initialise();
  8186. // before device detection
  8187. cgsem_init(&usb_resource_sem);
  8188. usbres_thr_id = 1;
  8189. thr = &control_thr[usbres_thr_id];
  8190. if (thr_info_create(thr, NULL, usb_resource_thread, thr))
  8191. early_quit(1, "usb resource thread create failed");
  8192. pthread_detach(thr->pth);
  8193. #endif
  8194. /* Use the DRIVER_PARSE_COMMANDS macro to fill all the device_drvs */
  8195. DRIVER_PARSE_COMMANDS(DRIVER_FILL_DEVICE_DRV)
  8196. /* Use the DRIVER_PARSE_COMMANDS macro to detect all devices */
  8197. DRIVER_PARSE_COMMANDS(DRIVER_DRV_DETECT_ALL)
  8198. if (opt_display_devs) {
  8199. applog(LOG_ERR, "Devices detected:");
  8200. for (i = 0; i < total_devices; ++i) {
  8201. struct cgpu_info *cgpu = devices[i];
  8202. if (cgpu->name)
  8203. applog(LOG_ERR, " %2d. %s %d: %s (driver: %s)", i, cgpu->drv->name, cgpu->device_id, cgpu->name, cgpu->drv->dname);
  8204. else
  8205. applog(LOG_ERR, " %2d. %s %d (driver: %s)", i, cgpu->drv->name, cgpu->device_id, cgpu->drv->dname);
  8206. }
  8207. early_quit(0, "%d devices listed", total_devices);
  8208. }
  8209. mining_threads = 0;
  8210. for (i = 0; i < total_devices; ++i)
  8211. enable_device(devices[i]);
  8212. #ifdef USE_USBUTILS
  8213. if (!total_devices) {
  8214. applog(LOG_WARNING, "No devices detected!");
  8215. applog(LOG_WARNING, "Waiting for USB hotplug devices or press q to quit");
  8216. }
  8217. #else
  8218. if (!total_devices)
  8219. early_quit(1, "All devices disabled, cannot mine!");
  8220. #endif
  8221. if (opt_queue == -1)
  8222. opt_queue = (opt_scrypt) ? total_devices : 9999;
  8223. most_devices = total_devices;
  8224. load_temp_cutoffs();
  8225. for (i = 0; i < total_devices; ++i)
  8226. devices[i]->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  8227. if (!opt_compact) {
  8228. logstart += most_devices;
  8229. logcursor = logstart + 1;
  8230. #ifdef HAVE_CURSES
  8231. check_winsizes();
  8232. #endif
  8233. }
  8234. if (!total_pools) {
  8235. applog(LOG_WARNING, "Need to specify at least one pool server.");
  8236. #ifdef HAVE_CURSES
  8237. if (!use_curses || !input_pool(false))
  8238. #endif
  8239. early_quit(1, "Pool setup failed");
  8240. }
  8241. for (i = 0; i < total_pools; i++) {
  8242. struct pool *pool = pools[i];
  8243. size_t siz;
  8244. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  8245. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  8246. if (!pool->rpc_userpass) {
  8247. if (!pool->rpc_user || !pool->rpc_pass)
  8248. early_quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  8249. siz = strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2;
  8250. pool->rpc_userpass = malloc(siz);
  8251. if (!pool->rpc_userpass)
  8252. early_quit(1, "Failed to malloc userpass");
  8253. snprintf(pool->rpc_userpass, siz, "%s:%s", pool->rpc_user, pool->rpc_pass);
  8254. }
  8255. }
  8256. /* Set the currentpool to pool 0 */
  8257. currentpool = pools[0];
  8258. #ifdef HAVE_SYSLOG_H
  8259. if (use_syslog)
  8260. openlog(PACKAGE, LOG_PID, LOG_USER);
  8261. #endif
  8262. #if defined(unix) || defined(__APPLE__)
  8263. if (opt_stderr_cmd)
  8264. fork_monitor();
  8265. #endif // defined(unix)
  8266. mining_thr = calloc(mining_threads, sizeof(thr));
  8267. if (!mining_thr)
  8268. early_quit(1, "Failed to calloc mining_thr");
  8269. for (i = 0; i < mining_threads; i++) {
  8270. mining_thr[i] = calloc(1, sizeof(*thr));
  8271. if (!mining_thr[i])
  8272. early_quit(1, "Failed to calloc mining_thr[%d]", i);
  8273. }
  8274. // Start threads
  8275. k = 0;
  8276. for (i = 0; i < total_devices; ++i) {
  8277. struct cgpu_info *cgpu = devices[i];
  8278. cgpu->thr = malloc(sizeof(*cgpu->thr) * (cgpu->threads+1));
  8279. cgpu->thr[cgpu->threads] = NULL;
  8280. cgpu->status = LIFE_INIT;
  8281. for (j = 0; j < cgpu->threads; ++j, ++k) {
  8282. thr = get_thread(k);
  8283. thr->id = k;
  8284. thr->cgpu = cgpu;
  8285. thr->device_thread = j;
  8286. if (!cgpu->drv->thread_prepare(thr))
  8287. continue;
  8288. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  8289. early_quit(1, "thread %d create failed", thr->id);
  8290. cgpu->thr[j] = thr;
  8291. /* Enable threads for devices set not to mine but disable
  8292. * their queue in case we wish to enable them later */
  8293. if (cgpu->deven != DEV_DISABLED) {
  8294. applog(LOG_DEBUG, "Pushing sem post to thread %d", thr->id);
  8295. cgsem_post(&thr->sem);
  8296. }
  8297. }
  8298. }
  8299. if (opt_benchmark || opt_benchfile)
  8300. goto begin_bench;
  8301. for (i = 0; i < total_pools; i++) {
  8302. struct pool *pool = pools[i];
  8303. enable_pool(pool);
  8304. pool->idle = true;
  8305. }
  8306. /* Look for at least one active pool before starting */
  8307. applog(LOG_NOTICE, "Probing for an alive pool");
  8308. probe_pools();
  8309. do {
  8310. sleep(1);
  8311. slept++;
  8312. } while (!pools_active && slept < 60);
  8313. while (!pools_active) {
  8314. if (!pool_msg) {
  8315. applog(LOG_ERR, "No servers were found that could be used to get work from.");
  8316. applog(LOG_ERR, "Please check the details from the list below of the servers you have input");
  8317. applog(LOG_ERR, "Most likely you have input the wrong URL, forgotten to add a port, or have not set up workers");
  8318. for (i = 0; i < total_pools; i++) {
  8319. struct pool *pool = pools[i];
  8320. applog(LOG_WARNING, "Pool: %d URL: %s User: %s Password: %s",
  8321. i, pool->rpc_url, pool->rpc_user, pool->rpc_pass);
  8322. }
  8323. pool_msg = true;
  8324. if (use_curses)
  8325. applog(LOG_ERR, "Press any key to exit, or cgminer will wait indefinitely for an alive pool.");
  8326. }
  8327. if (!use_curses)
  8328. early_quit(0, "No servers could be used! Exiting.");
  8329. #ifdef HAVE_CURSES
  8330. touchwin(logwin);
  8331. wrefresh(logwin);
  8332. halfdelay(10);
  8333. if (getch() != ERR)
  8334. early_quit(0, "No servers could be used! Exiting.");
  8335. cbreak();
  8336. #endif
  8337. };
  8338. begin_bench:
  8339. total_mhashes_done = 0;
  8340. for (i = 0; i < total_devices; i++) {
  8341. struct cgpu_info *cgpu = devices[i];
  8342. cgpu->rolling = cgpu->total_mhashes = 0;
  8343. }
  8344. cgtime(&total_tv_start);
  8345. cgtime(&total_tv_end);
  8346. cgtime(&tv_hashmeter);
  8347. get_datestamp(datestamp, sizeof(datestamp), &total_tv_start);
  8348. watchpool_thr_id = 2;
  8349. thr = &control_thr[watchpool_thr_id];
  8350. /* start watchpool thread */
  8351. if (thr_info_create(thr, NULL, watchpool_thread, NULL))
  8352. early_quit(1, "watchpool thread create failed");
  8353. pthread_detach(thr->pth);
  8354. watchdog_thr_id = 3;
  8355. thr = &control_thr[watchdog_thr_id];
  8356. /* start watchdog thread */
  8357. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  8358. early_quit(1, "watchdog thread create failed");
  8359. pthread_detach(thr->pth);
  8360. /* Create API socket thread */
  8361. api_thr_id = 5;
  8362. thr = &control_thr[api_thr_id];
  8363. if (thr_info_create(thr, NULL, api_thread, thr))
  8364. early_quit(1, "API thread create failed");
  8365. #ifdef USE_USBUTILS
  8366. hotplug_thr_id = 6;
  8367. thr = &control_thr[hotplug_thr_id];
  8368. if (thr_info_create(thr, NULL, hotplug_thread, thr))
  8369. early_quit(1, "hotplug thread create failed");
  8370. pthread_detach(thr->pth);
  8371. #endif
  8372. #ifdef HAVE_CURSES
  8373. /* Create curses input thread for keyboard input. Create this last so
  8374. * that we know all threads are created since this can call kill_work
  8375. * to try and shut down all previous threads. */
  8376. input_thr_id = 7;
  8377. thr = &control_thr[input_thr_id];
  8378. if (thr_info_create(thr, NULL, input_thread, thr))
  8379. early_quit(1, "input thread create failed");
  8380. pthread_detach(thr->pth);
  8381. #endif
  8382. /* Just to be sure */
  8383. if (total_control_threads != 8)
  8384. early_quit(1, "incorrect total_control_threads (%d) should be 8", total_control_threads);
  8385. set_highprio();
  8386. /* Once everything is set up, main() becomes the getwork scheduler */
  8387. while (42) {
  8388. int ts, max_staged = max_queue;
  8389. struct pool *pool, *cp;
  8390. bool lagging = false;
  8391. if (opt_work_update)
  8392. signal_work_update();
  8393. opt_work_update = false;
  8394. cp = current_pool();
  8395. /* If the primary pool is a getwork pool and cannot roll work,
  8396. * try to stage one extra work per mining thread */
  8397. if (!pool_localgen(cp) && !staged_rollable)
  8398. max_staged += mining_threads;
  8399. mutex_lock(stgd_lock);
  8400. ts = __total_staged();
  8401. if (!pool_localgen(cp) && !ts && !opt_fail_only)
  8402. lagging = true;
  8403. /* Wait until hash_pop tells us we need to create more work */
  8404. if (ts > max_staged) {
  8405. if (work_emptied && max_queue < opt_queue) {
  8406. max_queue++;
  8407. work_emptied = false;
  8408. }
  8409. work_filled = true;
  8410. pthread_cond_wait(&gws_cond, stgd_lock);
  8411. ts = __total_staged();
  8412. }
  8413. mutex_unlock(stgd_lock);
  8414. if (ts > max_staged) {
  8415. /* Keeps slowly generating work even if it's not being
  8416. * used to keep last_getwork incrementing and to see
  8417. * if pools are still alive. */
  8418. if (work_emptied && max_queue < opt_queue) {
  8419. max_queue++;
  8420. work_emptied = false;
  8421. }
  8422. work_filled = true;
  8423. work = hash_pop(false);
  8424. if (work)
  8425. discard_work(work);
  8426. continue;
  8427. }
  8428. if (work)
  8429. discard_work(work);
  8430. work = make_work();
  8431. if (lagging && !pool_tset(cp, &cp->lagging)) {
  8432. applog(LOG_WARNING, "Pool %d not providing work fast enough", cp->pool_no);
  8433. cp->getfail_occasions++;
  8434. total_go++;
  8435. if (!pool_localgen(cp) && max_queue < opt_queue)
  8436. applog(LOG_INFO, "Increasing queue to %d", ++max_queue);
  8437. }
  8438. pool = select_pool(lagging);
  8439. retry:
  8440. if (pool->has_stratum) {
  8441. while (!pool->stratum_active || !pool->stratum_notify) {
  8442. struct pool *altpool = select_pool(true);
  8443. cgsleep_ms(5000);
  8444. if (altpool != pool) {
  8445. pool = altpool;
  8446. goto retry;
  8447. }
  8448. }
  8449. gen_stratum_work(pool, work);
  8450. applog(LOG_DEBUG, "Generated stratum work");
  8451. stage_work(work);
  8452. continue;
  8453. }
  8454. if (opt_benchfile) {
  8455. get_benchfile_work(work);
  8456. applog(LOG_DEBUG, "Generated benchfile work");
  8457. stage_work(work);
  8458. continue;
  8459. } else if (opt_benchmark) {
  8460. get_benchmark_work(work);
  8461. applog(LOG_DEBUG, "Generated benchmark work");
  8462. stage_work(work);
  8463. continue;
  8464. }
  8465. #ifdef HAVE_LIBCURL
  8466. struct curl_ent *ce;
  8467. if (pool->gbt_solo) {
  8468. while (pool->idle) {
  8469. struct pool *altpool = select_pool(true);
  8470. cgsleep_ms(5000);
  8471. if (altpool != pool) {
  8472. pool = altpool;
  8473. goto retry;
  8474. }
  8475. }
  8476. gen_solo_work(pool, work);
  8477. applog(LOG_DEBUG, "Generated GBT SOLO work");
  8478. stage_work(work);
  8479. continue;
  8480. }
  8481. if (pool->has_gbt) {
  8482. while (pool->idle) {
  8483. struct pool *altpool = select_pool(true);
  8484. cgsleep_ms(5000);
  8485. if (altpool != pool) {
  8486. pool = altpool;
  8487. goto retry;
  8488. }
  8489. }
  8490. gen_gbt_work(pool, work);
  8491. applog(LOG_DEBUG, "Generated GBT work");
  8492. stage_work(work);
  8493. continue;
  8494. }
  8495. if (clone_available()) {
  8496. applog(LOG_DEBUG, "Cloned getwork work");
  8497. free_work(work);
  8498. continue;
  8499. }
  8500. work->pool = pool;
  8501. ce = pop_curl_entry(pool);
  8502. /* obtain new work from bitcoin via JSON-RPC */
  8503. if (!get_upstream_work(work, ce->curl)) {
  8504. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, retrying in 5s", pool->pool_no);
  8505. /* Make sure the pool just hasn't stopped serving
  8506. * requests but is up as we'll keep hammering it */
  8507. if (++pool->seq_getfails > mining_threads + opt_queue)
  8508. pool_died(pool);
  8509. cgsleep_ms(5000);
  8510. push_curl_entry(ce, pool);
  8511. pool = select_pool(!opt_fail_only);
  8512. free_work(work);
  8513. goto retry;
  8514. }
  8515. if (ts >= max_staged)
  8516. pool_tclear(pool, &pool->lagging);
  8517. if (pool_tclear(pool, &pool->idle))
  8518. pool_resus(pool);
  8519. applog(LOG_DEBUG, "Generated getwork work");
  8520. stage_work(work);
  8521. push_curl_entry(ce, pool);
  8522. #endif
  8523. }
  8524. return 0;
  8525. }