cgminer.c 191 KB

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