cgminer.c 187 KB

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