cgminer.c 170 KB

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