miner.c 159 KB

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