cgminer.c 185 KB

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