miner.c 306 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987
  1. /*
  2. * Copyright 2011-2013 Con Kolivas
  3. * Copyright 2011-2013 Luke Dashjr
  4. * Copyright 2012-2013 Andrew Smith
  5. * Copyright 2010 Jeff Garzik
  6. *
  7. * This program is free software; you can redistribute it and/or modify it
  8. * under the terms of the GNU General Public License as published by the Free
  9. * Software Foundation; either version 3 of the License, or (at your option)
  10. * any later version. See COPYING for more details.
  11. */
  12. #include "config.h"
  13. #ifdef HAVE_CURSES
  14. #ifdef USE_UNICODE
  15. #define PDC_WIDE
  16. #endif
  17. // Must be before stdbool, since pdcurses typedefs bool :/
  18. #include <curses.h>
  19. #endif
  20. #include <ctype.h>
  21. #include <limits.h>
  22. #include <locale.h>
  23. #include <stdio.h>
  24. #include <stdlib.h>
  25. #include <string.h>
  26. #include <stdbool.h>
  27. #include <stdint.h>
  28. #include <unistd.h>
  29. #include <sys/time.h>
  30. #include <time.h>
  31. #include <math.h>
  32. #include <stdarg.h>
  33. #include <assert.h>
  34. #include <signal.h>
  35. #include <wctype.h>
  36. #include <sys/stat.h>
  37. #include <sys/types.h>
  38. #include <dirent.h>
  39. #ifdef HAVE_PWD_H
  40. #include <pwd.h>
  41. #endif
  42. #ifndef WIN32
  43. #include <sys/resource.h>
  44. #include <sys/socket.h>
  45. #if defined(HAVE_LIBUDEV) && defined(HAVE_SYS_EPOLL_H)
  46. #include <libudev.h>
  47. #include <sys/epoll.h>
  48. #define HAVE_BFG_HOTPLUG
  49. #endif
  50. #else
  51. #include <winsock2.h>
  52. #include <windows.h>
  53. #include <dbt.h>
  54. #define HAVE_BFG_HOTPLUG
  55. #endif
  56. #include <ccan/opt/opt.h>
  57. #include <jansson.h>
  58. #include <curl/curl.h>
  59. #include <libgen.h>
  60. #include <sha2.h>
  61. #include <utlist.h>
  62. #include <blkmaker.h>
  63. #include <blkmaker_jansson.h>
  64. #include <blktemplate.h>
  65. #include "compat.h"
  66. #include "deviceapi.h"
  67. #include "logging.h"
  68. #include "miner.h"
  69. #include "findnonce.h"
  70. #include "adl.h"
  71. #include "driver-cpu.h"
  72. #include "driver-opencl.h"
  73. #include "bench_block.h"
  74. #include "scrypt.h"
  75. #ifdef USE_AVALON
  76. #include "driver-avalon.h"
  77. #endif
  78. #ifdef HAVE_BFG_LOWLEVEL
  79. #include "lowlevel.h"
  80. #endif
  81. #if defined(unix) || defined(__APPLE__)
  82. #include <errno.h>
  83. #include <fcntl.h>
  84. #include <sys/wait.h>
  85. #endif
  86. #ifdef USE_SCRYPT
  87. #include "scrypt.h"
  88. #endif
  89. #if defined(USE_AVALON) || defined(USE_BITFORCE) || defined(USE_ICARUS) || defined(USE_MODMINER) || defined(USE_NANOFURY) || defined(USE_X6500) || defined(USE_ZTEX)
  90. # define USE_FPGA
  91. #endif
  92. struct strategies strategies[] = {
  93. { "Failover" },
  94. { "Round Robin" },
  95. { "Rotate" },
  96. { "Load Balance" },
  97. { "Balance" },
  98. };
  99. static char packagename[256];
  100. bool opt_protocol;
  101. bool opt_dev_protocol;
  102. static bool opt_benchmark;
  103. static bool want_longpoll = true;
  104. static bool want_gbt = true;
  105. static bool want_getwork = true;
  106. #if BLKMAKER_VERSION > 1
  107. struct _cbscript_t {
  108. char *data;
  109. size_t sz;
  110. };
  111. static struct _cbscript_t opt_coinbase_script;
  112. static uint32_t template_nonce;
  113. #endif
  114. #if BLKMAKER_VERSION > 0
  115. char *opt_coinbase_sig;
  116. #endif
  117. char *request_target_str;
  118. float request_pdiff = 1.0;
  119. double request_bdiff;
  120. static bool want_stratum = true;
  121. bool have_longpoll;
  122. int opt_skip_checks;
  123. bool want_per_device_stats;
  124. bool use_syslog;
  125. bool opt_quiet_work_updates;
  126. bool opt_quiet;
  127. bool opt_realquiet;
  128. int loginput_size;
  129. bool opt_compact;
  130. bool opt_show_procs;
  131. const int opt_cutofftemp = 95;
  132. int opt_hysteresis = 3;
  133. static int opt_retries = -1;
  134. int opt_fail_pause = 5;
  135. int opt_log_interval = 5;
  136. int opt_queue = 1;
  137. int opt_scantime = 60;
  138. int opt_expiry = 120;
  139. int opt_expiry_lp = 3600;
  140. int opt_bench_algo = -1;
  141. unsigned long long global_hashrate;
  142. static bool opt_unittest = false;
  143. unsigned long global_quota_gcd = 1;
  144. time_t last_getwork;
  145. #ifdef HAVE_OPENCL
  146. int opt_dynamic_interval = 7;
  147. int nDevs;
  148. int opt_g_threads = -1;
  149. #endif
  150. #ifdef USE_SCRYPT
  151. static char detect_algo = 1;
  152. bool opt_scrypt;
  153. #else
  154. static char detect_algo;
  155. #endif
  156. bool opt_restart = true;
  157. #ifdef USE_LIBMICROHTTPD
  158. #include "httpsrv.h"
  159. int httpsrv_port = -1;
  160. #endif
  161. #ifdef USE_LIBEVENT
  162. int stratumsrv_port = -1;
  163. #endif
  164. const
  165. int rescan_delay_ms = 1000;
  166. #ifdef HAVE_BFG_HOTPLUG
  167. bool opt_hotplug = 1;
  168. const
  169. int hotplug_delay_ms = 100;
  170. #else
  171. const bool opt_hotplug;
  172. #endif
  173. struct string_elist *scan_devices;
  174. static struct string_elist *opt_set_device_list;
  175. bool opt_force_dev_init;
  176. static struct string_elist *opt_devices_enabled_list;
  177. static bool opt_display_devs;
  178. int total_devices;
  179. struct cgpu_info **devices;
  180. int total_devices_new;
  181. struct cgpu_info **devices_new;
  182. bool have_opencl;
  183. int opt_n_threads = -1;
  184. int mining_threads;
  185. int num_processors;
  186. #ifdef HAVE_CURSES
  187. bool use_curses = true;
  188. #else
  189. bool use_curses;
  190. #endif
  191. #ifdef HAVE_LIBUSB
  192. bool have_libusb;
  193. #endif
  194. static bool opt_submit_stale = true;
  195. static int opt_shares;
  196. static int opt_submit_threads = 0x40;
  197. bool opt_fail_only;
  198. bool opt_autofan;
  199. bool opt_autoengine;
  200. bool opt_noadl;
  201. char *opt_api_allow = NULL;
  202. char *opt_api_groups;
  203. char *opt_api_description = PACKAGE_STRING;
  204. int opt_api_port = 4028;
  205. bool opt_api_listen;
  206. bool opt_api_mcast;
  207. char *opt_api_mcast_addr = API_MCAST_ADDR;
  208. char *opt_api_mcast_code = API_MCAST_CODE;
  209. char *opt_api_mcast_des = "";
  210. int opt_api_mcast_port = 4028;
  211. bool opt_api_network;
  212. bool opt_delaynet;
  213. bool opt_disable_pool;
  214. static bool no_work;
  215. char *opt_icarus_options = NULL;
  216. char *opt_icarus_timing = NULL;
  217. bool opt_worktime;
  218. bool opt_weighed_stats;
  219. #ifdef USE_AVALON
  220. char *opt_avalon_options = NULL;
  221. #endif
  222. #ifdef USE_KLONDIKE
  223. char *opt_klondike_options = NULL;
  224. #endif
  225. char *opt_kernel_path;
  226. char *cgminer_path;
  227. #if defined(USE_BITFORCE)
  228. bool opt_bfl_noncerange;
  229. #endif
  230. #define QUIET (opt_quiet || opt_realquiet)
  231. struct thr_info *control_thr;
  232. struct thr_info **mining_thr;
  233. static int gwsched_thr_id;
  234. static int watchpool_thr_id;
  235. static int watchdog_thr_id;
  236. #ifdef HAVE_CURSES
  237. static int input_thr_id;
  238. #endif
  239. int gpur_thr_id;
  240. static int api_thr_id;
  241. static int total_control_threads;
  242. pthread_mutex_t hash_lock;
  243. static pthread_mutex_t *stgd_lock;
  244. pthread_mutex_t console_lock;
  245. cglock_t ch_lock;
  246. static pthread_rwlock_t blk_lock;
  247. static pthread_mutex_t sshare_lock;
  248. pthread_rwlock_t netacc_lock;
  249. pthread_rwlock_t mining_thr_lock;
  250. pthread_rwlock_t devices_lock;
  251. static pthread_mutex_t lp_lock;
  252. static pthread_cond_t lp_cond;
  253. pthread_cond_t gws_cond;
  254. bool shutting_down;
  255. double total_rolling;
  256. double total_mhashes_done;
  257. static struct timeval total_tv_start, total_tv_end;
  258. static struct timeval miner_started;
  259. cglock_t control_lock;
  260. pthread_mutex_t stats_lock;
  261. static pthread_mutex_t submitting_lock;
  262. static int total_submitting;
  263. static struct work *submit_waiting;
  264. notifier_t submit_waiting_notifier;
  265. int hw_errors;
  266. int total_accepted, total_rejected;
  267. int total_getworks, total_stale, total_discarded;
  268. uint64_t total_bytes_rcvd, total_bytes_sent;
  269. double total_diff1, total_bad_diff1;
  270. double total_diff_accepted, total_diff_rejected, total_diff_stale;
  271. static int staged_rollable;
  272. unsigned int new_blocks;
  273. unsigned int found_blocks;
  274. unsigned int local_work;
  275. unsigned int total_go, total_ro;
  276. struct pool **pools;
  277. static struct pool *currentpool = NULL;
  278. int total_pools, enabled_pools;
  279. enum pool_strategy pool_strategy = POOL_FAILOVER;
  280. int opt_rotate_period;
  281. static int total_urls, total_users, total_passes;
  282. static
  283. #ifndef HAVE_CURSES
  284. const
  285. #endif
  286. bool curses_active;
  287. #ifdef HAVE_CURSES
  288. #if !(defined(PDCURSES) || defined(NCURSES_VERSION))
  289. const
  290. #endif
  291. short default_bgcolor = COLOR_BLACK;
  292. static int attr_title = A_BOLD;
  293. #endif
  294. static
  295. #if defined(HAVE_CURSES) && defined(USE_UNICODE)
  296. bool use_unicode;
  297. static
  298. bool have_unicode_degrees;
  299. static
  300. wchar_t unicode_micro = 'u';
  301. #else
  302. const bool use_unicode;
  303. static
  304. const bool have_unicode_degrees;
  305. static
  306. const char unicode_micro = 'u';
  307. #endif
  308. #ifdef HAVE_CURSES
  309. #define U8_BAD_START "\xef\x80\x81"
  310. #define U8_BAD_END "\xef\x80\x80"
  311. #define AS_BAD(x) U8_BAD_START x U8_BAD_END
  312. bool selecting_device;
  313. unsigned selected_device;
  314. #endif
  315. static char current_block[40];
  316. /* Protected by ch_lock */
  317. static char *current_hash;
  318. static uint32_t current_block_id;
  319. char *current_fullhash;
  320. static char datestamp[40];
  321. static char blocktime[32];
  322. time_t block_time;
  323. static char best_share[8] = "0";
  324. double current_diff = 0xFFFFFFFFFFFFFFFFULL;
  325. static char block_diff[8];
  326. static char net_hashrate[10];
  327. uint64_t best_diff = 0;
  328. static bool known_blkheight_current;
  329. static uint32_t known_blkheight;
  330. static uint32_t known_blkheight_blkid;
  331. static uint64_t block_subsidy;
  332. struct block {
  333. char hash[40];
  334. UT_hash_handle hh;
  335. int block_no;
  336. };
  337. static struct block *blocks = NULL;
  338. int swork_id;
  339. /* For creating a hash database of stratum shares submitted that have not had
  340. * a response yet */
  341. struct stratum_share {
  342. UT_hash_handle hh;
  343. bool block;
  344. struct work *work;
  345. int id;
  346. };
  347. static struct stratum_share *stratum_shares = NULL;
  348. char *opt_socks_proxy = NULL;
  349. static const char def_conf[] = "bfgminer.conf";
  350. static bool config_loaded;
  351. static int include_count;
  352. #define JSON_INCLUDE_CONF "include"
  353. #define JSON_LOAD_ERROR "JSON decode of file '%s' failed\n %s"
  354. #define JSON_LOAD_ERROR_LEN strlen(JSON_LOAD_ERROR)
  355. #define JSON_MAX_DEPTH 10
  356. #define JSON_MAX_DEPTH_ERR "Too many levels of JSON includes (limit 10) or a loop"
  357. char *cmd_idle, *cmd_sick, *cmd_dead;
  358. #if defined(unix) || defined(__APPLE__)
  359. static char *opt_stderr_cmd = NULL;
  360. static int forkpid;
  361. #endif // defined(unix)
  362. #ifdef HAVE_CHROOT
  363. char *chroot_dir;
  364. #endif
  365. #ifdef HAVE_PWD_H
  366. char *opt_setuid;
  367. #endif
  368. struct sigaction termhandler, inthandler;
  369. struct thread_q *getq;
  370. static int total_work;
  371. static bool staged_full;
  372. struct work *staged_work = NULL;
  373. struct schedtime {
  374. bool enable;
  375. struct tm tm;
  376. };
  377. struct schedtime schedstart;
  378. struct schedtime schedstop;
  379. bool sched_paused;
  380. static bool time_before(struct tm *tm1, struct tm *tm2)
  381. {
  382. if (tm1->tm_hour < tm2->tm_hour)
  383. return true;
  384. if (tm1->tm_hour == tm2->tm_hour && tm1->tm_min < tm2->tm_min)
  385. return true;
  386. return false;
  387. }
  388. static bool should_run(void)
  389. {
  390. struct tm tm;
  391. time_t tt;
  392. bool within_range;
  393. if (!schedstart.enable && !schedstop.enable)
  394. return true;
  395. tt = time(NULL);
  396. localtime_r(&tt, &tm);
  397. // NOTE: This is delicately balanced so that should_run is always false if schedstart==schedstop
  398. if (time_before(&schedstop.tm, &schedstart.tm))
  399. within_range = (time_before(&tm, &schedstop.tm) || !time_before(&tm, &schedstart.tm));
  400. else
  401. within_range = (time_before(&tm, &schedstop.tm) && !time_before(&tm, &schedstart.tm));
  402. if (within_range && !schedstop.enable)
  403. /* This is a once off event with no stop time set */
  404. schedstart.enable = false;
  405. return within_range;
  406. }
  407. void get_datestamp(char *f, size_t fsiz, time_t tt)
  408. {
  409. struct tm _tm;
  410. struct tm *tm = &_tm;
  411. if (tt == INVALID_TIMESTAMP)
  412. tt = time(NULL);
  413. localtime_r(&tt, tm);
  414. snprintf(f, fsiz, "[%d-%02d-%02d %02d:%02d:%02d]",
  415. tm->tm_year + 1900,
  416. tm->tm_mon + 1,
  417. tm->tm_mday,
  418. tm->tm_hour,
  419. tm->tm_min,
  420. tm->tm_sec);
  421. }
  422. static
  423. void get_timestamp(char *f, size_t fsiz, time_t tt)
  424. {
  425. struct tm _tm;
  426. struct tm *tm = &_tm;
  427. localtime_r(&tt, tm);
  428. snprintf(f, fsiz, "[%02d:%02d:%02d]",
  429. tm->tm_hour,
  430. tm->tm_min,
  431. tm->tm_sec);
  432. }
  433. static void applog_and_exit(const char *fmt, ...) FORMAT_SYNTAX_CHECK(printf, 1, 2);
  434. static char exit_buf[512];
  435. static void applog_and_exit(const char *fmt, ...)
  436. {
  437. va_list ap;
  438. va_start(ap, fmt);
  439. vsnprintf(exit_buf, sizeof(exit_buf), fmt, ap);
  440. va_end(ap);
  441. _applog(LOG_ERR, exit_buf);
  442. exit(1);
  443. }
  444. char *devpath_to_devid(const char *devpath)
  445. {
  446. #ifndef WIN32
  447. struct stat my_stat;
  448. if (stat(devpath, &my_stat))
  449. return NULL;
  450. char *devs = malloc(6 + (sizeof(dev_t) * 2) + 1);
  451. memcpy(devs, "dev_t:", 6);
  452. bin2hex(&devs[6], &my_stat.st_rdev, sizeof(dev_t));
  453. #else
  454. if (!strncmp(devpath, "\\\\.\\", 4))
  455. devpath += 4;
  456. if (strncasecmp(devpath, "COM", 3) || !devpath[3])
  457. return NULL;
  458. devpath += 3;
  459. char *p;
  460. strtol(devpath, &p, 10);
  461. if (p[0])
  462. return NULL;
  463. const int sz = (p - devpath);
  464. char *devs = malloc(4 + sz + 1);
  465. sprintf(devs, "com:%s", devpath);
  466. #endif
  467. return devs;
  468. }
  469. static
  470. bool devpaths_match(const char * const ap, const char * const bp)
  471. {
  472. char * const a = devpath_to_devid(ap);
  473. if (!a)
  474. return false;
  475. char * const b = devpath_to_devid(bp);
  476. bool rv = false;
  477. if (b)
  478. {
  479. rv = !strcmp(a, b);
  480. free(b);
  481. }
  482. free(a);
  483. return rv;
  484. }
  485. static
  486. int proc_letter_to_number(const char *s, const char ** const rem)
  487. {
  488. int n = 0, c;
  489. for ( ; s[0]; ++s)
  490. {
  491. if (unlikely(n > INT_MAX / 26))
  492. break;
  493. c = tolower(s[0]) - 'a';
  494. if (unlikely(c < 0 || c > 25))
  495. break;
  496. if (unlikely(INT_MAX - c < n))
  497. break;
  498. n = (n * 26) + c;
  499. }
  500. *rem = s;
  501. return n;
  502. }
  503. static
  504. bool cgpu_match(const char * const pattern, const struct cgpu_info * const cgpu)
  505. {
  506. // all - matches anything
  507. // d0 - matches all processors of device 0
  508. // d0-3 - matches all processors of device 0, 1, 2, or 3
  509. // d0a - matches first processor of device 0
  510. // 0 - matches processor 0
  511. // 0-4 - matches processors 0, 1, 2, 3, or 4
  512. // ___ - matches all processors on all devices using driver/name ___
  513. // ___0 - matches all processors of 0th device using driver/name ___
  514. // ___0a - matches first processor of 0th device using driver/name ___
  515. // @* - matches device with serial or path *
  516. // @*@a - matches first processor of device with serial or path *
  517. // ___@* - matches device with serial or path * using driver/name ___
  518. if (!strcasecmp(pattern, "all"))
  519. return true;
  520. const struct device_drv * const drv = cgpu->drv;
  521. const char *p = pattern, *p2;
  522. size_t L;
  523. int n, i, c = -1;
  524. int n2;
  525. int proc_first = -1, proc_last = -1;
  526. struct cgpu_info *device;
  527. if (!(strncasecmp(drv->dname, p, (L = strlen(drv->dname)))
  528. && strncasecmp(drv-> name, p, (L = strlen(drv-> name)))))
  529. // dname or name
  530. p = &pattern[L];
  531. else
  532. if (p[0] == 'd' && (isdigit(p[1]) || p[1] == '-'))
  533. // d#
  534. ++p;
  535. else
  536. if (isdigit(p[0]) || p[0] == '@' || p[0] == '-')
  537. // # or @
  538. {}
  539. else
  540. return false;
  541. L = p - pattern;
  542. while (isspace(p[0]))
  543. ++p;
  544. if (p[0] == '@')
  545. {
  546. // Serial/path
  547. const char * const ser = &p[1];
  548. for (p = ser; p[0] != '@' && p[0] != '\0'; ++p)
  549. {}
  550. p2 = (p[0] == '@') ? &p[1] : p;
  551. const size_t serlen = (p - ser);
  552. p = "";
  553. n = n2 = 0;
  554. const char * const devpath = cgpu->device_path ?: "";
  555. const char * const devser = cgpu->dev_serial ?: "";
  556. if ((!strncmp(devpath, ser, serlen)) && devpath[serlen] == '\0')
  557. {} // Match
  558. else
  559. if ((!strncmp(devser, ser, serlen)) && devser[serlen] == '\0')
  560. {} // Match
  561. else
  562. {
  563. char devpath2[serlen + 1];
  564. memcpy(devpath2, ser, serlen);
  565. devpath2[serlen] = '\0';
  566. if (!devpaths_match(devpath, ser))
  567. return false;
  568. }
  569. }
  570. else
  571. {
  572. if (isdigit(p[0]))
  573. n = strtol(p, (void*)&p2, 0);
  574. else
  575. {
  576. n = 0;
  577. p2 = p;
  578. }
  579. if (p2[0] == '-')
  580. {
  581. ++p2;
  582. if (p2[0] && isdigit(p2[0]))
  583. n2 = strtol(p2, (void*)&p2, 0);
  584. else
  585. n2 = INT_MAX;
  586. }
  587. else
  588. n2 = n;
  589. if (p == pattern)
  590. {
  591. if (!p[0])
  592. return true;
  593. if (p2 && p2[0])
  594. goto invsyntax;
  595. for (i = n; i <= n2; ++i)
  596. {
  597. if (i >= total_devices)
  598. break;
  599. if (cgpu == devices[i])
  600. return true;
  601. }
  602. return false;
  603. }
  604. }
  605. if (p2[0])
  606. {
  607. proc_first = proc_letter_to_number(&p2[0], &p2);
  608. if (p2[0] == '-')
  609. {
  610. ++p2;
  611. if (p2[0])
  612. proc_last = proc_letter_to_number(p2, &p2);
  613. else
  614. proc_last = INT_MAX;
  615. }
  616. else
  617. proc_last = proc_first;
  618. if (p2[0])
  619. goto invsyntax;
  620. }
  621. if (L > 1 || tolower(pattern[0]) != 'd' || !p[0])
  622. {
  623. if ((L == 3 && !strncasecmp(pattern, drv->name, 3)) ||
  624. (!L) ||
  625. (L == strlen(drv->dname) && !strncasecmp(pattern, drv->dname, L)))
  626. {} // Matched name or dname
  627. else
  628. return false;
  629. if (p[0] && (cgpu->device_id < n || cgpu->device_id > n2))
  630. return false;
  631. if (proc_first != -1 && (cgpu->proc_id < proc_first || cgpu->proc_id > proc_last))
  632. return false;
  633. return true;
  634. }
  635. // d#
  636. c = -1;
  637. for (i = 0; ; ++i)
  638. {
  639. if (i == total_devices)
  640. return false;
  641. if (devices[i]->device != devices[i])
  642. continue;
  643. ++c;
  644. if (c < n)
  645. continue;
  646. if (c > n2)
  647. break;
  648. for (device = devices[i]; device; device = device->next_proc)
  649. {
  650. if (proc_first != -1 && (device->proc_id < proc_first || device->proc_id > proc_last))
  651. continue;
  652. if (device == cgpu)
  653. return true;
  654. }
  655. }
  656. return false;
  657. invsyntax:
  658. applog(LOG_WARNING, "%s: Invalid syntax: %s", __func__, pattern);
  659. return false;
  660. }
  661. #define TEST_CGPU_MATCH(pattern) \
  662. if (!cgpu_match(pattern, &cgpu)) \
  663. applog(LOG_ERR, "%s: Pattern \"%s\" should have matched!", __func__, pattern); \
  664. // END TEST_CGPU_MATCH
  665. #define TEST_CGPU_NOMATCH(pattern) \
  666. if (cgpu_match(pattern, &cgpu)) \
  667. applog(LOG_ERR, "%s: Pattern \"%s\" should NOT have matched!", __func__, pattern); \
  668. // END TEST_CGPU_MATCH
  669. static __maybe_unused
  670. void test_cgpu_match()
  671. {
  672. struct device_drv drv = {
  673. .dname = "test",
  674. .name = "TST",
  675. };
  676. struct cgpu_info cgpu = {
  677. .drv = &drv,
  678. .device = &cgpu,
  679. .device_id = 1,
  680. .proc_id = 1,
  681. .proc_repr = "TST 1b",
  682. }, cgpu0a = {
  683. .drv = &drv,
  684. .device = &cgpu0a,
  685. .device_id = 0,
  686. .proc_id = 0,
  687. .proc_repr = "TST 0a",
  688. }, cgpu1a = {
  689. .drv = &drv,
  690. .device = &cgpu0a,
  691. .device_id = 1,
  692. .proc_id = 0,
  693. .proc_repr = "TST 1a",
  694. };
  695. struct cgpu_info *devices_list[3] = {&cgpu0a, &cgpu1a, &cgpu,};
  696. devices = devices_list;
  697. total_devices = 3;
  698. TEST_CGPU_MATCH("all")
  699. TEST_CGPU_MATCH("d1")
  700. TEST_CGPU_NOMATCH("d2")
  701. TEST_CGPU_MATCH("d0-5")
  702. TEST_CGPU_NOMATCH("d0-0")
  703. TEST_CGPU_NOMATCH("d2-5")
  704. TEST_CGPU_MATCH("d-1")
  705. TEST_CGPU_MATCH("d1-")
  706. TEST_CGPU_NOMATCH("d-0")
  707. TEST_CGPU_NOMATCH("d2-")
  708. TEST_CGPU_MATCH("2")
  709. TEST_CGPU_NOMATCH("3")
  710. TEST_CGPU_MATCH("1-2")
  711. TEST_CGPU_MATCH("2-3")
  712. TEST_CGPU_NOMATCH("1-1")
  713. TEST_CGPU_NOMATCH("3-4")
  714. TEST_CGPU_MATCH("TST")
  715. TEST_CGPU_MATCH("test")
  716. TEST_CGPU_MATCH("tst")
  717. TEST_CGPU_MATCH("TEST")
  718. TEST_CGPU_NOMATCH("TSF")
  719. TEST_CGPU_NOMATCH("TS")
  720. TEST_CGPU_NOMATCH("TSTF")
  721. TEST_CGPU_MATCH("TST1")
  722. TEST_CGPU_MATCH("test1")
  723. TEST_CGPU_MATCH("TST0-1")
  724. TEST_CGPU_MATCH("TST 1")
  725. TEST_CGPU_MATCH("TST 1-2")
  726. TEST_CGPU_MATCH("TEST 1-2")
  727. TEST_CGPU_NOMATCH("TST2")
  728. TEST_CGPU_NOMATCH("TST2-3")
  729. TEST_CGPU_NOMATCH("TST0-0")
  730. TEST_CGPU_MATCH("TST1b")
  731. TEST_CGPU_MATCH("tst1b")
  732. TEST_CGPU_NOMATCH("TST1c")
  733. TEST_CGPU_NOMATCH("TST1bb")
  734. TEST_CGPU_MATCH("TST0-1b")
  735. TEST_CGPU_NOMATCH("TST0-1c")
  736. TEST_CGPU_MATCH("TST1a-d")
  737. TEST_CGPU_NOMATCH("TST1a-a")
  738. TEST_CGPU_NOMATCH("TST1-a")
  739. TEST_CGPU_NOMATCH("TST1c-z")
  740. TEST_CGPU_NOMATCH("TST1c-")
  741. TEST_CGPU_MATCH("@")
  742. TEST_CGPU_NOMATCH("@abc")
  743. TEST_CGPU_MATCH("@@b")
  744. TEST_CGPU_NOMATCH("@@c")
  745. TEST_CGPU_MATCH("TST@")
  746. TEST_CGPU_NOMATCH("TST@abc")
  747. TEST_CGPU_MATCH("TST@@b")
  748. TEST_CGPU_NOMATCH("TST@@c")
  749. TEST_CGPU_MATCH("TST@@b-f")
  750. TEST_CGPU_NOMATCH("TST@@c-f")
  751. TEST_CGPU_NOMATCH("TST@@-a")
  752. cgpu.device_path = "/dev/test";
  753. cgpu.dev_serial = "testy";
  754. TEST_CGPU_MATCH("TST@/dev/test")
  755. TEST_CGPU_MATCH("TST@testy")
  756. TEST_CGPU_NOMATCH("TST@")
  757. TEST_CGPU_NOMATCH("TST@/dev/test5@b")
  758. TEST_CGPU_NOMATCH("TST@testy3@b")
  759. TEST_CGPU_MATCH("TST@/dev/test@b")
  760. TEST_CGPU_MATCH("TST@testy@b")
  761. TEST_CGPU_NOMATCH("TST@/dev/test@c")
  762. TEST_CGPU_NOMATCH("TST@testy@c")
  763. cgpu.device_path = "usb:000:999";
  764. TEST_CGPU_MATCH("TST@usb:000:999")
  765. drv.dname = "test7";
  766. TEST_CGPU_MATCH("test7")
  767. TEST_CGPU_MATCH("TEST7")
  768. TEST_CGPU_NOMATCH("test&")
  769. TEST_CGPU_MATCH("test7 1-2")
  770. TEST_CGPU_MATCH("test7@testy@b")
  771. }
  772. static
  773. int cgpu_search(const char * const pattern, const int first)
  774. {
  775. int i;
  776. struct cgpu_info *cgpu;
  777. #define CHECK_CGPU_SEARCH do{ \
  778. cgpu = get_devices(i); \
  779. if (cgpu_match(pattern, cgpu)) \
  780. return i; \
  781. }while(0)
  782. for (i = first; i < total_devices; ++i)
  783. CHECK_CGPU_SEARCH;
  784. for (i = 0; i < first; ++i)
  785. CHECK_CGPU_SEARCH;
  786. #undef CHECK_CGPU_SEARCH
  787. return -1;
  788. }
  789. static pthread_mutex_t sharelog_lock;
  790. static FILE *sharelog_file = NULL;
  791. struct thr_info *get_thread(int thr_id)
  792. {
  793. struct thr_info *thr;
  794. rd_lock(&mining_thr_lock);
  795. thr = mining_thr[thr_id];
  796. rd_unlock(&mining_thr_lock);
  797. return thr;
  798. }
  799. static struct cgpu_info *get_thr_cgpu(int thr_id)
  800. {
  801. struct thr_info *thr = get_thread(thr_id);
  802. return thr->cgpu;
  803. }
  804. struct cgpu_info *get_devices(int id)
  805. {
  806. struct cgpu_info *cgpu;
  807. rd_lock(&devices_lock);
  808. cgpu = devices[id];
  809. rd_unlock(&devices_lock);
  810. return cgpu;
  811. }
  812. static pthread_mutex_t noncelog_lock = PTHREAD_MUTEX_INITIALIZER;
  813. static FILE *noncelog_file = NULL;
  814. static
  815. void noncelog(const struct work * const work)
  816. {
  817. const int thr_id = work->thr_id;
  818. const struct cgpu_info *proc = get_thr_cgpu(thr_id);
  819. char buf[0x200], hash[65], data[161], midstate[65];
  820. int rv;
  821. size_t ret;
  822. bin2hex(hash, work->hash, 32);
  823. bin2hex(data, work->data, 80);
  824. bin2hex(midstate, work->midstate, 32);
  825. // timestamp,proc,hash,data,midstate
  826. rv = snprintf(buf, sizeof(buf), "%lu,%s,%s,%s,%s\n",
  827. (unsigned long)time(NULL), proc->proc_repr_ns,
  828. hash, data, midstate);
  829. if (unlikely(rv < 1))
  830. {
  831. applog(LOG_ERR, "noncelog printf error");
  832. return;
  833. }
  834. mutex_lock(&noncelog_lock);
  835. ret = fwrite(buf, rv, 1, noncelog_file);
  836. fflush(noncelog_file);
  837. mutex_unlock(&noncelog_lock);
  838. if (ret != 1)
  839. applog(LOG_ERR, "noncelog fwrite error");
  840. }
  841. static void sharelog(const char*disposition, const struct work*work)
  842. {
  843. char target[(sizeof(work->target) * 2) + 1];
  844. char hash[(sizeof(work->hash) * 2) + 1];
  845. char data[(sizeof(work->data) * 2) + 1];
  846. struct cgpu_info *cgpu;
  847. unsigned long int t;
  848. struct pool *pool;
  849. int thr_id, rv;
  850. char s[1024];
  851. size_t ret;
  852. if (!sharelog_file)
  853. return;
  854. thr_id = work->thr_id;
  855. cgpu = get_thr_cgpu(thr_id);
  856. pool = work->pool;
  857. t = work->ts_getwork + timer_elapsed(&work->tv_getwork, &work->tv_work_found);
  858. bin2hex(target, work->target, sizeof(work->target));
  859. bin2hex(hash, work->hash, sizeof(work->hash));
  860. bin2hex(data, work->data, sizeof(work->data));
  861. // timestamp,disposition,target,pool,dev,thr,sharehash,sharedata
  862. rv = snprintf(s, sizeof(s), "%lu,%s,%s,%s,%s,%u,%s,%s\n", t, disposition, target, pool->rpc_url, cgpu->proc_repr_ns, thr_id, hash, data);
  863. if (rv >= (int)(sizeof(s)))
  864. s[sizeof(s) - 1] = '\0';
  865. else if (rv < 0) {
  866. applog(LOG_ERR, "sharelog printf error");
  867. return;
  868. }
  869. mutex_lock(&sharelog_lock);
  870. ret = fwrite(s, rv, 1, sharelog_file);
  871. fflush(sharelog_file);
  872. mutex_unlock(&sharelog_lock);
  873. if (ret != 1)
  874. applog(LOG_ERR, "sharelog fwrite error");
  875. }
  876. static char *getwork_req = "{\"method\": \"getwork\", \"params\": [], \"id\":0}\n";
  877. /* Adjust all the pools' quota to the greatest common denominator after a pool
  878. * has been added or the quotas changed. */
  879. void adjust_quota_gcd(void)
  880. {
  881. unsigned long gcd, lowest_quota = ~0UL, quota;
  882. struct pool *pool;
  883. int i;
  884. for (i = 0; i < total_pools; i++) {
  885. pool = pools[i];
  886. quota = pool->quota;
  887. if (!quota)
  888. continue;
  889. if (quota < lowest_quota)
  890. lowest_quota = quota;
  891. }
  892. if (likely(lowest_quota < ~0UL)) {
  893. gcd = lowest_quota;
  894. for (i = 0; i < total_pools; i++) {
  895. pool = pools[i];
  896. quota = pool->quota;
  897. if (!quota)
  898. continue;
  899. while (quota % gcd)
  900. gcd--;
  901. }
  902. } else
  903. gcd = 1;
  904. for (i = 0; i < total_pools; i++) {
  905. pool = pools[i];
  906. pool->quota_used *= global_quota_gcd;
  907. pool->quota_used /= gcd;
  908. pool->quota_gcd = pool->quota / gcd;
  909. }
  910. global_quota_gcd = gcd;
  911. applog(LOG_DEBUG, "Global quota greatest common denominator set to %lu", gcd);
  912. }
  913. /* Return value is ignored if not called from add_pool_details */
  914. struct pool *add_pool(void)
  915. {
  916. struct pool *pool;
  917. pool = calloc(sizeof(struct pool), 1);
  918. if (!pool)
  919. quit(1, "Failed to malloc pool in add_pool");
  920. pool->pool_no = pool->prio = total_pools;
  921. mutex_init(&pool->last_work_lock);
  922. mutex_init(&pool->pool_lock);
  923. if (unlikely(pthread_cond_init(&pool->cr_cond, NULL)))
  924. quit(1, "Failed to pthread_cond_init in add_pool");
  925. cglock_init(&pool->data_lock);
  926. mutex_init(&pool->stratum_lock);
  927. timer_unset(&pool->swork.tv_transparency);
  928. /* Make sure the pool doesn't think we've been idle since time 0 */
  929. pool->tv_idle.tv_sec = ~0UL;
  930. cgtime(&pool->cgminer_stats.start_tv);
  931. pool->rpc_proxy = NULL;
  932. pool->quota = 1;
  933. adjust_quota_gcd();
  934. pool->sock = INVSOCK;
  935. pool->lp_socket = CURL_SOCKET_BAD;
  936. pools = realloc(pools, sizeof(struct pool *) * (total_pools + 2));
  937. pools[total_pools++] = pool;
  938. return pool;
  939. }
  940. /* Pool variant of test and set */
  941. static bool pool_tset(struct pool *pool, bool *var)
  942. {
  943. bool ret;
  944. mutex_lock(&pool->pool_lock);
  945. ret = *var;
  946. *var = true;
  947. mutex_unlock(&pool->pool_lock);
  948. return ret;
  949. }
  950. bool pool_tclear(struct pool *pool, bool *var)
  951. {
  952. bool ret;
  953. mutex_lock(&pool->pool_lock);
  954. ret = *var;
  955. *var = false;
  956. mutex_unlock(&pool->pool_lock);
  957. return ret;
  958. }
  959. struct pool *current_pool(void)
  960. {
  961. struct pool *pool;
  962. cg_rlock(&control_lock);
  963. pool = currentpool;
  964. cg_runlock(&control_lock);
  965. return pool;
  966. }
  967. char *set_int_range(const char *arg, int *i, int min, int max)
  968. {
  969. char *err = opt_set_intval(arg, i);
  970. if (err)
  971. return err;
  972. if (*i < min || *i > max)
  973. return "Value out of range";
  974. return NULL;
  975. }
  976. static char *set_int_0_to_9999(const char *arg, int *i)
  977. {
  978. return set_int_range(arg, i, 0, 9999);
  979. }
  980. static char *set_int_1_to_65535(const char *arg, int *i)
  981. {
  982. return set_int_range(arg, i, 1, 65535);
  983. }
  984. static char *set_int_0_to_10(const char *arg, int *i)
  985. {
  986. return set_int_range(arg, i, 0, 10);
  987. }
  988. static char *set_int_1_to_10(const char *arg, int *i)
  989. {
  990. return set_int_range(arg, i, 1, 10);
  991. }
  992. char *set_strdup(const char *arg, char **p)
  993. {
  994. *p = strdup((char *)arg);
  995. return NULL;
  996. }
  997. #if BLKMAKER_VERSION > 1
  998. static char *set_b58addr(const char *arg, struct _cbscript_t *p)
  999. {
  1000. size_t scriptsz = blkmk_address_to_script(NULL, 0, arg);
  1001. if (!scriptsz)
  1002. return "Invalid address";
  1003. char *script = malloc(scriptsz);
  1004. if (blkmk_address_to_script(script, scriptsz, arg) != scriptsz) {
  1005. free(script);
  1006. return "Failed to convert address to script";
  1007. }
  1008. p->data = script;
  1009. p->sz = scriptsz;
  1010. return NULL;
  1011. }
  1012. #endif
  1013. static void bdiff_target_leadzero(unsigned char *target, double diff);
  1014. char *set_request_diff(const char *arg, float *p)
  1015. {
  1016. unsigned char target[32];
  1017. char *e = opt_set_floatval(arg, p);
  1018. if (e)
  1019. return e;
  1020. request_bdiff = (double)*p * 0.9999847412109375;
  1021. bdiff_target_leadzero(target, request_bdiff);
  1022. request_target_str = malloc(65);
  1023. bin2hex(request_target_str, target, 32);
  1024. return NULL;
  1025. }
  1026. #ifdef NEED_BFG_LOWL_VCOM
  1027. extern struct lowlevel_device_info *_vcom_devinfo_findorcreate(struct lowlevel_device_info **, const char *);
  1028. #ifdef WIN32
  1029. void _vcom_devinfo_scan_querydosdevice(struct lowlevel_device_info ** const devinfo_list)
  1030. {
  1031. char dev[PATH_MAX];
  1032. char *devp = dev;
  1033. size_t bufLen = 0x100;
  1034. tryagain: ;
  1035. char buf[bufLen];
  1036. if (!QueryDosDevice(NULL, buf, bufLen)) {
  1037. if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
  1038. bufLen *= 2;
  1039. applog(LOG_DEBUG, "QueryDosDevice returned insufficent buffer error; enlarging to %lx", (unsigned long)bufLen);
  1040. goto tryagain;
  1041. }
  1042. applogr(, LOG_WARNING, "Error occurred trying to enumerate COM ports with QueryDosDevice");
  1043. }
  1044. size_t tLen;
  1045. memcpy(devp, "\\\\.\\", 4);
  1046. devp = &devp[4];
  1047. for (char *t = buf; *t; t += tLen) {
  1048. tLen = strlen(t) + 1;
  1049. if (strncmp("COM", t, 3))
  1050. continue;
  1051. memcpy(devp, t, tLen);
  1052. // NOTE: We depend on _vcom_devinfo_findorcreate to further check that there's a number (and only a number) on the end
  1053. _vcom_devinfo_findorcreate(devinfo_list, dev);
  1054. }
  1055. }
  1056. #else
  1057. void _vcom_devinfo_scan_lsdev(struct lowlevel_device_info ** const devinfo_list)
  1058. {
  1059. char dev[PATH_MAX];
  1060. char *devp = dev;
  1061. DIR *D;
  1062. struct dirent *de;
  1063. const char devdir[] = "/dev";
  1064. const size_t devdirlen = sizeof(devdir) - 1;
  1065. char *devpath = devp;
  1066. char *devfile = devpath + devdirlen + 1;
  1067. D = opendir(devdir);
  1068. if (!D)
  1069. applogr(, LOG_DEBUG, "No /dev directory to look for VCOM devices in");
  1070. memcpy(devpath, devdir, devdirlen);
  1071. devpath[devdirlen] = '/';
  1072. while ( (de = readdir(D)) ) {
  1073. if (!strncmp(de->d_name, "cu.", 3)
  1074. //don't probe Bluetooth devices - causes bus errors and segfaults
  1075. && strncmp(de->d_name, "cu.Bluetooth", 12))
  1076. goto trydev;
  1077. if (strncmp(de->d_name, "tty", 3))
  1078. continue;
  1079. if (strncmp(&de->d_name[3], "USB", 3) && strncmp(&de->d_name[3], "ACM", 3))
  1080. continue;
  1081. trydev:
  1082. strcpy(devfile, de->d_name);
  1083. _vcom_devinfo_findorcreate(devinfo_list, dev);
  1084. }
  1085. closedir(D);
  1086. }
  1087. #endif
  1088. #endif
  1089. static char *add_serial(const char *arg)
  1090. {
  1091. string_elist_add(arg, &scan_devices);
  1092. return NULL;
  1093. }
  1094. static
  1095. char *opt_string_elist_add(const char *arg, struct string_elist **elist)
  1096. {
  1097. string_elist_add(arg, elist);
  1098. return NULL;
  1099. }
  1100. bool get_intrange(const char *arg, int *val1, int *val2)
  1101. {
  1102. // NOTE: This could be done with sscanf, but its %n is broken in strange ways on Windows
  1103. char *p, *p2;
  1104. *val1 = strtol(arg, &p, 0);
  1105. if (arg == p)
  1106. // Zero-length ending number, invalid
  1107. return false;
  1108. while (true)
  1109. {
  1110. if (!p[0])
  1111. {
  1112. *val2 = *val1;
  1113. return true;
  1114. }
  1115. if (p[0] == '-')
  1116. break;
  1117. if (!isspace(p[0]))
  1118. // Garbage, invalid
  1119. return false;
  1120. ++p;
  1121. }
  1122. p2 = &p[1];
  1123. *val2 = strtol(p2, &p, 0);
  1124. if (p2 == p)
  1125. // Zero-length ending number, invalid
  1126. return false;
  1127. while (true)
  1128. {
  1129. if (!p[0])
  1130. return true;
  1131. if (!isspace(p[0]))
  1132. // Garbage, invalid
  1133. return false;
  1134. ++p;
  1135. }
  1136. }
  1137. static
  1138. void _test_intrange(const char *s, const int v[2])
  1139. {
  1140. int a[2];
  1141. if (!get_intrange(s, &a[0], &a[1]))
  1142. applog(LOG_ERR, "Test \"%s\" failed: returned false", s);
  1143. for (int i = 0; i < 2; ++i)
  1144. if (unlikely(a[i] != v[i]))
  1145. applog(LOG_ERR, "Test \"%s\" failed: value %d should be %d but got %d", s, i, v[i], a[i]);
  1146. }
  1147. #define _test_intrange(s, ...) _test_intrange(s, (int[]){ __VA_ARGS__ })
  1148. static
  1149. void _test_intrange_fail(const char *s)
  1150. {
  1151. int a[2];
  1152. if (get_intrange(s, &a[0], &a[1]))
  1153. applog(LOG_ERR, "Test !\"%s\" failed: returned true with %d and %d", s, a[0], a[1]);
  1154. }
  1155. static
  1156. void test_intrange()
  1157. {
  1158. _test_intrange("-1--2", -1, -2);
  1159. _test_intrange("-1-2", -1, 2);
  1160. _test_intrange("1--2", 1, -2);
  1161. _test_intrange("1-2", 1, 2);
  1162. _test_intrange("111-222", 111, 222);
  1163. _test_intrange(" 11 - 22 ", 11, 22);
  1164. _test_intrange("+11-+22", 11, 22);
  1165. _test_intrange("-1", -1, -1);
  1166. _test_intrange_fail("all");
  1167. _test_intrange_fail("1-");
  1168. _test_intrange_fail("");
  1169. _test_intrange_fail("1-54x");
  1170. }
  1171. static char *set_devices(char *arg)
  1172. {
  1173. if (*arg) {
  1174. if (*arg == '?') {
  1175. opt_display_devs = true;
  1176. return NULL;
  1177. }
  1178. } else
  1179. return "Invalid device parameters";
  1180. string_elist_add(arg, &opt_devices_enabled_list);
  1181. return NULL;
  1182. }
  1183. static char *set_balance(enum pool_strategy *strategy)
  1184. {
  1185. *strategy = POOL_BALANCE;
  1186. return NULL;
  1187. }
  1188. static char *set_loadbalance(enum pool_strategy *strategy)
  1189. {
  1190. *strategy = POOL_LOADBALANCE;
  1191. return NULL;
  1192. }
  1193. static char *set_rotate(const char *arg, int *i)
  1194. {
  1195. pool_strategy = POOL_ROTATE;
  1196. return set_int_range(arg, i, 0, 9999);
  1197. }
  1198. static char *set_rr(enum pool_strategy *strategy)
  1199. {
  1200. *strategy = POOL_ROUNDROBIN;
  1201. return NULL;
  1202. }
  1203. /* Detect that url is for a stratum protocol either via the presence of
  1204. * stratum+tcp or by detecting a stratum server response */
  1205. bool detect_stratum(struct pool *pool, char *url)
  1206. {
  1207. if (!extract_sockaddr(url, &pool->sockaddr_url, &pool->stratum_port))
  1208. return false;
  1209. if (!strncasecmp(url, "stratum+tcp://", 14)) {
  1210. pool->rpc_url = strdup(url);
  1211. pool->has_stratum = true;
  1212. pool->stratum_url = pool->sockaddr_url;
  1213. return true;
  1214. }
  1215. return false;
  1216. }
  1217. static struct pool *add_url(void)
  1218. {
  1219. total_urls++;
  1220. if (total_urls > total_pools)
  1221. add_pool();
  1222. return pools[total_urls - 1];
  1223. }
  1224. static void setup_url(struct pool *pool, char *arg)
  1225. {
  1226. if (detect_stratum(pool, arg))
  1227. return;
  1228. opt_set_charp(arg, &pool->rpc_url);
  1229. if (strncmp(arg, "http://", 7) &&
  1230. strncmp(arg, "https://", 8)) {
  1231. const size_t L = strlen(arg);
  1232. char *httpinput;
  1233. httpinput = malloc(8 + L);
  1234. if (!httpinput)
  1235. quit(1, "Failed to malloc httpinput");
  1236. sprintf(httpinput, "http://%s", arg);
  1237. pool->rpc_url = httpinput;
  1238. }
  1239. }
  1240. static char *set_url(char *arg)
  1241. {
  1242. struct pool *pool = add_url();
  1243. setup_url(pool, arg);
  1244. return NULL;
  1245. }
  1246. static char *set_quota(char *arg)
  1247. {
  1248. char *semicolon = strchr(arg, ';'), *url;
  1249. int len, qlen, quota;
  1250. struct pool *pool;
  1251. if (!semicolon)
  1252. return "No semicolon separated quota;URL pair found";
  1253. len = strlen(arg);
  1254. *semicolon = '\0';
  1255. qlen = strlen(arg);
  1256. if (!qlen)
  1257. return "No parameter for quota found";
  1258. len -= qlen + 1;
  1259. if (len < 1)
  1260. return "No parameter for URL found";
  1261. quota = atoi(arg);
  1262. if (quota < 0)
  1263. return "Invalid negative parameter for quota set";
  1264. url = arg + qlen + 1;
  1265. pool = add_url();
  1266. setup_url(pool, url);
  1267. pool->quota = quota;
  1268. applog(LOG_INFO, "Setting pool %d to quota %d", pool->pool_no, pool->quota);
  1269. adjust_quota_gcd();
  1270. return NULL;
  1271. }
  1272. static char *set_user(const char *arg)
  1273. {
  1274. struct pool *pool;
  1275. total_users++;
  1276. if (total_users > total_pools)
  1277. add_pool();
  1278. pool = pools[total_users - 1];
  1279. opt_set_charp(arg, &pool->rpc_user);
  1280. return NULL;
  1281. }
  1282. static char *set_pass(const char *arg)
  1283. {
  1284. struct pool *pool;
  1285. total_passes++;
  1286. if (total_passes > total_pools)
  1287. add_pool();
  1288. pool = pools[total_passes - 1];
  1289. opt_set_charp(arg, &pool->rpc_pass);
  1290. return NULL;
  1291. }
  1292. static char *set_userpass(const char *arg)
  1293. {
  1294. struct pool *pool;
  1295. char *updup;
  1296. if (total_users != total_passes)
  1297. return "User + pass options must be balanced before userpass";
  1298. ++total_users;
  1299. ++total_passes;
  1300. if (total_users > total_pools)
  1301. add_pool();
  1302. pool = pools[total_users - 1];
  1303. updup = strdup(arg);
  1304. opt_set_charp(arg, &pool->rpc_userpass);
  1305. pool->rpc_user = strtok(updup, ":");
  1306. if (!pool->rpc_user)
  1307. return "Failed to find : delimited user info";
  1308. pool->rpc_pass = strtok(NULL, ":");
  1309. if (!pool->rpc_pass)
  1310. pool->rpc_pass = "";
  1311. return NULL;
  1312. }
  1313. static char *set_pool_priority(const char *arg)
  1314. {
  1315. struct pool *pool;
  1316. if (!total_pools)
  1317. return "Usage of --pool-priority before pools are defined does not make sense";
  1318. pool = pools[total_pools - 1];
  1319. opt_set_intval(arg, &pool->prio);
  1320. return NULL;
  1321. }
  1322. static char *set_pool_proxy(const char *arg)
  1323. {
  1324. struct pool *pool;
  1325. if (!total_pools)
  1326. return "Usage of --pool-proxy before pools are defined does not make sense";
  1327. if (!our_curl_supports_proxy_uris())
  1328. return "Your installed cURL library does not support proxy URIs. At least version 7.21.7 is required.";
  1329. pool = pools[total_pools - 1];
  1330. opt_set_charp(arg, &pool->rpc_proxy);
  1331. return NULL;
  1332. }
  1333. static char *set_pool_force_rollntime(const char *arg)
  1334. {
  1335. struct pool *pool;
  1336. if (!total_pools)
  1337. return "Usage of --force-rollntime before pools are defined does not make sense";
  1338. pool = pools[total_pools - 1];
  1339. opt_set_intval(arg, &pool->force_rollntime);
  1340. return NULL;
  1341. }
  1342. static char *enable_debug(bool *flag)
  1343. {
  1344. *flag = true;
  1345. opt_debug_console = true;
  1346. /* Turn on verbose output, too. */
  1347. opt_log_output = true;
  1348. return NULL;
  1349. }
  1350. static char *set_schedtime(const char *arg, struct schedtime *st)
  1351. {
  1352. if (sscanf(arg, "%d:%d", &st->tm.tm_hour, &st->tm.tm_min) != 2)
  1353. {
  1354. if (strcasecmp(arg, "now"))
  1355. return "Invalid time set, should be HH:MM";
  1356. } else
  1357. schedstop.tm.tm_sec = 0;
  1358. if (st->tm.tm_hour > 23 || st->tm.tm_min > 59 || st->tm.tm_hour < 0 || st->tm.tm_min < 0)
  1359. return "Invalid time set.";
  1360. st->enable = true;
  1361. return NULL;
  1362. }
  1363. static
  1364. char *set_log_file(char *arg)
  1365. {
  1366. char *r = "";
  1367. long int i = strtol(arg, &r, 10);
  1368. int fd, stderr_fd = fileno(stderr);
  1369. if ((!*r) && i >= 0 && i <= INT_MAX)
  1370. fd = i;
  1371. else
  1372. if (!strcmp(arg, "-"))
  1373. {
  1374. fd = fileno(stdout);
  1375. if (unlikely(fd == -1))
  1376. return "Standard output missing for log-file";
  1377. }
  1378. else
  1379. {
  1380. fd = open(arg, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR);
  1381. if (unlikely(fd == -1))
  1382. return "Failed to open log-file";
  1383. }
  1384. close(stderr_fd);
  1385. if (unlikely(-1 == dup2(fd, stderr_fd)))
  1386. return "Failed to dup2 for log-file";
  1387. close(fd);
  1388. return NULL;
  1389. }
  1390. static
  1391. char *_bfgopt_set_file(const char *arg, FILE **F, const char *mode, const char *purpose)
  1392. {
  1393. char *r = "";
  1394. long int i = strtol(arg, &r, 10);
  1395. static char *err = NULL;
  1396. const size_t errbufsz = 0x100;
  1397. free(err);
  1398. err = NULL;
  1399. if ((!*r) && i >= 0 && i <= INT_MAX) {
  1400. *F = fdopen((int)i, mode);
  1401. if (!*F)
  1402. {
  1403. err = malloc(errbufsz);
  1404. snprintf(err, errbufsz, "Failed to open fd %d for %s",
  1405. (int)i, purpose);
  1406. return err;
  1407. }
  1408. } else if (!strcmp(arg, "-")) {
  1409. *F = (mode[0] == 'a') ? stdout : stdin;
  1410. if (!*F)
  1411. {
  1412. err = malloc(errbufsz);
  1413. snprintf(err, errbufsz, "Standard %sput missing for %s",
  1414. (mode[0] == 'a') ? "out" : "in", purpose);
  1415. return err;
  1416. }
  1417. } else {
  1418. *F = fopen(arg, mode);
  1419. if (!*F)
  1420. {
  1421. err = malloc(errbufsz);
  1422. snprintf(err, errbufsz, "Failed to open %s for %s",
  1423. arg, purpose);
  1424. return err;
  1425. }
  1426. }
  1427. return NULL;
  1428. }
  1429. static char *set_noncelog(char *arg)
  1430. {
  1431. return _bfgopt_set_file(arg, &noncelog_file, "a", "nonce log");
  1432. }
  1433. static char *set_sharelog(char *arg)
  1434. {
  1435. return _bfgopt_set_file(arg, &sharelog_file, "a", "share log");
  1436. }
  1437. static char *temp_cutoff_str = "";
  1438. static char *temp_target_str = "";
  1439. char *set_temp_cutoff(char *arg)
  1440. {
  1441. int val;
  1442. if (!(arg && arg[0]))
  1443. return "Invalid parameters for set temp cutoff";
  1444. val = atoi(arg);
  1445. if (val < 0 || val > 200)
  1446. return "Invalid value passed to set temp cutoff";
  1447. temp_cutoff_str = arg;
  1448. return NULL;
  1449. }
  1450. char *set_temp_target(char *arg)
  1451. {
  1452. int val;
  1453. if (!(arg && arg[0]))
  1454. return "Invalid parameters for set temp target";
  1455. val = atoi(arg);
  1456. if (val < 0 || val > 200)
  1457. return "Invalid value passed to set temp target";
  1458. temp_target_str = arg;
  1459. return NULL;
  1460. }
  1461. // For a single element string, this always returns the number (for all calls)
  1462. // For multi-element strings, it returns each element as a number in order, and 0 when there are no more
  1463. static int temp_strtok(char *base, char **n)
  1464. {
  1465. char *i = *n;
  1466. char *p = strchr(i, ',');
  1467. if (p) {
  1468. p[0] = '\0';
  1469. *n = &p[1];
  1470. }
  1471. else
  1472. if (base != i)
  1473. *n = strchr(i, '\0');
  1474. return atoi(i);
  1475. }
  1476. static void load_temp_config_cgpu(struct cgpu_info *cgpu, char **cutoff_np, char **target_np)
  1477. {
  1478. int target_off, val;
  1479. // cutoff default may be specified by driver during probe; otherwise, opt_cutofftemp (const)
  1480. if (!cgpu->cutofftemp)
  1481. cgpu->cutofftemp = opt_cutofftemp;
  1482. // target default may be specified by driver, and is moved with offset; otherwise, offset minus 6
  1483. if (cgpu->targettemp)
  1484. target_off = cgpu->targettemp - cgpu->cutofftemp;
  1485. else
  1486. target_off = -6;
  1487. cgpu->cutofftemp_default = cgpu->cutofftemp;
  1488. val = temp_strtok(temp_cutoff_str, cutoff_np);
  1489. if (val < 0 || val > 200)
  1490. quit(1, "Invalid value passed to set temp cutoff");
  1491. if (val)
  1492. cgpu->cutofftemp = val;
  1493. cgpu->targettemp_default = cgpu->cutofftemp + target_off;
  1494. val = temp_strtok(temp_target_str, target_np);
  1495. if (val < 0 || val > 200)
  1496. quit(1, "Invalid value passed to set temp target");
  1497. if (val)
  1498. cgpu->targettemp = val;
  1499. else
  1500. cgpu->targettemp = cgpu->cutofftemp + target_off;
  1501. applog(LOG_DEBUG, "%"PRIprepr": Set temperature config: target=%d cutoff=%d",
  1502. cgpu->proc_repr,
  1503. cgpu->targettemp, cgpu->cutofftemp);
  1504. }
  1505. static void load_temp_config()
  1506. {
  1507. int i;
  1508. char *cutoff_n, *target_n;
  1509. struct cgpu_info *cgpu;
  1510. cutoff_n = temp_cutoff_str;
  1511. target_n = temp_target_str;
  1512. for (i = 0; i < total_devices; ++i) {
  1513. cgpu = get_devices(i);
  1514. load_temp_config_cgpu(cgpu, &cutoff_n, &target_n);
  1515. }
  1516. if (cutoff_n != temp_cutoff_str && cutoff_n[0])
  1517. quit(1, "Too many values passed to set temp cutoff");
  1518. if (target_n != temp_target_str && target_n[0])
  1519. quit(1, "Too many values passed to set temp target");
  1520. }
  1521. static char *set_api_allow(const char *arg)
  1522. {
  1523. opt_set_charp(arg, &opt_api_allow);
  1524. return NULL;
  1525. }
  1526. static char *set_api_groups(const char *arg)
  1527. {
  1528. opt_set_charp(arg, &opt_api_groups);
  1529. return NULL;
  1530. }
  1531. static char *set_api_description(const char *arg)
  1532. {
  1533. opt_set_charp(arg, &opt_api_description);
  1534. return NULL;
  1535. }
  1536. static char *set_api_mcast_des(const char *arg)
  1537. {
  1538. opt_set_charp(arg, &opt_api_mcast_des);
  1539. return NULL;
  1540. }
  1541. #ifdef USE_ICARUS
  1542. static char *set_icarus_options(const char *arg)
  1543. {
  1544. opt_set_charp(arg, &opt_icarus_options);
  1545. return NULL;
  1546. }
  1547. static char *set_icarus_timing(const char *arg)
  1548. {
  1549. opt_set_charp(arg, &opt_icarus_timing);
  1550. return NULL;
  1551. }
  1552. #endif
  1553. #ifdef USE_AVALON
  1554. static char *set_avalon_options(const char *arg)
  1555. {
  1556. opt_set_charp(arg, &opt_avalon_options);
  1557. return NULL;
  1558. }
  1559. #endif
  1560. #ifdef USE_KLONDIKE
  1561. static char *set_klondike_options(const char *arg)
  1562. {
  1563. opt_set_charp(arg, &opt_klondike_options);
  1564. return NULL;
  1565. }
  1566. #endif
  1567. __maybe_unused
  1568. static char *set_null(const char __maybe_unused *arg)
  1569. {
  1570. return NULL;
  1571. }
  1572. /* These options are available from config file or commandline */
  1573. static struct opt_table opt_config_table[] = {
  1574. #ifdef WANT_CPUMINE
  1575. OPT_WITH_ARG("--algo|-a",
  1576. set_algo, show_algo, &opt_algo,
  1577. "Specify sha256 implementation for CPU mining:\n"
  1578. "\tfastauto*\tQuick benchmark at startup to pick a working algorithm\n"
  1579. "\tauto\t\tBenchmark at startup and pick fastest algorithm"
  1580. "\n\tc\t\tLinux kernel sha256, implemented in C"
  1581. #ifdef WANT_SSE2_4WAY
  1582. "\n\t4way\t\ttcatm's 4-way SSE2 implementation"
  1583. #endif
  1584. #ifdef WANT_VIA_PADLOCK
  1585. "\n\tvia\t\tVIA padlock implementation"
  1586. #endif
  1587. "\n\tcryptopp\tCrypto++ C/C++ implementation"
  1588. #ifdef WANT_CRYPTOPP_ASM32
  1589. "\n\tcryptopp_asm32\tCrypto++ 32-bit assembler implementation"
  1590. #endif
  1591. #ifdef WANT_X8632_SSE2
  1592. "\n\tsse2_32\t\tSSE2 32 bit implementation for i386 machines"
  1593. #endif
  1594. #ifdef WANT_X8664_SSE2
  1595. "\n\tsse2_64\t\tSSE2 64 bit implementation for x86_64 machines"
  1596. #endif
  1597. #ifdef WANT_X8664_SSE4
  1598. "\n\tsse4_64\t\tSSE4.1 64 bit implementation for x86_64 machines"
  1599. #endif
  1600. #ifdef WANT_ALTIVEC_4WAY
  1601. "\n\taltivec_4way\tAltivec implementation for PowerPC G4 and G5 machines"
  1602. #endif
  1603. ),
  1604. #endif
  1605. OPT_WITH_ARG("--api-allow",
  1606. set_api_allow, NULL, NULL,
  1607. "Allow API access only to the given list of [G:]IP[/Prefix] addresses[/subnets]"),
  1608. OPT_WITH_ARG("--api-description",
  1609. set_api_description, NULL, NULL,
  1610. "Description placed in the API status header, default: BFGMiner version"),
  1611. OPT_WITH_ARG("--api-groups",
  1612. set_api_groups, NULL, NULL,
  1613. "API one letter groups G:cmd:cmd[,P:cmd:*...] defining the cmds a groups can use"),
  1614. OPT_WITHOUT_ARG("--api-listen",
  1615. opt_set_bool, &opt_api_listen,
  1616. "Enable API, default: disabled"),
  1617. OPT_WITHOUT_ARG("--api-mcast",
  1618. opt_set_bool, &opt_api_mcast,
  1619. "Enable API Multicast listener, default: disabled"),
  1620. OPT_WITH_ARG("--api-mcast-addr",
  1621. opt_set_charp, opt_show_charp, &opt_api_mcast_addr,
  1622. "API Multicast listen address"),
  1623. OPT_WITH_ARG("--api-mcast-code",
  1624. opt_set_charp, opt_show_charp, &opt_api_mcast_code,
  1625. "Code expected in the API Multicast message, don't use '-'"),
  1626. OPT_WITH_ARG("--api-mcast-des",
  1627. set_api_mcast_des, NULL, NULL,
  1628. "Description appended to the API Multicast reply, default: ''"),
  1629. OPT_WITH_ARG("--api-mcast-port",
  1630. set_int_1_to_65535, opt_show_intval, &opt_api_mcast_port,
  1631. "API Multicast listen port"),
  1632. OPT_WITHOUT_ARG("--api-network",
  1633. opt_set_bool, &opt_api_network,
  1634. "Allow API (if enabled) to listen on/for any address, default: only 127.0.0.1"),
  1635. OPT_WITH_ARG("--api-port",
  1636. set_int_1_to_65535, opt_show_intval, &opt_api_port,
  1637. "Port number of miner API"),
  1638. #ifdef HAVE_ADL
  1639. OPT_WITHOUT_ARG("--auto-fan",
  1640. opt_set_bool, &opt_autofan,
  1641. "Automatically adjust all GPU fan speeds to maintain a target temperature"),
  1642. OPT_WITHOUT_ARG("--auto-gpu",
  1643. opt_set_bool, &opt_autoengine,
  1644. "Automatically adjust all GPU engine clock speeds to maintain a target temperature"),
  1645. #endif
  1646. OPT_WITHOUT_ARG("--balance",
  1647. set_balance, &pool_strategy,
  1648. "Change multipool strategy from failover to even share balance"),
  1649. OPT_WITHOUT_ARG("--benchmark",
  1650. opt_set_bool, &opt_benchmark,
  1651. "Run BFGMiner in benchmark mode - produces no shares"),
  1652. #if defined(USE_BITFORCE)
  1653. OPT_WITHOUT_ARG("--bfl-range",
  1654. opt_set_bool, &opt_bfl_noncerange,
  1655. "Use nonce range on bitforce devices if supported"),
  1656. #endif
  1657. #ifdef WANT_CPUMINE
  1658. OPT_WITH_ARG("--bench-algo|-b",
  1659. set_int_0_to_9999, opt_show_intval, &opt_bench_algo,
  1660. opt_hidden),
  1661. #endif
  1662. #ifdef HAVE_CHROOT
  1663. OPT_WITH_ARG("--chroot-dir",
  1664. opt_set_charp, NULL, &chroot_dir,
  1665. "Chroot to a directory right after startup"),
  1666. #endif
  1667. OPT_WITH_ARG("--cmd-idle",
  1668. opt_set_charp, NULL, &cmd_idle,
  1669. "Execute a command when a device is allowed to be idle (rest or wait)"),
  1670. OPT_WITH_ARG("--cmd-sick",
  1671. opt_set_charp, NULL, &cmd_sick,
  1672. "Execute a command when a device is declared sick"),
  1673. OPT_WITH_ARG("--cmd-dead",
  1674. opt_set_charp, NULL, &cmd_dead,
  1675. "Execute a command when a device is declared dead"),
  1676. #if BLKMAKER_VERSION > 1
  1677. OPT_WITH_ARG("--coinbase-addr",
  1678. set_b58addr, NULL, &opt_coinbase_script,
  1679. "Set coinbase payout address for solo mining"),
  1680. OPT_WITH_ARG("--coinbase-address|--coinbase-payout|--cbaddress|--cbaddr|--cb-address|--cb-addr|--payout",
  1681. set_b58addr, NULL, &opt_coinbase_script,
  1682. opt_hidden),
  1683. #endif
  1684. #if BLKMAKER_VERSION > 0
  1685. OPT_WITH_ARG("--coinbase-sig",
  1686. set_strdup, NULL, &opt_coinbase_sig,
  1687. "Set coinbase signature when possible"),
  1688. OPT_WITH_ARG("--coinbase|--cbsig|--cb-sig|--cb|--prayer",
  1689. set_strdup, NULL, &opt_coinbase_sig,
  1690. opt_hidden),
  1691. #endif
  1692. #ifdef HAVE_CURSES
  1693. OPT_WITHOUT_ARG("--compact",
  1694. opt_set_bool, &opt_compact,
  1695. "Use compact display without per device statistics"),
  1696. #endif
  1697. #ifdef WANT_CPUMINE
  1698. OPT_WITH_ARG("--cpu-threads|-t",
  1699. force_nthreads_int, opt_show_intval, &opt_n_threads,
  1700. "Number of miner CPU threads"),
  1701. #endif
  1702. OPT_WITHOUT_ARG("--debug|-D",
  1703. enable_debug, &opt_debug,
  1704. "Enable debug output"),
  1705. OPT_WITHOUT_ARG("--debuglog",
  1706. opt_set_bool, &opt_debug,
  1707. "Enable debug logging"),
  1708. OPT_WITHOUT_ARG("--device-protocol-dump",
  1709. opt_set_bool, &opt_dev_protocol,
  1710. "Verbose dump of device protocol-level activities"),
  1711. OPT_WITH_ARG("--device|-d",
  1712. set_devices, NULL, NULL,
  1713. "Enable only devices matching pattern (default: all)"),
  1714. OPT_WITHOUT_ARG("--disable-rejecting",
  1715. opt_set_bool, &opt_disable_pool,
  1716. "Automatically disable pools that continually reject shares"),
  1717. #ifdef USE_LIBMICROHTTPD
  1718. OPT_WITH_ARG("--http-port",
  1719. opt_set_intval, opt_show_intval, &httpsrv_port,
  1720. "Port number to listen on for HTTP getwork miners (-1 means disabled)"),
  1721. #endif
  1722. #if defined(WANT_CPUMINE) && (defined(HAVE_OPENCL) || defined(USE_FPGA))
  1723. OPT_WITHOUT_ARG("--enable-cpu|-C",
  1724. opt_set_bool, &opt_usecpu,
  1725. opt_hidden),
  1726. #endif
  1727. OPT_WITH_ARG("--expiry|-E",
  1728. set_int_0_to_9999, opt_show_intval, &opt_expiry,
  1729. "Upper bound on how many seconds after getting work we consider a share from it stale (w/o longpoll active)"),
  1730. OPT_WITH_ARG("--expiry-lp",
  1731. set_int_0_to_9999, opt_show_intval, &opt_expiry_lp,
  1732. "Upper bound on how many seconds after getting work we consider a share from it stale (with longpoll active)"),
  1733. OPT_WITHOUT_ARG("--failover-only",
  1734. opt_set_bool, &opt_fail_only,
  1735. "Don't leak work to backup pools when primary pool is lagging"),
  1736. #ifdef USE_FPGA
  1737. OPT_WITHOUT_ARG("--force-dev-init",
  1738. opt_set_bool, &opt_force_dev_init,
  1739. "Always initialize devices when possible (such as bitstream uploads to some FPGAs)"),
  1740. #endif
  1741. #ifdef HAVE_OPENCL
  1742. OPT_WITH_ARG("--gpu-dyninterval",
  1743. set_int_1_to_65535, opt_show_intval, &opt_dynamic_interval,
  1744. "Set the refresh interval in ms for GPUs using dynamic intensity"),
  1745. OPT_WITH_ARG("--gpu-platform",
  1746. set_int_0_to_9999, opt_show_intval, &opt_platform_id,
  1747. "Select OpenCL platform ID to use for GPU mining"),
  1748. OPT_WITH_ARG("--gpu-threads|-g",
  1749. set_int_1_to_10, opt_show_intval, &opt_g_threads,
  1750. "Number of threads per GPU (1 - 10)"),
  1751. #ifdef HAVE_ADL
  1752. OPT_WITH_ARG("--gpu-engine",
  1753. set_gpu_engine, NULL, NULL,
  1754. "GPU engine (over)clock range in MHz - one value, range and/or comma separated list (e.g. 850-900,900,750-850)"),
  1755. OPT_WITH_ARG("--gpu-fan",
  1756. set_gpu_fan, NULL, NULL,
  1757. "GPU fan percentage range - one value, range and/or comma separated list (e.g. 0-85,85,65)"),
  1758. OPT_WITH_ARG("--gpu-map",
  1759. set_gpu_map, NULL, NULL,
  1760. "Map OpenCL to ADL device order manually, paired CSV (e.g. 1:0,2:1 maps OpenCL 1 to ADL 0, 2 to 1)"),
  1761. OPT_WITH_ARG("--gpu-memclock",
  1762. set_gpu_memclock, NULL, NULL,
  1763. "Set the GPU memory (over)clock in MHz - one value for all or separate by commas for per card"),
  1764. OPT_WITH_ARG("--gpu-memdiff",
  1765. set_gpu_memdiff, NULL, NULL,
  1766. "Set a fixed difference in clock speed between the GPU and memory in auto-gpu mode"),
  1767. OPT_WITH_ARG("--gpu-powertune",
  1768. set_gpu_powertune, NULL, NULL,
  1769. "Set the GPU powertune percentage - one value for all or separate by commas for per card"),
  1770. OPT_WITHOUT_ARG("--gpu-reorder",
  1771. opt_set_bool, &opt_reorder,
  1772. "Attempt to reorder GPU devices according to PCI Bus ID"),
  1773. OPT_WITH_ARG("--gpu-vddc",
  1774. set_gpu_vddc, NULL, NULL,
  1775. "Set the GPU voltage in Volts - one value for all or separate by commas for per card"),
  1776. #endif
  1777. #ifdef USE_SCRYPT
  1778. OPT_WITH_ARG("--lookup-gap",
  1779. set_lookup_gap, NULL, NULL,
  1780. "Set GPU lookup gap for scrypt mining, comma separated"),
  1781. OPT_WITH_ARG("--intensity|-I",
  1782. set_intensity, NULL, NULL,
  1783. "Intensity of GPU scanning (d or " MIN_SHA_INTENSITY_STR
  1784. " -> " MAX_SCRYPT_INTENSITY_STR
  1785. ",default: d to maintain desktop interactivity)"),
  1786. #else
  1787. OPT_WITH_ARG("--intensity|-I",
  1788. set_intensity, NULL, NULL,
  1789. "Intensity of GPU scanning (d or " MIN_SHA_INTENSITY_STR
  1790. " -> " MAX_SHA_INTENSITY_STR
  1791. ",default: d to maintain desktop interactivity)"),
  1792. #endif
  1793. #endif
  1794. #if defined(HAVE_OPENCL) || defined(USE_MODMINER) || defined(USE_X6500) || defined(USE_ZTEX)
  1795. OPT_WITH_ARG("--kernel-path|-K",
  1796. opt_set_charp, opt_show_charp, &opt_kernel_path,
  1797. "Specify a path to where bitstream and kernel files are"),
  1798. #endif
  1799. #ifdef HAVE_OPENCL
  1800. OPT_WITH_ARG("--kernel|-k",
  1801. set_kernel, NULL, NULL,
  1802. "Override sha256 kernel to use (diablo, poclbm, phatk or diakgcn) - one value or comma separated"),
  1803. #endif
  1804. #ifdef USE_ICARUS
  1805. OPT_WITH_ARG("--icarus-options",
  1806. set_icarus_options, NULL, NULL,
  1807. opt_hidden),
  1808. OPT_WITH_ARG("--icarus-timing",
  1809. set_icarus_timing, NULL, NULL,
  1810. opt_hidden),
  1811. #endif
  1812. #ifdef USE_AVALON
  1813. OPT_WITH_ARG("--avalon-options",
  1814. set_avalon_options, NULL, NULL,
  1815. opt_hidden),
  1816. #endif
  1817. #ifdef USE_KLONDIKE
  1818. OPT_WITH_ARG("--klondike-options",
  1819. set_klondike_options, NULL, NULL,
  1820. "Set klondike options clock:temptarget"),
  1821. #endif
  1822. OPT_WITHOUT_ARG("--load-balance",
  1823. set_loadbalance, &pool_strategy,
  1824. "Change multipool strategy from failover to quota based balance"),
  1825. OPT_WITH_ARG("--log|-l",
  1826. set_int_0_to_9999, opt_show_intval, &opt_log_interval,
  1827. "Interval in seconds between log output"),
  1828. OPT_WITH_ARG("--log-file|-L",
  1829. set_log_file, NULL, NULL,
  1830. "Append log file for output messages"),
  1831. OPT_WITH_ARG("--logfile",
  1832. set_log_file, NULL, NULL,
  1833. opt_hidden),
  1834. OPT_WITHOUT_ARG("--log-microseconds",
  1835. opt_set_bool, &opt_log_microseconds,
  1836. "Include microseconds in log output"),
  1837. #if defined(unix) || defined(__APPLE__)
  1838. OPT_WITH_ARG("--monitor|-m",
  1839. opt_set_charp, NULL, &opt_stderr_cmd,
  1840. "Use custom pipe cmd for output messages"),
  1841. #endif // defined(unix)
  1842. OPT_WITHOUT_ARG("--net-delay",
  1843. opt_set_bool, &opt_delaynet,
  1844. "Impose small delays in networking to avoid overloading slow routers"),
  1845. OPT_WITHOUT_ARG("--no-adl",
  1846. opt_set_bool, &opt_noadl,
  1847. #ifdef HAVE_ADL
  1848. "Disable the ATI display library used for monitoring and setting GPU parameters"
  1849. #else
  1850. opt_hidden
  1851. #endif
  1852. ),
  1853. OPT_WITHOUT_ARG("--no-gbt",
  1854. opt_set_invbool, &want_gbt,
  1855. "Disable getblocktemplate support"),
  1856. OPT_WITHOUT_ARG("--no-getwork",
  1857. opt_set_invbool, &want_getwork,
  1858. "Disable getwork support"),
  1859. OPT_WITHOUT_ARG("--no-hotplug",
  1860. #ifdef HAVE_BFG_HOTPLUG
  1861. opt_set_invbool, &opt_hotplug,
  1862. "Disable hotplug detection"
  1863. #else
  1864. set_null, &opt_hotplug,
  1865. opt_hidden
  1866. #endif
  1867. ),
  1868. OPT_WITHOUT_ARG("--no-longpoll",
  1869. opt_set_invbool, &want_longpoll,
  1870. "Disable X-Long-Polling support"),
  1871. OPT_WITHOUT_ARG("--no-pool-disable",
  1872. opt_set_invbool, &opt_disable_pool,
  1873. opt_hidden),
  1874. OPT_WITHOUT_ARG("--no-restart",
  1875. opt_set_invbool, &opt_restart,
  1876. "Do not attempt to restart devices that hang"
  1877. ),
  1878. OPT_WITHOUT_ARG("--no-show-processors",
  1879. opt_set_invbool, &opt_show_procs,
  1880. opt_hidden),
  1881. OPT_WITHOUT_ARG("--no-show-procs",
  1882. opt_set_invbool, &opt_show_procs,
  1883. opt_hidden),
  1884. OPT_WITHOUT_ARG("--no-stratum",
  1885. opt_set_invbool, &want_stratum,
  1886. "Disable Stratum detection"),
  1887. OPT_WITHOUT_ARG("--no-submit-stale",
  1888. opt_set_invbool, &opt_submit_stale,
  1889. "Don't submit shares if they are detected as stale"),
  1890. #ifdef HAVE_OPENCL
  1891. OPT_WITHOUT_ARG("--no-opencl-binaries",
  1892. opt_set_invbool, &opt_opencl_binaries,
  1893. "Don't attempt to use or save OpenCL kernel binaries"),
  1894. #endif
  1895. OPT_WITHOUT_ARG("--no-unicode",
  1896. #ifdef USE_UNICODE
  1897. opt_set_invbool, &use_unicode,
  1898. "Don't use Unicode characters in TUI"
  1899. #else
  1900. set_null, &use_unicode,
  1901. opt_hidden
  1902. #endif
  1903. ),
  1904. OPT_WITH_ARG("--noncelog",
  1905. set_noncelog, NULL, NULL,
  1906. "Create log of all nonces found"),
  1907. OPT_WITH_ARG("--pass|-p",
  1908. set_pass, NULL, NULL,
  1909. "Password for bitcoin JSON-RPC server"),
  1910. OPT_WITHOUT_ARG("--per-device-stats",
  1911. opt_set_bool, &want_per_device_stats,
  1912. "Force verbose mode and output per-device statistics"),
  1913. OPT_WITH_ARG("--userpass|-O", // duplicate to ensure config loads it before pool-priority
  1914. set_userpass, NULL, NULL,
  1915. opt_hidden),
  1916. OPT_WITH_ARG("--pool-priority",
  1917. set_pool_priority, NULL, NULL,
  1918. "Priority for just the previous-defined pool"),
  1919. OPT_WITH_ARG("--pool-proxy|-x",
  1920. set_pool_proxy, NULL, NULL,
  1921. "Proxy URI to use for connecting to just the previous-defined pool"),
  1922. OPT_WITH_ARG("--force-rollntime", // NOTE: must be after --pass for config file ordering
  1923. set_pool_force_rollntime, NULL, NULL,
  1924. opt_hidden),
  1925. OPT_WITHOUT_ARG("--protocol-dump|-P",
  1926. opt_set_bool, &opt_protocol,
  1927. "Verbose dump of protocol-level activities"),
  1928. OPT_WITH_ARG("--queue|-Q",
  1929. set_int_0_to_9999, opt_show_intval, &opt_queue,
  1930. "Minimum number of work items to have queued (0+)"),
  1931. OPT_WITHOUT_ARG("--quiet|-q",
  1932. opt_set_bool, &opt_quiet,
  1933. "Disable logging output, display status and errors"),
  1934. OPT_WITHOUT_ARG("--quiet-work-updates|--quiet-work-update",
  1935. opt_set_bool, &opt_quiet_work_updates,
  1936. opt_hidden),
  1937. OPT_WITH_ARG("--quota|-U",
  1938. set_quota, NULL, NULL,
  1939. "quota;URL combination for server with load-balance strategy quotas"),
  1940. OPT_WITHOUT_ARG("--real-quiet",
  1941. opt_set_bool, &opt_realquiet,
  1942. "Disable all output"),
  1943. OPT_WITH_ARG("--request-diff",
  1944. set_request_diff, opt_show_floatval, &request_pdiff,
  1945. "Request a specific difficulty from pools"),
  1946. OPT_WITH_ARG("--retries",
  1947. opt_set_intval, opt_show_intval, &opt_retries,
  1948. "Number of times to retry failed submissions before giving up (-1 means never)"),
  1949. OPT_WITH_ARG("--retry-pause",
  1950. set_null, NULL, NULL,
  1951. opt_hidden),
  1952. OPT_WITH_ARG("--rotate",
  1953. set_rotate, opt_show_intval, &opt_rotate_period,
  1954. "Change multipool strategy from failover to regularly rotate at N minutes"),
  1955. OPT_WITHOUT_ARG("--round-robin",
  1956. set_rr, &pool_strategy,
  1957. "Change multipool strategy from failover to round robin on failure"),
  1958. OPT_WITH_ARG("--scan|-S",
  1959. add_serial, NULL, NULL,
  1960. "Configure how to scan for mining devices"),
  1961. OPT_WITH_ARG("--scan-device|--scan-serial|--devscan",
  1962. add_serial, NULL, NULL,
  1963. opt_hidden),
  1964. OPT_WITH_ARG("--scan-time|-s",
  1965. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  1966. "Upper bound on time spent scanning current work, in seconds"),
  1967. OPT_WITH_ARG("--scantime",
  1968. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  1969. opt_hidden),
  1970. OPT_WITH_ARG("--sched-start",
  1971. set_schedtime, NULL, &schedstart,
  1972. "Set a time of day in HH:MM to start mining (a once off without a stop time)"),
  1973. OPT_WITH_ARG("--sched-stop",
  1974. set_schedtime, NULL, &schedstop,
  1975. "Set a time of day in HH:MM to stop mining (will quit without a start time)"),
  1976. #ifdef USE_SCRYPT
  1977. OPT_WITHOUT_ARG("--scrypt",
  1978. opt_set_bool, &opt_scrypt,
  1979. "Use the scrypt algorithm for mining (non-bitcoin)"),
  1980. #endif
  1981. OPT_WITH_ARG("--set-device",
  1982. opt_string_elist_add, NULL, &opt_set_device_list,
  1983. "Set default parameters on devices; eg, NFY:osc6_bits=50"),
  1984. #if defined(USE_SCRYPT) && defined(HAVE_OPENCL)
  1985. OPT_WITH_ARG("--shaders",
  1986. set_shaders, NULL, NULL,
  1987. "GPU shaders per card for tuning scrypt, comma separated"),
  1988. #endif
  1989. #ifdef HAVE_PWD_H
  1990. OPT_WITH_ARG("--setuid",
  1991. opt_set_charp, NULL, &opt_setuid,
  1992. "Username of an unprivileged user to run as"),
  1993. #endif
  1994. OPT_WITH_ARG("--sharelog",
  1995. set_sharelog, NULL, NULL,
  1996. "Append share log to file"),
  1997. OPT_WITH_ARG("--shares",
  1998. opt_set_intval, NULL, &opt_shares,
  1999. "Quit after mining N shares (default: unlimited)"),
  2000. OPT_WITHOUT_ARG("--show-processors",
  2001. opt_set_bool, &opt_show_procs,
  2002. "Show per processor statistics in summary"),
  2003. OPT_WITHOUT_ARG("--show-procs",
  2004. opt_set_bool, &opt_show_procs,
  2005. opt_hidden),
  2006. OPT_WITH_ARG("--skip-security-checks",
  2007. set_int_0_to_9999, NULL, &opt_skip_checks,
  2008. "Skip security checks sometimes to save bandwidth; only check 1/<arg>th of the time (default: never skip)"),
  2009. OPT_WITH_ARG("--socks-proxy",
  2010. opt_set_charp, NULL, &opt_socks_proxy,
  2011. "Set socks proxy (host:port)"),
  2012. #ifdef USE_LIBEVENT
  2013. OPT_WITH_ARG("--stratum-port",
  2014. opt_set_intval, opt_show_intval, &stratumsrv_port,
  2015. "Port number to listen on for stratum miners (-1 means disabled)"),
  2016. #endif
  2017. OPT_WITHOUT_ARG("--submit-stale",
  2018. opt_set_bool, &opt_submit_stale,
  2019. opt_hidden),
  2020. OPT_WITH_ARG("--submit-threads",
  2021. opt_set_intval, opt_show_intval, &opt_submit_threads,
  2022. "Minimum number of concurrent share submissions (default: 64)"),
  2023. #ifdef HAVE_SYSLOG_H
  2024. OPT_WITHOUT_ARG("--syslog",
  2025. opt_set_bool, &use_syslog,
  2026. "Use system log for output messages (default: standard error)"),
  2027. #endif
  2028. OPT_WITH_ARG("--temp-cutoff",
  2029. set_temp_cutoff, NULL, &opt_cutofftemp,
  2030. "Maximum temperature devices will be allowed to reach before being disabled, one value or comma separated list"),
  2031. OPT_WITH_ARG("--temp-hysteresis",
  2032. set_int_1_to_10, opt_show_intval, &opt_hysteresis,
  2033. "Set how much the temperature can fluctuate outside limits when automanaging speeds"),
  2034. #ifdef HAVE_ADL
  2035. OPT_WITH_ARG("--temp-overheat",
  2036. set_temp_overheat, opt_show_intval, &opt_overheattemp,
  2037. "Overheat temperature when automatically managing fan and GPU speeds, one value or comma separated list"),
  2038. #endif
  2039. OPT_WITH_ARG("--temp-target",
  2040. set_temp_target, NULL, NULL,
  2041. "Target temperature when automatically managing fan and clock speeds, one value or comma separated list"),
  2042. OPT_WITHOUT_ARG("--text-only|-T",
  2043. opt_set_invbool, &use_curses,
  2044. #ifdef HAVE_CURSES
  2045. "Disable ncurses formatted screen output"
  2046. #else
  2047. opt_hidden
  2048. #endif
  2049. ),
  2050. #if defined(USE_SCRYPT) && defined(HAVE_OPENCL)
  2051. OPT_WITH_ARG("--thread-concurrency",
  2052. set_thread_concurrency, NULL, NULL,
  2053. "Set GPU thread concurrency for scrypt mining, comma separated"),
  2054. #endif
  2055. #ifdef USE_UNICODE
  2056. OPT_WITHOUT_ARG("--unicode",
  2057. opt_set_bool, &use_unicode,
  2058. "Use Unicode characters in TUI"),
  2059. #endif
  2060. OPT_WITH_ARG("--url|-o",
  2061. set_url, NULL, NULL,
  2062. "URL for bitcoin JSON-RPC server"),
  2063. OPT_WITH_ARG("--user|-u",
  2064. set_user, NULL, NULL,
  2065. "Username for bitcoin JSON-RPC server"),
  2066. #ifdef HAVE_OPENCL
  2067. OPT_WITH_ARG("--vectors|-v",
  2068. set_vector, NULL, NULL,
  2069. "Override detected optimal vector (1, 2 or 4) - one value or comma separated list"),
  2070. #endif
  2071. OPT_WITHOUT_ARG("--verbose",
  2072. opt_set_bool, &opt_log_output,
  2073. "Log verbose output to stderr as well as status output"),
  2074. OPT_WITHOUT_ARG("--weighed-stats",
  2075. opt_set_bool, &opt_weighed_stats,
  2076. "Display statistics weighed to difficulty 1"),
  2077. #ifdef HAVE_OPENCL
  2078. OPT_WITH_ARG("--worksize|-w",
  2079. set_worksize, NULL, NULL,
  2080. "Override detected optimal worksize - one value or comma separated list"),
  2081. #endif
  2082. OPT_WITHOUT_ARG("--unittest",
  2083. opt_set_bool, &opt_unittest, opt_hidden),
  2084. OPT_WITH_ARG("--userpass|-O",
  2085. set_userpass, NULL, NULL,
  2086. "Username:Password pair for bitcoin JSON-RPC server"),
  2087. OPT_WITHOUT_ARG("--worktime",
  2088. opt_set_bool, &opt_worktime,
  2089. "Display extra work time debug information"),
  2090. OPT_WITH_ARG("--pools",
  2091. opt_set_bool, NULL, NULL, opt_hidden),
  2092. OPT_ENDTABLE
  2093. };
  2094. static char *load_config(const char *arg, void __maybe_unused *unused);
  2095. static int fileconf_load;
  2096. static char *parse_config(json_t *config, bool fileconf)
  2097. {
  2098. static char err_buf[200];
  2099. struct opt_table *opt;
  2100. json_t *val;
  2101. if (fileconf && !fileconf_load)
  2102. fileconf_load = 1;
  2103. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  2104. char *p, *name, *sp;
  2105. /* We don't handle subtables. */
  2106. assert(!(opt->type & OPT_SUBTABLE));
  2107. if (!opt->names)
  2108. continue;
  2109. /* Pull apart the option name(s). */
  2110. name = strdup(opt->names);
  2111. for (p = strtok_r(name, "|", &sp); p; p = strtok_r(NULL, "|", &sp)) {
  2112. char *err = "Invalid value";
  2113. /* Ignore short options. */
  2114. if (p[1] != '-')
  2115. continue;
  2116. val = json_object_get(config, p+2);
  2117. if (!val)
  2118. continue;
  2119. if (opt->type & OPT_HASARG) {
  2120. if (json_is_string(val)) {
  2121. err = opt->cb_arg(json_string_value(val),
  2122. opt->u.arg);
  2123. } else if (json_is_number(val)) {
  2124. char buf[256], *p, *q;
  2125. snprintf(buf, 256, "%f", json_number_value(val));
  2126. if ( (p = strchr(buf, '.')) ) {
  2127. // Trim /\.0*$/ to work properly with integer-only arguments
  2128. q = p;
  2129. while (*(++q) == '0') {}
  2130. if (*q == '\0')
  2131. *p = '\0';
  2132. }
  2133. err = opt->cb_arg(buf, opt->u.arg);
  2134. } else if (json_is_array(val)) {
  2135. int n, size = json_array_size(val);
  2136. err = NULL;
  2137. for (n = 0; n < size && !err; n++) {
  2138. if (json_is_string(json_array_get(val, n)))
  2139. err = opt->cb_arg(json_string_value(json_array_get(val, n)), opt->u.arg);
  2140. else if (json_is_object(json_array_get(val, n)))
  2141. err = parse_config(json_array_get(val, n), false);
  2142. }
  2143. }
  2144. } else if (opt->type & OPT_NOARG) {
  2145. if (json_is_true(val))
  2146. err = opt->cb(opt->u.arg);
  2147. else if (json_is_boolean(val)) {
  2148. if (opt->cb == (void*)opt_set_bool)
  2149. err = opt_set_invbool(opt->u.arg);
  2150. else if (opt->cb == (void*)opt_set_invbool)
  2151. err = opt_set_bool(opt->u.arg);
  2152. }
  2153. }
  2154. if (err) {
  2155. /* Allow invalid values to be in configuration
  2156. * file, just skipping over them provided the
  2157. * JSON is still valid after that. */
  2158. if (fileconf) {
  2159. applog(LOG_ERR, "Invalid config option %s: %s", p, err);
  2160. fileconf_load = -1;
  2161. } else {
  2162. snprintf(err_buf, sizeof(err_buf), "Parsing JSON option %s: %s",
  2163. p, err);
  2164. return err_buf;
  2165. }
  2166. }
  2167. }
  2168. free(name);
  2169. }
  2170. val = json_object_get(config, JSON_INCLUDE_CONF);
  2171. if (val && json_is_string(val))
  2172. return load_config(json_string_value(val), NULL);
  2173. return NULL;
  2174. }
  2175. char *cnfbuf = NULL;
  2176. static char *load_config(const char *arg, void __maybe_unused *unused)
  2177. {
  2178. json_error_t err;
  2179. json_t *config;
  2180. char *json_error;
  2181. size_t siz;
  2182. if (!cnfbuf)
  2183. cnfbuf = strdup(arg);
  2184. if (++include_count > JSON_MAX_DEPTH)
  2185. return JSON_MAX_DEPTH_ERR;
  2186. #if JANSSON_MAJOR_VERSION > 1
  2187. config = json_load_file(arg, 0, &err);
  2188. #else
  2189. config = json_load_file(arg, &err);
  2190. #endif
  2191. if (!json_is_object(config)) {
  2192. siz = JSON_LOAD_ERROR_LEN + strlen(arg) + strlen(err.text);
  2193. json_error = malloc(siz);
  2194. if (!json_error)
  2195. quit(1, "Malloc failure in json error");
  2196. snprintf(json_error, siz, JSON_LOAD_ERROR, arg, err.text);
  2197. return json_error;
  2198. }
  2199. config_loaded = true;
  2200. /* Parse the config now, so we can override it. That can keep pointers
  2201. * so don't free config object. */
  2202. return parse_config(config, true);
  2203. }
  2204. static void load_default_config(void)
  2205. {
  2206. cnfbuf = malloc(PATH_MAX);
  2207. #if defined(unix)
  2208. if (getenv("HOME") && *getenv("HOME")) {
  2209. strcpy(cnfbuf, getenv("HOME"));
  2210. strcat(cnfbuf, "/");
  2211. } else
  2212. strcpy(cnfbuf, "");
  2213. char *dirp = cnfbuf + strlen(cnfbuf);
  2214. strcpy(dirp, ".bfgminer/");
  2215. strcat(dirp, def_conf);
  2216. if (access(cnfbuf, R_OK))
  2217. // No BFGMiner config, try Cgminer's...
  2218. strcpy(dirp, ".cgminer/cgminer.conf");
  2219. #else
  2220. strcpy(cnfbuf, "");
  2221. strcat(cnfbuf, def_conf);
  2222. #endif
  2223. if (!access(cnfbuf, R_OK))
  2224. load_config(cnfbuf, NULL);
  2225. else {
  2226. free(cnfbuf);
  2227. cnfbuf = NULL;
  2228. }
  2229. }
  2230. extern const char *opt_argv0;
  2231. static char *opt_verusage_and_exit(const char *extra)
  2232. {
  2233. puts(packagename);
  2234. printf(" Drivers:%s\n", BFG_DRIVERLIST);
  2235. printf(" Algoritms:%s\n", BFG_ALGOLIST);
  2236. printf(" Options:%s\n", BFG_OPTLIST);
  2237. printf("%s", opt_usage(opt_argv0, extra));
  2238. fflush(stdout);
  2239. exit(0);
  2240. }
  2241. /* These options are available from commandline only */
  2242. static struct opt_table opt_cmdline_table[] = {
  2243. OPT_WITH_ARG("--config|-c",
  2244. load_config, NULL, NULL,
  2245. "Load a JSON-format configuration file\n"
  2246. "See example.conf for an example configuration."),
  2247. OPT_WITHOUT_ARG("--help|-h",
  2248. opt_verusage_and_exit, NULL,
  2249. "Print this message"),
  2250. #ifdef HAVE_OPENCL
  2251. OPT_WITHOUT_ARG("--ndevs|-n",
  2252. print_ndevs_and_exit, &nDevs,
  2253. opt_hidden),
  2254. #endif
  2255. OPT_WITHOUT_ARG("--version|-V",
  2256. opt_version_and_exit, packagename,
  2257. "Display version and exit"),
  2258. OPT_ENDTABLE
  2259. };
  2260. static bool jobj_binary(const json_t *obj, const char *key,
  2261. void *buf, size_t buflen, bool required)
  2262. {
  2263. const char *hexstr;
  2264. json_t *tmp;
  2265. tmp = json_object_get(obj, key);
  2266. if (unlikely(!tmp)) {
  2267. if (unlikely(required))
  2268. applog(LOG_ERR, "JSON key '%s' not found", key);
  2269. return false;
  2270. }
  2271. hexstr = json_string_value(tmp);
  2272. if (unlikely(!hexstr)) {
  2273. applog(LOG_ERR, "JSON key '%s' is not a string", key);
  2274. return false;
  2275. }
  2276. if (!hex2bin(buf, hexstr, buflen))
  2277. return false;
  2278. return true;
  2279. }
  2280. static void calc_midstate(struct work *work)
  2281. {
  2282. union {
  2283. unsigned char c[64];
  2284. uint32_t i[16];
  2285. } data;
  2286. swap32yes(&data.i[0], work->data, 16);
  2287. sha256_ctx ctx;
  2288. sha256_init(&ctx);
  2289. sha256_update(&ctx, data.c, 64);
  2290. memcpy(work->midstate, ctx.h, sizeof(work->midstate));
  2291. swap32tole(work->midstate, work->midstate, 8);
  2292. }
  2293. static struct work *make_work(void)
  2294. {
  2295. struct work *work = calloc(1, sizeof(struct work));
  2296. if (unlikely(!work))
  2297. quit(1, "Failed to calloc work in make_work");
  2298. cg_wlock(&control_lock);
  2299. work->id = total_work++;
  2300. cg_wunlock(&control_lock);
  2301. return work;
  2302. }
  2303. /* This is the central place all work that is about to be retired should be
  2304. * cleaned to remove any dynamically allocated arrays within the struct */
  2305. void clean_work(struct work *work)
  2306. {
  2307. free(work->job_id);
  2308. bytes_free(&work->nonce2);
  2309. free(work->nonce1);
  2310. if (work->tmpl) {
  2311. struct pool *pool = work->pool;
  2312. mutex_lock(&pool->pool_lock);
  2313. bool free_tmpl = !--*work->tmpl_refcount;
  2314. mutex_unlock(&pool->pool_lock);
  2315. if (free_tmpl) {
  2316. blktmpl_free(work->tmpl);
  2317. free(work->tmpl_refcount);
  2318. }
  2319. }
  2320. memset(work, 0, sizeof(struct work));
  2321. }
  2322. /* All dynamically allocated work structs should be freed here to not leak any
  2323. * ram from arrays allocated within the work struct */
  2324. void free_work(struct work *work)
  2325. {
  2326. clean_work(work);
  2327. free(work);
  2328. }
  2329. static const char *workpadding_bin = "\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\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x80\x02\0\0";
  2330. // Must only be called with ch_lock held!
  2331. static
  2332. void __update_block_title(const unsigned char *hash_swap)
  2333. {
  2334. if (hash_swap) {
  2335. char tmp[17];
  2336. // Only provided when the block has actually changed
  2337. free(current_hash);
  2338. current_hash = malloc(3 /* ... */ + 16 /* block hash segment */ + 1);
  2339. bin2hex(tmp, &hash_swap[24], 8);
  2340. memset(current_hash, '.', 3);
  2341. memcpy(&current_hash[3], tmp, 17);
  2342. known_blkheight_current = false;
  2343. } else if (likely(known_blkheight_current)) {
  2344. return;
  2345. }
  2346. if (current_block_id == known_blkheight_blkid) {
  2347. // FIXME: The block number will overflow this sometime around AD 2025-2027
  2348. if (known_blkheight < 1000000) {
  2349. memmove(&current_hash[3], &current_hash[11], 8);
  2350. snprintf(&current_hash[11], 20-11, " #%6u", known_blkheight);
  2351. }
  2352. known_blkheight_current = true;
  2353. }
  2354. }
  2355. static
  2356. void have_block_height(uint32_t block_id, uint32_t blkheight)
  2357. {
  2358. if (known_blkheight == blkheight)
  2359. return;
  2360. applog(LOG_DEBUG, "Learned that block id %08" PRIx32 " is height %" PRIu32, (uint32_t)be32toh(block_id), blkheight);
  2361. cg_wlock(&ch_lock);
  2362. known_blkheight = blkheight;
  2363. known_blkheight_blkid = block_id;
  2364. block_subsidy = 5000000000LL >> (blkheight / 210000);
  2365. if (block_id == current_block_id)
  2366. __update_block_title(NULL);
  2367. cg_wunlock(&ch_lock);
  2368. }
  2369. static
  2370. void pool_set_opaque(struct pool *pool, bool opaque)
  2371. {
  2372. if (pool->swork.opaque == opaque)
  2373. return;
  2374. pool->swork.opaque = opaque;
  2375. if (opaque)
  2376. applog(LOG_WARNING, "Pool %u is hiding block contents from us",
  2377. pool->pool_no);
  2378. else
  2379. applog(LOG_NOTICE, "Pool %u now providing block contents to us",
  2380. pool->pool_no);
  2381. }
  2382. static bool work_decode(struct pool *pool, struct work *work, json_t *val)
  2383. {
  2384. json_t *res_val = json_object_get(val, "result");
  2385. json_t *tmp_val;
  2386. bool ret = false;
  2387. if (unlikely(detect_algo == 1)) {
  2388. json_t *tmp = json_object_get(res_val, "algorithm");
  2389. const char *v = tmp ? json_string_value(tmp) : "";
  2390. if (strncasecmp(v, "scrypt", 6))
  2391. detect_algo = 2;
  2392. }
  2393. if (work->tmpl) {
  2394. struct timeval tv_now;
  2395. cgtime(&tv_now);
  2396. const char *err = blktmpl_add_jansson(work->tmpl, res_val, tv_now.tv_sec);
  2397. if (err) {
  2398. applog(LOG_ERR, "blktmpl error: %s", err);
  2399. return false;
  2400. }
  2401. work->rolltime = blkmk_time_left(work->tmpl, tv_now.tv_sec);
  2402. #if BLKMAKER_VERSION > 1
  2403. if (opt_coinbase_script.sz)
  2404. {
  2405. bool newcb;
  2406. #if BLKMAKER_VERSION > 2
  2407. blkmk_init_generation2(work->tmpl, opt_coinbase_script.data, opt_coinbase_script.sz, &newcb);
  2408. #else
  2409. newcb = !work->tmpl->cbtxn;
  2410. blkmk_init_generation(work->tmpl, opt_coinbase_script.data, opt_coinbase_script.sz);
  2411. #endif
  2412. if (newcb)
  2413. {
  2414. ssize_t ae = blkmk_append_coinbase_safe(work->tmpl, &template_nonce, sizeof(template_nonce));
  2415. if (ae < (ssize_t)sizeof(template_nonce))
  2416. applog(LOG_WARNING, "Cannot append template-nonce to coinbase on pool %u (%"PRId64") - you might be wasting hashing!", work->pool->pool_no, (int64_t)ae);
  2417. ++template_nonce;
  2418. }
  2419. }
  2420. #endif
  2421. #if BLKMAKER_VERSION > 0
  2422. {
  2423. ssize_t ae = blkmk_append_coinbase_safe(work->tmpl, opt_coinbase_sig, 101);
  2424. static bool appenderr = false;
  2425. if (ae <= 0) {
  2426. if (opt_coinbase_sig) {
  2427. applog((appenderr ? LOG_DEBUG : LOG_WARNING), "Cannot append coinbase signature at all on pool %u (%"PRId64")", pool->pool_no, (int64_t)ae);
  2428. appenderr = true;
  2429. }
  2430. } else if (ae >= 3 || opt_coinbase_sig) {
  2431. const char *cbappend = opt_coinbase_sig;
  2432. const char full[] = PACKAGE " " VERSION;
  2433. if (!cbappend) {
  2434. if ((size_t)ae >= sizeof(full) - 1)
  2435. cbappend = full;
  2436. else if ((size_t)ae >= sizeof(PACKAGE) - 1)
  2437. cbappend = PACKAGE;
  2438. else
  2439. cbappend = "BFG";
  2440. }
  2441. size_t cbappendsz = strlen(cbappend);
  2442. static bool truncatewarning = false;
  2443. if (cbappendsz <= (size_t)ae) {
  2444. if (cbappendsz < (size_t)ae)
  2445. // If we have space, include the trailing \0
  2446. ++cbappendsz;
  2447. ae = cbappendsz;
  2448. truncatewarning = false;
  2449. } else {
  2450. char *tmp = malloc(ae + 1);
  2451. memcpy(tmp, opt_coinbase_sig, ae);
  2452. tmp[ae] = '\0';
  2453. applog((truncatewarning ? LOG_DEBUG : LOG_WARNING),
  2454. "Pool %u truncating appended coinbase signature at %"PRId64" bytes: %s(%s)",
  2455. pool->pool_no, (int64_t)ae, tmp, &opt_coinbase_sig[ae]);
  2456. free(tmp);
  2457. truncatewarning = true;
  2458. }
  2459. ae = blkmk_append_coinbase_safe(work->tmpl, cbappend, ae);
  2460. if (ae <= 0) {
  2461. applog((appenderr ? LOG_DEBUG : LOG_WARNING), "Error appending coinbase signature (%"PRId64")", (int64_t)ae);
  2462. appenderr = true;
  2463. } else
  2464. appenderr = false;
  2465. }
  2466. }
  2467. #endif
  2468. if (blkmk_get_data(work->tmpl, work->data, 80, tv_now.tv_sec, NULL, &work->dataid) < 76)
  2469. return false;
  2470. swap32yes(work->data, work->data, 80 / 4);
  2471. memcpy(&work->data[80], workpadding_bin, 48);
  2472. const struct blktmpl_longpoll_req *lp;
  2473. if ((lp = blktmpl_get_longpoll(work->tmpl)) && ((!pool->lp_id) || strcmp(lp->id, pool->lp_id))) {
  2474. free(pool->lp_id);
  2475. pool->lp_id = strdup(lp->id);
  2476. #if 0 /* This just doesn't work :( */
  2477. curl_socket_t sock = pool->lp_socket;
  2478. if (sock != CURL_SOCKET_BAD) {
  2479. pool->lp_socket = CURL_SOCKET_BAD;
  2480. applog(LOG_WARNING, "Pool %u long poll request hanging, reconnecting", pool->pool_no);
  2481. shutdown(sock, SHUT_RDWR);
  2482. }
  2483. #endif
  2484. }
  2485. }
  2486. else
  2487. if (unlikely(!jobj_binary(res_val, "data", work->data, sizeof(work->data), true))) {
  2488. applog(LOG_ERR, "JSON inval data");
  2489. return false;
  2490. }
  2491. if (!jobj_binary(res_val, "midstate", work->midstate, sizeof(work->midstate), false)) {
  2492. // Calculate it ourselves
  2493. applog(LOG_DEBUG, "Calculating midstate locally");
  2494. calc_midstate(work);
  2495. }
  2496. if (unlikely(!jobj_binary(res_val, "target", work->target, sizeof(work->target), true))) {
  2497. applog(LOG_ERR, "JSON inval target");
  2498. return false;
  2499. }
  2500. if (work->tmpl) {
  2501. for (size_t i = 0; i < sizeof(work->target) / 2; ++i)
  2502. {
  2503. int p = (sizeof(work->target) - 1) - i;
  2504. unsigned char c = work->target[i];
  2505. work->target[i] = work->target[p];
  2506. work->target[p] = c;
  2507. }
  2508. }
  2509. if ( (tmp_val = json_object_get(res_val, "height")) ) {
  2510. uint32_t blkheight = json_number_value(tmp_val);
  2511. uint32_t block_id = ((uint32_t*)work->data)[1];
  2512. have_block_height(block_id, blkheight);
  2513. }
  2514. memset(work->hash, 0, sizeof(work->hash));
  2515. cgtime(&work->tv_staged);
  2516. pool_set_opaque(pool, !work->tmpl);
  2517. ret = true;
  2518. return ret;
  2519. }
  2520. /* Returns whether the pool supports local work generation or not. */
  2521. static bool pool_localgen(struct pool *pool)
  2522. {
  2523. return (pool->last_work_copy || pool->has_stratum);
  2524. }
  2525. int dev_from_id(int thr_id)
  2526. {
  2527. struct cgpu_info *cgpu = get_thr_cgpu(thr_id);
  2528. return cgpu->device_id;
  2529. }
  2530. /* Create an exponentially decaying average over the opt_log_interval */
  2531. void decay_time(double *f, double fadd, double fsecs)
  2532. {
  2533. double ftotal, fprop;
  2534. fprop = 1.0 - 1 / (exp(fsecs / (double)opt_log_interval));
  2535. ftotal = 1.0 + fprop;
  2536. *f += (fadd * fprop);
  2537. *f /= ftotal;
  2538. }
  2539. static int __total_staged(void)
  2540. {
  2541. return HASH_COUNT(staged_work);
  2542. }
  2543. static int total_staged(void)
  2544. {
  2545. int ret;
  2546. mutex_lock(stgd_lock);
  2547. ret = __total_staged();
  2548. mutex_unlock(stgd_lock);
  2549. return ret;
  2550. }
  2551. #ifdef HAVE_CURSES
  2552. WINDOW *mainwin, *statuswin, *logwin;
  2553. #endif
  2554. double total_secs = 1.0;
  2555. static char statusline[256];
  2556. /* logstart is where the log window should start */
  2557. static int devcursor, logstart, logcursor;
  2558. #ifdef HAVE_CURSES
  2559. /* statusy is where the status window goes up to in cases where it won't fit at startup */
  2560. static int statusy;
  2561. static int devsummaryYOffset;
  2562. static int total_lines;
  2563. #endif
  2564. #ifdef HAVE_OPENCL
  2565. struct cgpu_info gpus[MAX_GPUDEVICES]; /* Maximum number apparently possible */
  2566. #endif
  2567. struct cgpu_info *cpus;
  2568. bool _bfg_console_cancel_disabled;
  2569. int _bfg_console_prev_cancelstate;
  2570. #ifdef HAVE_CURSES
  2571. #define lock_curses() bfg_console_lock()
  2572. #define unlock_curses() bfg_console_unlock()
  2573. static bool curses_active_locked(void)
  2574. {
  2575. bool ret;
  2576. lock_curses();
  2577. ret = curses_active;
  2578. if (!ret)
  2579. unlock_curses();
  2580. return ret;
  2581. }
  2582. // Cancellable getch
  2583. int my_cancellable_getch(void)
  2584. {
  2585. // This only works because the macro only hits direct getch() calls
  2586. typedef int (*real_getch_t)(void);
  2587. const real_getch_t real_getch = __real_getch;
  2588. int type, rv;
  2589. bool sct;
  2590. sct = !pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &type);
  2591. rv = real_getch();
  2592. if (sct)
  2593. pthread_setcanceltype(type, &type);
  2594. return rv;
  2595. }
  2596. #ifdef PDCURSES
  2597. static
  2598. int bfg_wresize(WINDOW *win, int lines, int columns)
  2599. {
  2600. int rv = wresize(win, lines, columns);
  2601. int x, y;
  2602. getyx(win, y, x);
  2603. if (unlikely(y >= lines || x >= columns))
  2604. {
  2605. if (y >= lines)
  2606. y = lines - 1;
  2607. if (x >= columns)
  2608. x = columns - 1;
  2609. wmove(win, y, x);
  2610. }
  2611. return rv;
  2612. }
  2613. #else
  2614. # define bfg_wresize wresize
  2615. #endif
  2616. #endif
  2617. void tailsprintf(char *buf, size_t bufsz, const char *fmt, ...)
  2618. {
  2619. va_list ap;
  2620. size_t presz = strlen(buf);
  2621. va_start(ap, fmt);
  2622. vsnprintf(&buf[presz], bufsz - presz, fmt, ap);
  2623. va_end(ap);
  2624. }
  2625. double stats_elapsed(struct cgminer_stats *stats)
  2626. {
  2627. struct timeval now;
  2628. double elapsed;
  2629. if (stats->start_tv.tv_sec == 0)
  2630. elapsed = total_secs;
  2631. else {
  2632. cgtime(&now);
  2633. elapsed = tdiff(&now, &stats->start_tv);
  2634. }
  2635. if (elapsed < 1.0)
  2636. elapsed = 1.0;
  2637. return elapsed;
  2638. }
  2639. bool drv_ready(struct cgpu_info *cgpu)
  2640. {
  2641. switch (cgpu->status) {
  2642. case LIFE_INIT:
  2643. case LIFE_DEAD2:
  2644. return false;
  2645. default:
  2646. return true;
  2647. }
  2648. }
  2649. double cgpu_utility(struct cgpu_info *cgpu)
  2650. {
  2651. double dev_runtime = cgpu_runtime(cgpu);
  2652. return cgpu->utility = cgpu->accepted / dev_runtime * 60;
  2653. }
  2654. #define suffix_string(val, buf, bufsiz, sigdigits) do{ \
  2655. _Static_assert(sigdigits == 0, "suffix_string only supported with sigdigits==0"); \
  2656. format_unit3(buf, bufsiz, FUP_DIFF, "", H2B_SHORTV, val, -1); \
  2657. }while(0)
  2658. static float
  2659. utility_to_hashrate(double utility)
  2660. {
  2661. return utility * 0x4444444;
  2662. }
  2663. static const char*_unitchar = "pn\xb5m kMGTPEZY?";
  2664. static const int _unitbase = 4;
  2665. static
  2666. void pick_unit(float hashrate, unsigned char *unit)
  2667. {
  2668. unsigned char i;
  2669. if (hashrate == 0)
  2670. {
  2671. if (*unit < _unitbase)
  2672. *unit = _unitbase;
  2673. return;
  2674. }
  2675. hashrate *= 1e12;
  2676. for (i = 0; i < *unit; ++i)
  2677. hashrate /= 1e3;
  2678. // 1000 but with tolerance for floating-point rounding, avoid showing "1000.0"
  2679. while (hashrate >= 999.95)
  2680. {
  2681. hashrate /= 1e3;
  2682. if (likely(_unitchar[*unit] != '?'))
  2683. ++*unit;
  2684. }
  2685. }
  2686. #define hashrate_pick_unit(hashrate, unit) pick_unit(hashrate, unit)
  2687. enum h2bs_fmt {
  2688. H2B_NOUNIT, // "xxx.x"
  2689. H2B_SHORT, // "xxx.xMH/s"
  2690. H2B_SPACED, // "xxx.x MH/s"
  2691. H2B_SHORTV, // Like H2B_SHORT, but omit space for base unit
  2692. };
  2693. static const size_t h2bs_fmt_size[] = {6, 10, 11};
  2694. enum bfu_floatprec {
  2695. FUP_INTEGER,
  2696. FUP_HASHES,
  2697. FUP_BTC,
  2698. FUP_DIFF,
  2699. };
  2700. static
  2701. int format_unit3(char *buf, size_t sz, enum bfu_floatprec fprec, const char *measurement, enum h2bs_fmt fmt, float hashrate, signed char unitin)
  2702. {
  2703. char *s = buf;
  2704. unsigned char prec, i, unit;
  2705. int rv = 0;
  2706. if (unitin == -1)
  2707. {
  2708. unit = 0;
  2709. hashrate_pick_unit(hashrate, &unit);
  2710. }
  2711. else
  2712. unit = unitin;
  2713. hashrate *= 1e12;
  2714. for (i = 0; i < unit; ++i)
  2715. hashrate /= 1000;
  2716. switch (fprec)
  2717. {
  2718. case FUP_HASHES:
  2719. // 100 but with tolerance for floating-point rounding, max "99.99" then "100.0"
  2720. if (hashrate >= 99.995 || unit < 6)
  2721. prec = 1;
  2722. else
  2723. prec = 2;
  2724. _SNP("%5.*f", prec, hashrate);
  2725. break;
  2726. case FUP_INTEGER:
  2727. _SNP("%3d", (int)hashrate);
  2728. break;
  2729. case FUP_BTC:
  2730. if (hashrate >= 99.995)
  2731. prec = 0;
  2732. else
  2733. prec = 2;
  2734. _SNP("%5.*f", prec, hashrate);
  2735. break;
  2736. case FUP_DIFF:
  2737. if (unit > _unitbase)
  2738. _SNP("%.3g", hashrate);
  2739. else
  2740. _SNP("%u", (unsigned int)hashrate);
  2741. }
  2742. switch (fmt) {
  2743. case H2B_SPACED:
  2744. _SNP(" ");
  2745. case H2B_SHORT:
  2746. _SNP("%c%s", _unitchar[unit], measurement);
  2747. default:
  2748. break;
  2749. case H2B_SHORTV:
  2750. _SNP("%.1s%s", (unit == _unitbase) ? "" : &_unitchar[unit], measurement);
  2751. }
  2752. return rv;
  2753. }
  2754. #define format_unit2(buf, sz, floatprec, measurement, fmt, n, unit) \
  2755. format_unit3(buf, sz, floatprec ? FUP_HASHES : FUP_INTEGER, measurement, fmt, n, unit)
  2756. static
  2757. char *_multi_format_unit(char **buflist, size_t *bufszlist, bool floatprec, const char *measurement, enum h2bs_fmt fmt, const char *delim, int count, const float *numbers, bool isarray)
  2758. {
  2759. unsigned char unit = 0;
  2760. bool allzero = true;
  2761. int i;
  2762. size_t delimsz = 0;
  2763. char *buf = buflist[0];
  2764. size_t bufsz = bufszlist[0];
  2765. size_t itemwidth = (floatprec ? 5 : 3);
  2766. if (!isarray)
  2767. delimsz = strlen(delim);
  2768. for (i = 0; i < count; ++i)
  2769. if (numbers[i] != 0)
  2770. {
  2771. pick_unit(numbers[i], &unit);
  2772. allzero = false;
  2773. }
  2774. if (allzero)
  2775. unit = _unitbase;
  2776. --count;
  2777. for (i = 0; i < count; ++i)
  2778. {
  2779. format_unit2(buf, bufsz, floatprec, NULL, H2B_NOUNIT, numbers[i], unit);
  2780. if (isarray)
  2781. {
  2782. buf = buflist[i + 1];
  2783. bufsz = bufszlist[i + 1];
  2784. }
  2785. else
  2786. {
  2787. buf += itemwidth;
  2788. bufsz -= itemwidth;
  2789. if (delimsz > bufsz)
  2790. delimsz = bufsz;
  2791. memcpy(buf, delim, delimsz);
  2792. buf += delimsz;
  2793. bufsz -= delimsz;
  2794. }
  2795. }
  2796. // Last entry has the unit
  2797. format_unit2(buf, bufsz, floatprec, measurement, fmt, numbers[count], unit);
  2798. return buflist[0];
  2799. }
  2800. #define multi_format_unit2(buf, bufsz, floatprec, measurement, fmt, delim, count, ...) _multi_format_unit((char *[]){buf}, (size_t[]){bufsz}, floatprec, measurement, fmt, delim, count, (float[]){ __VA_ARGS__ }, false)
  2801. #define multi_format_unit_array2(buflist, bufszlist, floatprec, measurement, fmt, count, ...) (void)_multi_format_unit(buflist, bufszlist, floatprec, measurement, fmt, NULL, count, (float[]){ __VA_ARGS__ }, true)
  2802. static
  2803. int percentf3(char * const buf, size_t sz, double p, const double t)
  2804. {
  2805. char *s = buf;
  2806. int rv = 0;
  2807. if (!p)
  2808. _SNP("none");
  2809. else
  2810. if (t <= p)
  2811. _SNP("100%%");
  2812. else
  2813. {
  2814. p /= t;
  2815. if (p < 0.00995) // 0.01 but with tolerance for floating-point rounding, max ".99%"
  2816. _SNP(".%02.0f%%", p * 10000); // ".01%"
  2817. else
  2818. if (p < 0.0995) // 0.1 but with tolerance for floating-point rounding, max "9.9%"
  2819. _SNP("%.1f%%", p * 100); // "9.1%"
  2820. else
  2821. _SNP("%3.0f%%", p * 100); // " 99%"
  2822. }
  2823. return rv;
  2824. }
  2825. #define percentf4(buf, bufsz, p, t) percentf3(buf, bufsz, p, p + t)
  2826. static
  2827. void test_decimal_width()
  2828. {
  2829. // The pipe character at end of each line should perfectly line up
  2830. char printbuf[512];
  2831. char testbuf1[64];
  2832. char testbuf2[64];
  2833. char testbuf3[64];
  2834. char testbuf4[64];
  2835. double testn;
  2836. int width;
  2837. int saved;
  2838. // Hotspots around 0.1 and 0.01
  2839. saved = -1;
  2840. for (testn = 0.09; testn <= 0.11; testn += 0.000001) {
  2841. percentf3(testbuf1, sizeof(testbuf1), testn, 1.0);
  2842. percentf3(testbuf2, sizeof(testbuf2), testn, 10.0);
  2843. width = snprintf(printbuf, sizeof(printbuf), "%10g %s %s |", testn, testbuf1, testbuf2);
  2844. if (unlikely((saved != -1) && (width != saved))) {
  2845. applog(LOG_ERR, "Test width mismatch in percentf3! %d not %d at %10g", width, saved, testn);
  2846. applog(LOG_ERR, "%s", printbuf);
  2847. }
  2848. saved = width;
  2849. }
  2850. // Hotspot around 100 (but test this in several units because format_unit2 also has unit<2 check)
  2851. saved = -1;
  2852. for (testn = 99.0; testn <= 101.0; testn += 0.0001) {
  2853. format_unit2(testbuf1, sizeof(testbuf1), true, "x", H2B_SHORT, testn , -1);
  2854. format_unit2(testbuf2, sizeof(testbuf2), true, "x", H2B_SHORT, testn * 1e3, -1);
  2855. format_unit2(testbuf3, sizeof(testbuf3), true, "x", H2B_SHORT, testn * 1e6, -1);
  2856. width = snprintf(printbuf, sizeof(printbuf), "%10g %s %s %s |", testn, testbuf1, testbuf2, testbuf3);
  2857. if (unlikely((saved != -1) && (width != saved))) {
  2858. applog(LOG_ERR, "Test width mismatch in format_unit2! %d not %d at %10g", width, saved, testn);
  2859. applog(LOG_ERR, "%s", printbuf);
  2860. }
  2861. saved = width;
  2862. }
  2863. // Hotspot around unit transition boundary in pick_unit
  2864. saved = -1;
  2865. for (testn = 999.0; testn <= 1001.0; testn += 0.0001) {
  2866. format_unit2(testbuf1, sizeof(testbuf1), true, "x", H2B_SHORT, testn , -1);
  2867. format_unit2(testbuf2, sizeof(testbuf2), true, "x", H2B_SHORT, testn * 1e3, -1);
  2868. format_unit2(testbuf3, sizeof(testbuf3), true, "x", H2B_SHORT, testn * 1e6, -1);
  2869. format_unit2(testbuf4, sizeof(testbuf4), true, "x", H2B_SHORT, testn * 1e9, -1);
  2870. width = snprintf(printbuf, sizeof(printbuf), "%10g %s %s %s %s |", testn, testbuf1, testbuf2, testbuf3, testbuf4);
  2871. if (unlikely((saved != -1) && (width != saved))) {
  2872. applog(LOG_ERR, "Test width mismatch in pick_unit! %d not %d at %10g", width, saved, testn);
  2873. applog(LOG_ERR, "%s", printbuf);
  2874. }
  2875. saved = width;
  2876. }
  2877. }
  2878. #ifdef HAVE_CURSES
  2879. static void adj_width(int var, int *length);
  2880. #endif
  2881. #ifdef HAVE_CURSES
  2882. static int awidth = 1, rwidth = 1, swidth = 1, hwwidth = 1;
  2883. static
  2884. void format_statline(char *buf, size_t bufsz, const char *cHr, const char *aHr, const char *uHr, int accepted, int rejected, int stale, int wnotaccepted, int waccepted, int hwerrs, int bad_diff1, int allnonces)
  2885. {
  2886. char rejpcbuf[6];
  2887. char bnbuf[6];
  2888. adj_width(accepted, &awidth);
  2889. adj_width(rejected, &rwidth);
  2890. adj_width(stale, &swidth);
  2891. adj_width(hwerrs, &hwwidth);
  2892. percentf4(rejpcbuf, sizeof(rejpcbuf), wnotaccepted, waccepted);
  2893. percentf3(bnbuf, sizeof(bnbuf), bad_diff1, allnonces);
  2894. tailsprintf(buf, bufsz, "%s/%s/%s | A:%*d R:%*d+%*d(%s) HW:%*d/%s",
  2895. cHr, aHr, uHr,
  2896. awidth, accepted,
  2897. rwidth, rejected,
  2898. swidth, stale,
  2899. rejpcbuf,
  2900. hwwidth, hwerrs,
  2901. bnbuf
  2902. );
  2903. }
  2904. #endif
  2905. static inline
  2906. void temperature_column(char *buf, size_t bufsz, bool maybe_unicode, const float * const temp)
  2907. {
  2908. if (!(use_unicode && have_unicode_degrees))
  2909. maybe_unicode = false;
  2910. if (temp && *temp > 0.)
  2911. if (maybe_unicode)
  2912. snprintf(buf, bufsz, "%4.1f"U8_DEGREE"C", *temp);
  2913. else
  2914. snprintf(buf, bufsz, "%4.1fC", *temp);
  2915. else
  2916. {
  2917. if (temp)
  2918. snprintf(buf, bufsz, " ");
  2919. if (maybe_unicode)
  2920. tailsprintf(buf, bufsz, " ");
  2921. }
  2922. tailsprintf(buf, bufsz, " | ");
  2923. }
  2924. void get_statline3(char *buf, size_t bufsz, struct cgpu_info *cgpu, bool for_curses, bool opt_show_procs)
  2925. {
  2926. #ifndef HAVE_CURSES
  2927. assert(for_curses == false);
  2928. #endif
  2929. struct device_drv *drv = cgpu->drv;
  2930. enum h2bs_fmt hashrate_style = for_curses ? H2B_SHORT : H2B_SPACED;
  2931. char cHr[h2bs_fmt_size[H2B_NOUNIT]], aHr[h2bs_fmt_size[H2B_NOUNIT]], uHr[h2bs_fmt_size[hashrate_style]];
  2932. char rejpcbuf[6];
  2933. char bnbuf[6];
  2934. double dev_runtime;
  2935. if (!opt_show_procs)
  2936. cgpu = cgpu->device;
  2937. dev_runtime = cgpu_runtime(cgpu);
  2938. double rolling, mhashes;
  2939. int accepted, rejected, stale;
  2940. double waccepted;
  2941. double wnotaccepted;
  2942. int hwerrs;
  2943. double bad_diff1, good_diff1;
  2944. rolling = mhashes = waccepted = wnotaccepted = 0;
  2945. accepted = rejected = stale = hwerrs = bad_diff1 = good_diff1 = 0;
  2946. {
  2947. struct cgpu_info *slave = cgpu;
  2948. for (int i = 0; i < cgpu->procs; ++i, (slave = slave->next_proc))
  2949. {
  2950. slave->utility = slave->accepted / dev_runtime * 60;
  2951. slave->utility_diff1 = slave->diff_accepted / dev_runtime * 60;
  2952. rolling += slave->rolling;
  2953. mhashes += slave->total_mhashes;
  2954. if (opt_weighed_stats)
  2955. {
  2956. accepted += slave->diff_accepted;
  2957. rejected += slave->diff_rejected;
  2958. stale += slave->diff_stale;
  2959. }
  2960. else
  2961. {
  2962. accepted += slave->accepted;
  2963. rejected += slave->rejected;
  2964. stale += slave->stale;
  2965. }
  2966. waccepted += slave->diff_accepted;
  2967. wnotaccepted += slave->diff_rejected + slave->diff_stale;
  2968. hwerrs += slave->hw_errors;
  2969. bad_diff1 += slave->bad_diff1;
  2970. good_diff1 += slave->diff1;
  2971. if (opt_show_procs)
  2972. break;
  2973. }
  2974. }
  2975. double wtotal = (waccepted + wnotaccepted);
  2976. multi_format_unit_array2(
  2977. ((char*[]){cHr, aHr, uHr}),
  2978. ((size_t[]){h2bs_fmt_size[H2B_NOUNIT], h2bs_fmt_size[H2B_NOUNIT], h2bs_fmt_size[hashrate_style]}),
  2979. true, "h/s", hashrate_style,
  2980. 3,
  2981. 1e6*rolling,
  2982. 1e6*mhashes / dev_runtime,
  2983. utility_to_hashrate(good_diff1 * (wtotal ? (waccepted / wtotal) : 1) * 60 / dev_runtime));
  2984. // Processor representation
  2985. #ifdef HAVE_CURSES
  2986. if (for_curses)
  2987. {
  2988. if (opt_show_procs)
  2989. snprintf(buf, bufsz, " %"PRIprepr": ", cgpu->proc_repr);
  2990. else
  2991. snprintf(buf, bufsz, " %s: ", cgpu->dev_repr);
  2992. }
  2993. else
  2994. #endif
  2995. snprintf(buf, bufsz, "%s ", opt_show_procs ? cgpu->proc_repr_ns : cgpu->dev_repr_ns);
  2996. if (unlikely(cgpu->status == LIFE_INIT))
  2997. {
  2998. tailsprintf(buf, bufsz, "Initializing...");
  2999. return;
  3000. }
  3001. {
  3002. const size_t bufln = strlen(buf);
  3003. const size_t abufsz = (bufln >= bufsz) ? 0 : (bufsz - bufln);
  3004. if (likely(cgpu->status != LIFE_DEAD2) && drv->override_statline_temp2 && drv->override_statline_temp2(buf, bufsz, cgpu, opt_show_procs))
  3005. temperature_column(&buf[bufln], abufsz, for_curses, NULL);
  3006. else
  3007. {
  3008. float temp = cgpu->temp;
  3009. if (!opt_show_procs)
  3010. {
  3011. // Find the highest temperature of all processors
  3012. struct cgpu_info *proc = cgpu;
  3013. for (int i = 0; i < cgpu->procs; ++i, (proc = proc->next_proc))
  3014. if (proc->temp > temp)
  3015. temp = proc->temp;
  3016. }
  3017. temperature_column(&buf[bufln], abufsz, for_curses, &temp);
  3018. }
  3019. }
  3020. #ifdef HAVE_CURSES
  3021. if (for_curses)
  3022. {
  3023. const char *cHrStatsOpt[] = {AS_BAD("DEAD "), AS_BAD("SICK "), "OFF ", AS_BAD("REST "), AS_BAD(" ERR "), AS_BAD("WAIT "), cHr};
  3024. const char *cHrStats;
  3025. int cHrStatsI = (sizeof(cHrStatsOpt) / sizeof(*cHrStatsOpt)) - 1;
  3026. bool all_dead = true, all_off = true, all_rdrv = true;
  3027. struct cgpu_info *proc = cgpu;
  3028. for (int i = 0; i < cgpu->procs; ++i, (proc = proc->next_proc))
  3029. {
  3030. switch (cHrStatsI) {
  3031. default:
  3032. if (proc->status == LIFE_WAIT)
  3033. cHrStatsI = 5;
  3034. case 5:
  3035. if (proc->deven == DEV_RECOVER_ERR)
  3036. cHrStatsI = 4;
  3037. case 4:
  3038. if (proc->deven == DEV_RECOVER)
  3039. cHrStatsI = 3;
  3040. case 3:
  3041. if (proc->status == LIFE_SICK || proc->status == LIFE_DEAD || proc->status == LIFE_DEAD2)
  3042. {
  3043. cHrStatsI = 1;
  3044. all_off = false;
  3045. }
  3046. else
  3047. {
  3048. if (likely(proc->deven == DEV_ENABLED))
  3049. all_off = false;
  3050. if (proc->deven != DEV_RECOVER_DRV)
  3051. all_rdrv = false;
  3052. }
  3053. case 1:
  3054. break;
  3055. }
  3056. if (likely(proc->status != LIFE_DEAD && proc->status != LIFE_DEAD2))
  3057. all_dead = false;
  3058. if (opt_show_procs)
  3059. break;
  3060. }
  3061. if (unlikely(all_dead))
  3062. cHrStatsI = 0;
  3063. else
  3064. if (unlikely(all_off))
  3065. cHrStatsI = 2;
  3066. cHrStats = cHrStatsOpt[cHrStatsI];
  3067. if (cHrStatsI == 2 && all_rdrv)
  3068. cHrStats = " RST ";
  3069. format_statline(buf, bufsz,
  3070. cHrStats,
  3071. aHr, uHr,
  3072. accepted, rejected, stale,
  3073. wnotaccepted, waccepted,
  3074. hwerrs,
  3075. bad_diff1, bad_diff1 + good_diff1);
  3076. }
  3077. else
  3078. #endif
  3079. {
  3080. percentf4(rejpcbuf, sizeof(rejpcbuf), wnotaccepted, waccepted);
  3081. percentf4(bnbuf, sizeof(bnbuf), bad_diff1, good_diff1);
  3082. tailsprintf(buf, bufsz, "%ds:%s avg:%s u:%s | A:%d R:%d+%d(%s) HW:%d/%s",
  3083. opt_log_interval,
  3084. cHr, aHr, uHr,
  3085. accepted,
  3086. rejected,
  3087. stale,
  3088. rejpcbuf,
  3089. hwerrs,
  3090. bnbuf
  3091. );
  3092. }
  3093. }
  3094. #define get_statline(buf, bufsz, cgpu) get_statline3(buf, bufsz, cgpu, false, opt_show_procs)
  3095. #define get_statline2(buf, bufsz, cgpu, for_curses) get_statline3(buf, bufsz, cgpu, for_curses, opt_show_procs)
  3096. static void text_print_status(int thr_id)
  3097. {
  3098. struct cgpu_info *cgpu;
  3099. char logline[256];
  3100. cgpu = get_thr_cgpu(thr_id);
  3101. if (cgpu) {
  3102. get_statline(logline, sizeof(logline), cgpu);
  3103. printf("%s\n", logline);
  3104. }
  3105. }
  3106. #ifdef HAVE_CURSES
  3107. static int attr_bad = A_BOLD;
  3108. #ifdef WIN32
  3109. #define swprintf snwprintf
  3110. #endif
  3111. static
  3112. void bfg_waddstr(WINDOW *win, const char *s)
  3113. {
  3114. const char *p = s;
  3115. int32_t w;
  3116. int wlen;
  3117. unsigned char stop_ascii = (use_unicode ? '|' : 0x80);
  3118. while (true)
  3119. {
  3120. while (likely(p[0] == '\n' || (p[0] >= 0x20 && p[0] < stop_ascii)))
  3121. {
  3122. // Printable ASCII
  3123. ++p;
  3124. }
  3125. if (p != s)
  3126. waddnstr(win, s, p - s);
  3127. w = utf8_decode(p, &wlen);
  3128. if (unlikely(p[0] == '\xb5')) // HACK for Mu (SI prefix micro-)
  3129. {
  3130. w = unicode_micro;
  3131. wlen = 1;
  3132. }
  3133. s = p += wlen;
  3134. switch(w)
  3135. {
  3136. // NOTE: U+F000-U+F7FF are reserved for font hacks
  3137. case '\0':
  3138. return;
  3139. case 0xf000: // "bad" off
  3140. wattroff(win, attr_bad);
  3141. break;
  3142. case 0xf001: // "bad" on
  3143. wattron(win, attr_bad);
  3144. break;
  3145. #ifdef USE_UNICODE
  3146. case '|':
  3147. wadd_wch(win, WACS_VLINE);
  3148. break;
  3149. #endif
  3150. case 0x2500: // BOX DRAWINGS LIGHT HORIZONTAL
  3151. case 0x2534: // BOX DRAWINGS LIGHT UP AND HORIZONTAL
  3152. if (!use_unicode)
  3153. {
  3154. waddch(win, '-');
  3155. break;
  3156. }
  3157. #ifdef USE_UNICODE
  3158. wadd_wch(win, (w == 0x2500) ? WACS_HLINE : WACS_BTEE);
  3159. break;
  3160. #endif
  3161. case 0x2022:
  3162. if (w > WCHAR_MAX || !iswprint(w))
  3163. w = '*';
  3164. default:
  3165. if (w > WCHAR_MAX || !(iswprint(w) || w == '\n'))
  3166. {
  3167. #if REPLACEMENT_CHAR <= WCHAR_MAX
  3168. if (iswprint(REPLACEMENT_CHAR))
  3169. w = REPLACEMENT_CHAR;
  3170. else
  3171. #endif
  3172. w = '?';
  3173. }
  3174. {
  3175. #ifdef USE_UNICODE
  3176. wchar_t wbuf[0x10];
  3177. int wbuflen = sizeof(wbuf) / sizeof(*wbuf);
  3178. wbuflen = swprintf(wbuf, wbuflen, L"%lc", (wint_t)w);
  3179. waddnwstr(win, wbuf, wbuflen);
  3180. #else
  3181. wprintw(win, "%lc", (wint_t)w);
  3182. #endif
  3183. }
  3184. }
  3185. }
  3186. }
  3187. static inline
  3188. void bfg_hline(WINDOW *win, int y)
  3189. {
  3190. int maxx, __maybe_unused maxy;
  3191. getmaxyx(win, maxy, maxx);
  3192. #ifdef USE_UNICODE
  3193. if (use_unicode)
  3194. mvwhline_set(win, y, 0, WACS_HLINE, maxx);
  3195. else
  3196. #endif
  3197. mvwhline(win, y, 0, '-', maxx);
  3198. }
  3199. // Spaces until end of line, using current attributes (ie, not completely clear)
  3200. static
  3201. void bfg_wspctoeol(WINDOW * const win, const int offset)
  3202. {
  3203. int x, maxx;
  3204. int __maybe_unused y;
  3205. getmaxyx(win, y, maxx);
  3206. getyx(win, y, x);
  3207. const int space_count = (maxx - x) - offset;
  3208. // Check for negative - terminal too narrow
  3209. if (space_count <= 0)
  3210. return;
  3211. char buf[space_count];
  3212. memset(buf, ' ', space_count);
  3213. waddnstr(win, buf, space_count);
  3214. }
  3215. static int menu_attr = A_REVERSE;
  3216. #define CURBUFSIZ 256
  3217. #define cg_mvwprintw(win, y, x, fmt, ...) do { \
  3218. char tmp42[CURBUFSIZ]; \
  3219. snprintf(tmp42, sizeof(tmp42), fmt, ##__VA_ARGS__); \
  3220. wmove(win, y, x); \
  3221. bfg_waddstr(win, tmp42); \
  3222. } while (0)
  3223. #define cg_wprintw(win, fmt, ...) do { \
  3224. char tmp42[CURBUFSIZ]; \
  3225. snprintf(tmp42, sizeof(tmp42), fmt, ##__VA_ARGS__); \
  3226. bfg_waddstr(win, tmp42); \
  3227. } while (0)
  3228. /* Must be called with curses mutex lock held and curses_active */
  3229. static void curses_print_status(const int ts)
  3230. {
  3231. struct pool *pool = currentpool;
  3232. struct timeval now, tv;
  3233. float efficiency;
  3234. double income;
  3235. int logdiv;
  3236. efficiency = total_bytes_xfer ? total_diff_accepted * 2048. / total_bytes_xfer : 0.0;
  3237. wattron(statuswin, attr_title);
  3238. cg_mvwprintw(statuswin, 0, 0, " " PACKAGE " version " VERSION " - Started: %s", datestamp);
  3239. timer_set_now(&now);
  3240. {
  3241. unsigned int days, hours;
  3242. div_t d;
  3243. timersub(&now, &miner_started, &tv);
  3244. d = div(tv.tv_sec, 86400);
  3245. days = d.quot;
  3246. d = div(d.rem, 3600);
  3247. hours = d.quot;
  3248. d = div(d.rem, 60);
  3249. cg_wprintw(statuswin, " - [%3u day%c %02d:%02d:%02d]"
  3250. , days
  3251. , (days == 1) ? ' ' : 's'
  3252. , hours
  3253. , d.quot
  3254. , d.rem
  3255. );
  3256. }
  3257. bfg_wspctoeol(statuswin, 0);
  3258. wattroff(statuswin, attr_title);
  3259. wattron(statuswin, menu_attr);
  3260. wmove(statuswin, 1, 0);
  3261. bfg_waddstr(statuswin, " [M]anage devices [P]ool management [S]ettings [D]isplay options ");
  3262. bfg_wspctoeol(statuswin, 14);
  3263. bfg_waddstr(statuswin, "[H]elp [Q]uit ");
  3264. wattroff(statuswin, menu_attr);
  3265. if ((pool_strategy == POOL_LOADBALANCE || pool_strategy == POOL_BALANCE) && total_pools > 1) {
  3266. cg_mvwprintw(statuswin, 2, 0, " Connected to multiple pools with%s block change notify",
  3267. have_longpoll ? "": "out");
  3268. } else if (pool->has_stratum) {
  3269. cg_mvwprintw(statuswin, 2, 0, " Connected to %s diff %s with stratum as user %s",
  3270. pool->sockaddr_url, pool->diff, pool->rpc_user);
  3271. } else {
  3272. cg_mvwprintw(statuswin, 2, 0, " Connected to %s diff %s with%s LP as user %s",
  3273. pool->sockaddr_url, pool->diff, have_longpoll ? "": "out", pool->rpc_user);
  3274. }
  3275. wclrtoeol(statuswin);
  3276. cg_mvwprintw(statuswin, 3, 0, " Block: %s Diff:%s (%s) Started: %s",
  3277. current_hash, block_diff, net_hashrate, blocktime);
  3278. income = total_diff_accepted * 3600 * block_subsidy / total_secs / current_diff;
  3279. char bwstr[12], incomestr[13];
  3280. format_unit3(incomestr, sizeof(incomestr), FUP_BTC, "BTC/hr", H2B_SHORT, income/1e8, -1);
  3281. cg_mvwprintw(statuswin, 4, 0, " ST:%d F:%d NB:%d AS:%d BW:[%s] E:%.2f I:%s BS:%s",
  3282. ts,
  3283. total_go + total_ro,
  3284. new_blocks,
  3285. total_submitting,
  3286. multi_format_unit2(bwstr, sizeof(bwstr),
  3287. false, "B/s", H2B_SHORT, "/", 2,
  3288. (float)(total_bytes_rcvd / total_secs),
  3289. (float)(total_bytes_sent / total_secs)),
  3290. efficiency,
  3291. incomestr,
  3292. best_share);
  3293. wclrtoeol(statuswin);
  3294. mvwaddstr(statuswin, 5, 0, " ");
  3295. bfg_waddstr(statuswin, statusline);
  3296. wclrtoeol(statuswin);
  3297. logdiv = statusy - 1;
  3298. bfg_hline(statuswin, 6);
  3299. bfg_hline(statuswin, logdiv);
  3300. #ifdef USE_UNICODE
  3301. if (use_unicode)
  3302. {
  3303. int offset = 8 /* device */ + 5 /* temperature */ + 1 /* padding space */;
  3304. if (opt_show_procs && !opt_compact)
  3305. ++offset; // proc letter
  3306. if (have_unicode_degrees)
  3307. ++offset; // degrees symbol
  3308. mvwadd_wch(statuswin, 6, offset, WACS_PLUS);
  3309. mvwadd_wch(statuswin, logdiv, offset, WACS_BTEE);
  3310. offset += 24; // hashrates etc
  3311. mvwadd_wch(statuswin, 6, offset, WACS_PLUS);
  3312. mvwadd_wch(statuswin, logdiv, offset, WACS_BTEE);
  3313. }
  3314. #endif
  3315. }
  3316. static void adj_width(int var, int *length)
  3317. {
  3318. if ((int)(log10(var) + 1) > *length)
  3319. (*length)++;
  3320. }
  3321. static int dev_width;
  3322. static void curses_print_devstatus(struct cgpu_info *cgpu)
  3323. {
  3324. char logline[256];
  3325. int ypos;
  3326. if (opt_compact)
  3327. return;
  3328. /* Check this isn't out of the window size */
  3329. if (opt_show_procs)
  3330. ypos = cgpu->cgminer_id;
  3331. else
  3332. {
  3333. if (cgpu->proc_id)
  3334. return;
  3335. ypos = cgpu->device_line_id;
  3336. }
  3337. ypos += devsummaryYOffset;
  3338. if (ypos < 0)
  3339. return;
  3340. ypos += devcursor - 1;
  3341. if (ypos >= statusy - 1)
  3342. return;
  3343. if (wmove(statuswin, ypos, 0) == ERR)
  3344. return;
  3345. get_statline2(logline, sizeof(logline), cgpu, true);
  3346. if (selecting_device && (opt_show_procs ? (selected_device == cgpu->cgminer_id) : (devices[selected_device]->device == cgpu)))
  3347. wattron(statuswin, A_REVERSE);
  3348. bfg_waddstr(statuswin, logline);
  3349. wattroff(statuswin, A_REVERSE);
  3350. wclrtoeol(statuswin);
  3351. }
  3352. static
  3353. void _refresh_devstatus(const bool already_have_lock) {
  3354. if ((!opt_compact) && (already_have_lock || curses_active_locked())) {
  3355. int i;
  3356. if (unlikely(!total_devices))
  3357. {
  3358. const int ypos = devcursor - 1;
  3359. if (ypos < statusy - 1 && wmove(statuswin, ypos, 0) != ERR)
  3360. {
  3361. wattron(statuswin, attr_bad);
  3362. bfg_waddstr(statuswin, "NO DEVICES FOUND: Press 'M' and '+' to add");
  3363. wclrtoeol(statuswin);
  3364. wattroff(statuswin, attr_bad);
  3365. }
  3366. }
  3367. for (i = 0; i < total_devices; i++)
  3368. curses_print_devstatus(get_devices(i));
  3369. touchwin(statuswin);
  3370. wrefresh(statuswin);
  3371. if (!already_have_lock)
  3372. unlock_curses();
  3373. }
  3374. }
  3375. #define refresh_devstatus() _refresh_devstatus(false)
  3376. #endif
  3377. static void print_status(int thr_id)
  3378. {
  3379. if (!curses_active)
  3380. text_print_status(thr_id);
  3381. }
  3382. #ifdef HAVE_CURSES
  3383. static
  3384. bool set_statusy(int maxy)
  3385. {
  3386. if (loginput_size)
  3387. {
  3388. maxy -= loginput_size;
  3389. if (maxy < 0)
  3390. maxy = 0;
  3391. }
  3392. if (logstart < maxy)
  3393. maxy = logstart;
  3394. if (statusy == maxy)
  3395. return false;
  3396. statusy = maxy;
  3397. logcursor = statusy;
  3398. return true;
  3399. }
  3400. /* Check for window resize. Called with curses mutex locked */
  3401. static inline void change_logwinsize(void)
  3402. {
  3403. int x, y, logx, logy;
  3404. getmaxyx(mainwin, y, x);
  3405. if (x < 80 || y < 25)
  3406. return;
  3407. if (y > statusy + 2 && statusy < logstart) {
  3408. set_statusy(y - 2);
  3409. mvwin(logwin, logcursor, 0);
  3410. bfg_wresize(statuswin, statusy, x);
  3411. }
  3412. y -= logcursor;
  3413. getmaxyx(logwin, logy, logx);
  3414. /* Detect screen size change */
  3415. if (x != logx || y != logy)
  3416. bfg_wresize(logwin, y, x);
  3417. }
  3418. static void check_winsizes(void)
  3419. {
  3420. if (!use_curses)
  3421. return;
  3422. if (curses_active_locked()) {
  3423. int y, x;
  3424. x = getmaxx(statuswin);
  3425. if (set_statusy(LINES - 2))
  3426. {
  3427. erase();
  3428. bfg_wresize(statuswin, statusy, x);
  3429. getmaxyx(mainwin, y, x);
  3430. y -= logcursor;
  3431. bfg_wresize(logwin, y, x);
  3432. mvwin(logwin, logcursor, 0);
  3433. }
  3434. unlock_curses();
  3435. }
  3436. }
  3437. static int device_line_id_count;
  3438. static void switch_logsize(void)
  3439. {
  3440. if (curses_active_locked()) {
  3441. if (opt_compact) {
  3442. logstart = devcursor - 1;
  3443. logcursor = logstart + 1;
  3444. } else {
  3445. total_lines = (opt_show_procs ? total_devices : device_line_id_count) ?: 1;
  3446. logstart = devcursor + total_lines;
  3447. logcursor = logstart;
  3448. }
  3449. unlock_curses();
  3450. }
  3451. check_winsizes();
  3452. }
  3453. /* For mandatory printing when mutex is already locked */
  3454. void _wlog(const char *str)
  3455. {
  3456. static bool newline;
  3457. size_t end = strlen(str) - 1;
  3458. if (newline)
  3459. bfg_waddstr(logwin, "\n");
  3460. if (str[end] == '\n')
  3461. {
  3462. char *s;
  3463. newline = true;
  3464. s = alloca(end + 1);
  3465. memcpy(s, str, end);
  3466. s[end] = '\0';
  3467. str = s;
  3468. }
  3469. else
  3470. newline = false;
  3471. bfg_waddstr(logwin, str);
  3472. }
  3473. /* Mandatory printing */
  3474. void _wlogprint(const char *str)
  3475. {
  3476. if (curses_active_locked()) {
  3477. _wlog(str);
  3478. unlock_curses();
  3479. }
  3480. }
  3481. #endif
  3482. #ifdef HAVE_CURSES
  3483. bool _log_curses_only(int prio, const char *datetime, const char *str)
  3484. {
  3485. bool high_prio;
  3486. high_prio = (prio == LOG_WARNING || prio == LOG_ERR);
  3487. if (curses_active)
  3488. {
  3489. if (!loginput_size || high_prio) {
  3490. wlog(" %s %s\n", datetime, str);
  3491. if (high_prio) {
  3492. touchwin(logwin);
  3493. wrefresh(logwin);
  3494. }
  3495. }
  3496. return true;
  3497. }
  3498. return false;
  3499. }
  3500. void clear_logwin(void)
  3501. {
  3502. if (curses_active_locked()) {
  3503. wclear(logwin);
  3504. unlock_curses();
  3505. }
  3506. }
  3507. void logwin_update(void)
  3508. {
  3509. if (curses_active_locked()) {
  3510. touchwin(logwin);
  3511. wrefresh(logwin);
  3512. unlock_curses();
  3513. }
  3514. }
  3515. #endif
  3516. static void enable_pool(struct pool *pool)
  3517. {
  3518. if (pool->enabled != POOL_ENABLED) {
  3519. enabled_pools++;
  3520. pool->enabled = POOL_ENABLED;
  3521. }
  3522. }
  3523. #ifdef HAVE_CURSES
  3524. static void disable_pool(struct pool *pool)
  3525. {
  3526. if (pool->enabled == POOL_ENABLED)
  3527. enabled_pools--;
  3528. pool->enabled = POOL_DISABLED;
  3529. }
  3530. #endif
  3531. static void reject_pool(struct pool *pool)
  3532. {
  3533. if (pool->enabled == POOL_ENABLED)
  3534. enabled_pools--;
  3535. pool->enabled = POOL_REJECTING;
  3536. }
  3537. static uint64_t share_diff(const struct work *);
  3538. static
  3539. void share_result_msg(const struct work *work, const char *disp, const char *reason, bool resubmit, const char *worktime) {
  3540. struct cgpu_info *cgpu;
  3541. const unsigned char *hashpart = &work->hash[opt_scrypt ? 26 : 24];
  3542. char shrdiffdisp[16];
  3543. int tgtdiff = floor(work->work_difficulty);
  3544. char tgtdiffdisp[16];
  3545. char where[20];
  3546. cgpu = get_thr_cgpu(work->thr_id);
  3547. suffix_string(work->share_diff, shrdiffdisp, sizeof(shrdiffdisp), 0);
  3548. suffix_string(tgtdiff, tgtdiffdisp, sizeof(tgtdiffdisp), 0);
  3549. if (total_pools > 1)
  3550. snprintf(where, sizeof(where), " pool %d", work->pool->pool_no);
  3551. else
  3552. where[0] = '\0';
  3553. applog(LOG_NOTICE, "%s %02x%02x%02x%02x %"PRIprepr"%s Diff %s/%s%s %s%s",
  3554. disp,
  3555. (unsigned)hashpart[3], (unsigned)hashpart[2], (unsigned)hashpart[1], (unsigned)hashpart[0],
  3556. cgpu->proc_repr,
  3557. where,
  3558. shrdiffdisp, tgtdiffdisp,
  3559. reason,
  3560. resubmit ? "(resubmit)" : "",
  3561. worktime
  3562. );
  3563. }
  3564. static bool test_work_current(struct work *);
  3565. static void _submit_work_async(struct work *);
  3566. static
  3567. void maybe_local_submit(const struct work *work)
  3568. {
  3569. #if BLKMAKER_VERSION > 3
  3570. if (unlikely(work->block && work->tmpl))
  3571. {
  3572. // This is a block with a full template (GBT)
  3573. // Regardless of the result, submit to local bitcoind(s) as well
  3574. struct work *work_cp;
  3575. char *p;
  3576. for (int i = 0; i < total_pools; ++i)
  3577. {
  3578. p = strchr(pools[i]->rpc_url, '#');
  3579. if (likely(!(p && strstr(&p[1], "allblocks"))))
  3580. continue;
  3581. applog(LOG_DEBUG, "Attempting submission of full block to pool %d", pools[i]->pool_no);
  3582. work_cp = copy_work(work);
  3583. work_cp->pool = pools[i];
  3584. work_cp->do_foreign_submit = true;
  3585. _submit_work_async(work_cp);
  3586. }
  3587. }
  3588. #endif
  3589. }
  3590. /* Theoretically threads could race when modifying accepted and
  3591. * rejected values but the chance of two submits completing at the
  3592. * same time is zero so there is no point adding extra locking */
  3593. static void
  3594. share_result(json_t *val, json_t *res, json_t *err, const struct work *work,
  3595. /*char *hashshow,*/ bool resubmit, char *worktime)
  3596. {
  3597. struct pool *pool = work->pool;
  3598. struct cgpu_info *cgpu;
  3599. cgpu = get_thr_cgpu(work->thr_id);
  3600. if ((json_is_null(err) || !err) && (json_is_null(res) || json_is_true(res))) {
  3601. mutex_lock(&stats_lock);
  3602. cgpu->accepted++;
  3603. total_accepted++;
  3604. pool->accepted++;
  3605. cgpu->diff_accepted += work->work_difficulty;
  3606. total_diff_accepted += work->work_difficulty;
  3607. pool->diff_accepted += work->work_difficulty;
  3608. mutex_unlock(&stats_lock);
  3609. pool->seq_rejects = 0;
  3610. cgpu->last_share_pool = pool->pool_no;
  3611. cgpu->last_share_pool_time = time(NULL);
  3612. cgpu->last_share_diff = work->work_difficulty;
  3613. pool->last_share_time = cgpu->last_share_pool_time;
  3614. pool->last_share_diff = work->work_difficulty;
  3615. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  3616. if (!QUIET) {
  3617. share_result_msg(work, "Accepted", "", resubmit, worktime);
  3618. }
  3619. sharelog("accept", work);
  3620. if (opt_shares && total_diff_accepted >= opt_shares) {
  3621. applog(LOG_WARNING, "Successfully mined %d accepted shares as requested and exiting.", opt_shares);
  3622. kill_work();
  3623. return;
  3624. }
  3625. /* Detect if a pool that has been temporarily disabled for
  3626. * continually rejecting shares has started accepting shares.
  3627. * This will only happen with the work returned from a
  3628. * longpoll */
  3629. if (unlikely(pool->enabled == POOL_REJECTING)) {
  3630. applog(LOG_WARNING, "Rejecting pool %d now accepting shares, re-enabling!", pool->pool_no);
  3631. enable_pool(pool);
  3632. switch_pools(NULL);
  3633. }
  3634. if (unlikely(work->block)) {
  3635. // Force moving on to this new block :)
  3636. struct work fakework;
  3637. memset(&fakework, 0, sizeof(fakework));
  3638. fakework.pool = work->pool;
  3639. // Copy block version, bits, and time from share
  3640. memcpy(&fakework.data[ 0], &work->data[ 0], 4);
  3641. memcpy(&fakework.data[68], &work->data[68], 8);
  3642. // Set prevblock to winning hash (swap32'd)
  3643. swap32yes(&fakework.data[4], &work->hash[0], 32 / 4);
  3644. test_work_current(&fakework);
  3645. }
  3646. } else {
  3647. mutex_lock(&stats_lock);
  3648. cgpu->rejected++;
  3649. total_rejected++;
  3650. pool->rejected++;
  3651. cgpu->diff_rejected += work->work_difficulty;
  3652. total_diff_rejected += work->work_difficulty;
  3653. pool->diff_rejected += work->work_difficulty;
  3654. pool->seq_rejects++;
  3655. mutex_unlock(&stats_lock);
  3656. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  3657. if (!QUIET) {
  3658. char where[20];
  3659. char disposition[36] = "reject";
  3660. char reason[32];
  3661. strcpy(reason, "");
  3662. if (total_pools > 1)
  3663. snprintf(where, sizeof(where), "pool %d", work->pool->pool_no);
  3664. else
  3665. strcpy(where, "");
  3666. if (!json_is_string(res))
  3667. res = json_object_get(val, "reject-reason");
  3668. if (res) {
  3669. const char *reasontmp = json_string_value(res);
  3670. size_t reasonLen = strlen(reasontmp);
  3671. if (reasonLen > 28)
  3672. reasonLen = 28;
  3673. reason[0] = ' '; reason[1] = '(';
  3674. memcpy(2 + reason, reasontmp, reasonLen);
  3675. reason[reasonLen + 2] = ')'; reason[reasonLen + 3] = '\0';
  3676. memcpy(disposition + 7, reasontmp, reasonLen);
  3677. disposition[6] = ':'; disposition[reasonLen + 7] = '\0';
  3678. } else if (work->stratum && err && json_is_array(err)) {
  3679. json_t *reason_val = json_array_get(err, 1);
  3680. char *reason_str;
  3681. if (reason_val && json_is_string(reason_val)) {
  3682. reason_str = (char *)json_string_value(reason_val);
  3683. snprintf(reason, 31, " (%s)", reason_str);
  3684. }
  3685. }
  3686. share_result_msg(work, "Rejected", reason, resubmit, worktime);
  3687. sharelog(disposition, work);
  3688. }
  3689. /* Once we have more than a nominal amount of sequential rejects,
  3690. * at least 10 and more than 3 mins at the current utility,
  3691. * disable the pool because some pool error is likely to have
  3692. * ensued. Do not do this if we know the share just happened to
  3693. * be stale due to networking delays.
  3694. */
  3695. if (pool->seq_rejects > 10 && !work->stale && opt_disable_pool && enabled_pools > 1) {
  3696. double utility = total_accepted / total_secs * 60;
  3697. if (pool->seq_rejects > utility * 3) {
  3698. applog(LOG_WARNING, "Pool %d rejected %d sequential shares, disabling!",
  3699. pool->pool_no, pool->seq_rejects);
  3700. reject_pool(pool);
  3701. if (pool == current_pool())
  3702. switch_pools(NULL);
  3703. pool->seq_rejects = 0;
  3704. }
  3705. }
  3706. }
  3707. maybe_local_submit(work);
  3708. }
  3709. static char *submit_upstream_work_request(struct work *work)
  3710. {
  3711. char *hexstr = NULL;
  3712. char *s, *sd;
  3713. struct pool *pool = work->pool;
  3714. if (work->tmpl) {
  3715. json_t *req;
  3716. unsigned char data[80];
  3717. swap32yes(data, work->data, 80 / 4);
  3718. #if BLKMAKER_VERSION > 3
  3719. if (work->do_foreign_submit)
  3720. req = blkmk_submit_foreign_jansson(work->tmpl, data, work->dataid, le32toh(*((uint32_t*)&work->data[76])));
  3721. else
  3722. #endif
  3723. req = blkmk_submit_jansson(work->tmpl, data, work->dataid, le32toh(*((uint32_t*)&work->data[76])));
  3724. s = json_dumps(req, 0);
  3725. json_decref(req);
  3726. sd = malloc(161);
  3727. bin2hex(sd, data, 80);
  3728. } else {
  3729. /* build hex string */
  3730. hexstr = malloc((sizeof(work->data) * 2) + 1);
  3731. bin2hex(hexstr, work->data, sizeof(work->data));
  3732. /* build JSON-RPC request */
  3733. s = strdup("{\"method\": \"getwork\", \"params\": [ \"");
  3734. s = realloc_strcat(s, hexstr);
  3735. s = realloc_strcat(s, "\" ], \"id\":1}");
  3736. free(hexstr);
  3737. sd = s;
  3738. }
  3739. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->rpc_url, sd);
  3740. if (work->tmpl)
  3741. free(sd);
  3742. else
  3743. s = realloc_strcat(s, "\n");
  3744. return s;
  3745. }
  3746. static bool submit_upstream_work_completed(struct work *work, bool resubmit, struct timeval *ptv_submit, json_t *val) {
  3747. json_t *res, *err;
  3748. bool rc = false;
  3749. int thr_id = work->thr_id;
  3750. struct pool *pool = work->pool;
  3751. struct timeval tv_submit_reply;
  3752. time_t ts_submit_reply;
  3753. char worktime[200] = "";
  3754. cgtime(&tv_submit_reply);
  3755. ts_submit_reply = time(NULL);
  3756. if (unlikely(!val)) {
  3757. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  3758. if (!pool_tset(pool, &pool->submit_fail)) {
  3759. total_ro++;
  3760. pool->remotefail_occasions++;
  3761. applog(LOG_WARNING, "Pool %d communication failure, caching submissions", pool->pool_no);
  3762. }
  3763. goto out;
  3764. } else if (pool_tclear(pool, &pool->submit_fail))
  3765. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  3766. res = json_object_get(val, "result");
  3767. err = json_object_get(val, "error");
  3768. if (!QUIET) {
  3769. if (opt_worktime) {
  3770. char workclone[20];
  3771. struct tm _tm;
  3772. struct tm *tm, tm_getwork, tm_submit_reply;
  3773. tm = &_tm;
  3774. double getwork_time = tdiff((struct timeval *)&(work->tv_getwork_reply),
  3775. (struct timeval *)&(work->tv_getwork));
  3776. double getwork_to_work = tdiff((struct timeval *)&(work->tv_work_start),
  3777. (struct timeval *)&(work->tv_getwork_reply));
  3778. double work_time = tdiff((struct timeval *)&(work->tv_work_found),
  3779. (struct timeval *)&(work->tv_work_start));
  3780. double work_to_submit = tdiff(ptv_submit,
  3781. (struct timeval *)&(work->tv_work_found));
  3782. double submit_time = tdiff(&tv_submit_reply, ptv_submit);
  3783. int diffplaces = 3;
  3784. localtime_r(&work->ts_getwork, tm);
  3785. memcpy(&tm_getwork, tm, sizeof(struct tm));
  3786. localtime_r(&ts_submit_reply, tm);
  3787. memcpy(&tm_submit_reply, tm, sizeof(struct tm));
  3788. if (work->clone) {
  3789. snprintf(workclone, sizeof(workclone), "C:%1.3f",
  3790. tdiff((struct timeval *)&(work->tv_cloned),
  3791. (struct timeval *)&(work->tv_getwork_reply)));
  3792. }
  3793. else
  3794. strcpy(workclone, "O");
  3795. if (work->work_difficulty < 1)
  3796. diffplaces = 6;
  3797. snprintf(worktime, sizeof(worktime),
  3798. " <-%08lx.%08lx M:%c D:%1.*f G:%02d:%02d:%02d:%1.3f %s (%1.3f) W:%1.3f (%1.3f) S:%1.3f R:%02d:%02d:%02d",
  3799. (unsigned long)be32toh(*(uint32_t *)&(work->data[opt_scrypt ? 32 : 28])),
  3800. (unsigned long)be32toh(*(uint32_t *)&(work->data[opt_scrypt ? 28 : 24])),
  3801. work->getwork_mode, diffplaces, work->work_difficulty,
  3802. tm_getwork.tm_hour, tm_getwork.tm_min,
  3803. tm_getwork.tm_sec, getwork_time, workclone,
  3804. getwork_to_work, work_time, work_to_submit, submit_time,
  3805. tm_submit_reply.tm_hour, tm_submit_reply.tm_min,
  3806. tm_submit_reply.tm_sec);
  3807. }
  3808. }
  3809. share_result(val, res, err, work, resubmit, worktime);
  3810. if (!opt_realquiet)
  3811. print_status(thr_id);
  3812. if (!want_per_device_stats) {
  3813. char logline[256];
  3814. struct cgpu_info *cgpu;
  3815. cgpu = get_thr_cgpu(thr_id);
  3816. get_statline(logline, sizeof(logline), cgpu);
  3817. applog(LOG_INFO, "%s", logline);
  3818. }
  3819. json_decref(val);
  3820. rc = true;
  3821. out:
  3822. return rc;
  3823. }
  3824. /* Specifies whether we can use this pool for work or not. */
  3825. static bool pool_unworkable(struct pool *pool)
  3826. {
  3827. if (pool->idle)
  3828. return true;
  3829. if (pool->enabled != POOL_ENABLED)
  3830. return true;
  3831. if (pool->has_stratum && !pool->stratum_active)
  3832. return true;
  3833. return false;
  3834. }
  3835. /* In balanced mode, the amount of diff1 solutions per pool is monitored as a
  3836. * rolling average per 10 minutes and if pools start getting more, it biases
  3837. * away from them to distribute work evenly. The share count is reset to the
  3838. * rolling average every 10 minutes to not send all work to one pool after it
  3839. * has been disabled/out for an extended period. */
  3840. static struct pool *select_balanced(struct pool *cp)
  3841. {
  3842. int i, lowest = cp->shares;
  3843. struct pool *ret = cp;
  3844. for (i = 0; i < total_pools; i++) {
  3845. struct pool *pool = pools[i];
  3846. if (pool_unworkable(pool))
  3847. continue;
  3848. if (pool->shares < lowest) {
  3849. lowest = pool->shares;
  3850. ret = pool;
  3851. }
  3852. }
  3853. ret->shares++;
  3854. return ret;
  3855. }
  3856. static bool pool_active(struct pool *, bool pinging);
  3857. static void pool_died(struct pool *);
  3858. static struct pool *priority_pool(int choice);
  3859. static bool pool_unusable(struct pool *pool);
  3860. /* Select any active pool in a rotating fashion when loadbalance is chosen if
  3861. * it has any quota left. */
  3862. static inline struct pool *select_pool(bool lagging)
  3863. {
  3864. static int rotating_pool = 0;
  3865. struct pool *pool, *cp;
  3866. bool avail = false;
  3867. int tested, i;
  3868. cp = current_pool();
  3869. retry:
  3870. if (pool_strategy == POOL_BALANCE) {
  3871. pool = select_balanced(cp);
  3872. goto out;
  3873. }
  3874. if (pool_strategy != POOL_LOADBALANCE && (!lagging || opt_fail_only)) {
  3875. pool = cp;
  3876. goto out;
  3877. } else
  3878. pool = NULL;
  3879. for (i = 0; i < total_pools; i++) {
  3880. struct pool *tp = pools[i];
  3881. if (tp->quota_used < tp->quota_gcd) {
  3882. avail = true;
  3883. break;
  3884. }
  3885. }
  3886. /* There are no pools with quota, so reset them. */
  3887. if (!avail) {
  3888. for (i = 0; i < total_pools; i++)
  3889. pools[i]->quota_used = 0;
  3890. if (++rotating_pool >= total_pools)
  3891. rotating_pool = 0;
  3892. }
  3893. /* Try to find the first pool in the rotation that is usable */
  3894. tested = 0;
  3895. while (!pool && tested++ < total_pools) {
  3896. pool = pools[rotating_pool];
  3897. if (pool->quota_used++ < pool->quota_gcd) {
  3898. if (!pool_unworkable(pool))
  3899. break;
  3900. /* Failover-only flag for load-balance means distribute
  3901. * unused quota to priority pool 0. */
  3902. if (opt_fail_only)
  3903. priority_pool(0)->quota_used--;
  3904. }
  3905. pool = NULL;
  3906. if (++rotating_pool >= total_pools)
  3907. rotating_pool = 0;
  3908. }
  3909. /* If there are no alive pools with quota, choose according to
  3910. * priority. */
  3911. if (!pool) {
  3912. for (i = 0; i < total_pools; i++) {
  3913. struct pool *tp = priority_pool(i);
  3914. if (!pool_unusable(tp)) {
  3915. pool = tp;
  3916. break;
  3917. }
  3918. }
  3919. }
  3920. /* If still nothing is usable, use the current pool */
  3921. if (!pool)
  3922. pool = cp;
  3923. out:
  3924. if (cp != pool)
  3925. {
  3926. if (!pool_active(pool, false))
  3927. {
  3928. pool_died(pool);
  3929. goto retry;
  3930. }
  3931. pool_tclear(pool, &pool->idle);
  3932. }
  3933. applog(LOG_DEBUG, "Selecting pool %d for work", pool->pool_no);
  3934. return pool;
  3935. }
  3936. static double DIFFEXACTONE = 26959946667150639794667015087019630673637144422540572481103610249215.0;
  3937. static const uint64_t diffone = 0xFFFF000000000000ull;
  3938. static double target_diff(const unsigned char *target)
  3939. {
  3940. double targ = 0;
  3941. signed int i;
  3942. for (i = 31; i >= 0; --i)
  3943. targ = (targ * 0x100) + target[i];
  3944. return DIFFEXACTONE / (targ ?: 1);
  3945. }
  3946. /*
  3947. * Calculate the work share difficulty
  3948. */
  3949. static void calc_diff(struct work *work, int known)
  3950. {
  3951. struct cgminer_pool_stats *pool_stats = &(work->pool->cgminer_pool_stats);
  3952. double difficulty;
  3953. if (!known) {
  3954. work->work_difficulty = target_diff(work->target);
  3955. } else
  3956. work->work_difficulty = known;
  3957. difficulty = work->work_difficulty;
  3958. pool_stats->last_diff = difficulty;
  3959. suffix_string((uint64_t)difficulty, work->pool->diff, sizeof(work->pool->diff), 0);
  3960. if (difficulty == pool_stats->min_diff)
  3961. pool_stats->min_diff_count++;
  3962. else if (difficulty < pool_stats->min_diff || pool_stats->min_diff == 0) {
  3963. pool_stats->min_diff = difficulty;
  3964. pool_stats->min_diff_count = 1;
  3965. }
  3966. if (difficulty == pool_stats->max_diff)
  3967. pool_stats->max_diff_count++;
  3968. else if (difficulty > pool_stats->max_diff) {
  3969. pool_stats->max_diff = difficulty;
  3970. pool_stats->max_diff_count = 1;
  3971. }
  3972. }
  3973. static void get_benchmark_work(struct work *work)
  3974. {
  3975. // Use a random work block pulled from a pool
  3976. static uint8_t bench_block[] = { CGMINER_BENCHMARK_BLOCK };
  3977. size_t bench_size = sizeof(*work);
  3978. size_t work_size = sizeof(bench_block);
  3979. size_t min_size = (work_size < bench_size ? work_size : bench_size);
  3980. memset(work, 0, sizeof(*work));
  3981. memcpy(work, &bench_block, min_size);
  3982. work->mandatory = true;
  3983. work->pool = pools[0];
  3984. cgtime(&work->tv_getwork);
  3985. copy_time(&work->tv_getwork_reply, &work->tv_getwork);
  3986. work->getwork_mode = GETWORK_MODE_BENCHMARK;
  3987. calc_diff(work, 0);
  3988. }
  3989. static void wake_gws(void);
  3990. static void update_last_work(struct work *work)
  3991. {
  3992. if (!work->tmpl)
  3993. // Only save GBT jobs, since rollntime isn't coordinated well yet
  3994. return;
  3995. struct pool *pool = work->pool;
  3996. mutex_lock(&pool->last_work_lock);
  3997. if (pool->last_work_copy)
  3998. free_work(pool->last_work_copy);
  3999. pool->last_work_copy = copy_work(work);
  4000. pool->last_work_copy->work_restart_id = pool->work_restart_id;
  4001. mutex_unlock(&pool->last_work_lock);
  4002. }
  4003. static
  4004. void gbt_req_target(json_t *req)
  4005. {
  4006. json_t *j;
  4007. json_t *n;
  4008. if (!request_target_str)
  4009. return;
  4010. j = json_object_get(req, "params");
  4011. if (!j)
  4012. {
  4013. n = json_array();
  4014. if (!n)
  4015. return;
  4016. if (json_object_set_new(req, "params", n))
  4017. goto erradd;
  4018. j = n;
  4019. }
  4020. n = json_array_get(j, 0);
  4021. if (!n)
  4022. {
  4023. n = json_object();
  4024. if (!n)
  4025. return;
  4026. if (json_array_append_new(j, n))
  4027. goto erradd;
  4028. }
  4029. j = n;
  4030. n = json_string(request_target_str);
  4031. if (!n)
  4032. return;
  4033. if (json_object_set_new(j, "target", n))
  4034. goto erradd;
  4035. return;
  4036. erradd:
  4037. json_decref(n);
  4038. }
  4039. static char *prepare_rpc_req2(struct work *work, enum pool_protocol proto, const char *lpid, bool probe)
  4040. {
  4041. char *rpc_req;
  4042. clean_work(work);
  4043. switch (proto) {
  4044. case PLP_GETWORK:
  4045. work->getwork_mode = GETWORK_MODE_POOL;
  4046. return strdup(getwork_req);
  4047. case PLP_GETBLOCKTEMPLATE:
  4048. work->getwork_mode = GETWORK_MODE_GBT;
  4049. work->tmpl_refcount = malloc(sizeof(*work->tmpl_refcount));
  4050. if (!work->tmpl_refcount)
  4051. return NULL;
  4052. work->tmpl = blktmpl_create();
  4053. if (!work->tmpl)
  4054. goto gbtfail2;
  4055. *work->tmpl_refcount = 1;
  4056. gbt_capabilities_t caps = blktmpl_addcaps(work->tmpl);
  4057. if (!caps)
  4058. goto gbtfail;
  4059. caps |= GBT_LONGPOLL;
  4060. #if BLKMAKER_VERSION > 1
  4061. if (opt_coinbase_script.sz)
  4062. caps |= GBT_CBVALUE;
  4063. #endif
  4064. json_t *req = blktmpl_request_jansson(caps, lpid);
  4065. if (!req)
  4066. goto gbtfail;
  4067. if (probe)
  4068. gbt_req_target(req);
  4069. rpc_req = json_dumps(req, 0);
  4070. if (!rpc_req)
  4071. goto gbtfail;
  4072. json_decref(req);
  4073. return rpc_req;
  4074. default:
  4075. return NULL;
  4076. }
  4077. return NULL;
  4078. gbtfail:
  4079. blktmpl_free(work->tmpl);
  4080. work->tmpl = NULL;
  4081. gbtfail2:
  4082. free(work->tmpl_refcount);
  4083. work->tmpl_refcount = NULL;
  4084. return NULL;
  4085. }
  4086. #define prepare_rpc_req(work, proto, lpid) prepare_rpc_req2(work, proto, lpid, false)
  4087. #define prepare_rpc_req_probe(work, proto, lpid) prepare_rpc_req2(work, proto, lpid, true)
  4088. static const char *pool_protocol_name(enum pool_protocol proto)
  4089. {
  4090. switch (proto) {
  4091. case PLP_GETBLOCKTEMPLATE:
  4092. return "getblocktemplate";
  4093. case PLP_GETWORK:
  4094. return "getwork";
  4095. default:
  4096. return "UNKNOWN";
  4097. }
  4098. }
  4099. static enum pool_protocol pool_protocol_fallback(enum pool_protocol proto)
  4100. {
  4101. switch (proto) {
  4102. case PLP_GETBLOCKTEMPLATE:
  4103. if (want_getwork)
  4104. return PLP_GETWORK;
  4105. default:
  4106. return PLP_NONE;
  4107. }
  4108. }
  4109. static bool get_upstream_work(struct work *work, CURL *curl)
  4110. {
  4111. struct pool *pool = work->pool;
  4112. struct cgminer_pool_stats *pool_stats = &(pool->cgminer_pool_stats);
  4113. struct timeval tv_elapsed;
  4114. json_t *val = NULL;
  4115. bool rc = false;
  4116. char *url;
  4117. enum pool_protocol proto;
  4118. char *rpc_req;
  4119. if (pool->proto == PLP_NONE)
  4120. pool->proto = PLP_GETBLOCKTEMPLATE;
  4121. tryagain:
  4122. rpc_req = prepare_rpc_req(work, pool->proto, NULL);
  4123. work->pool = pool;
  4124. if (!rpc_req)
  4125. return false;
  4126. applog(LOG_DEBUG, "DBG: sending %s get RPC call: %s", pool->rpc_url, rpc_req);
  4127. url = pool->rpc_url;
  4128. cgtime(&work->tv_getwork);
  4129. val = json_rpc_call(curl, url, pool->rpc_userpass, rpc_req, false,
  4130. false, &work->rolltime, pool, false);
  4131. pool_stats->getwork_attempts++;
  4132. free(rpc_req);
  4133. if (likely(val)) {
  4134. rc = work_decode(pool, work, val);
  4135. if (unlikely(!rc))
  4136. applog(LOG_DEBUG, "Failed to decode work in get_upstream_work");
  4137. } else if (PLP_NONE != (proto = pool_protocol_fallback(pool->proto))) {
  4138. applog(LOG_WARNING, "Pool %u failed getblocktemplate request; falling back to getwork protocol", pool->pool_no);
  4139. pool->proto = proto;
  4140. goto tryagain;
  4141. } else
  4142. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  4143. cgtime(&work->tv_getwork_reply);
  4144. timersub(&(work->tv_getwork_reply), &(work->tv_getwork), &tv_elapsed);
  4145. pool_stats->getwork_wait_rolling += ((double)tv_elapsed.tv_sec + ((double)tv_elapsed.tv_usec / 1000000)) * 0.63;
  4146. pool_stats->getwork_wait_rolling /= 1.63;
  4147. timeradd(&tv_elapsed, &(pool_stats->getwork_wait), &(pool_stats->getwork_wait));
  4148. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_max), >)) {
  4149. pool_stats->getwork_wait_max.tv_sec = tv_elapsed.tv_sec;
  4150. pool_stats->getwork_wait_max.tv_usec = tv_elapsed.tv_usec;
  4151. }
  4152. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_min), <)) {
  4153. pool_stats->getwork_wait_min.tv_sec = tv_elapsed.tv_sec;
  4154. pool_stats->getwork_wait_min.tv_usec = tv_elapsed.tv_usec;
  4155. }
  4156. pool_stats->getwork_calls++;
  4157. work->pool = pool;
  4158. work->longpoll = false;
  4159. calc_diff(work, 0);
  4160. total_getworks++;
  4161. pool->getwork_requested++;
  4162. if (rc)
  4163. update_last_work(work);
  4164. if (likely(val))
  4165. json_decref(val);
  4166. return rc;
  4167. }
  4168. #ifdef HAVE_CURSES
  4169. static void disable_curses(void)
  4170. {
  4171. if (curses_active_locked()) {
  4172. use_curses = false;
  4173. curses_active = false;
  4174. leaveok(logwin, false);
  4175. leaveok(statuswin, false);
  4176. leaveok(mainwin, false);
  4177. nocbreak();
  4178. echo();
  4179. delwin(logwin);
  4180. delwin(statuswin);
  4181. delwin(mainwin);
  4182. endwin();
  4183. #ifdef WIN32
  4184. // Move the cursor to after curses output.
  4185. HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
  4186. CONSOLE_SCREEN_BUFFER_INFO csbi;
  4187. COORD coord;
  4188. if (GetConsoleScreenBufferInfo(hout, &csbi)) {
  4189. coord.X = 0;
  4190. coord.Y = csbi.dwSize.Y - 1;
  4191. SetConsoleCursorPosition(hout, coord);
  4192. }
  4193. #endif
  4194. unlock_curses();
  4195. }
  4196. }
  4197. #endif
  4198. static void __kill_work(void)
  4199. {
  4200. struct cgpu_info *cgpu;
  4201. struct thr_info *thr;
  4202. int i;
  4203. if (!successful_connect)
  4204. return;
  4205. applog(LOG_INFO, "Received kill message");
  4206. shutting_down = true;
  4207. applog(LOG_DEBUG, "Prompting submit_work thread to finish");
  4208. notifier_wake(submit_waiting_notifier);
  4209. #ifdef USE_LIBMICROHTTPD
  4210. httpsrv_stop();
  4211. #endif
  4212. applog(LOG_DEBUG, "Killing off watchpool thread");
  4213. /* Kill the watchpool thread */
  4214. thr = &control_thr[watchpool_thr_id];
  4215. thr_info_cancel(thr);
  4216. applog(LOG_DEBUG, "Killing off watchdog thread");
  4217. /* Kill the watchdog thread */
  4218. thr = &control_thr[watchdog_thr_id];
  4219. thr_info_cancel(thr);
  4220. applog(LOG_DEBUG, "Shutting down mining threads");
  4221. for (i = 0; i < mining_threads; i++) {
  4222. thr = get_thread(i);
  4223. if (!thr)
  4224. continue;
  4225. cgpu = thr->cgpu;
  4226. if (!cgpu)
  4227. continue;
  4228. if (!cgpu->threads)
  4229. continue;
  4230. cgpu->shutdown = true;
  4231. thr->work_restart = true;
  4232. notifier_wake(thr->notifier);
  4233. notifier_wake(thr->work_restart_notifier);
  4234. }
  4235. sleep(1);
  4236. applog(LOG_DEBUG, "Killing off mining threads");
  4237. /* Kill the mining threads*/
  4238. for (i = 0; i < mining_threads; i++) {
  4239. thr = get_thread(i);
  4240. if (!thr)
  4241. continue;
  4242. cgpu = thr->cgpu;
  4243. if (cgpu->threads)
  4244. {
  4245. applog(LOG_WARNING, "Killing %"PRIpreprv, thr->cgpu->proc_repr);
  4246. thr_info_cancel(thr);
  4247. }
  4248. cgpu->status = LIFE_DEAD2;
  4249. }
  4250. /* Stop the others */
  4251. applog(LOG_DEBUG, "Killing off API thread");
  4252. thr = &control_thr[api_thr_id];
  4253. thr_info_cancel(thr);
  4254. }
  4255. /* This should be the common exit path */
  4256. void kill_work(void)
  4257. {
  4258. __kill_work();
  4259. quit(0, "Shutdown signal received.");
  4260. }
  4261. static
  4262. #ifdef WIN32
  4263. #ifndef _WIN64
  4264. const
  4265. #endif
  4266. #endif
  4267. char **initial_args;
  4268. void _bfg_clean_up(bool);
  4269. void app_restart(void)
  4270. {
  4271. applog(LOG_WARNING, "Attempting to restart %s", packagename);
  4272. __kill_work();
  4273. _bfg_clean_up(true);
  4274. #if defined(unix) || defined(__APPLE__)
  4275. if (forkpid > 0) {
  4276. kill(forkpid, SIGTERM);
  4277. forkpid = 0;
  4278. }
  4279. #endif
  4280. execv(initial_args[0], initial_args);
  4281. applog(LOG_WARNING, "Failed to restart application");
  4282. }
  4283. static void sighandler(int __maybe_unused sig)
  4284. {
  4285. /* Restore signal handlers so we can still quit if kill_work fails */
  4286. sigaction(SIGTERM, &termhandler, NULL);
  4287. sigaction(SIGINT, &inthandler, NULL);
  4288. kill_work();
  4289. }
  4290. static void start_longpoll(void);
  4291. static void stop_longpoll(void);
  4292. /* Called with pool_lock held. Recruit an extra curl if none are available for
  4293. * this pool. */
  4294. static void recruit_curl(struct pool *pool)
  4295. {
  4296. struct curl_ent *ce = calloc(sizeof(struct curl_ent), 1);
  4297. if (unlikely(!ce))
  4298. quit(1, "Failed to calloc in recruit_curl");
  4299. ce->curl = curl_easy_init();
  4300. if (unlikely(!ce->curl))
  4301. quit(1, "Failed to init in recruit_curl");
  4302. LL_PREPEND(pool->curllist, ce);
  4303. pool->curls++;
  4304. }
  4305. /* Grab an available curl if there is one. If not, then recruit extra curls
  4306. * unless we are in a submit_fail situation, or we have opt_delaynet enabled
  4307. * and there are already 5 curls in circulation. Limit total number to the
  4308. * number of mining threads per pool as well to prevent blasting a pool during
  4309. * network delays/outages. */
  4310. static struct curl_ent *pop_curl_entry3(struct pool *pool, int blocking)
  4311. {
  4312. int curl_limit = opt_delaynet ? 5 : (mining_threads + opt_queue) * 2;
  4313. bool recruited = false;
  4314. struct curl_ent *ce;
  4315. mutex_lock(&pool->pool_lock);
  4316. retry:
  4317. if (!pool->curls) {
  4318. recruit_curl(pool);
  4319. recruited = true;
  4320. } else if (!pool->curllist) {
  4321. if (blocking < 2 && pool->curls >= curl_limit && (blocking || pool->curls >= opt_submit_threads)) {
  4322. if (!blocking) {
  4323. mutex_unlock(&pool->pool_lock);
  4324. return NULL;
  4325. }
  4326. pthread_cond_wait(&pool->cr_cond, &pool->pool_lock);
  4327. goto retry;
  4328. } else {
  4329. recruit_curl(pool);
  4330. recruited = true;
  4331. }
  4332. }
  4333. ce = pool->curllist;
  4334. LL_DELETE(pool->curllist, ce);
  4335. mutex_unlock(&pool->pool_lock);
  4336. if (recruited)
  4337. applog(LOG_DEBUG, "Recruited curl for pool %d", pool->pool_no);
  4338. return ce;
  4339. }
  4340. static struct curl_ent *pop_curl_entry2(struct pool *pool, bool blocking)
  4341. {
  4342. return pop_curl_entry3(pool, blocking ? 1 : 0);
  4343. }
  4344. __maybe_unused
  4345. static struct curl_ent *pop_curl_entry(struct pool *pool)
  4346. {
  4347. return pop_curl_entry3(pool, 1);
  4348. }
  4349. static void push_curl_entry(struct curl_ent *ce, struct pool *pool)
  4350. {
  4351. mutex_lock(&pool->pool_lock);
  4352. if (!ce || !ce->curl)
  4353. quithere(1, "Attempted to add NULL");
  4354. LL_PREPEND(pool->curllist, ce);
  4355. cgtime(&ce->tv);
  4356. pthread_cond_broadcast(&pool->cr_cond);
  4357. mutex_unlock(&pool->pool_lock);
  4358. }
  4359. bool stale_work(struct work *work, bool share);
  4360. static inline bool should_roll(struct work *work)
  4361. {
  4362. struct timeval now;
  4363. time_t expiry;
  4364. if (work->pool != current_pool() && pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE)
  4365. return false;
  4366. if (stale_work(work, false))
  4367. return false;
  4368. if (work->rolltime > opt_scantime)
  4369. expiry = work->rolltime;
  4370. else
  4371. expiry = opt_scantime;
  4372. expiry = expiry * 2 / 3;
  4373. /* We shouldn't roll if we're unlikely to get one shares' duration
  4374. * work out of doing so */
  4375. cgtime(&now);
  4376. if (now.tv_sec - work->tv_staged.tv_sec > expiry)
  4377. return false;
  4378. return true;
  4379. }
  4380. /* Limit rolls to 7000 to not beyond 2 hours in the future where bitcoind will
  4381. * reject blocks as invalid. */
  4382. static inline bool can_roll(struct work *work)
  4383. {
  4384. if (work->stratum)
  4385. return false;
  4386. if (!(work->pool && !work->clone))
  4387. return false;
  4388. if (work->tmpl) {
  4389. if (stale_work(work, false))
  4390. return false;
  4391. return blkmk_work_left(work->tmpl);
  4392. }
  4393. return (work->rolltime &&
  4394. work->rolls < 7000 && !stale_work(work, false));
  4395. }
  4396. static void roll_work(struct work *work)
  4397. {
  4398. if (work->tmpl) {
  4399. struct timeval tv_now;
  4400. cgtime(&tv_now);
  4401. if (blkmk_get_data(work->tmpl, work->data, 80, tv_now.tv_sec, NULL, &work->dataid) < 76)
  4402. applog(LOG_ERR, "Failed to get next data from template; spinning wheels!");
  4403. swap32yes(work->data, work->data, 80 / 4);
  4404. calc_midstate(work);
  4405. applog(LOG_DEBUG, "Successfully rolled extranonce to dataid %u", work->dataid);
  4406. } else {
  4407. uint32_t *work_ntime;
  4408. uint32_t ntime;
  4409. work_ntime = (uint32_t *)(work->data + 68);
  4410. ntime = be32toh(*work_ntime);
  4411. ntime++;
  4412. *work_ntime = htobe32(ntime);
  4413. applog(LOG_DEBUG, "Successfully rolled time header in work");
  4414. }
  4415. local_work++;
  4416. work->rolls++;
  4417. work->blk.nonce = 0;
  4418. /* This is now a different work item so it needs a different ID for the
  4419. * hashtable */
  4420. work->id = total_work++;
  4421. }
  4422. /* Duplicates any dynamically allocated arrays within the work struct to
  4423. * prevent a copied work struct from freeing ram belonging to another struct */
  4424. static void _copy_work(struct work *work, const struct work *base_work, int noffset)
  4425. {
  4426. int id = work->id;
  4427. clean_work(work);
  4428. memcpy(work, base_work, sizeof(struct work));
  4429. /* Keep the unique new id assigned during make_work to prevent copied
  4430. * work from having the same id. */
  4431. work->id = id;
  4432. if (base_work->job_id)
  4433. work->job_id = strdup(base_work->job_id);
  4434. if (base_work->nonce1)
  4435. work->nonce1 = strdup(base_work->nonce1);
  4436. bytes_cpy(&work->nonce2, &base_work->nonce2);
  4437. if (base_work->tmpl) {
  4438. struct pool *pool = work->pool;
  4439. mutex_lock(&pool->pool_lock);
  4440. ++*work->tmpl_refcount;
  4441. mutex_unlock(&pool->pool_lock);
  4442. }
  4443. if (noffset)
  4444. {
  4445. uint32_t *work_ntime = (uint32_t *)(work->data + 68);
  4446. uint32_t ntime = be32toh(*work_ntime);
  4447. ntime += noffset;
  4448. *work_ntime = htobe32(ntime);
  4449. }
  4450. }
  4451. /* Generates a copy of an existing work struct, creating fresh heap allocations
  4452. * for all dynamically allocated arrays within the struct */
  4453. struct work *copy_work(const struct work *base_work)
  4454. {
  4455. struct work *work = make_work();
  4456. _copy_work(work, base_work, 0);
  4457. return work;
  4458. }
  4459. void __copy_work(struct work *work, const struct work *base_work)
  4460. {
  4461. _copy_work(work, base_work, 0);
  4462. }
  4463. static struct work *make_clone(struct work *work)
  4464. {
  4465. struct work *work_clone = copy_work(work);
  4466. work_clone->clone = true;
  4467. cgtime((struct timeval *)&(work_clone->tv_cloned));
  4468. work_clone->longpoll = false;
  4469. work_clone->mandatory = false;
  4470. /* Make cloned work appear slightly older to bias towards keeping the
  4471. * master work item which can be further rolled */
  4472. work_clone->tv_staged.tv_sec -= 1;
  4473. return work_clone;
  4474. }
  4475. static void stage_work(struct work *work);
  4476. static bool clone_available(void)
  4477. {
  4478. struct work *work_clone = NULL, *work, *tmp;
  4479. bool cloned = false;
  4480. mutex_lock(stgd_lock);
  4481. if (!staged_rollable)
  4482. goto out_unlock;
  4483. HASH_ITER(hh, staged_work, work, tmp) {
  4484. if (can_roll(work) && should_roll(work)) {
  4485. roll_work(work);
  4486. work_clone = make_clone(work);
  4487. applog(LOG_DEBUG, "%s: Rolling work %d to %d", __func__, work->id, work_clone->id);
  4488. roll_work(work);
  4489. cloned = true;
  4490. break;
  4491. }
  4492. }
  4493. out_unlock:
  4494. mutex_unlock(stgd_lock);
  4495. if (cloned) {
  4496. applog(LOG_DEBUG, "Pushing cloned available work to stage thread");
  4497. stage_work(work_clone);
  4498. }
  4499. return cloned;
  4500. }
  4501. static void pool_died(struct pool *pool)
  4502. {
  4503. if (!pool_tset(pool, &pool->idle)) {
  4504. cgtime(&pool->tv_idle);
  4505. if (pool == current_pool()) {
  4506. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  4507. switch_pools(NULL);
  4508. } else
  4509. applog(LOG_INFO, "Pool %d %s failed to return work", pool->pool_no, pool->rpc_url);
  4510. }
  4511. }
  4512. bool stale_work(struct work *work, bool share)
  4513. {
  4514. unsigned work_expiry;
  4515. struct pool *pool;
  4516. uint32_t block_id;
  4517. unsigned getwork_delay;
  4518. if (opt_benchmark)
  4519. return false;
  4520. block_id = ((uint32_t*)work->data)[1];
  4521. pool = work->pool;
  4522. /* Technically the rolltime should be correct but some pools
  4523. * advertise a broken expire= that is lower than a meaningful
  4524. * scantime */
  4525. if (work->rolltime >= opt_scantime || work->tmpl)
  4526. work_expiry = work->rolltime;
  4527. else
  4528. work_expiry = opt_expiry;
  4529. unsigned max_expiry = (have_longpoll ? opt_expiry_lp : opt_expiry);
  4530. if (work_expiry > max_expiry)
  4531. work_expiry = max_expiry;
  4532. if (share) {
  4533. /* If the share isn't on this pool's latest block, it's stale */
  4534. if (pool->block_id && pool->block_id != block_id)
  4535. {
  4536. applog(LOG_DEBUG, "Share stale due to block mismatch (%08lx != %08lx)", (long)block_id, (long)pool->block_id);
  4537. return true;
  4538. }
  4539. /* If the pool doesn't want old shares, then any found in work before
  4540. * the most recent longpoll is stale */
  4541. if ((!pool->submit_old) && work->work_restart_id != pool->work_restart_id)
  4542. {
  4543. applog(LOG_DEBUG, "Share stale due to mandatory work update (%02x != %02x)", work->work_restart_id, pool->work_restart_id);
  4544. return true;
  4545. }
  4546. } else {
  4547. /* If this work isn't for the latest Bitcoin block, it's stale */
  4548. /* But only care about the current pool if failover-only */
  4549. if (enabled_pools <= 1 || opt_fail_only) {
  4550. if (pool->block_id && block_id != pool->block_id)
  4551. {
  4552. applog(LOG_DEBUG, "Work stale due to block mismatch (%08lx != 1 ? %08lx : %08lx)", (long)block_id, (long)pool->block_id, (long)current_block_id);
  4553. return true;
  4554. }
  4555. } else {
  4556. if (block_id != current_block_id)
  4557. {
  4558. applog(LOG_DEBUG, "Work stale due to block mismatch (%08lx != 0 ? %08lx : %08lx)", (long)block_id, (long)pool->block_id, (long)current_block_id);
  4559. return true;
  4560. }
  4561. }
  4562. /* If the pool has asked us to restart since this work, it's stale */
  4563. if (work->work_restart_id != pool->work_restart_id)
  4564. {
  4565. applog(LOG_DEBUG, "Work stale due to work update (%02x != %02x)", work->work_restart_id, pool->work_restart_id);
  4566. return true;
  4567. }
  4568. if (pool->has_stratum && work->job_id) {
  4569. bool same_job;
  4570. if (!pool->stratum_active || !pool->stratum_notify) {
  4571. applog(LOG_DEBUG, "Work stale due to stratum inactive");
  4572. return true;
  4573. }
  4574. same_job = true;
  4575. cg_rlock(&pool->data_lock);
  4576. if (strcmp(work->job_id, pool->swork.job_id))
  4577. same_job = false;
  4578. cg_runlock(&pool->data_lock);
  4579. if (!same_job) {
  4580. applog(LOG_DEBUG, "Work stale due to stratum job_id mismatch");
  4581. return true;
  4582. }
  4583. }
  4584. /* Factor in the average getwork delay of this pool, rounding it up to
  4585. * the nearest second */
  4586. getwork_delay = pool->cgminer_pool_stats.getwork_wait_rolling * 5 + 1;
  4587. if (unlikely(work_expiry <= getwork_delay + 5))
  4588. work_expiry = 5;
  4589. else
  4590. work_expiry -= getwork_delay;
  4591. }
  4592. int elapsed_since_staged = timer_elapsed(&work->tv_staged, NULL);
  4593. if (elapsed_since_staged > work_expiry) {
  4594. applog(LOG_DEBUG, "%s stale due to expiry (%d >= %u)", share?"Share":"Work", elapsed_since_staged, work_expiry);
  4595. return true;
  4596. }
  4597. /* If the user only wants strict failover, any work from a pool other than
  4598. * the current one is always considered stale */
  4599. if (opt_fail_only && !share && pool != current_pool() && !work->mandatory &&
  4600. pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  4601. applog(LOG_DEBUG, "Work stale due to fail only pool mismatch (pool %u vs %u)", pool->pool_no, current_pool()->pool_no);
  4602. return true;
  4603. }
  4604. return false;
  4605. }
  4606. static uint64_t share_diff(const struct work *work)
  4607. {
  4608. uint64_t ret;
  4609. bool new_best = false;
  4610. ret = target_diff(work->hash);
  4611. cg_wlock(&control_lock);
  4612. if (unlikely(ret > best_diff)) {
  4613. new_best = true;
  4614. best_diff = ret;
  4615. suffix_string(best_diff, best_share, sizeof(best_share), 0);
  4616. }
  4617. if (unlikely(ret > work->pool->best_diff))
  4618. work->pool->best_diff = ret;
  4619. cg_wunlock(&control_lock);
  4620. if (unlikely(new_best))
  4621. applog(LOG_INFO, "New best share: %s", best_share);
  4622. return ret;
  4623. }
  4624. static void regen_hash(struct work *work)
  4625. {
  4626. hash_data(work->hash, work->data);
  4627. }
  4628. static void rebuild_hash(struct work *work)
  4629. {
  4630. if (opt_scrypt)
  4631. scrypt_regenhash(work);
  4632. else
  4633. regen_hash(work);
  4634. work->share_diff = share_diff(work);
  4635. if (unlikely(work->share_diff >= current_diff)) {
  4636. work->block = true;
  4637. work->pool->solved++;
  4638. found_blocks++;
  4639. work->mandatory = true;
  4640. applog(LOG_NOTICE, "Found block for pool %d!", work->pool->pool_no);
  4641. }
  4642. }
  4643. static void submit_discard_share2(const char *reason, struct work *work)
  4644. {
  4645. struct cgpu_info *cgpu = get_thr_cgpu(work->thr_id);
  4646. sharelog(reason, work);
  4647. mutex_lock(&stats_lock);
  4648. ++total_stale;
  4649. ++cgpu->stale;
  4650. ++(work->pool->stale_shares);
  4651. total_diff_stale += work->work_difficulty;
  4652. cgpu->diff_stale += work->work_difficulty;
  4653. work->pool->diff_stale += work->work_difficulty;
  4654. mutex_unlock(&stats_lock);
  4655. }
  4656. static void submit_discard_share(struct work *work)
  4657. {
  4658. submit_discard_share2("discard", work);
  4659. }
  4660. struct submit_work_state {
  4661. struct work *work;
  4662. bool resubmit;
  4663. struct curl_ent *ce;
  4664. int failures;
  4665. struct timeval tv_staleexpire;
  4666. char *s;
  4667. struct timeval tv_submit;
  4668. struct submit_work_state *next;
  4669. };
  4670. static int my_curl_timer_set(__maybe_unused CURLM *curlm, long timeout_ms, void *userp)
  4671. {
  4672. long *p_timeout_us = userp;
  4673. const long max_ms = LONG_MAX / 1000;
  4674. if (max_ms < timeout_ms)
  4675. timeout_ms = max_ms;
  4676. *p_timeout_us = timeout_ms * 1000;
  4677. return 0;
  4678. }
  4679. static void sws_has_ce(struct submit_work_state *sws)
  4680. {
  4681. struct pool *pool = sws->work->pool;
  4682. sws->s = submit_upstream_work_request(sws->work);
  4683. cgtime(&sws->tv_submit);
  4684. json_rpc_call_async(sws->ce->curl, pool->rpc_url, pool->rpc_userpass, sws->s, false, pool, true, sws);
  4685. }
  4686. static struct submit_work_state *begin_submission(struct work *work)
  4687. {
  4688. struct pool *pool;
  4689. struct submit_work_state *sws = NULL;
  4690. pool = work->pool;
  4691. sws = malloc(sizeof(*sws));
  4692. *sws = (struct submit_work_state){
  4693. .work = work,
  4694. };
  4695. rebuild_hash(work);
  4696. if (stale_work(work, true)) {
  4697. work->stale = true;
  4698. if (opt_submit_stale)
  4699. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as user requested", pool->pool_no);
  4700. else if (pool->submit_old)
  4701. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as pool requested", pool->pool_no);
  4702. else {
  4703. applog(LOG_NOTICE, "Pool %d stale share detected, discarding", pool->pool_no);
  4704. submit_discard_share(work);
  4705. goto out;
  4706. }
  4707. timer_set_delay_from_now(&sws->tv_staleexpire, 300000000);
  4708. }
  4709. if (work->stratum) {
  4710. char *s;
  4711. s = malloc(1024);
  4712. sws->s = s;
  4713. } else {
  4714. /* submit solution to bitcoin via JSON-RPC */
  4715. sws->ce = pop_curl_entry2(pool, false);
  4716. if (sws->ce) {
  4717. sws_has_ce(sws);
  4718. } else {
  4719. sws->next = pool->sws_waiting_on_curl;
  4720. pool->sws_waiting_on_curl = sws;
  4721. if (sws->next)
  4722. applog(LOG_DEBUG, "submit_thread queuing submission");
  4723. else
  4724. applog(LOG_WARNING, "submit_thread queuing submissions (see --submit-threads)");
  4725. }
  4726. }
  4727. return sws;
  4728. out:
  4729. free(sws);
  4730. return NULL;
  4731. }
  4732. static bool retry_submission(struct submit_work_state *sws)
  4733. {
  4734. struct work *work = sws->work;
  4735. struct pool *pool = work->pool;
  4736. sws->resubmit = true;
  4737. if ((!work->stale) && stale_work(work, true)) {
  4738. work->stale = true;
  4739. if (opt_submit_stale)
  4740. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, will retry as user requested", pool->pool_no);
  4741. else if (pool->submit_old)
  4742. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, will retry as pool requested", pool->pool_no);
  4743. else {
  4744. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, discarding", pool->pool_no);
  4745. submit_discard_share(work);
  4746. return false;
  4747. }
  4748. timer_set_delay_from_now(&sws->tv_staleexpire, 300000000);
  4749. }
  4750. if (unlikely((opt_retries >= 0) && (++sws->failures > opt_retries))) {
  4751. applog(LOG_ERR, "Pool %d failed %d submission retries, discarding", pool->pool_no, opt_retries);
  4752. submit_discard_share(work);
  4753. return false;
  4754. }
  4755. else if (work->stale) {
  4756. if (unlikely(opt_retries < 0 && timer_passed(&sws->tv_staleexpire, NULL)))
  4757. {
  4758. applog(LOG_NOTICE, "Pool %d stale share failed to submit for 5 minutes, discarding", pool->pool_no);
  4759. submit_discard_share(work);
  4760. return false;
  4761. }
  4762. }
  4763. /* pause, then restart work-request loop */
  4764. applog(LOG_INFO, "json_rpc_call failed on submit_work, retrying");
  4765. cgtime(&sws->tv_submit);
  4766. json_rpc_call_async(sws->ce->curl, pool->rpc_url, pool->rpc_userpass, sws->s, false, pool, true, sws);
  4767. return true;
  4768. }
  4769. static void free_sws(struct submit_work_state *sws)
  4770. {
  4771. free(sws->s);
  4772. free_work(sws->work);
  4773. free(sws);
  4774. }
  4775. static void *submit_work_thread(__maybe_unused void *userdata)
  4776. {
  4777. int wip = 0;
  4778. CURLM *curlm;
  4779. long curlm_timeout_us = -1;
  4780. struct timeval curlm_timer;
  4781. struct submit_work_state *sws, **swsp;
  4782. struct submit_work_state *write_sws = NULL;
  4783. unsigned tsreduce = 0;
  4784. pthread_detach(pthread_self());
  4785. RenameThread("submit_work");
  4786. applog(LOG_DEBUG, "Creating extra submit work thread");
  4787. curlm = curl_multi_init();
  4788. curlm_timeout_us = -1;
  4789. curl_multi_setopt(curlm, CURLMOPT_TIMERDATA, &curlm_timeout_us);
  4790. curl_multi_setopt(curlm, CURLMOPT_TIMERFUNCTION, my_curl_timer_set);
  4791. fd_set rfds, wfds, efds;
  4792. int maxfd;
  4793. struct timeval tv_timeout, tv_now;
  4794. int n;
  4795. CURLMsg *cm;
  4796. FD_ZERO(&rfds);
  4797. while (1) {
  4798. mutex_lock(&submitting_lock);
  4799. total_submitting -= tsreduce;
  4800. tsreduce = 0;
  4801. if (FD_ISSET(submit_waiting_notifier[0], &rfds)) {
  4802. notifier_read(submit_waiting_notifier);
  4803. }
  4804. // Receive any new submissions
  4805. while (submit_waiting) {
  4806. struct work *work = submit_waiting;
  4807. DL_DELETE(submit_waiting, work);
  4808. if ( (sws = begin_submission(work)) ) {
  4809. if (sws->ce)
  4810. curl_multi_add_handle(curlm, sws->ce->curl);
  4811. else if (sws->s) {
  4812. sws->next = write_sws;
  4813. write_sws = sws;
  4814. }
  4815. ++wip;
  4816. }
  4817. else {
  4818. --total_submitting;
  4819. free_work(work);
  4820. }
  4821. }
  4822. if (unlikely(shutting_down && !wip))
  4823. break;
  4824. mutex_unlock(&submitting_lock);
  4825. FD_ZERO(&rfds);
  4826. FD_ZERO(&wfds);
  4827. FD_ZERO(&efds);
  4828. tv_timeout.tv_sec = -1;
  4829. // Setup cURL with select
  4830. // Need to call perform to ensure the timeout gets updated
  4831. curl_multi_perform(curlm, &n);
  4832. curl_multi_fdset(curlm, &rfds, &wfds, &efds, &maxfd);
  4833. if (curlm_timeout_us >= 0)
  4834. {
  4835. timer_set_delay_from_now(&curlm_timer, curlm_timeout_us);
  4836. reduce_timeout_to(&tv_timeout, &curlm_timer);
  4837. }
  4838. // Setup waiting stratum submissions with select
  4839. for (sws = write_sws; sws; sws = sws->next)
  4840. {
  4841. struct pool *pool = sws->work->pool;
  4842. int fd = pool->sock;
  4843. if (fd == INVSOCK || (!pool->stratum_init) || !pool->stratum_notify)
  4844. continue;
  4845. FD_SET(fd, &wfds);
  4846. set_maxfd(&maxfd, fd);
  4847. }
  4848. // Setup "submit waiting" notifier with select
  4849. FD_SET(submit_waiting_notifier[0], &rfds);
  4850. set_maxfd(&maxfd, submit_waiting_notifier[0]);
  4851. // Wait for something interesting to happen :)
  4852. cgtime(&tv_now);
  4853. if (select(maxfd+1, &rfds, &wfds, &efds, select_timeout(&tv_timeout, &tv_now)) < 0) {
  4854. FD_ZERO(&rfds);
  4855. continue;
  4856. }
  4857. // Handle any stratum ready-to-write results
  4858. for (swsp = &write_sws; (sws = *swsp); ) {
  4859. struct work *work = sws->work;
  4860. struct pool *pool = work->pool;
  4861. int fd = pool->sock;
  4862. bool sessionid_match;
  4863. if (fd == INVSOCK || (!pool->stratum_init) || (!pool->stratum_notify) || !FD_ISSET(fd, &wfds)) {
  4864. next_write_sws:
  4865. // TODO: Check if stale, possibly discard etc
  4866. swsp = &sws->next;
  4867. continue;
  4868. }
  4869. cg_rlock(&pool->data_lock);
  4870. // NOTE: cgminer only does this check on retries, but BFGMiner does it for even the first/normal submit; therefore, it needs to be such that it always is true on the same connection regardless of session management
  4871. // NOTE: Worst case scenario for a false positive: the pool rejects it as H-not-zero
  4872. sessionid_match = (!pool->nonce1) || !strcmp(work->nonce1, pool->nonce1);
  4873. cg_runlock(&pool->data_lock);
  4874. if (!sessionid_match)
  4875. {
  4876. applog(LOG_DEBUG, "No matching session id for resubmitting stratum share");
  4877. submit_discard_share2("disconnect", work);
  4878. ++tsreduce;
  4879. next_write_sws_del:
  4880. // Clear the fd from wfds, to avoid potentially blocking on other submissions to the same socket
  4881. FD_CLR(fd, &wfds);
  4882. // Delete sws for this submission, since we're done with it
  4883. *swsp = sws->next;
  4884. free_sws(sws);
  4885. --wip;
  4886. continue;
  4887. }
  4888. char *s = sws->s;
  4889. struct stratum_share *sshare = calloc(sizeof(struct stratum_share), 1);
  4890. int sshare_id;
  4891. uint32_t nonce;
  4892. char nonce2hex[(bytes_len(&work->nonce2) * 2) + 1];
  4893. char noncehex[9];
  4894. char ntimehex[9];
  4895. sshare->work = copy_work(work);
  4896. bin2hex(nonce2hex, bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  4897. nonce = *((uint32_t *)(work->data + 76));
  4898. bin2hex(noncehex, (const unsigned char *)&nonce, 4);
  4899. bin2hex(ntimehex, (void *)&work->data[68], 4);
  4900. mutex_lock(&sshare_lock);
  4901. /* Give the stratum share a unique id */
  4902. sshare_id =
  4903. sshare->id = swork_id++;
  4904. HASH_ADD_INT(stratum_shares, id, sshare);
  4905. snprintf(s, 1024, "{\"params\": [\"%s\", \"%s\", \"%s\", \"%s\", \"%s\"], \"id\": %d, \"method\": \"mining.submit\"}",
  4906. pool->rpc_user, work->job_id, nonce2hex, ntimehex, noncehex, sshare->id);
  4907. mutex_unlock(&sshare_lock);
  4908. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->stratum_url, s);
  4909. if (likely(stratum_send(pool, s, strlen(s)))) {
  4910. if (pool_tclear(pool, &pool->submit_fail))
  4911. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  4912. applog(LOG_DEBUG, "Successfully submitted, adding to stratum_shares db");
  4913. goto next_write_sws_del;
  4914. } else if (!pool_tset(pool, &pool->submit_fail)) {
  4915. // Undo stuff
  4916. mutex_lock(&sshare_lock);
  4917. // NOTE: Need to find it again in case something else has consumed it already (like the stratum-disconnect resubmitter...)
  4918. HASH_FIND_INT(stratum_shares, &sshare_id, sshare);
  4919. if (sshare)
  4920. HASH_DEL(stratum_shares, sshare);
  4921. mutex_unlock(&sshare_lock);
  4922. if (sshare)
  4923. {
  4924. free_work(sshare->work);
  4925. free(sshare);
  4926. }
  4927. applog(LOG_WARNING, "Pool %d stratum share submission failure", pool->pool_no);
  4928. total_ro++;
  4929. pool->remotefail_occasions++;
  4930. if (!sshare)
  4931. goto next_write_sws_del;
  4932. goto next_write_sws;
  4933. }
  4934. }
  4935. // Handle any cURL activities
  4936. curl_multi_perform(curlm, &n);
  4937. while( (cm = curl_multi_info_read(curlm, &n)) ) {
  4938. if (cm->msg == CURLMSG_DONE)
  4939. {
  4940. bool finished;
  4941. json_t *val = json_rpc_call_completed(cm->easy_handle, cm->data.result, false, NULL, &sws);
  4942. curl_multi_remove_handle(curlm, cm->easy_handle);
  4943. finished = submit_upstream_work_completed(sws->work, sws->resubmit, &sws->tv_submit, val);
  4944. if (!finished) {
  4945. if (retry_submission(sws))
  4946. curl_multi_add_handle(curlm, sws->ce->curl);
  4947. else
  4948. finished = true;
  4949. }
  4950. if (finished) {
  4951. --wip;
  4952. ++tsreduce;
  4953. struct pool *pool = sws->work->pool;
  4954. if (pool->sws_waiting_on_curl) {
  4955. pool->sws_waiting_on_curl->ce = sws->ce;
  4956. sws_has_ce(pool->sws_waiting_on_curl);
  4957. pool->sws_waiting_on_curl = pool->sws_waiting_on_curl->next;
  4958. curl_multi_add_handle(curlm, sws->ce->curl);
  4959. } else {
  4960. push_curl_entry(sws->ce, sws->work->pool);
  4961. }
  4962. free_sws(sws);
  4963. }
  4964. }
  4965. }
  4966. }
  4967. assert(!write_sws);
  4968. mutex_unlock(&submitting_lock);
  4969. curl_multi_cleanup(curlm);
  4970. applog(LOG_DEBUG, "submit_work thread exiting");
  4971. return NULL;
  4972. }
  4973. /* Find the pool that currently has the highest priority */
  4974. static struct pool *priority_pool(int choice)
  4975. {
  4976. struct pool *ret = NULL;
  4977. int i;
  4978. for (i = 0; i < total_pools; i++) {
  4979. struct pool *pool = pools[i];
  4980. if (pool->prio == choice) {
  4981. ret = pool;
  4982. break;
  4983. }
  4984. }
  4985. if (unlikely(!ret)) {
  4986. applog(LOG_ERR, "WTF No pool %d found!", choice);
  4987. return pools[choice];
  4988. }
  4989. return ret;
  4990. }
  4991. int prioritize_pools(char *param, int *pid)
  4992. {
  4993. char *ptr, *next;
  4994. int i, pr, prio = 0;
  4995. if (total_pools == 0) {
  4996. return MSG_NOPOOL;
  4997. }
  4998. if (param == NULL || *param == '\0') {
  4999. return MSG_MISPID;
  5000. }
  5001. bool pools_changed[total_pools];
  5002. int new_prio[total_pools];
  5003. for (i = 0; i < total_pools; ++i)
  5004. pools_changed[i] = false;
  5005. next = param;
  5006. while (next && *next) {
  5007. ptr = next;
  5008. next = strchr(ptr, ',');
  5009. if (next)
  5010. *(next++) = '\0';
  5011. i = atoi(ptr);
  5012. if (i < 0 || i >= total_pools) {
  5013. *pid = i;
  5014. return MSG_INVPID;
  5015. }
  5016. if (pools_changed[i]) {
  5017. *pid = i;
  5018. return MSG_DUPPID;
  5019. }
  5020. pools_changed[i] = true;
  5021. new_prio[i] = prio++;
  5022. }
  5023. // Only change them if no errors
  5024. for (i = 0; i < total_pools; i++) {
  5025. if (pools_changed[i])
  5026. pools[i]->prio = new_prio[i];
  5027. }
  5028. // In priority order, cycle through the unchanged pools and append them
  5029. for (pr = 0; pr < total_pools; pr++)
  5030. for (i = 0; i < total_pools; i++) {
  5031. if (!pools_changed[i] && pools[i]->prio == pr) {
  5032. pools[i]->prio = prio++;
  5033. pools_changed[i] = true;
  5034. break;
  5035. }
  5036. }
  5037. if (current_pool()->prio)
  5038. switch_pools(NULL);
  5039. return MSG_POOLPRIO;
  5040. }
  5041. void validate_pool_priorities(void)
  5042. {
  5043. // TODO: this should probably do some sort of logging
  5044. int i, j;
  5045. bool used[total_pools];
  5046. bool valid[total_pools];
  5047. for (i = 0; i < total_pools; i++)
  5048. used[i] = valid[i] = false;
  5049. for (i = 0; i < total_pools; i++) {
  5050. if (pools[i]->prio >=0 && pools[i]->prio < total_pools) {
  5051. if (!used[pools[i]->prio]) {
  5052. valid[i] = true;
  5053. used[pools[i]->prio] = true;
  5054. }
  5055. }
  5056. }
  5057. for (i = 0; i < total_pools; i++) {
  5058. if (!valid[i]) {
  5059. for (j = 0; j < total_pools; j++) {
  5060. if (!used[j]) {
  5061. applog(LOG_WARNING, "Pool %d priority changed from %d to %d", i, pools[i]->prio, j);
  5062. pools[i]->prio = j;
  5063. used[j] = true;
  5064. break;
  5065. }
  5066. }
  5067. }
  5068. }
  5069. }
  5070. static void clear_pool_work(struct pool *pool);
  5071. /* Specifies whether we can switch to this pool or not. */
  5072. static bool pool_unusable(struct pool *pool)
  5073. {
  5074. if (pool->idle)
  5075. return true;
  5076. if (pool->enabled != POOL_ENABLED)
  5077. return true;
  5078. return false;
  5079. }
  5080. void switch_pools(struct pool *selected)
  5081. {
  5082. struct pool *pool, *last_pool;
  5083. int i, pool_no, next_pool;
  5084. cg_wlock(&control_lock);
  5085. last_pool = currentpool;
  5086. pool_no = currentpool->pool_no;
  5087. /* Switch selected to pool number 0 and move the rest down */
  5088. if (selected) {
  5089. if (selected->prio != 0) {
  5090. for (i = 0; i < total_pools; i++) {
  5091. pool = pools[i];
  5092. if (pool->prio < selected->prio)
  5093. pool->prio++;
  5094. }
  5095. selected->prio = 0;
  5096. }
  5097. }
  5098. switch (pool_strategy) {
  5099. /* All of these set to the master pool */
  5100. case POOL_BALANCE:
  5101. case POOL_FAILOVER:
  5102. case POOL_LOADBALANCE:
  5103. for (i = 0; i < total_pools; i++) {
  5104. pool = priority_pool(i);
  5105. if (pool_unusable(pool))
  5106. continue;
  5107. pool_no = pool->pool_no;
  5108. break;
  5109. }
  5110. break;
  5111. /* Both of these simply increment and cycle */
  5112. case POOL_ROUNDROBIN:
  5113. case POOL_ROTATE:
  5114. if (selected && !selected->idle) {
  5115. pool_no = selected->pool_no;
  5116. break;
  5117. }
  5118. next_pool = pool_no;
  5119. /* Select the next alive pool */
  5120. for (i = 1; i < total_pools; i++) {
  5121. next_pool++;
  5122. if (next_pool >= total_pools)
  5123. next_pool = 0;
  5124. pool = pools[next_pool];
  5125. if (pool_unusable(pool))
  5126. continue;
  5127. pool_no = next_pool;
  5128. break;
  5129. }
  5130. break;
  5131. default:
  5132. break;
  5133. }
  5134. currentpool = pools[pool_no];
  5135. pool = currentpool;
  5136. cg_wunlock(&control_lock);
  5137. /* Set the lagging flag to avoid pool not providing work fast enough
  5138. * messages in failover only mode since we have to get all fresh work
  5139. * as in restart_threads */
  5140. if (opt_fail_only)
  5141. pool_tset(pool, &pool->lagging);
  5142. if (pool != last_pool)
  5143. {
  5144. pool->block_id = 0;
  5145. if (pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  5146. applog(LOG_WARNING, "Switching to pool %d %s", pool->pool_no, pool->rpc_url);
  5147. if (pool_localgen(pool) || opt_fail_only)
  5148. clear_pool_work(last_pool);
  5149. }
  5150. }
  5151. mutex_lock(&lp_lock);
  5152. pthread_cond_broadcast(&lp_cond);
  5153. mutex_unlock(&lp_lock);
  5154. }
  5155. static void discard_work(struct work *work)
  5156. {
  5157. if (!work->clone && !work->rolls && !work->mined) {
  5158. if (work->pool) {
  5159. work->pool->discarded_work++;
  5160. work->pool->quota_used--;
  5161. work->pool->works--;
  5162. }
  5163. total_discarded++;
  5164. applog(LOG_DEBUG, "Discarded work");
  5165. } else
  5166. applog(LOG_DEBUG, "Discarded cloned or rolled work");
  5167. free_work(work);
  5168. }
  5169. static void wake_gws(void)
  5170. {
  5171. mutex_lock(stgd_lock);
  5172. pthread_cond_signal(&gws_cond);
  5173. mutex_unlock(stgd_lock);
  5174. }
  5175. static void discard_stale(void)
  5176. {
  5177. struct work *work, *tmp;
  5178. int stale = 0;
  5179. mutex_lock(stgd_lock);
  5180. HASH_ITER(hh, staged_work, work, tmp) {
  5181. if (stale_work(work, false)) {
  5182. HASH_DEL(staged_work, work);
  5183. discard_work(work);
  5184. stale++;
  5185. staged_full = false;
  5186. }
  5187. }
  5188. pthread_cond_signal(&gws_cond);
  5189. mutex_unlock(stgd_lock);
  5190. if (stale)
  5191. applog(LOG_DEBUG, "Discarded %d stales that didn't match current hash", stale);
  5192. }
  5193. bool stale_work_future(struct work *work, bool share, unsigned long ustime)
  5194. {
  5195. bool rv;
  5196. struct timeval tv, orig;
  5197. ldiv_t d;
  5198. d = ldiv(ustime, 1000000);
  5199. tv = (struct timeval){
  5200. .tv_sec = d.quot,
  5201. .tv_usec = d.rem,
  5202. };
  5203. orig = work->tv_staged;
  5204. timersub(&orig, &tv, &work->tv_staged);
  5205. rv = stale_work(work, share);
  5206. work->tv_staged = orig;
  5207. return rv;
  5208. }
  5209. static void restart_threads(void)
  5210. {
  5211. struct pool *cp = current_pool();
  5212. int i;
  5213. struct thr_info *thr;
  5214. /* Artificially set the lagging flag to avoid pool not providing work
  5215. * fast enough messages after every long poll */
  5216. pool_tset(cp, &cp->lagging);
  5217. /* Discard staged work that is now stale */
  5218. discard_stale();
  5219. rd_lock(&mining_thr_lock);
  5220. for (i = 0; i < mining_threads; i++)
  5221. {
  5222. thr = mining_thr[i];
  5223. thr->work_restart = true;
  5224. }
  5225. for (i = 0; i < mining_threads; i++)
  5226. {
  5227. thr = mining_thr[i];
  5228. notifier_wake(thr->work_restart_notifier);
  5229. }
  5230. rd_unlock(&mining_thr_lock);
  5231. }
  5232. static
  5233. void blkhashstr(char *rv, const unsigned char *hash)
  5234. {
  5235. unsigned char hash_swap[32];
  5236. swap256(hash_swap, hash);
  5237. swap32tole(hash_swap, hash_swap, 32 / 4);
  5238. bin2hex(rv, hash_swap, 32);
  5239. }
  5240. static void set_curblock(char *hexstr, unsigned char *hash)
  5241. {
  5242. unsigned char hash_swap[32];
  5243. current_block_id = ((uint32_t*)hash)[0];
  5244. strcpy(current_block, hexstr);
  5245. swap256(hash_swap, hash);
  5246. swap32tole(hash_swap, hash_swap, 32 / 4);
  5247. cg_wlock(&ch_lock);
  5248. block_time = time(NULL);
  5249. __update_block_title(hash_swap);
  5250. free(current_fullhash);
  5251. current_fullhash = malloc(65);
  5252. bin2hex(current_fullhash, hash_swap, 32);
  5253. get_timestamp(blocktime, sizeof(blocktime), block_time);
  5254. cg_wunlock(&ch_lock);
  5255. applog(LOG_INFO, "New block: %s diff %s (%s)", current_hash, block_diff, net_hashrate);
  5256. }
  5257. /* Search to see if this string is from a block that has been seen before */
  5258. static bool block_exists(char *hexstr)
  5259. {
  5260. struct block *s;
  5261. rd_lock(&blk_lock);
  5262. HASH_FIND_STR(blocks, hexstr, s);
  5263. rd_unlock(&blk_lock);
  5264. if (s)
  5265. return true;
  5266. return false;
  5267. }
  5268. /* Tests if this work is from a block that has been seen before */
  5269. static inline bool from_existing_block(struct work *work)
  5270. {
  5271. char hexstr[37];
  5272. bool ret;
  5273. bin2hex(hexstr, work->data + 8, 18);
  5274. ret = block_exists(hexstr);
  5275. return ret;
  5276. }
  5277. static int block_sort(struct block *blocka, struct block *blockb)
  5278. {
  5279. return blocka->block_no - blockb->block_no;
  5280. }
  5281. static void set_blockdiff(const struct work *work)
  5282. {
  5283. unsigned char target[32];
  5284. double diff;
  5285. uint64_t diff64;
  5286. real_block_target(target, work->data);
  5287. diff = target_diff(target);
  5288. diff64 = diff;
  5289. suffix_string(diff64, block_diff, sizeof(block_diff), 0);
  5290. format_unit2(net_hashrate, sizeof(net_hashrate),
  5291. true, "h/s", H2B_SHORT, diff * 7158278, -1);
  5292. if (unlikely(current_diff != diff))
  5293. applog(LOG_NOTICE, "Network difficulty changed to %s (%s)", block_diff, net_hashrate);
  5294. current_diff = diff;
  5295. }
  5296. static bool test_work_current(struct work *work)
  5297. {
  5298. bool ret = true;
  5299. char hexstr[65];
  5300. if (work->mandatory)
  5301. return ret;
  5302. uint32_t block_id = ((uint32_t*)(work->data))[1];
  5303. /* Hack to work around dud work sneaking into test */
  5304. bin2hex(hexstr, work->data + 8, 18);
  5305. if (!strncmp(hexstr, "000000000000000000000000000000000000", 36))
  5306. goto out_free;
  5307. /* Search to see if this block exists yet and if not, consider it a
  5308. * new block and set the current block details to this one */
  5309. if (!block_exists(hexstr)) {
  5310. struct block *s = calloc(sizeof(struct block), 1);
  5311. int deleted_block = 0;
  5312. ret = false;
  5313. if (unlikely(!s))
  5314. quit (1, "test_work_current OOM");
  5315. strcpy(s->hash, hexstr);
  5316. s->block_no = new_blocks++;
  5317. wr_lock(&blk_lock);
  5318. /* Only keep the last hour's worth of blocks in memory since
  5319. * work from blocks before this is virtually impossible and we
  5320. * want to prevent memory usage from continually rising */
  5321. if (HASH_COUNT(blocks) > 6) {
  5322. struct block *oldblock;
  5323. HASH_SORT(blocks, block_sort);
  5324. oldblock = blocks;
  5325. deleted_block = oldblock->block_no;
  5326. HASH_DEL(blocks, oldblock);
  5327. free(oldblock);
  5328. }
  5329. HASH_ADD_STR(blocks, hash, s);
  5330. set_blockdiff(work);
  5331. wr_unlock(&blk_lock);
  5332. work->pool->block_id = block_id;
  5333. if (deleted_block)
  5334. applog(LOG_DEBUG, "Deleted block %d from database", deleted_block);
  5335. #if BLKMAKER_VERSION > 1
  5336. template_nonce = 0;
  5337. #endif
  5338. set_curblock(hexstr, &work->data[4]);
  5339. if (unlikely(new_blocks == 1))
  5340. goto out_free;
  5341. if (!work->stratum) {
  5342. if (work->longpoll) {
  5343. applog(LOG_NOTICE, "Longpoll from pool %d detected new block",
  5344. work->pool->pool_no);
  5345. } else if (have_longpoll)
  5346. applog(LOG_NOTICE, "New block detected on network before longpoll");
  5347. else
  5348. applog(LOG_NOTICE, "New block detected on network");
  5349. }
  5350. restart_threads();
  5351. } else {
  5352. bool restart = false;
  5353. struct pool *curpool = NULL;
  5354. if (unlikely(work->pool->block_id != block_id)) {
  5355. bool was_active = work->pool->block_id != 0;
  5356. work->pool->block_id = block_id;
  5357. if (!work->longpoll)
  5358. update_last_work(work);
  5359. if (was_active) { // Pool actively changed block
  5360. if (work->pool == (curpool = current_pool()))
  5361. restart = true;
  5362. if (block_id == current_block_id) {
  5363. // Caught up, only announce if this pool is the one in use
  5364. if (restart)
  5365. applog(LOG_NOTICE, "%s %d caught up to new block",
  5366. work->longpoll ? "Longpoll from pool" : "Pool",
  5367. work->pool->pool_no);
  5368. } else {
  5369. // Switched to a block we know, but not the latest... why?
  5370. // This might detect pools trying to double-spend or 51%,
  5371. // but let's not make any accusations until it's had time
  5372. // in the real world.
  5373. blkhashstr(hexstr, &work->data[4]);
  5374. applog(LOG_WARNING, "%s %d is issuing work for an old block: %s",
  5375. work->longpoll ? "Longpoll from pool" : "Pool",
  5376. work->pool->pool_no,
  5377. hexstr);
  5378. }
  5379. }
  5380. }
  5381. if (work->longpoll) {
  5382. ++work->pool->work_restart_id;
  5383. update_last_work(work);
  5384. if ((!restart) && work->pool == current_pool()) {
  5385. applog(
  5386. (opt_quiet_work_updates ? LOG_DEBUG : LOG_NOTICE),
  5387. "Longpoll from pool %d requested work update",
  5388. work->pool->pool_no);
  5389. restart = true;
  5390. }
  5391. }
  5392. if (restart)
  5393. restart_threads();
  5394. }
  5395. work->longpoll = false;
  5396. out_free:
  5397. return ret;
  5398. }
  5399. static int tv_sort(struct work *worka, struct work *workb)
  5400. {
  5401. return worka->tv_staged.tv_sec - workb->tv_staged.tv_sec;
  5402. }
  5403. static bool work_rollable(struct work *work)
  5404. {
  5405. return (!work->clone && work->rolltime);
  5406. }
  5407. static bool hash_push(struct work *work)
  5408. {
  5409. bool rc = true;
  5410. mutex_lock(stgd_lock);
  5411. if (work_rollable(work))
  5412. staged_rollable++;
  5413. if (likely(!getq->frozen)) {
  5414. HASH_ADD_INT(staged_work, id, work);
  5415. HASH_SORT(staged_work, tv_sort);
  5416. } else
  5417. rc = false;
  5418. pthread_cond_broadcast(&getq->cond);
  5419. mutex_unlock(stgd_lock);
  5420. return rc;
  5421. }
  5422. static void stage_work(struct work *work)
  5423. {
  5424. applog(LOG_DEBUG, "Pushing work %d from pool %d to hash queue",
  5425. work->id, work->pool->pool_no);
  5426. work->work_restart_id = work->pool->work_restart_id;
  5427. work->pool->last_work_time = time(NULL);
  5428. cgtime(&work->pool->tv_last_work_time);
  5429. test_work_current(work);
  5430. work->pool->works++;
  5431. hash_push(work);
  5432. }
  5433. #ifdef HAVE_CURSES
  5434. int curses_int(const char *query)
  5435. {
  5436. int ret;
  5437. char *cvar;
  5438. cvar = curses_input(query);
  5439. if (unlikely(!cvar))
  5440. return -1;
  5441. ret = atoi(cvar);
  5442. free(cvar);
  5443. return ret;
  5444. }
  5445. #endif
  5446. #ifdef HAVE_CURSES
  5447. static bool input_pool(bool live);
  5448. #endif
  5449. #ifdef HAVE_CURSES
  5450. static void display_pool_summary(struct pool *pool)
  5451. {
  5452. double efficiency = 0.0;
  5453. char xfer[17], bw[19];
  5454. int pool_secs;
  5455. if (curses_active_locked()) {
  5456. wlog("Pool: %s\n", pool->rpc_url);
  5457. if (pool->solved)
  5458. wlog("SOLVED %d BLOCK%s!\n", pool->solved, pool->solved > 1 ? "S" : "");
  5459. if (!pool->has_stratum)
  5460. wlog("%s own long-poll support\n", pool->lp_url ? "Has" : "Does not have");
  5461. wlog(" Queued work requests: %d\n", pool->getwork_requested);
  5462. wlog(" Share submissions: %d\n", pool->accepted + pool->rejected);
  5463. wlog(" Accepted shares: %d\n", pool->accepted);
  5464. wlog(" Rejected shares: %d + %d stale (%.2f%%)\n",
  5465. pool->rejected, pool->stale_shares,
  5466. (float)(pool->rejected + pool->stale_shares) / (float)(pool->rejected + pool->stale_shares + pool->accepted)
  5467. );
  5468. wlog(" Accepted difficulty shares: %1.f\n", pool->diff_accepted);
  5469. wlog(" Rejected difficulty shares: %1.f\n", pool->diff_rejected);
  5470. pool_secs = timer_elapsed(&pool->cgminer_stats.start_tv, NULL);
  5471. wlog(" Network transfer: %s (%s)\n",
  5472. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  5473. (float)pool->cgminer_pool_stats.net_bytes_received,
  5474. (float)pool->cgminer_pool_stats.net_bytes_sent),
  5475. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  5476. (float)(pool->cgminer_pool_stats.net_bytes_received / pool_secs),
  5477. (float)(pool->cgminer_pool_stats.net_bytes_sent / pool_secs)));
  5478. uint64_t pool_bytes_xfer = pool->cgminer_pool_stats.net_bytes_received + pool->cgminer_pool_stats.net_bytes_sent;
  5479. efficiency = pool_bytes_xfer ? pool->diff_accepted * 2048. / pool_bytes_xfer : 0.0;
  5480. wlog(" Efficiency (accepted * difficulty / 2 KB): %.2f\n", efficiency);
  5481. wlog(" Items worked on: %d\n", pool->works);
  5482. wlog(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  5483. wlog(" Unable to get work from server occasions: %d\n", pool->getfail_occasions);
  5484. wlog(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  5485. unlock_curses();
  5486. }
  5487. }
  5488. #endif
  5489. /* We can't remove the memory used for this struct pool because there may
  5490. * still be work referencing it. We just remove it from the pools list */
  5491. void remove_pool(struct pool *pool)
  5492. {
  5493. int i, last_pool = total_pools - 1;
  5494. struct pool *other;
  5495. /* Boost priority of any lower prio than this one */
  5496. for (i = 0; i < total_pools; i++) {
  5497. other = pools[i];
  5498. if (other->prio > pool->prio)
  5499. other->prio--;
  5500. }
  5501. if (pool->pool_no < last_pool) {
  5502. /* Swap the last pool for this one */
  5503. (pools[last_pool])->pool_no = pool->pool_no;
  5504. pools[pool->pool_no] = pools[last_pool];
  5505. }
  5506. /* Give it an invalid number */
  5507. pool->pool_no = total_pools;
  5508. pool->removed = true;
  5509. pool->has_stratum = false;
  5510. total_pools--;
  5511. }
  5512. /* add a mutex if this needs to be thread safe in the future */
  5513. static struct JE {
  5514. char *buf;
  5515. struct JE *next;
  5516. } *jedata = NULL;
  5517. static void json_escape_free()
  5518. {
  5519. struct JE *jeptr = jedata;
  5520. struct JE *jenext;
  5521. jedata = NULL;
  5522. while (jeptr) {
  5523. jenext = jeptr->next;
  5524. free(jeptr->buf);
  5525. free(jeptr);
  5526. jeptr = jenext;
  5527. }
  5528. }
  5529. static
  5530. char *json_escape(const char *str)
  5531. {
  5532. struct JE *jeptr;
  5533. char *buf, *ptr;
  5534. /* 2x is the max, may as well just allocate that */
  5535. ptr = buf = malloc(strlen(str) * 2 + 1);
  5536. jeptr = malloc(sizeof(*jeptr));
  5537. jeptr->buf = buf;
  5538. jeptr->next = jedata;
  5539. jedata = jeptr;
  5540. while (*str) {
  5541. if (*str == '\\' || *str == '"')
  5542. *(ptr++) = '\\';
  5543. *(ptr++) = *(str++);
  5544. }
  5545. *ptr = '\0';
  5546. return buf;
  5547. }
  5548. void _write_config_temps(FILE *fcfg, const char *configname, size_t settingoffset, size_t defoffset)
  5549. {
  5550. int i, commas;
  5551. int *setp, allset;
  5552. uint8_t *defp;
  5553. for (i = 0; ; ++i)
  5554. {
  5555. if (i == total_devices)
  5556. // All defaults
  5557. return;
  5558. setp = ((void*)devices[i]) + settingoffset;
  5559. defp = ((void*)devices[i]) + defoffset;
  5560. allset = *setp;
  5561. if (*setp != *defp)
  5562. break;
  5563. }
  5564. fprintf(fcfg, ",\n\"%s\" : \"", configname);
  5565. for (i = 1; ; ++i)
  5566. {
  5567. if (i == total_devices)
  5568. {
  5569. // All the same
  5570. fprintf(fcfg, "%d\"", allset);
  5571. return;
  5572. }
  5573. setp = ((void*)devices[i]) + settingoffset;
  5574. if (allset != *setp)
  5575. break;
  5576. }
  5577. commas = 0;
  5578. for (i = 0; i < total_devices; ++i)
  5579. {
  5580. setp = ((void*)devices[i]) + settingoffset;
  5581. defp = ((void*)devices[i]) + defoffset;
  5582. if (*setp != *defp)
  5583. {
  5584. for ( ; commas; --commas)
  5585. fputs(",", fcfg);
  5586. fprintf(fcfg, "%d", *setp);
  5587. }
  5588. ++commas;
  5589. }
  5590. fputs("\"", fcfg);
  5591. }
  5592. #define write_config_temps(fcfg, configname, settingname) \
  5593. _write_config_temps(fcfg, configname, offsetof(struct cgpu_info, settingname), offsetof(struct cgpu_info, settingname ## _default))
  5594. static
  5595. void _write_config_string_elist(FILE *fcfg, const char *configname, struct string_elist * const elist)
  5596. {
  5597. if (!elist)
  5598. return;
  5599. static struct string_elist *entry;
  5600. fprintf(fcfg, ",\n\"%s\" : [", configname);
  5601. bool first = true;
  5602. DL_FOREACH(elist, entry)
  5603. {
  5604. const char * const s = entry->string;
  5605. fprintf(fcfg, "%s\n\t\"%s\"", first ? "" : ",", json_escape(s));
  5606. first = false;
  5607. }
  5608. fprintf(fcfg, "\n]");
  5609. }
  5610. void write_config(FILE *fcfg)
  5611. {
  5612. int i;
  5613. /* Write pool values */
  5614. fputs("{\n\"pools\" : [", fcfg);
  5615. for(i = 0; i < total_pools; i++) {
  5616. struct pool *pool = pools[i];
  5617. if (pool->quota != 1) {
  5618. fprintf(fcfg, "%s\n\t{\n\t\t\"quota\" : \"%d;%s\",", i > 0 ? "," : "",
  5619. pool->quota,
  5620. json_escape(pool->rpc_url));
  5621. } else {
  5622. fprintf(fcfg, "%s\n\t{\n\t\t\"url\" : \"%s\",", i > 0 ? "," : "",
  5623. json_escape(pool->rpc_url));
  5624. }
  5625. if (pool->rpc_proxy)
  5626. fprintf(fcfg, "\n\t\t\"pool-proxy\" : \"%s\",", json_escape(pool->rpc_proxy));
  5627. fprintf(fcfg, "\n\t\t\"user\" : \"%s\",", json_escape(pool->rpc_user));
  5628. fprintf(fcfg, "\n\t\t\"pass\" : \"%s\",", json_escape(pool->rpc_pass));
  5629. fprintf(fcfg, "\n\t\t\"pool-priority\" : \"%d\"", pool->prio);
  5630. if (pool->force_rollntime)
  5631. fprintf(fcfg, ",\n\t\t\"force-rollntime\" : %d", pool->force_rollntime);
  5632. fprintf(fcfg, "\n\t}");
  5633. }
  5634. fputs("\n]\n", fcfg);
  5635. write_config_temps(fcfg, "temp-cutoff", cutofftemp);
  5636. write_config_temps(fcfg, "temp-target", targettemp);
  5637. #ifdef HAVE_OPENCL
  5638. if (nDevs) {
  5639. /* Write GPU device values */
  5640. fputs(",\n\"intensity\" : \"", fcfg);
  5641. for(i = 0; i < nDevs; i++)
  5642. {
  5643. if (i > 0)
  5644. fputc(',', fcfg);
  5645. if (gpus[i].dynamic)
  5646. fputc('d', fcfg);
  5647. else
  5648. fprintf(fcfg, "%d", gpus[i].intensity);
  5649. }
  5650. fputs("\",\n\"vectors\" : \"", fcfg);
  5651. for(i = 0; i < nDevs; i++)
  5652. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  5653. gpus[i].vwidth);
  5654. fputs("\",\n\"worksize\" : \"", fcfg);
  5655. for(i = 0; i < nDevs; i++)
  5656. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  5657. (int)gpus[i].work_size);
  5658. fputs("\",\n\"kernel\" : \"", fcfg);
  5659. for(i = 0; i < nDevs; i++) {
  5660. fprintf(fcfg, "%s", i > 0 ? "," : "");
  5661. switch (gpus[i].kernel) {
  5662. case KL_NONE: // Shouldn't happen
  5663. break;
  5664. case KL_POCLBM:
  5665. fprintf(fcfg, "poclbm");
  5666. break;
  5667. case KL_PHATK:
  5668. fprintf(fcfg, "phatk");
  5669. break;
  5670. case KL_DIAKGCN:
  5671. fprintf(fcfg, "diakgcn");
  5672. break;
  5673. case KL_DIABLO:
  5674. fprintf(fcfg, "diablo");
  5675. break;
  5676. case KL_SCRYPT:
  5677. fprintf(fcfg, "scrypt");
  5678. break;
  5679. }
  5680. }
  5681. #ifdef USE_SCRYPT
  5682. fputs("\",\n\"lookup-gap\" : \"", fcfg);
  5683. for(i = 0; i < nDevs; i++)
  5684. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  5685. (int)gpus[i].opt_lg);
  5686. fputs("\",\n\"thread-concurrency\" : \"", fcfg);
  5687. for(i = 0; i < nDevs; i++)
  5688. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  5689. (int)gpus[i].opt_tc);
  5690. fputs("\",\n\"shaders\" : \"", fcfg);
  5691. for(i = 0; i < nDevs; i++)
  5692. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  5693. (int)gpus[i].shaders);
  5694. #endif
  5695. #ifdef HAVE_ADL
  5696. fputs("\",\n\"gpu-engine\" : \"", fcfg);
  5697. for(i = 0; i < nDevs; i++)
  5698. fprintf(fcfg, "%s%d-%d", i > 0 ? "," : "", gpus[i].min_engine, gpus[i].gpu_engine);
  5699. fputs("\",\n\"gpu-fan\" : \"", fcfg);
  5700. for(i = 0; i < nDevs; i++)
  5701. fprintf(fcfg, "%s%d-%d", i > 0 ? "," : "", gpus[i].min_fan, gpus[i].gpu_fan);
  5702. fputs("\",\n\"gpu-memclock\" : \"", fcfg);
  5703. for(i = 0; i < nDevs; i++)
  5704. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_memclock);
  5705. fputs("\",\n\"gpu-memdiff\" : \"", fcfg);
  5706. for(i = 0; i < nDevs; i++)
  5707. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_memdiff);
  5708. fputs("\",\n\"gpu-powertune\" : \"", fcfg);
  5709. for(i = 0; i < nDevs; i++)
  5710. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_powertune);
  5711. fputs("\",\n\"gpu-vddc\" : \"", fcfg);
  5712. for(i = 0; i < nDevs; i++)
  5713. fprintf(fcfg, "%s%1.3f", i > 0 ? "," : "", gpus[i].gpu_vddc);
  5714. fputs("\",\n\"temp-overheat\" : \"", fcfg);
  5715. for(i = 0; i < nDevs; i++)
  5716. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].adl.overtemp);
  5717. #endif
  5718. fputs("\"", fcfg);
  5719. }
  5720. #endif
  5721. #ifdef HAVE_ADL
  5722. if (opt_reorder)
  5723. fprintf(fcfg, ",\n\"gpu-reorder\" : true");
  5724. #endif
  5725. #ifdef WANT_CPUMINE
  5726. fprintf(fcfg, ",\n\"algo\" : \"%s\"", algo_names[opt_algo]);
  5727. #endif
  5728. /* Simple bool and int options */
  5729. struct opt_table *opt;
  5730. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  5731. char *p, *name = strdup(opt->names);
  5732. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  5733. if (p[1] != '-')
  5734. continue;
  5735. if (opt->type & OPT_NOARG &&
  5736. ((void *)opt->cb == (void *)opt_set_bool || (void *)opt->cb == (void *)opt_set_invbool) &&
  5737. (*(bool *)opt->u.arg == ((void *)opt->cb == (void *)opt_set_bool)))
  5738. fprintf(fcfg, ",\n\"%s\" : true", p+2);
  5739. if (opt->type & OPT_HASARG &&
  5740. ((void *)opt->cb_arg == (void *)set_int_0_to_9999 ||
  5741. (void *)opt->cb_arg == (void *)set_int_1_to_65535 ||
  5742. (void *)opt->cb_arg == (void *)set_int_0_to_10 ||
  5743. (void *)opt->cb_arg == (void *)set_int_1_to_10) &&
  5744. opt->desc != opt_hidden &&
  5745. 0 <= *(int *)opt->u.arg)
  5746. fprintf(fcfg, ",\n\"%s\" : \"%d\"", p+2, *(int *)opt->u.arg);
  5747. }
  5748. }
  5749. /* Special case options */
  5750. if (request_target_str)
  5751. {
  5752. if (request_pdiff == (long)request_pdiff)
  5753. fprintf(fcfg, ",\n\"request-diff\" : %ld", (long)request_pdiff);
  5754. else
  5755. fprintf(fcfg, ",\n\"request-diff\" : %f", request_pdiff);
  5756. }
  5757. fprintf(fcfg, ",\n\"shares\" : \"%d\"", opt_shares);
  5758. if (pool_strategy == POOL_BALANCE)
  5759. fputs(",\n\"balance\" : true", fcfg);
  5760. if (pool_strategy == POOL_LOADBALANCE)
  5761. fputs(",\n\"load-balance\" : true", fcfg);
  5762. if (pool_strategy == POOL_ROUNDROBIN)
  5763. fputs(",\n\"round-robin\" : true", fcfg);
  5764. if (pool_strategy == POOL_ROTATE)
  5765. fprintf(fcfg, ",\n\"rotate\" : \"%d\"", opt_rotate_period);
  5766. #if defined(unix) || defined(__APPLE__)
  5767. if (opt_stderr_cmd && *opt_stderr_cmd)
  5768. fprintf(fcfg, ",\n\"monitor\" : \"%s\"", json_escape(opt_stderr_cmd));
  5769. #endif // defined(unix)
  5770. if (opt_kernel_path && *opt_kernel_path) {
  5771. char *kpath = strdup(opt_kernel_path);
  5772. if (kpath[strlen(kpath)-1] == '/')
  5773. kpath[strlen(kpath)-1] = 0;
  5774. fprintf(fcfg, ",\n\"kernel-path\" : \"%s\"", json_escape(kpath));
  5775. free(kpath);
  5776. }
  5777. if (schedstart.enable)
  5778. fprintf(fcfg, ",\n\"sched-time\" : \"%d:%d\"", schedstart.tm.tm_hour, schedstart.tm.tm_min);
  5779. if (schedstop.enable)
  5780. fprintf(fcfg, ",\n\"stop-time\" : \"%d:%d\"", schedstop.tm.tm_hour, schedstop.tm.tm_min);
  5781. if (opt_socks_proxy && *opt_socks_proxy)
  5782. fprintf(fcfg, ",\n\"socks-proxy\" : \"%s\"", json_escape(opt_socks_proxy));
  5783. _write_config_string_elist(fcfg, "scan", scan_devices);
  5784. #ifdef USE_LIBMICROHTTPD
  5785. if (httpsrv_port != -1)
  5786. fprintf(fcfg, ",\n\"http-port\" : %d", httpsrv_port);
  5787. #endif
  5788. #ifdef USE_LIBEVENT
  5789. if (stratumsrv_port != -1)
  5790. fprintf(fcfg, ",\n\"stratum-port\" : %d", stratumsrv_port);
  5791. #endif
  5792. _write_config_string_elist(fcfg, "device", opt_devices_enabled_list);
  5793. _write_config_string_elist(fcfg, "set-device", opt_set_device_list);
  5794. if (opt_api_allow)
  5795. fprintf(fcfg, ",\n\"api-allow\" : \"%s\"", json_escape(opt_api_allow));
  5796. if (strcmp(opt_api_mcast_addr, API_MCAST_ADDR) != 0)
  5797. fprintf(fcfg, ",\n\"api-mcast-addr\" : \"%s\"", json_escape(opt_api_mcast_addr));
  5798. if (strcmp(opt_api_mcast_code, API_MCAST_CODE) != 0)
  5799. fprintf(fcfg, ",\n\"api-mcast-code\" : \"%s\"", json_escape(opt_api_mcast_code));
  5800. if (*opt_api_mcast_des)
  5801. fprintf(fcfg, ",\n\"api-mcast-des\" : \"%s\"", json_escape(opt_api_mcast_des));
  5802. if (strcmp(opt_api_description, PACKAGE_STRING) != 0)
  5803. fprintf(fcfg, ",\n\"api-description\" : \"%s\"", json_escape(opt_api_description));
  5804. if (opt_api_groups)
  5805. fprintf(fcfg, ",\n\"api-groups\" : \"%s\"", json_escape(opt_api_groups));
  5806. if (opt_icarus_options)
  5807. fprintf(fcfg, ",\n\"icarus-options\" : \"%s\"", json_escape(opt_icarus_options));
  5808. if (opt_icarus_timing)
  5809. fprintf(fcfg, ",\n\"icarus-timing\" : \"%s\"", json_escape(opt_icarus_timing));
  5810. #ifdef USE_KLONDIKE
  5811. if (opt_klondike_options)
  5812. fprintf(fcfg, ",\n\"klondike-options\" : \"%s\"", json_escape(opt_klondike_options));
  5813. #endif
  5814. fputs("\n}\n", fcfg);
  5815. json_escape_free();
  5816. }
  5817. void zero_bestshare(void)
  5818. {
  5819. int i;
  5820. best_diff = 0;
  5821. memset(best_share, 0, 8);
  5822. suffix_string(best_diff, best_share, sizeof(best_share), 0);
  5823. for (i = 0; i < total_pools; i++) {
  5824. struct pool *pool = pools[i];
  5825. pool->best_diff = 0;
  5826. }
  5827. }
  5828. void zero_stats(void)
  5829. {
  5830. int i;
  5831. applog(LOG_DEBUG, "Zeroing stats");
  5832. cgtime(&total_tv_start);
  5833. miner_started = total_tv_start;
  5834. total_rolling = 0;
  5835. total_mhashes_done = 0;
  5836. total_getworks = 0;
  5837. total_accepted = 0;
  5838. total_rejected = 0;
  5839. hw_errors = 0;
  5840. total_stale = 0;
  5841. total_discarded = 0;
  5842. total_bytes_rcvd = total_bytes_sent = 0;
  5843. new_blocks = 0;
  5844. local_work = 0;
  5845. total_go = 0;
  5846. total_ro = 0;
  5847. total_secs = 1.0;
  5848. total_diff1 = 0;
  5849. total_bad_diff1 = 0;
  5850. found_blocks = 0;
  5851. total_diff_accepted = 0;
  5852. total_diff_rejected = 0;
  5853. total_diff_stale = 0;
  5854. #ifdef HAVE_CURSES
  5855. awidth = rwidth = swidth = hwwidth = 1;
  5856. #endif
  5857. for (i = 0; i < total_pools; i++) {
  5858. struct pool *pool = pools[i];
  5859. pool->getwork_requested = 0;
  5860. pool->accepted = 0;
  5861. pool->rejected = 0;
  5862. pool->solved = 0;
  5863. pool->getwork_requested = 0;
  5864. pool->stale_shares = 0;
  5865. pool->discarded_work = 0;
  5866. pool->getfail_occasions = 0;
  5867. pool->remotefail_occasions = 0;
  5868. pool->last_share_time = 0;
  5869. pool->diff1 = 0;
  5870. pool->diff_accepted = 0;
  5871. pool->diff_rejected = 0;
  5872. pool->diff_stale = 0;
  5873. pool->last_share_diff = 0;
  5874. pool->cgminer_stats.start_tv = total_tv_start;
  5875. pool->cgminer_stats.getwork_calls = 0;
  5876. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  5877. pool->cgminer_stats.getwork_wait_max.tv_sec = 0;
  5878. pool->cgminer_stats.getwork_wait_max.tv_usec = 0;
  5879. pool->cgminer_pool_stats.getwork_calls = 0;
  5880. pool->cgminer_pool_stats.getwork_attempts = 0;
  5881. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  5882. pool->cgminer_pool_stats.getwork_wait_max.tv_sec = 0;
  5883. pool->cgminer_pool_stats.getwork_wait_max.tv_usec = 0;
  5884. pool->cgminer_pool_stats.min_diff = 0;
  5885. pool->cgminer_pool_stats.max_diff = 0;
  5886. pool->cgminer_pool_stats.min_diff_count = 0;
  5887. pool->cgminer_pool_stats.max_diff_count = 0;
  5888. pool->cgminer_pool_stats.times_sent = 0;
  5889. pool->cgminer_pool_stats.bytes_sent = 0;
  5890. pool->cgminer_pool_stats.net_bytes_sent = 0;
  5891. pool->cgminer_pool_stats.times_received = 0;
  5892. pool->cgminer_pool_stats.bytes_received = 0;
  5893. pool->cgminer_pool_stats.net_bytes_received = 0;
  5894. }
  5895. zero_bestshare();
  5896. for (i = 0; i < total_devices; ++i) {
  5897. struct cgpu_info *cgpu = get_devices(i);
  5898. mutex_lock(&hash_lock);
  5899. cgpu->total_mhashes = 0;
  5900. cgpu->accepted = 0;
  5901. cgpu->rejected = 0;
  5902. cgpu->stale = 0;
  5903. cgpu->hw_errors = 0;
  5904. cgpu->utility = 0.0;
  5905. cgpu->utility_diff1 = 0;
  5906. cgpu->last_share_pool_time = 0;
  5907. cgpu->bad_diff1 = 0;
  5908. cgpu->diff1 = 0;
  5909. cgpu->diff_accepted = 0;
  5910. cgpu->diff_rejected = 0;
  5911. cgpu->diff_stale = 0;
  5912. cgpu->last_share_diff = 0;
  5913. cgpu->thread_fail_init_count = 0;
  5914. cgpu->thread_zero_hash_count = 0;
  5915. cgpu->thread_fail_queue_count = 0;
  5916. cgpu->dev_sick_idle_60_count = 0;
  5917. cgpu->dev_dead_idle_600_count = 0;
  5918. cgpu->dev_nostart_count = 0;
  5919. cgpu->dev_over_heat_count = 0;
  5920. cgpu->dev_thermal_cutoff_count = 0;
  5921. cgpu->dev_comms_error_count = 0;
  5922. cgpu->dev_throttle_count = 0;
  5923. cgpu->cgminer_stats.start_tv = total_tv_start;
  5924. cgpu->cgminer_stats.getwork_calls = 0;
  5925. cgpu->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  5926. cgpu->cgminer_stats.getwork_wait_max.tv_sec = 0;
  5927. cgpu->cgminer_stats.getwork_wait_max.tv_usec = 0;
  5928. mutex_unlock(&hash_lock);
  5929. }
  5930. }
  5931. #ifdef HAVE_CURSES
  5932. static
  5933. void loginput_mode(const int size)
  5934. {
  5935. clear_logwin();
  5936. loginput_size = size;
  5937. check_winsizes();
  5938. }
  5939. static void display_pools(void)
  5940. {
  5941. struct pool *pool;
  5942. int selected, i, j;
  5943. char input;
  5944. loginput_mode(7 + total_pools);
  5945. immedok(logwin, true);
  5946. updated:
  5947. for (j = 0; j < total_pools; j++) {
  5948. for (i = 0; i < total_pools; i++) {
  5949. pool = pools[i];
  5950. if (pool->prio != j)
  5951. continue;
  5952. if (pool == current_pool())
  5953. wattron(logwin, A_BOLD);
  5954. if (pool->enabled != POOL_ENABLED)
  5955. wattron(logwin, A_DIM);
  5956. wlogprint("%d: ", pool->prio);
  5957. switch (pool->enabled) {
  5958. case POOL_ENABLED:
  5959. wlogprint("Enabled ");
  5960. break;
  5961. case POOL_DISABLED:
  5962. wlogprint("Disabled ");
  5963. break;
  5964. case POOL_REJECTING:
  5965. wlogprint("Rejectin ");
  5966. break;
  5967. }
  5968. if (pool->idle)
  5969. wlogprint("Dead ");
  5970. else
  5971. if (pool->has_stratum)
  5972. wlogprint("Strtm");
  5973. else
  5974. if (pool->lp_url && pool->proto != pool->lp_proto)
  5975. wlogprint("Mixed");
  5976. else
  5977. switch (pool->proto) {
  5978. case PLP_GETBLOCKTEMPLATE:
  5979. wlogprint(" GBT ");
  5980. break;
  5981. case PLP_GETWORK:
  5982. wlogprint("GWork");
  5983. break;
  5984. default:
  5985. wlogprint("Alive");
  5986. }
  5987. wlogprint(" Quota %d Pool %d: %s User:%s\n",
  5988. pool->quota,
  5989. pool->pool_no,
  5990. pool->rpc_url, pool->rpc_user);
  5991. wattroff(logwin, A_BOLD | A_DIM);
  5992. break; //for (i = 0; i < total_pools; i++)
  5993. }
  5994. }
  5995. retry:
  5996. wlogprint("\nCurrent pool management strategy: %s\n",
  5997. strategies[pool_strategy].s);
  5998. if (pool_strategy == POOL_ROTATE)
  5999. wlogprint("Set to rotate every %d minutes\n", opt_rotate_period);
  6000. wlogprint("[F]ailover only %s\n", opt_fail_only ? "enabled" : "disabled");
  6001. wlogprint("Pool [A]dd [R]emove [D]isable [E]nable [P]rioritize [Q]uota change\n");
  6002. wlogprint("[C]hange management strategy [S]witch pool [I]nformation\n");
  6003. wlogprint("Or press any other key to continue\n");
  6004. logwin_update();
  6005. input = getch();
  6006. if (!strncasecmp(&input, "a", 1)) {
  6007. input_pool(true);
  6008. goto updated;
  6009. } else if (!strncasecmp(&input, "r", 1)) {
  6010. if (total_pools <= 1) {
  6011. wlogprint("Cannot remove last pool");
  6012. goto retry;
  6013. }
  6014. selected = curses_int("Select pool number");
  6015. if (selected < 0 || selected >= total_pools) {
  6016. wlogprint("Invalid selection\n");
  6017. goto retry;
  6018. }
  6019. pool = pools[selected];
  6020. if (pool == current_pool())
  6021. switch_pools(NULL);
  6022. if (pool == current_pool()) {
  6023. wlogprint("Unable to remove pool due to activity\n");
  6024. goto retry;
  6025. }
  6026. disable_pool(pool);
  6027. remove_pool(pool);
  6028. goto updated;
  6029. } else if (!strncasecmp(&input, "s", 1)) {
  6030. selected = curses_int("Select pool number");
  6031. if (selected < 0 || selected >= total_pools) {
  6032. wlogprint("Invalid selection\n");
  6033. goto retry;
  6034. }
  6035. pool = pools[selected];
  6036. enable_pool(pool);
  6037. switch_pools(pool);
  6038. goto updated;
  6039. } else if (!strncasecmp(&input, "d", 1)) {
  6040. if (enabled_pools <= 1) {
  6041. wlogprint("Cannot disable last pool");
  6042. goto retry;
  6043. }
  6044. selected = curses_int("Select pool number");
  6045. if (selected < 0 || selected >= total_pools) {
  6046. wlogprint("Invalid selection\n");
  6047. goto retry;
  6048. }
  6049. pool = pools[selected];
  6050. disable_pool(pool);
  6051. if (pool == current_pool())
  6052. switch_pools(NULL);
  6053. goto updated;
  6054. } else if (!strncasecmp(&input, "e", 1)) {
  6055. selected = curses_int("Select pool number");
  6056. if (selected < 0 || selected >= total_pools) {
  6057. wlogprint("Invalid selection\n");
  6058. goto retry;
  6059. }
  6060. pool = pools[selected];
  6061. enable_pool(pool);
  6062. if (pool->prio < current_pool()->prio)
  6063. switch_pools(pool);
  6064. goto updated;
  6065. } else if (!strncasecmp(&input, "c", 1)) {
  6066. for (i = 0; i <= TOP_STRATEGY; i++)
  6067. wlogprint("%d: %s\n", i, strategies[i].s);
  6068. selected = curses_int("Select strategy number type");
  6069. if (selected < 0 || selected > TOP_STRATEGY) {
  6070. wlogprint("Invalid selection\n");
  6071. goto retry;
  6072. }
  6073. if (selected == POOL_ROTATE) {
  6074. opt_rotate_period = curses_int("Select interval in minutes");
  6075. if (opt_rotate_period < 0 || opt_rotate_period > 9999) {
  6076. opt_rotate_period = 0;
  6077. wlogprint("Invalid selection\n");
  6078. goto retry;
  6079. }
  6080. }
  6081. pool_strategy = selected;
  6082. switch_pools(NULL);
  6083. goto updated;
  6084. } else if (!strncasecmp(&input, "i", 1)) {
  6085. selected = curses_int("Select pool number");
  6086. if (selected < 0 || selected >= total_pools) {
  6087. wlogprint("Invalid selection\n");
  6088. goto retry;
  6089. }
  6090. pool = pools[selected];
  6091. display_pool_summary(pool);
  6092. goto retry;
  6093. } else if (!strncasecmp(&input, "q", 1)) {
  6094. selected = curses_int("Select pool number");
  6095. if (selected < 0 || selected >= total_pools) {
  6096. wlogprint("Invalid selection\n");
  6097. goto retry;
  6098. }
  6099. pool = pools[selected];
  6100. selected = curses_int("Set quota");
  6101. if (selected < 0) {
  6102. wlogprint("Invalid negative quota\n");
  6103. goto retry;
  6104. }
  6105. pool->quota = selected;
  6106. adjust_quota_gcd();
  6107. goto updated;
  6108. } else if (!strncasecmp(&input, "f", 1)) {
  6109. opt_fail_only ^= true;
  6110. goto updated;
  6111. } else if (!strncasecmp(&input, "p", 1)) {
  6112. char *prilist = curses_input("Enter new pool priority (comma separated list)");
  6113. if (!prilist)
  6114. {
  6115. wlogprint("Not changing priorities\n");
  6116. goto retry;
  6117. }
  6118. int res = prioritize_pools(prilist, &i);
  6119. free(prilist);
  6120. switch (res) {
  6121. case MSG_NOPOOL:
  6122. wlogprint("No pools\n");
  6123. goto retry;
  6124. case MSG_MISPID:
  6125. wlogprint("Missing pool id parameter\n");
  6126. goto retry;
  6127. case MSG_INVPID:
  6128. wlogprint("Invalid pool id %d - range is 0 - %d\n", i, total_pools - 1);
  6129. goto retry;
  6130. case MSG_DUPPID:
  6131. wlogprint("Duplicate pool specified %d\n", i);
  6132. goto retry;
  6133. case MSG_POOLPRIO:
  6134. default:
  6135. goto updated;
  6136. }
  6137. }
  6138. immedok(logwin, false);
  6139. loginput_mode(0);
  6140. }
  6141. static const char *summary_detail_level_str(void)
  6142. {
  6143. if (opt_compact)
  6144. return "compact";
  6145. if (opt_show_procs)
  6146. return "processors";
  6147. return "devices";
  6148. }
  6149. static void display_options(void)
  6150. {
  6151. int selected;
  6152. char input;
  6153. immedok(logwin, true);
  6154. loginput_mode(12);
  6155. retry:
  6156. clear_logwin();
  6157. wlogprint("[N]ormal [C]lear [S]ilent mode (disable all output)\n");
  6158. wlogprint("[D]ebug:%s\n[P]er-device:%s\n[Q]uiet:%s\n[V]erbose:%s\n"
  6159. "[R]PC debug:%s\n[W]orkTime details:%s\nsu[M]mary detail level:%s\n"
  6160. "[L]og interval:%d\nS[T]atistical counts: %s\n[Z]ero statistics\n",
  6161. opt_debug_console ? "on" : "off",
  6162. want_per_device_stats? "on" : "off",
  6163. opt_quiet ? "on" : "off",
  6164. opt_log_output ? "on" : "off",
  6165. opt_protocol ? "on" : "off",
  6166. opt_worktime ? "on" : "off",
  6167. summary_detail_level_str(),
  6168. opt_log_interval,
  6169. opt_weighed_stats ? "weighed" : "absolute");
  6170. wlogprint("Select an option or any other key to return\n");
  6171. logwin_update();
  6172. input = getch();
  6173. if (!strncasecmp(&input, "q", 1)) {
  6174. opt_quiet ^= true;
  6175. wlogprint("Quiet mode %s\n", opt_quiet ? "enabled" : "disabled");
  6176. goto retry;
  6177. } else if (!strncasecmp(&input, "v", 1)) {
  6178. opt_log_output ^= true;
  6179. if (opt_log_output)
  6180. opt_quiet = false;
  6181. wlogprint("Verbose mode %s\n", opt_log_output ? "enabled" : "disabled");
  6182. goto retry;
  6183. } else if (!strncasecmp(&input, "n", 1)) {
  6184. opt_log_output = false;
  6185. opt_debug_console = false;
  6186. opt_quiet = false;
  6187. opt_protocol = false;
  6188. opt_compact = false;
  6189. opt_show_procs = false;
  6190. devsummaryYOffset = 0;
  6191. want_per_device_stats = false;
  6192. wlogprint("Output mode reset to normal\n");
  6193. switch_logsize();
  6194. goto retry;
  6195. } else if (!strncasecmp(&input, "d", 1)) {
  6196. opt_debug = true;
  6197. opt_debug_console ^= true;
  6198. opt_log_output = opt_debug_console;
  6199. if (opt_debug_console)
  6200. opt_quiet = false;
  6201. wlogprint("Debug mode %s\n", opt_debug_console ? "enabled" : "disabled");
  6202. goto retry;
  6203. } else if (!strncasecmp(&input, "m", 1)) {
  6204. if (opt_compact)
  6205. opt_compact = false;
  6206. else
  6207. if (!opt_show_procs)
  6208. opt_show_procs = true;
  6209. else
  6210. {
  6211. opt_compact = true;
  6212. opt_show_procs = false;
  6213. devsummaryYOffset = 0;
  6214. }
  6215. wlogprint("su[M]mary detail level changed to: %s\n", summary_detail_level_str());
  6216. switch_logsize();
  6217. goto retry;
  6218. } else if (!strncasecmp(&input, "p", 1)) {
  6219. want_per_device_stats ^= true;
  6220. opt_log_output = want_per_device_stats;
  6221. wlogprint("Per-device stats %s\n", want_per_device_stats ? "enabled" : "disabled");
  6222. goto retry;
  6223. } else if (!strncasecmp(&input, "r", 1)) {
  6224. opt_protocol ^= true;
  6225. if (opt_protocol)
  6226. opt_quiet = false;
  6227. wlogprint("RPC protocol debugging %s\n", opt_protocol ? "enabled" : "disabled");
  6228. goto retry;
  6229. } else if (!strncasecmp(&input, "c", 1))
  6230. clear_logwin();
  6231. else if (!strncasecmp(&input, "l", 1)) {
  6232. selected = curses_int("Interval in seconds");
  6233. if (selected < 0 || selected > 9999) {
  6234. wlogprint("Invalid selection\n");
  6235. goto retry;
  6236. }
  6237. opt_log_interval = selected;
  6238. wlogprint("Log interval set to %d seconds\n", opt_log_interval);
  6239. goto retry;
  6240. } else if (!strncasecmp(&input, "s", 1)) {
  6241. opt_realquiet = true;
  6242. } else if (!strncasecmp(&input, "w", 1)) {
  6243. opt_worktime ^= true;
  6244. wlogprint("WorkTime details %s\n", opt_worktime ? "enabled" : "disabled");
  6245. goto retry;
  6246. } else if (!strncasecmp(&input, "t", 1)) {
  6247. opt_weighed_stats ^= true;
  6248. wlogprint("Now displaying %s statistics\n", opt_weighed_stats ? "weighed" : "absolute");
  6249. goto retry;
  6250. } else if (!strncasecmp(&input, "z", 1)) {
  6251. zero_stats();
  6252. goto retry;
  6253. }
  6254. immedok(logwin, false);
  6255. loginput_mode(0);
  6256. }
  6257. #endif
  6258. void default_save_file(char *filename)
  6259. {
  6260. #if defined(unix) || defined(__APPLE__)
  6261. if (getenv("HOME") && *getenv("HOME")) {
  6262. strcpy(filename, getenv("HOME"));
  6263. strcat(filename, "/");
  6264. }
  6265. else
  6266. strcpy(filename, "");
  6267. strcat(filename, ".bfgminer/");
  6268. mkdir(filename, 0777);
  6269. #else
  6270. strcpy(filename, "");
  6271. #endif
  6272. strcat(filename, def_conf);
  6273. }
  6274. #ifdef HAVE_CURSES
  6275. static void set_options(void)
  6276. {
  6277. int selected;
  6278. char input;
  6279. immedok(logwin, true);
  6280. loginput_mode(8);
  6281. retry:
  6282. wlogprint("\n[L]ongpoll: %s\n", want_longpoll ? "On" : "Off");
  6283. wlogprint("[Q]ueue: %d\n[S]cantime: %d\n[E]xpiry: %d\n[R]etries: %d\n"
  6284. "[W]rite config file\n[B]FGMiner restart\n",
  6285. opt_queue, opt_scantime, opt_expiry, opt_retries);
  6286. wlogprint("Select an option or any other key to return\n");
  6287. logwin_update();
  6288. input = getch();
  6289. if (!strncasecmp(&input, "q", 1)) {
  6290. selected = curses_int("Extra work items to queue");
  6291. if (selected < 0 || selected > 9999) {
  6292. wlogprint("Invalid selection\n");
  6293. goto retry;
  6294. }
  6295. opt_queue = selected;
  6296. goto retry;
  6297. } else if (!strncasecmp(&input, "l", 1)) {
  6298. if (want_longpoll)
  6299. stop_longpoll();
  6300. else
  6301. start_longpoll();
  6302. applog(LOG_WARNING, "Longpoll %s", want_longpoll ? "enabled" : "disabled");
  6303. goto retry;
  6304. } else if (!strncasecmp(&input, "s", 1)) {
  6305. selected = curses_int("Set scantime in seconds");
  6306. if (selected < 0 || selected > 9999) {
  6307. wlogprint("Invalid selection\n");
  6308. goto retry;
  6309. }
  6310. opt_scantime = selected;
  6311. goto retry;
  6312. } else if (!strncasecmp(&input, "e", 1)) {
  6313. selected = curses_int("Set expiry time in seconds");
  6314. if (selected < 0 || selected > 9999) {
  6315. wlogprint("Invalid selection\n");
  6316. goto retry;
  6317. }
  6318. opt_expiry = selected;
  6319. goto retry;
  6320. } else if (!strncasecmp(&input, "r", 1)) {
  6321. selected = curses_int("Retries before failing (-1 infinite)");
  6322. if (selected < -1 || selected > 9999) {
  6323. wlogprint("Invalid selection\n");
  6324. goto retry;
  6325. }
  6326. opt_retries = selected;
  6327. goto retry;
  6328. } else if (!strncasecmp(&input, "w", 1)) {
  6329. FILE *fcfg;
  6330. char *str, filename[PATH_MAX], prompt[PATH_MAX + 50];
  6331. default_save_file(filename);
  6332. snprintf(prompt, sizeof(prompt), "Config filename to write (Enter for default) [%s]", filename);
  6333. str = curses_input(prompt);
  6334. if (str) {
  6335. struct stat statbuf;
  6336. strcpy(filename, str);
  6337. free(str);
  6338. if (!stat(filename, &statbuf)) {
  6339. wlogprint("File exists, overwrite?\n");
  6340. input = getch();
  6341. if (strncasecmp(&input, "y", 1))
  6342. goto retry;
  6343. }
  6344. }
  6345. fcfg = fopen(filename, "w");
  6346. if (!fcfg) {
  6347. wlogprint("Cannot open or create file\n");
  6348. goto retry;
  6349. }
  6350. write_config(fcfg);
  6351. fclose(fcfg);
  6352. goto retry;
  6353. } else if (!strncasecmp(&input, "b", 1)) {
  6354. wlogprint("Are you sure?\n");
  6355. input = getch();
  6356. if (!strncasecmp(&input, "y", 1))
  6357. app_restart();
  6358. else
  6359. clear_logwin();
  6360. } else
  6361. clear_logwin();
  6362. loginput_mode(0);
  6363. immedok(logwin, false);
  6364. }
  6365. int scan_serial(const char *);
  6366. static
  6367. void _managetui_msg(const char *repr, const char **msg)
  6368. {
  6369. if (*msg)
  6370. {
  6371. applog(LOG_DEBUG, "ManageTUI: %"PRIpreprv": %s", repr, *msg);
  6372. wattron(logwin, A_BOLD);
  6373. wlogprint("%s", *msg);
  6374. wattroff(logwin, A_BOLD);
  6375. *msg = NULL;
  6376. }
  6377. logwin_update();
  6378. }
  6379. void manage_device(void)
  6380. {
  6381. char logline[256];
  6382. const char *msg = NULL;
  6383. struct cgpu_info *cgpu;
  6384. const struct device_drv *drv;
  6385. selecting_device = true;
  6386. immedok(logwin, true);
  6387. loginput_mode(12);
  6388. devchange:
  6389. if (unlikely(!total_devices))
  6390. {
  6391. clear_logwin();
  6392. wlogprint("(no devices)\n");
  6393. wlogprint("[Plus] Add device(s) [Enter] Close device manager\n");
  6394. _managetui_msg("(none)", &msg);
  6395. int input = getch();
  6396. switch (input)
  6397. {
  6398. case '+': case '=': // add new device
  6399. goto addnew;
  6400. default:
  6401. goto out;
  6402. }
  6403. }
  6404. cgpu = devices[selected_device];
  6405. drv = cgpu->drv;
  6406. refresh_devstatus();
  6407. refresh:
  6408. clear_logwin();
  6409. wlogprint("Select processor to manage using up/down arrow keys\n");
  6410. get_statline3(logline, sizeof(logline), cgpu, true, true);
  6411. wattron(logwin, A_BOLD);
  6412. wlogprint("%s", logline);
  6413. wattroff(logwin, A_BOLD);
  6414. wlogprint("\n");
  6415. if (cgpu->dev_manufacturer)
  6416. wlogprint(" %s from %s\n", (cgpu->dev_product ?: "Device"), cgpu->dev_manufacturer);
  6417. else
  6418. if (cgpu->dev_product)
  6419. wlogprint(" %s\n", cgpu->dev_product);
  6420. if (cgpu->dev_serial)
  6421. wlogprint("Serial: %s\n", cgpu->dev_serial);
  6422. if (cgpu->kname)
  6423. wlogprint("Kernel: %s\n", cgpu->kname);
  6424. if (drv->proc_wlogprint_status && likely(cgpu->status != LIFE_INIT))
  6425. drv->proc_wlogprint_status(cgpu);
  6426. wlogprint("\n");
  6427. // TODO: Last share at TIMESTAMP on pool N
  6428. // TODO: Custom device info/commands
  6429. if (cgpu->deven != DEV_ENABLED)
  6430. wlogprint("[E]nable ");
  6431. if (cgpu->deven != DEV_DISABLED)
  6432. wlogprint("[D]isable ");
  6433. if (drv->identify_device)
  6434. wlogprint("[I]dentify ");
  6435. if (drv->proc_tui_wlogprint_choices && likely(cgpu->status != LIFE_INIT))
  6436. drv->proc_tui_wlogprint_choices(cgpu);
  6437. wlogprint("\n");
  6438. wlogprint("[Slash] Find processor [Plus] Add device(s) [Enter] Close device manager\n");
  6439. _managetui_msg(cgpu->proc_repr, &msg);
  6440. while (true)
  6441. {
  6442. int input = getch();
  6443. applog(LOG_DEBUG, "ManageTUI: %"PRIpreprv": (choice %d)", cgpu->proc_repr, input);
  6444. switch (input) {
  6445. case 'd': case 'D':
  6446. if (cgpu->deven == DEV_DISABLED)
  6447. msg = "Processor already disabled\n";
  6448. else
  6449. {
  6450. cgpu->deven = DEV_DISABLED;
  6451. msg = "Processor being disabled\n";
  6452. }
  6453. goto refresh;
  6454. case 'e': case 'E':
  6455. if (cgpu->deven == DEV_ENABLED)
  6456. msg = "Processor already enabled\n";
  6457. else
  6458. {
  6459. proc_enable(cgpu);
  6460. msg = "Processor being enabled\n";
  6461. }
  6462. goto refresh;
  6463. case 'i': case 'I':
  6464. if (drv->identify_device && drv->identify_device(cgpu))
  6465. msg = "Identify command sent\n";
  6466. else
  6467. goto key_default;
  6468. goto refresh;
  6469. case KEY_DOWN:
  6470. if (selected_device >= total_devices - 1)
  6471. break;
  6472. ++selected_device;
  6473. goto devchange;
  6474. case KEY_UP:
  6475. if (selected_device <= 0)
  6476. break;
  6477. --selected_device;
  6478. goto devchange;
  6479. case KEY_NPAGE:
  6480. {
  6481. if (selected_device >= total_devices - 1)
  6482. break;
  6483. struct cgpu_info *mdev = devices[selected_device]->device;
  6484. do {
  6485. ++selected_device;
  6486. } while (devices[selected_device]->device == mdev && selected_device < total_devices - 1);
  6487. goto devchange;
  6488. }
  6489. case KEY_PPAGE:
  6490. {
  6491. if (selected_device <= 0)
  6492. break;
  6493. struct cgpu_info *mdev = devices[selected_device]->device;
  6494. do {
  6495. --selected_device;
  6496. } while (devices[selected_device]->device == mdev && selected_device > 0);
  6497. goto devchange;
  6498. }
  6499. case '/': case '?': // find device
  6500. {
  6501. static char *pattern = NULL;
  6502. char *newpattern = curses_input("Enter pattern");
  6503. if (newpattern)
  6504. {
  6505. free(pattern);
  6506. pattern = newpattern;
  6507. }
  6508. else
  6509. if (!pattern)
  6510. pattern = calloc(1, 1);
  6511. int match = cgpu_search(pattern, selected_device + 1);
  6512. if (match == -1)
  6513. {
  6514. msg = "Couldn't find device\n";
  6515. goto refresh;
  6516. }
  6517. selected_device = match;
  6518. goto devchange;
  6519. }
  6520. case '+': case '=': // add new device
  6521. {
  6522. addnew:
  6523. clear_logwin();
  6524. _wlogprint(
  6525. "Enter \"auto\", \"all\", or a serial port to probe for mining devices.\n"
  6526. "Prefix by a driver name and colon to only probe a specific driver.\n"
  6527. "For example: erupter:"
  6528. #ifdef WIN32
  6529. "\\\\.\\COM40"
  6530. #elif defined(__APPLE__)
  6531. "/dev/cu.SLAB_USBtoUART"
  6532. #else
  6533. "/dev/ttyUSB39"
  6534. #endif
  6535. "\n"
  6536. );
  6537. char *scanser = curses_input("Enter target");
  6538. if (scan_serial(scanser))
  6539. {
  6540. selected_device = total_devices - 1;
  6541. msg = "Device scan succeeded\n";
  6542. }
  6543. else
  6544. msg = "No new devices found\n";
  6545. goto devchange;
  6546. }
  6547. case 'Q': case 'q':
  6548. case KEY_BREAK: case KEY_BACKSPACE: case KEY_CANCEL: case KEY_CLOSE: case KEY_EXIT:
  6549. case '\x1b': // ESC
  6550. case KEY_ENTER:
  6551. case '\r': // Ctrl-M on Windows, with nonl
  6552. #ifdef PADENTER
  6553. case PADENTER: // pdcurses, used by Enter key on Windows with nonl
  6554. #endif
  6555. case '\n':
  6556. goto out;
  6557. default:
  6558. ;
  6559. key_default:
  6560. if (drv->proc_tui_handle_choice && likely(drv_ready(cgpu)))
  6561. {
  6562. msg = drv->proc_tui_handle_choice(cgpu, input);
  6563. if (msg)
  6564. goto refresh;
  6565. }
  6566. }
  6567. }
  6568. out:
  6569. selecting_device = false;
  6570. loginput_mode(0);
  6571. immedok(logwin, false);
  6572. }
  6573. void show_help(void)
  6574. {
  6575. loginput_mode(10);
  6576. // NOTE: wlogprint is a macro with a buffer limit
  6577. _wlogprint(
  6578. "ST: work in queue | F: network fails | NB: new blocks detected\n"
  6579. "AS: shares being submitted | BW: bandwidth (up/down)\n"
  6580. "E: # shares * diff per 2kB bw | U: shares/minute | BS: best share ever found\n"
  6581. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6582. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6583. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6584. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_BTEE
  6585. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6586. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6587. U8_HLINE U8_HLINE U8_HLINE U8_BTEE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6588. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6589. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6590. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6591. "\n"
  6592. "devices/processors hashing (only for totals line), hottest temperature\n"
  6593. );
  6594. wlogprint(
  6595. "hashrates: %ds decaying / all-time average / all-time average (effective)\n"
  6596. , opt_log_interval);
  6597. _wlogprint(
  6598. "A: accepted shares | R: rejected+discarded(%% of total)\n"
  6599. "HW: hardware errors / %% nonces invalid\n"
  6600. "\n"
  6601. "Press any key to clear"
  6602. );
  6603. logwin_update();
  6604. getch();
  6605. loginput_mode(0);
  6606. }
  6607. static void *input_thread(void __maybe_unused *userdata)
  6608. {
  6609. RenameThread("input");
  6610. if (!curses_active)
  6611. return NULL;
  6612. while (1) {
  6613. int input;
  6614. input = getch();
  6615. switch (input) {
  6616. case 'h': case 'H': case '?':
  6617. case KEY_F(1):
  6618. show_help();
  6619. break;
  6620. case 'q': case 'Q':
  6621. kill_work();
  6622. return NULL;
  6623. case 'd': case 'D':
  6624. display_options();
  6625. break;
  6626. case 'm': case 'M':
  6627. manage_device();
  6628. break;
  6629. case 'p': case 'P':
  6630. display_pools();
  6631. break;
  6632. case 's': case 'S':
  6633. set_options();
  6634. break;
  6635. #ifdef HAVE_CURSES
  6636. case KEY_DOWN:
  6637. {
  6638. const int visible_lines = logcursor - devcursor;
  6639. const int invisible_lines = total_lines - visible_lines;
  6640. if (devsummaryYOffset <= -invisible_lines)
  6641. break;
  6642. devsummaryYOffset -= 2;
  6643. }
  6644. case KEY_UP:
  6645. if (devsummaryYOffset == 0)
  6646. break;
  6647. ++devsummaryYOffset;
  6648. refresh_devstatus();
  6649. break;
  6650. case KEY_NPAGE:
  6651. {
  6652. const int visible_lines = logcursor - devcursor;
  6653. const int invisible_lines = total_lines - visible_lines;
  6654. if (devsummaryYOffset - visible_lines <= -invisible_lines)
  6655. devsummaryYOffset = -invisible_lines;
  6656. else
  6657. devsummaryYOffset -= visible_lines;
  6658. refresh_devstatus();
  6659. break;
  6660. }
  6661. case KEY_PPAGE:
  6662. {
  6663. const int visible_lines = logcursor - devcursor;
  6664. if (devsummaryYOffset + visible_lines >= 0)
  6665. devsummaryYOffset = 0;
  6666. else
  6667. devsummaryYOffset += visible_lines;
  6668. refresh_devstatus();
  6669. break;
  6670. }
  6671. #endif
  6672. }
  6673. if (opt_realquiet) {
  6674. disable_curses();
  6675. break;
  6676. }
  6677. }
  6678. return NULL;
  6679. }
  6680. #endif
  6681. static void *api_thread(void *userdata)
  6682. {
  6683. struct thr_info *mythr = userdata;
  6684. pthread_detach(pthread_self());
  6685. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  6686. RenameThread("rpc");
  6687. api(api_thr_id);
  6688. mythr->has_pth = false;
  6689. return NULL;
  6690. }
  6691. void thread_reportin(struct thr_info *thr)
  6692. {
  6693. cgtime(&thr->last);
  6694. thr->cgpu->status = LIFE_WELL;
  6695. thr->getwork = 0;
  6696. thr->cgpu->device_last_well = time(NULL);
  6697. }
  6698. void thread_reportout(struct thr_info *thr)
  6699. {
  6700. thr->getwork = time(NULL);
  6701. }
  6702. static void hashmeter(int thr_id, struct timeval *diff,
  6703. uint64_t hashes_done)
  6704. {
  6705. char logstatusline[256];
  6706. struct timeval temp_tv_end, total_diff;
  6707. double secs;
  6708. double local_secs;
  6709. static double local_mhashes_done = 0;
  6710. double local_mhashes = (double)hashes_done / 1000000.0;
  6711. bool showlog = false;
  6712. char cHr[h2bs_fmt_size[H2B_NOUNIT]], aHr[h2bs_fmt_size[H2B_NOUNIT]], uHr[h2bs_fmt_size[H2B_SPACED]];
  6713. char rejpcbuf[6];
  6714. char bnbuf[6];
  6715. struct thr_info *thr;
  6716. /* Update the last time this thread reported in */
  6717. if (thr_id >= 0) {
  6718. thr = get_thread(thr_id);
  6719. cgtime(&(thr->last));
  6720. thr->cgpu->device_last_well = time(NULL);
  6721. }
  6722. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  6723. /* So we can call hashmeter from a non worker thread */
  6724. if (thr_id >= 0) {
  6725. struct cgpu_info *cgpu = thr->cgpu;
  6726. int threadobj = cgpu->threads ?: 1;
  6727. double thread_rolling = 0.0;
  6728. int i;
  6729. applog(LOG_DEBUG, "[thread %d: %"PRIu64" hashes, %.1f khash/sec]",
  6730. thr_id, hashes_done, hashes_done / 1000 / secs);
  6731. /* Rolling average for each thread and each device */
  6732. decay_time(&thr->rolling, local_mhashes / secs, secs);
  6733. for (i = 0; i < threadobj; i++)
  6734. thread_rolling += cgpu->thr[i]->rolling;
  6735. mutex_lock(&hash_lock);
  6736. decay_time(&cgpu->rolling, thread_rolling, secs);
  6737. cgpu->total_mhashes += local_mhashes;
  6738. mutex_unlock(&hash_lock);
  6739. // If needed, output detailed, per-device stats
  6740. if (want_per_device_stats) {
  6741. struct timeval now;
  6742. struct timeval elapsed;
  6743. struct timeval *last_msg_tv = opt_show_procs ? &thr->cgpu->last_message_tv : &thr->cgpu->device->last_message_tv;
  6744. cgtime(&now);
  6745. timersub(&now, last_msg_tv, &elapsed);
  6746. if (opt_log_interval <= elapsed.tv_sec) {
  6747. struct cgpu_info *cgpu = thr->cgpu;
  6748. char logline[255];
  6749. *last_msg_tv = now;
  6750. get_statline(logline, sizeof(logline), cgpu);
  6751. if (!curses_active) {
  6752. printf("%s \r", logline);
  6753. fflush(stdout);
  6754. } else
  6755. applog(LOG_INFO, "%s", logline);
  6756. }
  6757. }
  6758. }
  6759. /* Totals are updated by all threads so can race without locking */
  6760. mutex_lock(&hash_lock);
  6761. cgtime(&temp_tv_end);
  6762. timersub(&temp_tv_end, &total_tv_end, &total_diff);
  6763. total_mhashes_done += local_mhashes;
  6764. local_mhashes_done += local_mhashes;
  6765. /* Only update with opt_log_interval */
  6766. if (total_diff.tv_sec < opt_log_interval)
  6767. goto out_unlock;
  6768. showlog = true;
  6769. cgtime(&total_tv_end);
  6770. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  6771. decay_time(&total_rolling, local_mhashes_done / local_secs, local_secs);
  6772. global_hashrate = ((unsigned long long)lround(total_rolling)) * 1000000;
  6773. timersub(&total_tv_end, &total_tv_start, &total_diff);
  6774. total_secs = (double)total_diff.tv_sec +
  6775. ((double)total_diff.tv_usec / 1000000.0);
  6776. double wtotal = (total_diff_accepted + total_diff_rejected + total_diff_stale);
  6777. multi_format_unit_array2(
  6778. ((char*[]){cHr, aHr, uHr}),
  6779. ((size_t[]){h2bs_fmt_size[H2B_NOUNIT], h2bs_fmt_size[H2B_NOUNIT], h2bs_fmt_size[H2B_SPACED]}),
  6780. true, "h/s", H2B_SHORT,
  6781. 3,
  6782. 1e6*total_rolling,
  6783. 1e6*total_mhashes_done / total_secs,
  6784. utility_to_hashrate(total_diff1 * (wtotal ? (total_diff_accepted / wtotal) : 1) * 60 / total_secs));
  6785. int ui_accepted, ui_rejected, ui_stale;
  6786. if (opt_weighed_stats)
  6787. {
  6788. ui_accepted = total_diff_accepted;
  6789. ui_rejected = total_diff_rejected;
  6790. ui_stale = total_diff_stale;
  6791. }
  6792. else
  6793. {
  6794. ui_accepted = total_accepted;
  6795. ui_rejected = total_rejected;
  6796. ui_stale = total_stale;
  6797. }
  6798. #ifdef HAVE_CURSES
  6799. if (curses_active_locked()) {
  6800. float temp = 0;
  6801. struct cgpu_info *proc, *last_working_dev = NULL;
  6802. int i, working_devs = 0, working_procs = 0;
  6803. int divx;
  6804. bool bad = false;
  6805. // Find the highest temperature of all processors
  6806. for (i = 0; i < total_devices; ++i)
  6807. {
  6808. proc = get_devices(i);
  6809. if (proc->temp > temp)
  6810. temp = proc->temp;
  6811. if (unlikely(proc->deven == DEV_DISABLED))
  6812. ; // Just need to block it off from both conditions
  6813. else
  6814. if (likely(proc->status == LIFE_WELL && proc->deven == DEV_ENABLED))
  6815. {
  6816. if (proc->rolling > .1)
  6817. {
  6818. ++working_procs;
  6819. if (proc->device != last_working_dev)
  6820. {
  6821. ++working_devs;
  6822. last_working_dev = proc->device;
  6823. }
  6824. }
  6825. }
  6826. else
  6827. bad = true;
  6828. }
  6829. if (working_devs == working_procs)
  6830. snprintf(statusline, sizeof(statusline), "%s%d ", bad ? U8_BAD_START : "", working_devs);
  6831. else
  6832. snprintf(statusline, sizeof(statusline), "%s%d/%d ", bad ? U8_BAD_START : "", working_devs, working_procs);
  6833. divx = 7;
  6834. if (opt_show_procs && !opt_compact)
  6835. ++divx;
  6836. if (bad)
  6837. {
  6838. divx += sizeof(U8_BAD_START)-1;
  6839. strcpy(&statusline[divx], U8_BAD_END);
  6840. divx += sizeof(U8_BAD_END)-1;
  6841. }
  6842. temperature_column(&statusline[divx], sizeof(statusline)-divx, true, &temp);
  6843. format_statline(statusline, sizeof(statusline),
  6844. cHr, aHr,
  6845. uHr,
  6846. ui_accepted,
  6847. ui_rejected,
  6848. ui_stale,
  6849. total_diff_rejected + total_diff_stale, total_diff_accepted,
  6850. hw_errors,
  6851. total_bad_diff1, total_bad_diff1 + total_diff1);
  6852. unlock_curses();
  6853. }
  6854. #endif
  6855. // Add a space
  6856. memmove(&uHr[6], &uHr[5], strlen(&uHr[5]) + 1);
  6857. uHr[5] = ' ';
  6858. percentf4(rejpcbuf, sizeof(rejpcbuf), total_diff_rejected + total_diff_stale, total_diff_accepted);
  6859. percentf4(bnbuf, sizeof(bnbuf), total_bad_diff1, total_diff1);
  6860. snprintf(logstatusline, sizeof(logstatusline),
  6861. "%s%ds:%s avg:%s u:%s | A:%d R:%d+%d(%s) HW:%d/%s",
  6862. want_per_device_stats ? "ALL " : "",
  6863. opt_log_interval,
  6864. cHr, aHr,
  6865. uHr,
  6866. ui_accepted,
  6867. ui_rejected,
  6868. ui_stale,
  6869. rejpcbuf,
  6870. hw_errors,
  6871. bnbuf
  6872. );
  6873. local_mhashes_done = 0;
  6874. out_unlock:
  6875. mutex_unlock(&hash_lock);
  6876. if (showlog) {
  6877. if (!curses_active) {
  6878. printf("%s \r", logstatusline);
  6879. fflush(stdout);
  6880. } else
  6881. applog(LOG_INFO, "%s", logstatusline);
  6882. }
  6883. }
  6884. void hashmeter2(struct thr_info *thr)
  6885. {
  6886. struct timeval tv_now, tv_elapsed;
  6887. timerclear(&thr->tv_hashes_done);
  6888. cgtime(&tv_now);
  6889. timersub(&tv_now, &thr->tv_lastupdate, &tv_elapsed);
  6890. /* Update the hashmeter at most 5 times per second */
  6891. if ((thr->hashes_done && (tv_elapsed.tv_sec > 0 || tv_elapsed.tv_usec > 200000)) ||
  6892. tv_elapsed.tv_sec >= opt_log_interval) {
  6893. hashmeter(thr->id, &tv_elapsed, thr->hashes_done);
  6894. thr->hashes_done = 0;
  6895. thr->tv_lastupdate = tv_now;
  6896. }
  6897. }
  6898. static void stratum_share_result(json_t *val, json_t *res_val, json_t *err_val,
  6899. struct stratum_share *sshare)
  6900. {
  6901. struct work *work = sshare->work;
  6902. share_result(val, res_val, err_val, work, false, "");
  6903. }
  6904. /* Parses stratum json responses and tries to find the id that the request
  6905. * matched to and treat it accordingly. */
  6906. bool parse_stratum_response(struct pool *pool, char *s)
  6907. {
  6908. json_t *val = NULL, *err_val, *res_val, *id_val;
  6909. struct stratum_share *sshare;
  6910. json_error_t err;
  6911. bool ret = false;
  6912. int id;
  6913. val = JSON_LOADS(s, &err);
  6914. if (!val) {
  6915. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  6916. goto out;
  6917. }
  6918. res_val = json_object_get(val, "result");
  6919. err_val = json_object_get(val, "error");
  6920. id_val = json_object_get(val, "id");
  6921. if (json_is_null(id_val) || !id_val) {
  6922. char *ss;
  6923. if (err_val)
  6924. ss = json_dumps(err_val, JSON_INDENT(3));
  6925. else
  6926. ss = strdup("(unknown reason)");
  6927. applog(LOG_INFO, "JSON-RPC non method decode failed: %s", ss);
  6928. free(ss);
  6929. goto out;
  6930. }
  6931. if (!json_is_integer(id_val)) {
  6932. if (json_is_string(id_val)
  6933. && !strncmp(json_string_value(id_val), "txlist", 6))
  6934. {
  6935. const bool is_array = json_is_array(res_val);
  6936. applog(LOG_DEBUG, "Received %s for pool %u job %s",
  6937. is_array ? "transaction list" : "no-transaction-list response",
  6938. pool->pool_no, &json_string_value(id_val)[6]);
  6939. if (strcmp(json_string_value(id_val) + 6, pool->swork.job_id) || !is_array)
  6940. // We only care about a transaction list for the current job id
  6941. goto fishy;
  6942. // Check that the transactions actually hash to the merkle links
  6943. {
  6944. unsigned maxtx = 1 << pool->swork.merkles;
  6945. unsigned mintx = maxtx >> 1;
  6946. --maxtx;
  6947. unsigned acttx = (unsigned)json_array_size(res_val);
  6948. if (acttx < mintx || acttx > maxtx) {
  6949. applog(LOG_WARNING, "Pool %u is sending mismatched block contents to us (%u is not %u-%u)",
  6950. pool->pool_no, acttx, mintx, maxtx);
  6951. goto fishy;
  6952. }
  6953. // TODO: Check hashes match actual merkle links
  6954. }
  6955. pool_set_opaque(pool, false);
  6956. timer_unset(&pool->swork.tv_transparency);
  6957. fishy:
  6958. ret = true;
  6959. }
  6960. goto out;
  6961. }
  6962. id = json_integer_value(id_val);
  6963. mutex_lock(&sshare_lock);
  6964. HASH_FIND_INT(stratum_shares, &id, sshare);
  6965. if (sshare)
  6966. HASH_DEL(stratum_shares, sshare);
  6967. mutex_unlock(&sshare_lock);
  6968. if (!sshare) {
  6969. double pool_diff;
  6970. /* Since the share is untracked, we can only guess at what the
  6971. * work difficulty is based on the current pool diff. */
  6972. cg_rlock(&pool->data_lock);
  6973. pool_diff = pool->swork.diff;
  6974. cg_runlock(&pool->data_lock);
  6975. if (json_is_true(res_val)) {
  6976. applog(LOG_NOTICE, "Accepted untracked stratum share from pool %d", pool->pool_no);
  6977. /* We don't know what device this came from so we can't
  6978. * attribute the work to the relevant cgpu */
  6979. mutex_lock(&stats_lock);
  6980. total_accepted++;
  6981. pool->accepted++;
  6982. total_diff_accepted += pool_diff;
  6983. pool->diff_accepted += pool_diff;
  6984. mutex_unlock(&stats_lock);
  6985. } else {
  6986. applog(LOG_NOTICE, "Rejected untracked stratum share from pool %d", pool->pool_no);
  6987. mutex_lock(&stats_lock);
  6988. total_rejected++;
  6989. pool->rejected++;
  6990. total_diff_rejected += pool_diff;
  6991. pool->diff_rejected += pool_diff;
  6992. mutex_unlock(&stats_lock);
  6993. }
  6994. goto out;
  6995. }
  6996. else {
  6997. mutex_lock(&submitting_lock);
  6998. --total_submitting;
  6999. mutex_unlock(&submitting_lock);
  7000. }
  7001. stratum_share_result(val, res_val, err_val, sshare);
  7002. free_work(sshare->work);
  7003. free(sshare);
  7004. ret = true;
  7005. out:
  7006. if (val)
  7007. json_decref(val);
  7008. return ret;
  7009. }
  7010. static void shutdown_stratum(struct pool *pool)
  7011. {
  7012. // Shut down Stratum as if we never had it
  7013. pool->stratum_active = false;
  7014. pool->stratum_init = false;
  7015. pool->has_stratum = false;
  7016. shutdown(pool->sock, SHUT_RDWR);
  7017. free(pool->stratum_url);
  7018. if (pool->sockaddr_url == pool->stratum_url)
  7019. pool->sockaddr_url = NULL;
  7020. pool->stratum_url = NULL;
  7021. }
  7022. void clear_stratum_shares(struct pool *pool)
  7023. {
  7024. int my_mining_threads = mining_threads; // Cached outside of locking
  7025. struct stratum_share *sshare, *tmpshare;
  7026. struct work *work;
  7027. struct cgpu_info *cgpu;
  7028. double diff_cleared = 0;
  7029. double thr_diff_cleared[my_mining_threads];
  7030. int cleared = 0;
  7031. int thr_cleared[my_mining_threads];
  7032. // NOTE: This is per-thread rather than per-device to avoid getting devices lock in stratum_shares loop
  7033. for (int i = 0; i < my_mining_threads; ++i)
  7034. {
  7035. thr_diff_cleared[i] = 0;
  7036. thr_cleared[i] = 0;
  7037. }
  7038. mutex_lock(&sshare_lock);
  7039. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  7040. work = sshare->work;
  7041. if (sshare->work->pool == pool && work->thr_id < my_mining_threads) {
  7042. HASH_DEL(stratum_shares, sshare);
  7043. sharelog("disconnect", work);
  7044. diff_cleared += sshare->work->work_difficulty;
  7045. thr_diff_cleared[work->thr_id] += work->work_difficulty;
  7046. ++thr_cleared[work->thr_id];
  7047. free_work(sshare->work);
  7048. free(sshare);
  7049. cleared++;
  7050. }
  7051. }
  7052. mutex_unlock(&sshare_lock);
  7053. if (cleared) {
  7054. applog(LOG_WARNING, "Lost %d shares due to stratum disconnect on pool %d", cleared, pool->pool_no);
  7055. mutex_lock(&stats_lock);
  7056. pool->stale_shares += cleared;
  7057. total_stale += cleared;
  7058. pool->diff_stale += diff_cleared;
  7059. total_diff_stale += diff_cleared;
  7060. for (int i = 0; i < my_mining_threads; ++i)
  7061. if (thr_cleared[i])
  7062. {
  7063. cgpu = get_thr_cgpu(i);
  7064. cgpu->diff_stale += thr_diff_cleared[i];
  7065. cgpu->stale += thr_cleared[i];
  7066. }
  7067. mutex_unlock(&stats_lock);
  7068. mutex_lock(&submitting_lock);
  7069. total_submitting -= cleared;
  7070. mutex_unlock(&submitting_lock);
  7071. }
  7072. }
  7073. static void resubmit_stratum_shares(struct pool *pool)
  7074. {
  7075. struct stratum_share *sshare, *tmpshare;
  7076. struct work *work;
  7077. unsigned resubmitted = 0;
  7078. mutex_lock(&sshare_lock);
  7079. mutex_lock(&submitting_lock);
  7080. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  7081. if (sshare->work->pool != pool)
  7082. continue;
  7083. HASH_DEL(stratum_shares, sshare);
  7084. work = sshare->work;
  7085. DL_APPEND(submit_waiting, work);
  7086. free(sshare);
  7087. ++resubmitted;
  7088. }
  7089. mutex_unlock(&submitting_lock);
  7090. mutex_unlock(&sshare_lock);
  7091. if (resubmitted) {
  7092. notifier_wake(submit_waiting_notifier);
  7093. applog(LOG_DEBUG, "Resubmitting %u shares due to stratum disconnect on pool %u", resubmitted, pool->pool_no);
  7094. }
  7095. }
  7096. static void clear_pool_work(struct pool *pool)
  7097. {
  7098. struct work *work, *tmp;
  7099. int cleared = 0;
  7100. mutex_lock(stgd_lock);
  7101. HASH_ITER(hh, staged_work, work, tmp) {
  7102. if (work->pool == pool) {
  7103. HASH_DEL(staged_work, work);
  7104. free_work(work);
  7105. cleared++;
  7106. staged_full = false;
  7107. }
  7108. }
  7109. mutex_unlock(stgd_lock);
  7110. }
  7111. static int cp_prio(void)
  7112. {
  7113. int prio;
  7114. cg_rlock(&control_lock);
  7115. prio = currentpool->prio;
  7116. cg_runlock(&control_lock);
  7117. return prio;
  7118. }
  7119. /* We only need to maintain a secondary pool connection when we need the
  7120. * capacity to get work from the backup pools while still on the primary */
  7121. static bool cnx_needed(struct pool *pool)
  7122. {
  7123. struct pool *cp;
  7124. if (pool->enabled != POOL_ENABLED)
  7125. return false;
  7126. /* Balance strategies need all pools online */
  7127. if (pool_strategy == POOL_BALANCE)
  7128. return true;
  7129. if (pool_strategy == POOL_LOADBALANCE)
  7130. return true;
  7131. /* Idle stratum pool needs something to kick it alive again */
  7132. if (pool->has_stratum && pool->idle)
  7133. return true;
  7134. /* Getwork pools without opt_fail_only need backup pools up to be able
  7135. * to leak shares */
  7136. cp = current_pool();
  7137. if (cp == pool)
  7138. return true;
  7139. if (!pool_localgen(cp) && (!opt_fail_only || !cp->hdr_path))
  7140. return true;
  7141. /* Keep the connection open to allow any stray shares to be submitted
  7142. * on switching pools for 2 minutes. */
  7143. if (!timer_passed(&pool->tv_last_work_time, NULL))
  7144. return true;
  7145. /* If the pool has only just come to life and is higher priority than
  7146. * the current pool keep the connection open so we can fail back to
  7147. * it. */
  7148. if (pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  7149. return true;
  7150. if (pool_unworkable(cp))
  7151. return true;
  7152. /* We've run out of work, bring anything back to life. */
  7153. if (no_work)
  7154. return true;
  7155. return false;
  7156. }
  7157. static void wait_lpcurrent(struct pool *pool);
  7158. static void pool_resus(struct pool *pool);
  7159. static void gen_stratum_work(struct pool *pool, struct work *work);
  7160. static void stratum_resumed(struct pool *pool)
  7161. {
  7162. if (!pool->stratum_notify)
  7163. return;
  7164. if (pool_tclear(pool, &pool->idle)) {
  7165. applog(LOG_INFO, "Stratum connection to pool %d resumed", pool->pool_no);
  7166. pool_resus(pool);
  7167. }
  7168. }
  7169. static bool supports_resume(struct pool *pool)
  7170. {
  7171. bool ret;
  7172. cg_rlock(&pool->data_lock);
  7173. ret = (pool->sessionid != NULL);
  7174. cg_runlock(&pool->data_lock);
  7175. return ret;
  7176. }
  7177. /* One stratum thread per pool that has stratum waits on the socket checking
  7178. * for new messages and for the integrity of the socket connection. We reset
  7179. * the connection based on the integrity of the receive side only as the send
  7180. * side will eventually expire data it fails to send. */
  7181. static void *stratum_thread(void *userdata)
  7182. {
  7183. struct pool *pool = (struct pool *)userdata;
  7184. pthread_detach(pthread_self());
  7185. char threadname[20];
  7186. snprintf(threadname, 20, "stratum%u", pool->pool_no);
  7187. RenameThread(threadname);
  7188. srand(time(NULL) + (intptr_t)userdata);
  7189. while (42) {
  7190. struct timeval timeout;
  7191. int sel_ret;
  7192. fd_set rd;
  7193. char *s;
  7194. int sock;
  7195. if (unlikely(!pool->has_stratum))
  7196. break;
  7197. /* Check to see whether we need to maintain this connection
  7198. * indefinitely or just bring it up when we switch to this
  7199. * pool */
  7200. while (true)
  7201. {
  7202. sock = pool->sock;
  7203. if (sock == INVSOCK)
  7204. applog(LOG_DEBUG, "Pool %u: Invalid socket, suspending",
  7205. pool->pool_no);
  7206. else
  7207. if (!sock_full(pool) && !cnx_needed(pool))
  7208. applog(LOG_DEBUG, "Pool %u: Connection not needed, suspending",
  7209. pool->pool_no);
  7210. else
  7211. break;
  7212. suspend_stratum(pool);
  7213. clear_stratum_shares(pool);
  7214. clear_pool_work(pool);
  7215. wait_lpcurrent(pool);
  7216. if (!restart_stratum(pool)) {
  7217. pool_died(pool);
  7218. while (!restart_stratum(pool)) {
  7219. if (pool->removed)
  7220. goto out;
  7221. cgsleep_ms(30000);
  7222. }
  7223. }
  7224. }
  7225. FD_ZERO(&rd);
  7226. FD_SET(sock, &rd);
  7227. timeout.tv_sec = 120;
  7228. timeout.tv_usec = 0;
  7229. /* If we fail to receive any notify messages for 2 minutes we
  7230. * assume the connection has been dropped and treat this pool
  7231. * as dead */
  7232. if (!sock_full(pool) && (sel_ret = select(sock + 1, &rd, NULL, NULL, &timeout)) < 1) {
  7233. applog(LOG_DEBUG, "Stratum select failed on pool %d with value %d", pool->pool_no, sel_ret);
  7234. s = NULL;
  7235. } else
  7236. s = recv_line(pool);
  7237. if (!s) {
  7238. if (!pool->has_stratum)
  7239. break;
  7240. applog(LOG_NOTICE, "Stratum connection to pool %d interrupted", pool->pool_no);
  7241. pool->getfail_occasions++;
  7242. total_go++;
  7243. mutex_lock(&pool->stratum_lock);
  7244. pool->stratum_active = pool->stratum_notify = false;
  7245. pool->sock = INVSOCK;
  7246. mutex_unlock(&pool->stratum_lock);
  7247. /* If the socket to our stratum pool disconnects, all
  7248. * submissions need to be discarded or resent. */
  7249. if (!supports_resume(pool))
  7250. clear_stratum_shares(pool);
  7251. else
  7252. resubmit_stratum_shares(pool);
  7253. clear_pool_work(pool);
  7254. if (pool == current_pool())
  7255. restart_threads();
  7256. if (restart_stratum(pool))
  7257. continue;
  7258. shutdown_stratum(pool);
  7259. pool_died(pool);
  7260. break;
  7261. }
  7262. /* Check this pool hasn't died while being a backup pool and
  7263. * has not had its idle flag cleared */
  7264. stratum_resumed(pool);
  7265. if (!parse_method(pool, s) && !parse_stratum_response(pool, s))
  7266. applog(LOG_INFO, "Unknown stratum msg: %s", s);
  7267. free(s);
  7268. if (pool->swork.clean) {
  7269. struct work *work = make_work();
  7270. /* Generate a single work item to update the current
  7271. * block database */
  7272. pool->swork.clean = false;
  7273. gen_stratum_work(pool, work);
  7274. /* Try to extract block height from coinbase scriptSig */
  7275. uint8_t *bin_height = &bytes_buf(&pool->swork.coinbase)[4 /*version*/ + 1 /*txin count*/ + 36 /*prevout*/ + 1 /*scriptSig len*/ + 1 /*push opcode*/];
  7276. unsigned char cb_height_sz;
  7277. cb_height_sz = bin_height[-1];
  7278. if (cb_height_sz == 3) {
  7279. // FIXME: The block number will overflow this by AD 2173
  7280. uint32_t block_id = ((uint32_t*)work->data)[1];
  7281. uint32_t height = 0;
  7282. memcpy(&height, bin_height, 3);
  7283. height = le32toh(height);
  7284. have_block_height(block_id, height);
  7285. }
  7286. ++pool->work_restart_id;
  7287. if (test_work_current(work)) {
  7288. /* Only accept a work update if this stratum
  7289. * connection is from the current pool */
  7290. if (pool == current_pool()) {
  7291. restart_threads();
  7292. applog(
  7293. (opt_quiet_work_updates ? LOG_DEBUG : LOG_NOTICE),
  7294. "Stratum from pool %d requested work update", pool->pool_no);
  7295. }
  7296. } else
  7297. applog(LOG_NOTICE, "Stratum from pool %d detected new block", pool->pool_no);
  7298. free_work(work);
  7299. }
  7300. if (timer_passed(&pool->swork.tv_transparency, NULL)) {
  7301. // More than 4 timmills past since requested transactions
  7302. timer_unset(&pool->swork.tv_transparency);
  7303. pool_set_opaque(pool, true);
  7304. }
  7305. }
  7306. out:
  7307. return NULL;
  7308. }
  7309. static void init_stratum_thread(struct pool *pool)
  7310. {
  7311. have_longpoll = true;
  7312. if (unlikely(pthread_create(&pool->stratum_thread, NULL, stratum_thread, (void *)pool)))
  7313. quit(1, "Failed to create stratum thread");
  7314. }
  7315. static void *longpoll_thread(void *userdata);
  7316. static bool stratum_works(struct pool *pool)
  7317. {
  7318. applog(LOG_INFO, "Testing pool %d stratum %s", pool->pool_no, pool->stratum_url);
  7319. if (!extract_sockaddr(pool->stratum_url, &pool->sockaddr_url, &pool->stratum_port))
  7320. return false;
  7321. if (pool->stratum_active)
  7322. return true;
  7323. if (!initiate_stratum(pool))
  7324. return false;
  7325. return true;
  7326. }
  7327. static bool pool_active(struct pool *pool, bool pinging)
  7328. {
  7329. struct timeval tv_getwork, tv_getwork_reply;
  7330. bool ret = false;
  7331. json_t *val;
  7332. CURL *curl;
  7333. int rolltime;
  7334. char *rpc_req;
  7335. struct work *work;
  7336. enum pool_protocol proto;
  7337. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  7338. /* This is the central point we activate stratum when we can */
  7339. curl = curl_easy_init();
  7340. if (unlikely(!curl)) {
  7341. applog(LOG_ERR, "CURL initialisation failed");
  7342. return false;
  7343. }
  7344. if (!(want_gbt || want_getwork))
  7345. goto nohttp;
  7346. work = make_work();
  7347. /* Probe for GBT support on first pass */
  7348. proto = want_gbt ? PLP_GETBLOCKTEMPLATE : PLP_GETWORK;
  7349. tryagain:
  7350. rpc_req = prepare_rpc_req_probe(work, proto, NULL);
  7351. work->pool = pool;
  7352. if (!rpc_req)
  7353. goto out;
  7354. pool->probed = false;
  7355. cgtime(&tv_getwork);
  7356. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  7357. true, false, &rolltime, pool, false);
  7358. cgtime(&tv_getwork_reply);
  7359. free(rpc_req);
  7360. /* Detect if a http getwork pool has an X-Stratum header at startup,
  7361. * and if so, switch to that in preference to getwork if it works */
  7362. if (pool->stratum_url && want_stratum && (pool->has_stratum || stratum_works(pool))) {
  7363. if (!pool->has_stratum) {
  7364. applog(LOG_NOTICE, "Switching pool %d %s to %s", pool->pool_no, pool->rpc_url, pool->stratum_url);
  7365. if (!pool->rpc_url)
  7366. pool->rpc_url = strdup(pool->stratum_url);
  7367. pool->has_stratum = true;
  7368. }
  7369. free_work(work);
  7370. if (val)
  7371. json_decref(val);
  7372. retry_stratum:
  7373. curl_easy_cleanup(curl);
  7374. /* We create the stratum thread for each pool just after
  7375. * successful authorisation. Once the init flag has been set
  7376. * we never unset it and the stratum thread is responsible for
  7377. * setting/unsetting the active flag */
  7378. bool init = pool_tset(pool, &pool->stratum_init);
  7379. if (!init) {
  7380. bool ret = initiate_stratum(pool) && auth_stratum(pool);
  7381. if (ret)
  7382. {
  7383. detect_algo = 2;
  7384. init_stratum_thread(pool);
  7385. }
  7386. else
  7387. pool_tclear(pool, &pool->stratum_init);
  7388. return ret;
  7389. }
  7390. return pool->stratum_active;
  7391. }
  7392. else if (pool->has_stratum)
  7393. shutdown_stratum(pool);
  7394. if (val) {
  7395. bool rc;
  7396. json_t *res;
  7397. res = json_object_get(val, "result");
  7398. if ((!json_is_object(res)) || (proto == PLP_GETBLOCKTEMPLATE && !json_object_get(res, "bits")))
  7399. goto badwork;
  7400. work->rolltime = rolltime;
  7401. rc = work_decode(pool, work, val);
  7402. if (rc) {
  7403. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  7404. pool->pool_no, pool->rpc_url);
  7405. work->pool = pool;
  7406. copy_time(&work->tv_getwork, &tv_getwork);
  7407. copy_time(&work->tv_getwork_reply, &tv_getwork_reply);
  7408. work->getwork_mode = GETWORK_MODE_TESTPOOL;
  7409. calc_diff(work, 0);
  7410. update_last_work(work);
  7411. applog(LOG_DEBUG, "Pushing pooltest work to base pool");
  7412. stage_work(work);
  7413. total_getworks++;
  7414. pool->getwork_requested++;
  7415. ret = true;
  7416. cgtime(&pool->tv_idle);
  7417. } else {
  7418. badwork:
  7419. json_decref(val);
  7420. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher work from pool %u %s",
  7421. pool->pool_no, pool->rpc_url);
  7422. pool->proto = proto = pool_protocol_fallback(proto);
  7423. if (PLP_NONE != proto)
  7424. goto tryagain;
  7425. free_work(work);
  7426. goto out;
  7427. }
  7428. json_decref(val);
  7429. if (proto != pool->proto) {
  7430. pool->proto = proto;
  7431. applog(LOG_INFO, "Selected %s protocol for pool %u", pool_protocol_name(proto), pool->pool_no);
  7432. }
  7433. if (pool->lp_url)
  7434. goto out;
  7435. /* Decipher the longpoll URL, if any, and store it in ->lp_url */
  7436. const struct blktmpl_longpoll_req *lp;
  7437. if (work->tmpl && (lp = blktmpl_get_longpoll(work->tmpl))) {
  7438. // NOTE: work_decode takes care of lp id
  7439. pool->lp_url = lp->uri ? absolute_uri(lp->uri, pool->rpc_url) : pool->rpc_url;
  7440. if (!pool->lp_url)
  7441. {
  7442. ret = false;
  7443. goto out;
  7444. }
  7445. pool->lp_proto = PLP_GETBLOCKTEMPLATE;
  7446. }
  7447. else
  7448. if (pool->hdr_path && want_getwork) {
  7449. pool->lp_url = absolute_uri(pool->hdr_path, pool->rpc_url);
  7450. if (!pool->lp_url)
  7451. {
  7452. ret = false;
  7453. goto out;
  7454. }
  7455. pool->lp_proto = PLP_GETWORK;
  7456. } else
  7457. pool->lp_url = NULL;
  7458. if (want_longpoll && !pool->lp_started) {
  7459. pool->lp_started = true;
  7460. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  7461. quit(1, "Failed to create pool longpoll thread");
  7462. }
  7463. } else if (PLP_NONE != (proto = pool_protocol_fallback(proto))) {
  7464. pool->proto = proto;
  7465. goto tryagain;
  7466. } else {
  7467. free_work(work);
  7468. nohttp:
  7469. /* If we failed to parse a getwork, this could be a stratum
  7470. * url without the prefix stratum+tcp:// so let's check it */
  7471. if (extract_sockaddr(pool->rpc_url, &pool->sockaddr_url, &pool->stratum_port) && initiate_stratum(pool)) {
  7472. pool->has_stratum = true;
  7473. goto retry_stratum;
  7474. }
  7475. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  7476. pool->pool_no, pool->rpc_url);
  7477. if (!pinging)
  7478. applog(LOG_WARNING, "Pool %u slow/down or URL or credentials invalid", pool->pool_no);
  7479. }
  7480. out:
  7481. curl_easy_cleanup(curl);
  7482. return ret;
  7483. }
  7484. static void pool_resus(struct pool *pool)
  7485. {
  7486. if (pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  7487. applog(LOG_WARNING, "Pool %d %s alive, testing stability", pool->pool_no, pool->rpc_url);
  7488. else
  7489. applog(LOG_INFO, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  7490. }
  7491. static struct work *hash_pop(void)
  7492. {
  7493. struct work *work = NULL, *tmp;
  7494. int hc;
  7495. struct timespec ts;
  7496. retry:
  7497. mutex_lock(stgd_lock);
  7498. while (!HASH_COUNT(staged_work))
  7499. {
  7500. if (unlikely(staged_full))
  7501. {
  7502. if (likely(opt_queue < 10 + mining_threads))
  7503. {
  7504. ++opt_queue;
  7505. applog(LOG_WARNING, "Staged work underrun; increasing queue minimum to %d", opt_queue);
  7506. }
  7507. else
  7508. applog(LOG_WARNING, "Staged work underrun; not automatically increasing above %d", opt_queue);
  7509. staged_full = false; // Let it fill up before triggering an underrun again
  7510. no_work = true;
  7511. }
  7512. ts = (struct timespec){ .tv_sec = opt_log_interval, };
  7513. pthread_cond_signal(&gws_cond);
  7514. if (ETIMEDOUT == pthread_cond_timedwait(&getq->cond, stgd_lock, &ts))
  7515. {
  7516. run_cmd(cmd_idle);
  7517. pthread_cond_signal(&gws_cond);
  7518. pthread_cond_wait(&getq->cond, stgd_lock);
  7519. }
  7520. }
  7521. no_work = false;
  7522. hc = HASH_COUNT(staged_work);
  7523. /* Find clone work if possible, to allow masters to be reused */
  7524. if (hc > staged_rollable) {
  7525. HASH_ITER(hh, staged_work, work, tmp) {
  7526. if (!work_rollable(work))
  7527. break;
  7528. }
  7529. } else
  7530. work = staged_work;
  7531. if (can_roll(work) && should_roll(work))
  7532. {
  7533. // Instead of consuming it, force it to be cloned and grab the clone
  7534. mutex_unlock(stgd_lock);
  7535. clone_available();
  7536. goto retry;
  7537. }
  7538. HASH_DEL(staged_work, work);
  7539. if (work_rollable(work))
  7540. staged_rollable--;
  7541. /* Signal the getwork scheduler to look for more work */
  7542. pthread_cond_signal(&gws_cond);
  7543. /* Signal hash_pop again in case there are mutliple hash_pop waiters */
  7544. pthread_cond_signal(&getq->cond);
  7545. mutex_unlock(stgd_lock);
  7546. work->pool->last_work_time = time(NULL);
  7547. cgtime(&work->pool->tv_last_work_time);
  7548. return work;
  7549. }
  7550. /* Clones work by rolling it if possible, and returning a clone instead of the
  7551. * original work item which gets staged again to possibly be rolled again in
  7552. * the future */
  7553. static struct work *clone_work(struct work *work)
  7554. {
  7555. int mrs = mining_threads + opt_queue - total_staged();
  7556. struct work *work_clone;
  7557. bool cloned;
  7558. if (mrs < 1)
  7559. return work;
  7560. cloned = false;
  7561. work_clone = make_clone(work);
  7562. while (mrs-- > 0 && can_roll(work) && should_roll(work)) {
  7563. applog(LOG_DEBUG, "Pushing rolled converted work to stage thread");
  7564. stage_work(work_clone);
  7565. roll_work(work);
  7566. work_clone = make_clone(work);
  7567. /* Roll it again to prevent duplicates should this be used
  7568. * directly later on */
  7569. roll_work(work);
  7570. cloned = true;
  7571. }
  7572. if (cloned) {
  7573. stage_work(work);
  7574. return work_clone;
  7575. }
  7576. free_work(work_clone);
  7577. return work;
  7578. }
  7579. void gen_hash(unsigned char *data, unsigned char *hash, int len)
  7580. {
  7581. unsigned char hash1[32];
  7582. sha256(data, len, hash1);
  7583. sha256(hash1, 32, hash);
  7584. }
  7585. /* Diff 1 is a 256 bit unsigned integer of
  7586. * 0x00000000ffff0000000000000000000000000000000000000000000000000000
  7587. * so we use a big endian 64 bit unsigned integer centred on the 5th byte to
  7588. * cover a huge range of difficulty targets, though not all 256 bits' worth */
  7589. static void bdiff_target_leadzero(unsigned char *target, double diff)
  7590. {
  7591. uint64_t *data64, h64;
  7592. double d64;
  7593. d64 = diffone;
  7594. d64 /= diff;
  7595. d64 = ceil(d64);
  7596. h64 = d64;
  7597. memset(target, 0, 32);
  7598. if (d64 < 18446744073709551616.0) {
  7599. unsigned char *rtarget = target;
  7600. memset(rtarget, 0, 32);
  7601. if (opt_scrypt)
  7602. data64 = (uint64_t *)(rtarget + 2);
  7603. else
  7604. data64 = (uint64_t *)(rtarget + 4);
  7605. *data64 = htobe64(h64);
  7606. } else {
  7607. /* Support for the classic all FFs just-below-1 diff */
  7608. if (opt_scrypt)
  7609. memset(&target[2], 0xff, 30);
  7610. else
  7611. memset(&target[4], 0xff, 28);
  7612. }
  7613. }
  7614. void set_target(unsigned char *dest_target, double diff)
  7615. {
  7616. unsigned char rtarget[32];
  7617. bdiff_target_leadzero(rtarget, diff);
  7618. swab256(dest_target, rtarget);
  7619. if (opt_debug) {
  7620. char htarget[65];
  7621. bin2hex(htarget, rtarget, 32);
  7622. applog(LOG_DEBUG, "Generated target %s", htarget);
  7623. }
  7624. }
  7625. void stratum_work_cpy(struct stratum_work * const dst, const struct stratum_work * const src)
  7626. {
  7627. *dst = *src;
  7628. dst->job_id = strdup(src->job_id);
  7629. bytes_cpy(&dst->coinbase, &src->coinbase);
  7630. bytes_cpy(&dst->merkle_bin, &src->merkle_bin);
  7631. }
  7632. void stratum_work_clean(struct stratum_work * const swork)
  7633. {
  7634. free(swork->job_id);
  7635. bytes_free(&swork->coinbase);
  7636. bytes_free(&swork->merkle_bin);
  7637. }
  7638. /* Generates stratum based work based on the most recent notify information
  7639. * from the pool. This will keep generating work while a pool is down so we use
  7640. * other means to detect when the pool has died in stratum_thread */
  7641. static void gen_stratum_work(struct pool *pool, struct work *work)
  7642. {
  7643. clean_work(work);
  7644. cg_wlock(&pool->data_lock);
  7645. pool->swork.data_lock_p = &pool->data_lock;
  7646. bytes_resize(&work->nonce2, pool->n2size);
  7647. if (pool->nonce2sz < pool->n2size)
  7648. memset(&bytes_buf(&work->nonce2)[pool->nonce2sz], 0, pool->n2size - pool->nonce2sz);
  7649. memcpy(bytes_buf(&work->nonce2),
  7650. #ifdef WORDS_BIGENDIAN
  7651. // NOTE: On big endian, the most significant bits are stored at the end, so skip the LSBs
  7652. &((char*)&pool->nonce2)[pool->nonce2off],
  7653. #else
  7654. &pool->nonce2,
  7655. #endif
  7656. pool->nonce2sz);
  7657. pool->nonce2++;
  7658. work->pool = pool;
  7659. work->work_restart_id = work->pool->work_restart_id;
  7660. gen_stratum_work2(work, &pool->swork, pool->nonce1);
  7661. cgtime(&work->tv_staged);
  7662. }
  7663. void gen_stratum_work2(struct work *work, struct stratum_work *swork, const char *nonce1)
  7664. {
  7665. unsigned char *coinbase, merkle_root[32], merkle_sha[64];
  7666. uint8_t *merkle_bin;
  7667. uint32_t *data32, *swap32;
  7668. int i;
  7669. /* Generate coinbase */
  7670. coinbase = bytes_buf(&swork->coinbase);
  7671. memcpy(&coinbase[swork->nonce2_offset], bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  7672. /* Downgrade to a read lock to read off the variables */
  7673. if (swork->data_lock_p)
  7674. cg_dwlock(swork->data_lock_p);
  7675. /* Generate merkle root */
  7676. gen_hash(coinbase, merkle_root, bytes_len(&swork->coinbase));
  7677. memcpy(merkle_sha, merkle_root, 32);
  7678. merkle_bin = bytes_buf(&swork->merkle_bin);
  7679. for (i = 0; i < swork->merkles; ++i, merkle_bin += 32) {
  7680. memcpy(merkle_sha + 32, merkle_bin, 32);
  7681. gen_hash(merkle_sha, merkle_root, 64);
  7682. memcpy(merkle_sha, merkle_root, 32);
  7683. }
  7684. data32 = (uint32_t *)merkle_sha;
  7685. swap32 = (uint32_t *)merkle_root;
  7686. flip32(swap32, data32);
  7687. memcpy(&work->data[0], swork->header1, 36);
  7688. memcpy(&work->data[36], merkle_root, 32);
  7689. *((uint32_t*)&work->data[68]) = htobe32(swork->ntime + timer_elapsed(&swork->tv_received, NULL));
  7690. memcpy(&work->data[72], swork->diffbits, 4);
  7691. memset(&work->data[76], 0, 4); // nonce
  7692. memcpy(&work->data[80], workpadding_bin, 48);
  7693. /* Store the stratum work diff to check it still matches the pool's
  7694. * stratum diff when submitting shares */
  7695. work->sdiff = swork->diff;
  7696. /* Copy parameters required for share submission */
  7697. work->job_id = strdup(swork->job_id);
  7698. work->nonce1 = strdup(nonce1);
  7699. if (swork->data_lock_p)
  7700. cg_runlock(swork->data_lock_p);
  7701. if (opt_debug)
  7702. {
  7703. char header[161];
  7704. char nonce2hex[(bytes_len(&work->nonce2) * 2) + 1];
  7705. bin2hex(header, work->data, 80);
  7706. bin2hex(nonce2hex, bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  7707. applog(LOG_DEBUG, "Generated stratum header %s", header);
  7708. applog(LOG_DEBUG, "Work job_id %s nonce2 %s", work->job_id, nonce2hex);
  7709. }
  7710. calc_midstate(work);
  7711. set_target(work->target, work->sdiff);
  7712. local_work++;
  7713. work->stratum = true;
  7714. work->blk.nonce = 0;
  7715. work->id = total_work++;
  7716. work->longpoll = false;
  7717. work->getwork_mode = GETWORK_MODE_STRATUM;
  7718. /* Nominally allow a driver to ntime roll 60 seconds */
  7719. work->drv_rolllimit = 60;
  7720. calc_diff(work, 0);
  7721. }
  7722. void request_work(struct thr_info *thr)
  7723. {
  7724. struct cgpu_info *cgpu = thr->cgpu;
  7725. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  7726. /* Tell the watchdog thread this thread is waiting on getwork and
  7727. * should not be restarted */
  7728. thread_reportout(thr);
  7729. // HACK: Since get_work still blocks, reportout all processors dependent on this thread
  7730. for (struct cgpu_info *proc = thr->cgpu->next_proc; proc; proc = proc->next_proc)
  7731. {
  7732. if (proc->threads)
  7733. break;
  7734. thread_reportout(proc->thr[0]);
  7735. }
  7736. cgtime(&dev_stats->_get_start);
  7737. }
  7738. // FIXME: Make this non-blocking (and remove HACK above)
  7739. struct work *get_work(struct thr_info *thr)
  7740. {
  7741. const int thr_id = thr->id;
  7742. struct cgpu_info *cgpu = thr->cgpu;
  7743. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  7744. struct cgminer_stats *pool_stats;
  7745. struct timeval tv_get;
  7746. struct work *work = NULL;
  7747. applog(LOG_DEBUG, "%"PRIpreprv": Popping work from get queue to get work", cgpu->proc_repr);
  7748. while (!work) {
  7749. work = hash_pop();
  7750. if (stale_work(work, false)) {
  7751. staged_full = false; // It wasn't really full, since it was stale :(
  7752. discard_work(work);
  7753. work = NULL;
  7754. wake_gws();
  7755. }
  7756. }
  7757. last_getwork = time(NULL);
  7758. applog(LOG_DEBUG, "%"PRIpreprv": Got work %d from get queue to get work for thread %d",
  7759. cgpu->proc_repr, work->id, thr_id);
  7760. work->thr_id = thr_id;
  7761. thread_reportin(thr);
  7762. // HACK: Since get_work still blocks, reportin all processors dependent on this thread
  7763. for (struct cgpu_info *proc = thr->cgpu->next_proc; proc; proc = proc->next_proc)
  7764. {
  7765. if (proc->threads)
  7766. break;
  7767. thread_reportin(proc->thr[0]);
  7768. }
  7769. work->mined = true;
  7770. work->blk.nonce = 0;
  7771. cgtime(&tv_get);
  7772. timersub(&tv_get, &dev_stats->_get_start, &tv_get);
  7773. timeradd(&tv_get, &dev_stats->getwork_wait, &dev_stats->getwork_wait);
  7774. if (timercmp(&tv_get, &dev_stats->getwork_wait_max, >))
  7775. dev_stats->getwork_wait_max = tv_get;
  7776. if (timercmp(&tv_get, &dev_stats->getwork_wait_min, <))
  7777. dev_stats->getwork_wait_min = tv_get;
  7778. ++dev_stats->getwork_calls;
  7779. pool_stats = &(work->pool->cgminer_stats);
  7780. timeradd(&tv_get, &pool_stats->getwork_wait, &pool_stats->getwork_wait);
  7781. if (timercmp(&tv_get, &pool_stats->getwork_wait_max, >))
  7782. pool_stats->getwork_wait_max = tv_get;
  7783. if (timercmp(&tv_get, &pool_stats->getwork_wait_min, <))
  7784. pool_stats->getwork_wait_min = tv_get;
  7785. ++pool_stats->getwork_calls;
  7786. if (work->work_difficulty < 1)
  7787. {
  7788. if (unlikely(work->work_difficulty < cgpu->min_nonce_diff))
  7789. {
  7790. applog(LOG_WARNING, "%"PRIpreprv": Using work with lower difficulty than device supports",
  7791. cgpu->proc_repr);
  7792. work->nonce_diff = cgpu->min_nonce_diff;
  7793. }
  7794. else
  7795. work->nonce_diff = work->work_difficulty;
  7796. }
  7797. else
  7798. work->nonce_diff = 1;
  7799. return work;
  7800. }
  7801. static
  7802. void _submit_work_async(struct work *work)
  7803. {
  7804. applog(LOG_DEBUG, "Pushing submit work to work thread");
  7805. mutex_lock(&submitting_lock);
  7806. ++total_submitting;
  7807. DL_APPEND(submit_waiting, work);
  7808. mutex_unlock(&submitting_lock);
  7809. notifier_wake(submit_waiting_notifier);
  7810. }
  7811. /* Submit a copy of the tested, statistic recorded work item asynchronously */
  7812. static void submit_work_async2(struct work *work, struct timeval *tv_work_found)
  7813. {
  7814. if (tv_work_found)
  7815. copy_time(&work->tv_work_found, tv_work_found);
  7816. _submit_work_async(work);
  7817. }
  7818. void inc_hw_errors3(struct thr_info *thr, const struct work *work, const uint32_t *bad_nonce_p, float nonce_diff)
  7819. {
  7820. struct cgpu_info * const cgpu = thr->cgpu;
  7821. if (bad_nonce_p)
  7822. {
  7823. if (bad_nonce_p == UNKNOWN_NONCE)
  7824. applog(LOG_DEBUG, "%"PRIpreprv": invalid nonce - HW error",
  7825. cgpu->proc_repr);
  7826. else
  7827. applog(LOG_DEBUG, "%"PRIpreprv": invalid nonce (%08lx) - HW error",
  7828. cgpu->proc_repr, (unsigned long)be32toh(*bad_nonce_p));
  7829. }
  7830. mutex_lock(&stats_lock);
  7831. hw_errors++;
  7832. ++cgpu->hw_errors;
  7833. if (bad_nonce_p)
  7834. {
  7835. total_bad_diff1 += nonce_diff;
  7836. cgpu->bad_diff1 += nonce_diff;
  7837. }
  7838. mutex_unlock(&stats_lock);
  7839. if (thr->cgpu->drv->hw_error)
  7840. thr->cgpu->drv->hw_error(thr);
  7841. }
  7842. enum test_nonce2_result hashtest2(struct work *work, bool checktarget)
  7843. {
  7844. uint32_t *hash2_32 = (uint32_t *)&work->hash[0];
  7845. hash_data(work->hash, work->data);
  7846. if (hash2_32[7] != 0)
  7847. return TNR_BAD;
  7848. if (!checktarget)
  7849. return TNR_GOOD;
  7850. if (!hash_target_check_v(work->hash, work->target))
  7851. return TNR_HIGH;
  7852. return TNR_GOOD;
  7853. }
  7854. enum test_nonce2_result _test_nonce2(struct work *work, uint32_t nonce, bool checktarget)
  7855. {
  7856. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  7857. *work_nonce = htole32(nonce);
  7858. #ifdef USE_SCRYPT
  7859. if (opt_scrypt)
  7860. // NOTE: Depends on scrypt_test return matching enum values
  7861. return scrypt_test(work->data, work->target, nonce);
  7862. #endif
  7863. return hashtest2(work, checktarget);
  7864. }
  7865. /* Returns true if nonce for work was a valid share */
  7866. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  7867. {
  7868. return submit_noffset_nonce(thr, work, nonce, 0);
  7869. }
  7870. /* Allows drivers to submit work items where the driver has changed the ntime
  7871. * value by noffset. Must be only used with a work protocol that does not ntime
  7872. * roll itself intrinsically to generate work (eg stratum). We do not touch
  7873. * the original work struct, but the copy of it only. */
  7874. bool submit_noffset_nonce(struct thr_info *thr, struct work *work_in, uint32_t nonce,
  7875. int noffset)
  7876. {
  7877. struct work *work = make_work();
  7878. _copy_work(work, work_in, noffset);
  7879. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  7880. struct timeval tv_work_found;
  7881. enum test_nonce2_result res;
  7882. bool ret = true;
  7883. thread_reportout(thr);
  7884. cgtime(&tv_work_found);
  7885. *work_nonce = htole32(nonce);
  7886. work->thr_id = thr->id;
  7887. /* Do one last check before attempting to submit the work */
  7888. /* Side effect: sets work->data for us */
  7889. res = test_nonce2(work, nonce);
  7890. if (unlikely(res == TNR_BAD))
  7891. {
  7892. inc_hw_errors(thr, work, nonce);
  7893. ret = false;
  7894. goto out;
  7895. }
  7896. mutex_lock(&stats_lock);
  7897. total_diff1 += work->nonce_diff;
  7898. thr ->cgpu->diff1 += work->nonce_diff;
  7899. work->pool->diff1 += work->nonce_diff;
  7900. thr->cgpu->last_device_valid_work = time(NULL);
  7901. mutex_unlock(&stats_lock);
  7902. if (noncelog_file)
  7903. noncelog(work);
  7904. if (res == TNR_HIGH)
  7905. {
  7906. // Share above target, normal
  7907. /* Check the diff of the share, even if it didn't reach the
  7908. * target, just to set the best share value if it's higher. */
  7909. share_diff(work);
  7910. goto out;
  7911. }
  7912. submit_work_async2(work, &tv_work_found);
  7913. work = NULL; // Taken by submit_work_async2
  7914. out:
  7915. if (work)
  7916. free_work(work);
  7917. thread_reportin(thr);
  7918. return ret;
  7919. }
  7920. bool abandon_work(struct work *work, struct timeval *wdiff, uint64_t hashes)
  7921. {
  7922. if (wdiff->tv_sec > opt_scantime ||
  7923. work->blk.nonce >= MAXTHREADS - hashes ||
  7924. hashes >= 0xfffffffe ||
  7925. stale_work(work, false))
  7926. return true;
  7927. return false;
  7928. }
  7929. void __thr_being_msg(int prio, struct thr_info *thr, const char *being)
  7930. {
  7931. struct cgpu_info *proc = thr->cgpu;
  7932. if (proc->threads > 1)
  7933. applog(prio, "%"PRIpreprv" (thread %d) %s", proc->proc_repr, thr->id, being);
  7934. else
  7935. applog(prio, "%"PRIpreprv" %s", proc->proc_repr, being);
  7936. }
  7937. // Called by asynchronous minerloops, when they find their processor should be disabled
  7938. void mt_disable_start(struct thr_info *mythr)
  7939. {
  7940. struct cgpu_info *cgpu = mythr->cgpu;
  7941. struct device_drv *drv = cgpu->drv;
  7942. if (drv->thread_disable)
  7943. drv->thread_disable(mythr);
  7944. hashmeter2(mythr);
  7945. if (mythr->prev_work)
  7946. free_work(mythr->prev_work);
  7947. mythr->prev_work = mythr->work;
  7948. mythr->work = NULL;
  7949. mythr->_job_transition_in_progress = false;
  7950. __thr_being_msg(LOG_WARNING, mythr, "being disabled");
  7951. mythr->rolling = mythr->cgpu->rolling = 0;
  7952. thread_reportout(mythr);
  7953. mythr->_mt_disable_called = true;
  7954. }
  7955. /* Put a new unqueued work item in cgpu->unqueued_work under cgpu->qlock till
  7956. * the driver tells us it's full so that it may extract the work item using
  7957. * the get_queued() function which adds it to the hashtable on
  7958. * cgpu->queued_work. */
  7959. static void fill_queue(struct thr_info *mythr, struct cgpu_info *cgpu, struct device_drv *drv, const int thr_id)
  7960. {
  7961. thread_reportout(mythr);
  7962. do {
  7963. bool need_work;
  7964. /* Do this lockless just to know if we need more unqueued work. */
  7965. need_work = (!cgpu->unqueued_work);
  7966. /* get_work is a blocking function so do it outside of lock
  7967. * to prevent deadlocks with other locks. */
  7968. if (need_work) {
  7969. struct work *work = get_work(mythr);
  7970. wr_lock(&cgpu->qlock);
  7971. /* Check we haven't grabbed work somehow between
  7972. * checking and picking up the lock. */
  7973. if (likely(!cgpu->unqueued_work))
  7974. cgpu->unqueued_work = work;
  7975. else
  7976. need_work = false;
  7977. wr_unlock(&cgpu->qlock);
  7978. if (unlikely(!need_work))
  7979. discard_work(work);
  7980. }
  7981. /* The queue_full function should be used by the driver to
  7982. * actually place work items on the physical device if it
  7983. * does have a queue. */
  7984. } while (drv->queue_full && !drv->queue_full(cgpu));
  7985. }
  7986. /* Add a work item to a cgpu's queued hashlist */
  7987. void __add_queued(struct cgpu_info *cgpu, struct work *work)
  7988. {
  7989. cgpu->queued_count++;
  7990. HASH_ADD_INT(cgpu->queued_work, id, work);
  7991. }
  7992. /* This function is for retrieving one work item from the unqueued pointer and
  7993. * adding it to the hashtable of queued work. Code using this function must be
  7994. * able to handle NULL as a return which implies there is no work available. */
  7995. struct work *get_queued(struct cgpu_info *cgpu)
  7996. {
  7997. struct work *work = NULL;
  7998. wr_lock(&cgpu->qlock);
  7999. if (cgpu->unqueued_work) {
  8000. work = cgpu->unqueued_work;
  8001. __add_queued(cgpu, work);
  8002. cgpu->unqueued_work = NULL;
  8003. }
  8004. wr_unlock(&cgpu->qlock);
  8005. return work;
  8006. }
  8007. void add_queued(struct cgpu_info *cgpu, struct work *work)
  8008. {
  8009. wr_lock(&cgpu->qlock);
  8010. __add_queued(cgpu, work);
  8011. wr_unlock(&cgpu->qlock);
  8012. }
  8013. /* Get fresh work and add it to cgpu's queued hashlist */
  8014. struct work *get_queue_work(struct thr_info *thr, struct cgpu_info *cgpu, int thr_id)
  8015. {
  8016. struct work *work = get_work(thr);
  8017. add_queued(cgpu, work);
  8018. return work;
  8019. }
  8020. /* This function is for finding an already queued work item in the
  8021. * given que hashtable. Code using this function must be able
  8022. * to handle NULL as a return which implies there is no matching work.
  8023. * The calling function must lock access to the que if it is required.
  8024. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  8025. struct work *__find_work_bymidstate(struct work *que, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  8026. {
  8027. struct work *work, *tmp, *ret = NULL;
  8028. HASH_ITER(hh, que, work, tmp) {
  8029. if (memcmp(work->midstate, midstate, midstatelen) == 0 &&
  8030. memcmp(work->data + offset, data, datalen) == 0) {
  8031. ret = work;
  8032. break;
  8033. }
  8034. }
  8035. return ret;
  8036. }
  8037. /* This function is for finding an already queued work item in the
  8038. * device's queued_work hashtable. Code using this function must be able
  8039. * to handle NULL as a return which implies there is no matching work.
  8040. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  8041. struct work *find_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  8042. {
  8043. struct work *ret;
  8044. rd_lock(&cgpu->qlock);
  8045. ret = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  8046. rd_unlock(&cgpu->qlock);
  8047. return ret;
  8048. }
  8049. struct work *clone_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  8050. {
  8051. struct work *work, *ret = NULL;
  8052. rd_lock(&cgpu->qlock);
  8053. work = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  8054. if (work)
  8055. ret = copy_work(work);
  8056. rd_unlock(&cgpu->qlock);
  8057. return ret;
  8058. }
  8059. void __work_completed(struct cgpu_info *cgpu, struct work *work)
  8060. {
  8061. cgpu->queued_count--;
  8062. HASH_DEL(cgpu->queued_work, work);
  8063. }
  8064. /* This function should be used by queued device drivers when they're sure
  8065. * the work struct is no longer in use. */
  8066. void work_completed(struct cgpu_info *cgpu, struct work *work)
  8067. {
  8068. wr_lock(&cgpu->qlock);
  8069. __work_completed(cgpu, work);
  8070. wr_unlock(&cgpu->qlock);
  8071. free_work(work);
  8072. }
  8073. /* Combines find_queued_work_bymidstate and work_completed in one function
  8074. * withOUT destroying the work so the driver must free it. */
  8075. struct work *take_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  8076. {
  8077. struct work *work;
  8078. wr_lock(&cgpu->qlock);
  8079. work = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  8080. if (work)
  8081. __work_completed(cgpu, work);
  8082. wr_unlock(&cgpu->qlock);
  8083. return work;
  8084. }
  8085. static void flush_queue(struct cgpu_info *cgpu)
  8086. {
  8087. struct work *work = NULL;
  8088. wr_lock(&cgpu->qlock);
  8089. work = cgpu->unqueued_work;
  8090. cgpu->unqueued_work = NULL;
  8091. wr_unlock(&cgpu->qlock);
  8092. if (work) {
  8093. free_work(work);
  8094. applog(LOG_DEBUG, "Discarded queued work item");
  8095. }
  8096. }
  8097. /* This version of hash work is for devices that are fast enough to always
  8098. * perform a full nonce range and need a queue to maintain the device busy.
  8099. * Work creation and destruction is not done from within this function
  8100. * directly. */
  8101. void hash_queued_work(struct thr_info *mythr)
  8102. {
  8103. const long cycle = opt_log_interval / 5 ? : 1;
  8104. struct timeval tv_start = {0, 0}, tv_end;
  8105. struct cgpu_info *cgpu = mythr->cgpu;
  8106. struct device_drv *drv = cgpu->drv;
  8107. const int thr_id = mythr->id;
  8108. int64_t hashes_done = 0;
  8109. if (unlikely(cgpu->deven != DEV_ENABLED))
  8110. mt_disable(mythr);
  8111. while (likely(!cgpu->shutdown)) {
  8112. struct timeval diff;
  8113. int64_t hashes;
  8114. fill_queue(mythr, cgpu, drv, thr_id);
  8115. thread_reportin(mythr);
  8116. hashes = drv->scanwork(mythr);
  8117. /* Reset the bool here in case the driver looks for it
  8118. * synchronously in the scanwork loop. */
  8119. mythr->work_restart = false;
  8120. if (unlikely(hashes == -1 )) {
  8121. applog(LOG_ERR, "%s %d failure, disabling!", drv->name, cgpu->device_id);
  8122. cgpu->deven = DEV_DISABLED;
  8123. dev_error(cgpu, REASON_THREAD_ZERO_HASH);
  8124. mt_disable(mythr);
  8125. }
  8126. hashes_done += hashes;
  8127. cgtime(&tv_end);
  8128. timersub(&tv_end, &tv_start, &diff);
  8129. if (diff.tv_sec >= cycle) {
  8130. hashmeter(thr_id, &diff, hashes_done);
  8131. hashes_done = 0;
  8132. copy_time(&tv_start, &tv_end);
  8133. }
  8134. if (unlikely(mythr->pause || cgpu->deven != DEV_ENABLED))
  8135. mt_disable(mythr);
  8136. if (unlikely(mythr->work_restart)) {
  8137. flush_queue(cgpu);
  8138. if (drv->flush_work)
  8139. drv->flush_work(cgpu);
  8140. }
  8141. }
  8142. // cgpu->deven = DEV_DISABLED; set in miner_thread
  8143. }
  8144. // Called by minerloop, when it is re-enabling a processor
  8145. void mt_disable_finish(struct thr_info *mythr)
  8146. {
  8147. struct device_drv *drv = mythr->cgpu->drv;
  8148. thread_reportin(mythr);
  8149. __thr_being_msg(LOG_WARNING, mythr, "being re-enabled");
  8150. if (drv->thread_enable)
  8151. drv->thread_enable(mythr);
  8152. mythr->_mt_disable_called = false;
  8153. }
  8154. // Called by synchronous minerloops, when they find their processor should be disabled
  8155. // Calls mt_disable_start, waits until it's re-enabled, then calls mt_disable_finish
  8156. void mt_disable(struct thr_info *mythr)
  8157. {
  8158. const struct cgpu_info * const cgpu = mythr->cgpu;
  8159. mt_disable_start(mythr);
  8160. applog(LOG_DEBUG, "Waiting for wakeup notification in miner thread");
  8161. do {
  8162. notifier_read(mythr->notifier);
  8163. } while (mythr->pause || cgpu->deven != DEV_ENABLED);
  8164. mt_disable_finish(mythr);
  8165. }
  8166. enum {
  8167. STAT_SLEEP_INTERVAL = 1,
  8168. STAT_CTR_INTERVAL = 10000000,
  8169. FAILURE_INTERVAL = 30,
  8170. };
  8171. /* Stage another work item from the work returned in a longpoll */
  8172. static void convert_to_work(json_t *val, int rolltime, struct pool *pool, struct work *work, struct timeval *tv_lp, struct timeval *tv_lp_reply)
  8173. {
  8174. bool rc;
  8175. work->rolltime = rolltime;
  8176. rc = work_decode(pool, work, val);
  8177. if (unlikely(!rc)) {
  8178. applog(LOG_ERR, "Could not convert longpoll data to work");
  8179. free_work(work);
  8180. return;
  8181. }
  8182. total_getworks++;
  8183. pool->getwork_requested++;
  8184. work->pool = pool;
  8185. copy_time(&work->tv_getwork, tv_lp);
  8186. copy_time(&work->tv_getwork_reply, tv_lp_reply);
  8187. calc_diff(work, 0);
  8188. if (pool->enabled == POOL_REJECTING)
  8189. work->mandatory = true;
  8190. work->longpoll = true;
  8191. work->getwork_mode = GETWORK_MODE_LP;
  8192. update_last_work(work);
  8193. /* We'll be checking this work item twice, but we already know it's
  8194. * from a new block so explicitly force the new block detection now
  8195. * rather than waiting for it to hit the stage thread. This also
  8196. * allows testwork to know whether LP discovered the block or not. */
  8197. test_work_current(work);
  8198. /* Don't use backup LPs as work if we have failover-only enabled. Use
  8199. * the longpoll work from a pool that has been rejecting shares as a
  8200. * way to detect when the pool has recovered.
  8201. */
  8202. if (pool != current_pool() && opt_fail_only && pool->enabled != POOL_REJECTING) {
  8203. free_work(work);
  8204. return;
  8205. }
  8206. work = clone_work(work);
  8207. applog(LOG_DEBUG, "Pushing converted work to stage thread");
  8208. stage_work(work);
  8209. applog(LOG_DEBUG, "Converted longpoll data to work");
  8210. }
  8211. /* If we want longpoll, enable it for the chosen default pool, or, if
  8212. * the pool does not support longpoll, find the first one that does
  8213. * and use its longpoll support */
  8214. static struct pool *select_longpoll_pool(struct pool *cp)
  8215. {
  8216. int i;
  8217. if (cp->lp_url)
  8218. return cp;
  8219. for (i = 0; i < total_pools; i++) {
  8220. struct pool *pool = pools[i];
  8221. if (pool->has_stratum || pool->lp_url)
  8222. return pool;
  8223. }
  8224. return NULL;
  8225. }
  8226. /* This will make the longpoll thread wait till it's the current pool, or it
  8227. * has been flagged as rejecting, before attempting to open any connections.
  8228. */
  8229. static void wait_lpcurrent(struct pool *pool)
  8230. {
  8231. while (!cnx_needed(pool) && (pool->enabled == POOL_DISABLED ||
  8232. (pool != current_pool() && pool_strategy != POOL_LOADBALANCE &&
  8233. pool_strategy != POOL_BALANCE))) {
  8234. mutex_lock(&lp_lock);
  8235. pthread_cond_wait(&lp_cond, &lp_lock);
  8236. mutex_unlock(&lp_lock);
  8237. }
  8238. }
  8239. static curl_socket_t save_curl_socket(void *vpool, __maybe_unused curlsocktype purpose, struct curl_sockaddr *addr) {
  8240. struct pool *pool = vpool;
  8241. curl_socket_t sock = socket(addr->family, addr->socktype, addr->protocol);
  8242. pool->lp_socket = sock;
  8243. return sock;
  8244. }
  8245. static void *longpoll_thread(void *userdata)
  8246. {
  8247. struct pool *cp = (struct pool *)userdata;
  8248. /* This *pool is the source of the actual longpoll, not the pool we've
  8249. * tied it to */
  8250. struct timeval start, reply, end;
  8251. struct pool *pool = NULL;
  8252. char threadname[20];
  8253. CURL *curl = NULL;
  8254. int failures = 0;
  8255. char *lp_url;
  8256. int rolltime;
  8257. #ifndef HAVE_PTHREAD_CANCEL
  8258. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  8259. #endif
  8260. snprintf(threadname, 20, "longpoll%u", cp->pool_no);
  8261. RenameThread(threadname);
  8262. curl = curl_easy_init();
  8263. if (unlikely(!curl)) {
  8264. applog(LOG_ERR, "CURL initialisation failed");
  8265. return NULL;
  8266. }
  8267. retry_pool:
  8268. pool = select_longpoll_pool(cp);
  8269. if (!pool) {
  8270. applog(LOG_WARNING, "No suitable long-poll found for %s", cp->rpc_url);
  8271. while (!pool) {
  8272. cgsleep_ms(60000);
  8273. pool = select_longpoll_pool(cp);
  8274. }
  8275. }
  8276. if (pool->has_stratum) {
  8277. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  8278. cp->rpc_url, pool->rpc_url);
  8279. goto out;
  8280. }
  8281. /* Any longpoll from any pool is enough for this to be true */
  8282. have_longpoll = true;
  8283. wait_lpcurrent(cp);
  8284. {
  8285. lp_url = pool->lp_url;
  8286. if (cp == pool)
  8287. applog(LOG_WARNING, "Long-polling activated for %s (%s)", lp_url, pool_protocol_name(pool->lp_proto));
  8288. else
  8289. applog(LOG_WARNING, "Long-polling activated for %s via %s (%s)", cp->rpc_url, lp_url, pool_protocol_name(pool->lp_proto));
  8290. }
  8291. while (42) {
  8292. json_t *val, *soval;
  8293. struct work *work = make_work();
  8294. char *lpreq;
  8295. lpreq = prepare_rpc_req(work, pool->lp_proto, pool->lp_id);
  8296. work->pool = pool;
  8297. if (!lpreq)
  8298. {
  8299. free_work(work);
  8300. goto lpfail;
  8301. }
  8302. wait_lpcurrent(cp);
  8303. cgtime(&start);
  8304. /* Longpoll connections can be persistent for a very long time
  8305. * and any number of issues could have come up in the meantime
  8306. * so always establish a fresh connection instead of relying on
  8307. * a persistent one. */
  8308. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  8309. curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, save_curl_socket);
  8310. curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, pool);
  8311. val = json_rpc_call(curl, lp_url, pool->rpc_userpass,
  8312. lpreq, false, true, &rolltime, pool, false);
  8313. pool->lp_socket = CURL_SOCKET_BAD;
  8314. cgtime(&reply);
  8315. free(lpreq);
  8316. if (likely(val)) {
  8317. soval = json_object_get(json_object_get(val, "result"), "submitold");
  8318. if (soval)
  8319. pool->submit_old = json_is_true(soval);
  8320. else
  8321. pool->submit_old = false;
  8322. convert_to_work(val, rolltime, pool, work, &start, &reply);
  8323. failures = 0;
  8324. json_decref(val);
  8325. } else {
  8326. /* Some pools regularly drop the longpoll request so
  8327. * only see this as longpoll failure if it happens
  8328. * immediately and just restart it the rest of the
  8329. * time. */
  8330. cgtime(&end);
  8331. free_work(work);
  8332. if (end.tv_sec - start.tv_sec > 30)
  8333. continue;
  8334. if (failures == 1)
  8335. applog(LOG_WARNING, "longpoll failed for %s, retrying every 30s", lp_url);
  8336. lpfail:
  8337. cgsleep_ms(30000);
  8338. }
  8339. if (pool != cp) {
  8340. pool = select_longpoll_pool(cp);
  8341. if (pool->has_stratum) {
  8342. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  8343. cp->rpc_url, pool->rpc_url);
  8344. break;
  8345. }
  8346. if (unlikely(!pool))
  8347. goto retry_pool;
  8348. }
  8349. if (unlikely(pool->removed))
  8350. break;
  8351. }
  8352. out:
  8353. curl_easy_cleanup(curl);
  8354. return NULL;
  8355. }
  8356. static void stop_longpoll(void)
  8357. {
  8358. int i;
  8359. want_longpoll = false;
  8360. for (i = 0; i < total_pools; ++i)
  8361. {
  8362. struct pool *pool = pools[i];
  8363. if (unlikely(!pool->lp_started))
  8364. continue;
  8365. pool->lp_started = false;
  8366. pthread_cancel(pool->longpoll_thread);
  8367. }
  8368. have_longpoll = false;
  8369. }
  8370. static void start_longpoll(void)
  8371. {
  8372. int i;
  8373. want_longpoll = true;
  8374. for (i = 0; i < total_pools; ++i)
  8375. {
  8376. struct pool *pool = pools[i];
  8377. if (unlikely(pool->removed || pool->lp_started || !pool->lp_url))
  8378. continue;
  8379. pool->lp_started = true;
  8380. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  8381. quit(1, "Failed to create pool longpoll thread");
  8382. }
  8383. }
  8384. void reinit_device(struct cgpu_info *cgpu)
  8385. {
  8386. if (cgpu->drv->reinit_device)
  8387. cgpu->drv->reinit_device(cgpu);
  8388. }
  8389. static struct timeval rotate_tv;
  8390. /* We reap curls if they are unused for over a minute */
  8391. static void reap_curl(struct pool *pool)
  8392. {
  8393. struct curl_ent *ent, *iter;
  8394. struct timeval now;
  8395. int reaped = 0;
  8396. cgtime(&now);
  8397. mutex_lock(&pool->pool_lock);
  8398. LL_FOREACH_SAFE(pool->curllist, ent, iter) {
  8399. if (pool->curls < 2)
  8400. break;
  8401. if (now.tv_sec - ent->tv.tv_sec > 300) {
  8402. reaped++;
  8403. pool->curls--;
  8404. LL_DELETE(pool->curllist, ent);
  8405. curl_easy_cleanup(ent->curl);
  8406. free(ent);
  8407. }
  8408. }
  8409. mutex_unlock(&pool->pool_lock);
  8410. if (reaped)
  8411. applog(LOG_DEBUG, "Reaped %d curl%s from pool %d", reaped, reaped > 1 ? "s" : "", pool->pool_no);
  8412. }
  8413. static void *watchpool_thread(void __maybe_unused *userdata)
  8414. {
  8415. int intervals = 0;
  8416. #ifndef HAVE_PTHREAD_CANCEL
  8417. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  8418. #endif
  8419. RenameThread("watchpool");
  8420. while (42) {
  8421. struct timeval now;
  8422. int i;
  8423. if (++intervals > 20)
  8424. intervals = 0;
  8425. cgtime(&now);
  8426. for (i = 0; i < total_pools; i++) {
  8427. struct pool *pool = pools[i];
  8428. if (!opt_benchmark)
  8429. reap_curl(pool);
  8430. /* Get a rolling utility per pool over 10 mins */
  8431. if (intervals > 19) {
  8432. int shares = pool->diff1 - pool->last_shares;
  8433. pool->last_shares = pool->diff1;
  8434. pool->utility = (pool->utility + (double)shares * 0.63) / 1.63;
  8435. pool->shares = pool->utility;
  8436. }
  8437. if (pool->enabled == POOL_DISABLED)
  8438. continue;
  8439. /* Don't start testing any pools if the test threads
  8440. * from startup are still doing their first attempt. */
  8441. if (unlikely(pool->testing)) {
  8442. pthread_join(pool->test_thread, NULL);
  8443. }
  8444. /* Test pool is idle once every minute */
  8445. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 30) {
  8446. cgtime(&pool->tv_idle);
  8447. if (pool_active(pool, true) && pool_tclear(pool, &pool->idle))
  8448. pool_resus(pool);
  8449. }
  8450. /* Only switch pools if the failback pool has been
  8451. * alive for more than 5 minutes to prevent
  8452. * intermittently failing pools from being used. */
  8453. if (!pool->idle && pool_strategy == POOL_FAILOVER && pool->prio < cp_prio() &&
  8454. now.tv_sec - pool->tv_idle.tv_sec > 300) {
  8455. applog(LOG_WARNING, "Pool %d %s stable for 5 mins",
  8456. pool->pool_no, pool->rpc_url);
  8457. switch_pools(NULL);
  8458. }
  8459. }
  8460. if (current_pool()->idle)
  8461. switch_pools(NULL);
  8462. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  8463. cgtime(&rotate_tv);
  8464. switch_pools(NULL);
  8465. }
  8466. cgsleep_ms(30000);
  8467. }
  8468. return NULL;
  8469. }
  8470. void mt_enable(struct thr_info *thr)
  8471. {
  8472. applog(LOG_DEBUG, "Waking up thread %d", thr->id);
  8473. notifier_wake(thr->notifier);
  8474. }
  8475. void proc_enable(struct cgpu_info *cgpu)
  8476. {
  8477. int j;
  8478. cgpu->deven = DEV_ENABLED;
  8479. for (j = cgpu->threads ?: 1; j--; )
  8480. mt_enable(cgpu->thr[j]);
  8481. }
  8482. #define device_recovered(cgpu) proc_enable(cgpu)
  8483. void cgpu_set_defaults(struct cgpu_info * const cgpu)
  8484. {
  8485. const struct device_drv * const drv = cgpu->drv;
  8486. struct string_elist *setstr_elist;
  8487. const char *p, *p2;
  8488. char replybuf[0x2000];
  8489. size_t L;
  8490. DL_FOREACH(opt_set_device_list, setstr_elist)
  8491. {
  8492. const char * const setstr = setstr_elist->string;
  8493. p = strchr(setstr, ':');
  8494. if (!p)
  8495. p = setstr;
  8496. {
  8497. L = p - setstr;
  8498. char pattern[L + 1];
  8499. if (L)
  8500. memcpy(pattern, setstr, L);
  8501. pattern[L] = '\0';
  8502. if (!cgpu_match(pattern, cgpu))
  8503. continue;
  8504. }
  8505. applog(LOG_DEBUG, "%"PRIpreprv": %s: Matched with set default: %s",
  8506. cgpu->proc_repr, __func__, setstr);
  8507. if (!drv->set_device)
  8508. {
  8509. applog(LOG_WARNING, "%"PRIpreprv": set_device is not implemented (trying to apply rule: %s)",
  8510. cgpu->proc_repr, setstr);
  8511. continue;
  8512. }
  8513. if (p[0] == ':')
  8514. ++p;
  8515. p2 = strchr(p, '=');
  8516. if (!p2)
  8517. {
  8518. L = strlen(p);
  8519. p2 = "";
  8520. }
  8521. else
  8522. {
  8523. L = p2 - p;
  8524. ++p2;
  8525. }
  8526. char opt[L + 1];
  8527. if (L)
  8528. memcpy(opt, p, L);
  8529. opt[L] = '\0';
  8530. L = strlen(p2);
  8531. char setval[L + 1];
  8532. if (L)
  8533. memcpy(setval, p2, L);
  8534. setval[L] = '\0';
  8535. p = drv->set_device(cgpu, opt, setval, replybuf);
  8536. if (p)
  8537. applog(LOG_WARNING, "%"PRIpreprv": Applying rule %s: %s",
  8538. cgpu->proc_repr, setstr, p);
  8539. else
  8540. applog(LOG_DEBUG, "%"PRIpreprv": Applied rule %s",
  8541. cgpu->proc_repr, setstr);
  8542. }
  8543. cgpu->already_set_defaults = true;
  8544. }
  8545. void drv_set_defaults(const struct device_drv * const drv, char *(*set_func)(struct cgpu_info *, char *, char *, char *), void *userp)
  8546. {
  8547. struct device_drv dummy_drv = *drv;
  8548. struct cgpu_info dummy_cgpu = {
  8549. .drv = &dummy_drv,
  8550. .device = &dummy_cgpu,
  8551. .device_id = -1,
  8552. .proc_id = -1,
  8553. .device_data = userp,
  8554. };
  8555. strcpy(dummy_cgpu.proc_repr, drv->name);
  8556. dummy_drv.set_device = set_func;
  8557. cgpu_set_defaults(&dummy_cgpu);
  8558. }
  8559. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  8560. * the screen at regular intervals, and restarts threads if they appear to have
  8561. * died. */
  8562. #define WATCHDOG_SICK_TIME 60
  8563. #define WATCHDOG_DEAD_TIME 600
  8564. #define WATCHDOG_SICK_COUNT (WATCHDOG_SICK_TIME/WATCHDOG_INTERVAL)
  8565. #define WATCHDOG_DEAD_COUNT (WATCHDOG_DEAD_TIME/WATCHDOG_INTERVAL)
  8566. static void *watchdog_thread(void __maybe_unused *userdata)
  8567. {
  8568. const unsigned int interval = WATCHDOG_INTERVAL;
  8569. struct timeval zero_tv;
  8570. #ifndef HAVE_PTHREAD_CANCEL
  8571. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  8572. #endif
  8573. RenameThread("watchdog");
  8574. memset(&zero_tv, 0, sizeof(struct timeval));
  8575. cgtime(&rotate_tv);
  8576. while (1) {
  8577. int i;
  8578. struct timeval now;
  8579. sleep(interval);
  8580. discard_stale();
  8581. hashmeter(-1, &zero_tv, 0);
  8582. #ifdef HAVE_CURSES
  8583. const int ts = total_staged();
  8584. if (curses_active_locked()) {
  8585. change_logwinsize();
  8586. curses_print_status(ts);
  8587. _refresh_devstatus(true);
  8588. touchwin(logwin);
  8589. wrefresh(logwin);
  8590. unlock_curses();
  8591. }
  8592. #endif
  8593. cgtime(&now);
  8594. if (!sched_paused && !should_run()) {
  8595. applog(LOG_WARNING, "Pausing execution as per stop time %02d:%02d scheduled",
  8596. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  8597. if (!schedstart.enable) {
  8598. quit(0, "Terminating execution as planned");
  8599. break;
  8600. }
  8601. applog(LOG_WARNING, "Will restart execution as scheduled at %02d:%02d",
  8602. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  8603. sched_paused = true;
  8604. rd_lock(&mining_thr_lock);
  8605. for (i = 0; i < mining_threads; i++)
  8606. mining_thr[i]->pause = true;
  8607. rd_unlock(&mining_thr_lock);
  8608. } else if (sched_paused && should_run()) {
  8609. applog(LOG_WARNING, "Restarting execution as per start time %02d:%02d scheduled",
  8610. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  8611. if (schedstop.enable)
  8612. applog(LOG_WARNING, "Will pause execution as scheduled at %02d:%02d",
  8613. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  8614. sched_paused = false;
  8615. for (i = 0; i < mining_threads; i++) {
  8616. struct thr_info *thr;
  8617. thr = get_thread(i);
  8618. thr->pause = false;
  8619. }
  8620. for (i = 0; i < total_devices; ++i)
  8621. {
  8622. struct cgpu_info *cgpu = get_devices(i);
  8623. /* Don't touch disabled devices */
  8624. if (cgpu->deven == DEV_DISABLED)
  8625. continue;
  8626. proc_enable(cgpu);
  8627. }
  8628. }
  8629. for (i = 0; i < total_devices; ++i) {
  8630. struct cgpu_info *cgpu = get_devices(i);
  8631. if (!cgpu->disable_watchdog)
  8632. bfg_watchdog(cgpu, &now);
  8633. }
  8634. }
  8635. return NULL;
  8636. }
  8637. void bfg_watchdog(struct cgpu_info * const cgpu, struct timeval * const tvp_now)
  8638. {
  8639. struct thr_info *thr = cgpu->thr[0];
  8640. enum dev_enable *denable;
  8641. char *dev_str = cgpu->proc_repr;
  8642. int gpu;
  8643. if (likely(drv_ready(cgpu)))
  8644. {
  8645. if (unlikely(!cgpu->already_set_defaults))
  8646. cgpu_set_defaults(cgpu);
  8647. if (cgpu->drv->get_stats)
  8648. cgpu->drv->get_stats(cgpu);
  8649. }
  8650. gpu = cgpu->device_id;
  8651. denable = &cgpu->deven;
  8652. #ifdef HAVE_ADL
  8653. if (adl_active && cgpu->has_adl)
  8654. gpu_autotune(gpu, denable);
  8655. if (opt_debug && cgpu->has_adl) {
  8656. int engineclock = 0, memclock = 0, activity = 0, fanspeed = 0, fanpercent = 0, powertune = 0;
  8657. float temp = 0, vddc = 0;
  8658. if (gpu_stats(gpu, &temp, &engineclock, &memclock, &vddc, &activity, &fanspeed, &fanpercent, &powertune))
  8659. applog(LOG_DEBUG, "%.1f C F: %d%%(%dRPM) E: %dMHz M: %dMHz V: %.3fV A: %d%% P: %d%%",
  8660. temp, fanpercent, fanspeed, engineclock, memclock, vddc, activity, powertune);
  8661. }
  8662. #endif
  8663. /* Thread is disabled */
  8664. if (*denable == DEV_DISABLED)
  8665. return;
  8666. else
  8667. if (*denable == DEV_RECOVER_ERR) {
  8668. if (opt_restart && timer_elapsed(&cgpu->tv_device_last_not_well, NULL) > cgpu->reinit_backoff) {
  8669. applog(LOG_NOTICE, "Attempting to reinitialize %s",
  8670. dev_str);
  8671. if (cgpu->reinit_backoff < 300)
  8672. cgpu->reinit_backoff *= 2;
  8673. device_recovered(cgpu);
  8674. }
  8675. return;
  8676. }
  8677. else
  8678. if (*denable == DEV_RECOVER) {
  8679. if (opt_restart && cgpu->temp < cgpu->targettemp) {
  8680. applog(LOG_NOTICE, "%s recovered to temperature below target, re-enabling",
  8681. dev_str);
  8682. device_recovered(cgpu);
  8683. }
  8684. dev_error_update(cgpu, REASON_DEV_THERMAL_CUTOFF);
  8685. return;
  8686. }
  8687. else
  8688. if (cgpu->temp > cgpu->cutofftemp)
  8689. {
  8690. applog(LOG_WARNING, "%s hit thermal cutoff limit, disabling!",
  8691. dev_str);
  8692. *denable = DEV_RECOVER;
  8693. dev_error(cgpu, REASON_DEV_THERMAL_CUTOFF);
  8694. run_cmd(cmd_idle);
  8695. }
  8696. if (thr->getwork) {
  8697. if (cgpu->status == LIFE_WELL && thr->getwork < tvp_now->tv_sec - opt_log_interval) {
  8698. int thrid;
  8699. bool cgpu_idle = true;
  8700. thr->rolling = 0;
  8701. for (thrid = 0; thrid < cgpu->threads; ++thrid)
  8702. if (!cgpu->thr[thrid]->getwork)
  8703. cgpu_idle = false;
  8704. if (cgpu_idle) {
  8705. cgpu->rolling = 0;
  8706. cgpu->status = LIFE_WAIT;
  8707. }
  8708. }
  8709. return;
  8710. }
  8711. else if (cgpu->status == LIFE_WAIT)
  8712. cgpu->status = LIFE_WELL;
  8713. #ifdef WANT_CPUMINE
  8714. if (!strcmp(cgpu->drv->dname, "cpu"))
  8715. return;
  8716. #endif
  8717. if (cgpu->status != LIFE_WELL && (tvp_now->tv_sec - thr->last.tv_sec < WATCHDOG_SICK_TIME)) {
  8718. if (likely(cgpu->status != LIFE_INIT && cgpu->status != LIFE_INIT2))
  8719. applog(LOG_ERR, "%s: Recovered, declaring WELL!", dev_str);
  8720. cgpu->status = LIFE_WELL;
  8721. cgpu->device_last_well = time(NULL);
  8722. } else if (cgpu->status == LIFE_WELL && (tvp_now->tv_sec - thr->last.tv_sec > WATCHDOG_SICK_TIME)) {
  8723. thr->rolling = cgpu->rolling = 0;
  8724. cgpu->status = LIFE_SICK;
  8725. applog(LOG_ERR, "%s: Idle for more than 60 seconds, declaring SICK!", dev_str);
  8726. cgtime(&thr->sick);
  8727. dev_error(cgpu, REASON_DEV_SICK_IDLE_60);
  8728. run_cmd(cmd_sick);
  8729. #ifdef HAVE_ADL
  8730. if (adl_active && cgpu->has_adl && gpu_activity(gpu) > 50) {
  8731. applog(LOG_ERR, "GPU still showing activity suggesting a hard hang.");
  8732. applog(LOG_ERR, "Will not attempt to auto-restart it.");
  8733. } else
  8734. #endif
  8735. if (opt_restart && cgpu->drv->reinit_device) {
  8736. applog(LOG_ERR, "%s: Attempting to restart", dev_str);
  8737. reinit_device(cgpu);
  8738. }
  8739. } else if (cgpu->status == LIFE_SICK && (tvp_now->tv_sec - thr->last.tv_sec > WATCHDOG_DEAD_TIME)) {
  8740. cgpu->status = LIFE_DEAD;
  8741. applog(LOG_ERR, "%s: Not responded for more than 10 minutes, declaring DEAD!", dev_str);
  8742. cgtime(&thr->sick);
  8743. dev_error(cgpu, REASON_DEV_DEAD_IDLE_600);
  8744. run_cmd(cmd_dead);
  8745. } else if (tvp_now->tv_sec - thr->sick.tv_sec > 60 &&
  8746. (cgpu->status == LIFE_SICK || cgpu->status == LIFE_DEAD)) {
  8747. /* Attempt to restart a GPU that's sick or dead once every minute */
  8748. cgtime(&thr->sick);
  8749. #ifdef HAVE_ADL
  8750. if (adl_active && cgpu->has_adl && gpu_activity(gpu) > 50) {
  8751. /* Again do not attempt to restart a device that may have hard hung */
  8752. } else
  8753. #endif
  8754. if (opt_restart)
  8755. reinit_device(cgpu);
  8756. }
  8757. }
  8758. static void log_print_status(struct cgpu_info *cgpu)
  8759. {
  8760. char logline[255];
  8761. get_statline(logline, sizeof(logline), cgpu);
  8762. applog(LOG_WARNING, "%s", logline);
  8763. }
  8764. void print_summary(void)
  8765. {
  8766. struct timeval diff;
  8767. int hours, mins, secs, i;
  8768. double utility, efficiency = 0.0;
  8769. char xfer[17], bw[19];
  8770. int pool_secs;
  8771. timersub(&total_tv_end, &total_tv_start, &diff);
  8772. hours = diff.tv_sec / 3600;
  8773. mins = (diff.tv_sec % 3600) / 60;
  8774. secs = diff.tv_sec % 60;
  8775. utility = total_accepted / total_secs * 60;
  8776. efficiency = total_bytes_xfer ? total_diff_accepted * 2048. / total_bytes_xfer : 0.0;
  8777. applog(LOG_WARNING, "\nSummary of runtime statistics:\n");
  8778. applog(LOG_WARNING, "Started at %s", datestamp);
  8779. if (total_pools == 1)
  8780. applog(LOG_WARNING, "Pool: %s", pools[0]->rpc_url);
  8781. #ifdef WANT_CPUMINE
  8782. if (opt_n_threads)
  8783. applog(LOG_WARNING, "CPU hasher algorithm used: %s", algo_names[opt_algo]);
  8784. #endif
  8785. applog(LOG_WARNING, "Runtime: %d hrs : %d mins : %d secs", hours, mins, secs);
  8786. applog(LOG_WARNING, "Average hashrate: %.1f Megahash/s", total_mhashes_done / total_secs);
  8787. applog(LOG_WARNING, "Solved blocks: %d", found_blocks);
  8788. applog(LOG_WARNING, "Best share difficulty: %s", best_share);
  8789. applog(LOG_WARNING, "Share submissions: %d", total_accepted + total_rejected);
  8790. applog(LOG_WARNING, "Accepted shares: %d", total_accepted);
  8791. applog(LOG_WARNING, "Rejected shares: %d + %d stale (%.2f%%)",
  8792. total_rejected, total_stale,
  8793. (float)(total_rejected + total_stale) / (float)(total_rejected + total_stale + total_accepted)
  8794. );
  8795. applog(LOG_WARNING, "Accepted difficulty shares: %1.f", total_diff_accepted);
  8796. applog(LOG_WARNING, "Rejected difficulty shares: %1.f", total_diff_rejected);
  8797. applog(LOG_WARNING, "Hardware errors: %d", hw_errors);
  8798. applog(LOG_WARNING, "Network transfer: %s (%s)",
  8799. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  8800. (float)total_bytes_rcvd,
  8801. (float)total_bytes_sent),
  8802. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  8803. (float)(total_bytes_rcvd / total_secs),
  8804. (float)(total_bytes_sent / total_secs)));
  8805. applog(LOG_WARNING, "Efficiency (accepted shares * difficulty / 2 KB): %.2f", efficiency);
  8806. applog(LOG_WARNING, "Utility (accepted shares / min): %.2f/min\n", utility);
  8807. applog(LOG_WARNING, "Unable to get work from server occasions: %d", total_go);
  8808. applog(LOG_WARNING, "Work items generated locally: %d", local_work);
  8809. applog(LOG_WARNING, "Submitting work remotely delay occasions: %d", total_ro);
  8810. applog(LOG_WARNING, "New blocks detected on network: %d\n", new_blocks);
  8811. if (total_pools > 1) {
  8812. for (i = 0; i < total_pools; i++) {
  8813. struct pool *pool = pools[i];
  8814. applog(LOG_WARNING, "Pool: %s", pool->rpc_url);
  8815. if (pool->solved)
  8816. applog(LOG_WARNING, "SOLVED %d BLOCK%s!", pool->solved, pool->solved > 1 ? "S" : "");
  8817. applog(LOG_WARNING, " Share submissions: %d", pool->accepted + pool->rejected);
  8818. applog(LOG_WARNING, " Accepted shares: %d", pool->accepted);
  8819. applog(LOG_WARNING, " Rejected shares: %d + %d stale (%.2f%%)",
  8820. pool->rejected, pool->stale_shares,
  8821. (float)(pool->rejected + pool->stale_shares) / (float)(pool->rejected + pool->stale_shares + pool->accepted)
  8822. );
  8823. applog(LOG_WARNING, " Accepted difficulty shares: %1.f", pool->diff_accepted);
  8824. applog(LOG_WARNING, " Rejected difficulty shares: %1.f", pool->diff_rejected);
  8825. pool_secs = timer_elapsed(&pool->cgminer_stats.start_tv, NULL);
  8826. applog(LOG_WARNING, " Network transfer: %s (%s)",
  8827. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  8828. (float)pool->cgminer_pool_stats.net_bytes_received,
  8829. (float)pool->cgminer_pool_stats.net_bytes_sent),
  8830. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  8831. (float)(pool->cgminer_pool_stats.net_bytes_received / pool_secs),
  8832. (float)(pool->cgminer_pool_stats.net_bytes_sent / pool_secs)));
  8833. uint64_t pool_bytes_xfer = pool->cgminer_pool_stats.net_bytes_received + pool->cgminer_pool_stats.net_bytes_sent;
  8834. efficiency = pool_bytes_xfer ? pool->diff_accepted * 2048. / pool_bytes_xfer : 0.0;
  8835. applog(LOG_WARNING, " Efficiency (accepted * difficulty / 2 KB): %.2f", efficiency);
  8836. applog(LOG_WARNING, " Items worked on: %d", pool->works);
  8837. applog(LOG_WARNING, " Unable to get work from server occasions: %d", pool->getfail_occasions);
  8838. applog(LOG_WARNING, " Submitting work remotely delay occasions: %d\n", pool->remotefail_occasions);
  8839. }
  8840. }
  8841. applog(LOG_WARNING, "Summary of per device statistics:\n");
  8842. for (i = 0; i < total_devices; ++i) {
  8843. struct cgpu_info *cgpu = get_devices(i);
  8844. if ((!cgpu->proc_id) && cgpu->procs > 1)
  8845. {
  8846. // Device summary line
  8847. opt_show_procs = false;
  8848. log_print_status(cgpu);
  8849. opt_show_procs = true;
  8850. }
  8851. log_print_status(cgpu);
  8852. }
  8853. if (opt_shares) {
  8854. applog(LOG_WARNING, "Mined %.0f accepted shares of %d requested\n", total_diff_accepted, opt_shares);
  8855. if (opt_shares > total_diff_accepted)
  8856. applog(LOG_WARNING, "WARNING - Mined only %.0f shares of %d requested.", total_diff_accepted, opt_shares);
  8857. }
  8858. applog(LOG_WARNING, " ");
  8859. fflush(stderr);
  8860. fflush(stdout);
  8861. }
  8862. void _bfg_clean_up(bool restarting)
  8863. {
  8864. #ifdef HAVE_OPENCL
  8865. clear_adl(nDevs);
  8866. #endif
  8867. #ifdef HAVE_LIBUSB
  8868. if (likely(have_libusb))
  8869. libusb_exit(NULL);
  8870. #endif
  8871. cgtime(&total_tv_end);
  8872. #ifdef WIN32
  8873. timeEndPeriod(1);
  8874. #endif
  8875. if (!restarting) {
  8876. /* Attempting to disable curses or print a summary during a
  8877. * restart can lead to a deadlock. */
  8878. #ifdef HAVE_CURSES
  8879. disable_curses();
  8880. #endif
  8881. if (!opt_realquiet && successful_connect)
  8882. print_summary();
  8883. }
  8884. if (opt_n_threads)
  8885. free(cpus);
  8886. curl_global_cleanup();
  8887. #ifdef WIN32
  8888. WSACleanup();
  8889. #endif
  8890. }
  8891. void _quit(int status)
  8892. {
  8893. if (status) {
  8894. const char *ev = getenv("__BFGMINER_SEGFAULT_ERRQUIT");
  8895. if (unlikely(ev && ev[0] && ev[0] != '0')) {
  8896. int *p = NULL;
  8897. // NOTE debugger can bypass with: p = &p
  8898. *p = status; // Segfault, hopefully dumping core
  8899. }
  8900. }
  8901. #if defined(unix) || defined(__APPLE__)
  8902. if (forkpid > 0) {
  8903. kill(forkpid, SIGTERM);
  8904. forkpid = 0;
  8905. }
  8906. #endif
  8907. exit(status);
  8908. }
  8909. #ifdef HAVE_CURSES
  8910. char *curses_input(const char *query)
  8911. {
  8912. char *input;
  8913. echo();
  8914. input = malloc(255);
  8915. if (!input)
  8916. quit(1, "Failed to malloc input");
  8917. leaveok(logwin, false);
  8918. wlogprint("%s:\n", query);
  8919. wgetnstr(logwin, input, 255);
  8920. if (!strlen(input))
  8921. {
  8922. free(input);
  8923. input = NULL;
  8924. }
  8925. leaveok(logwin, true);
  8926. noecho();
  8927. return input;
  8928. }
  8929. #endif
  8930. static bool pools_active = false;
  8931. static void *test_pool_thread(void *arg)
  8932. {
  8933. struct pool *pool = (struct pool *)arg;
  8934. if (pool_active(pool, false)) {
  8935. pool_tset(pool, &pool->lagging);
  8936. pool_tclear(pool, &pool->idle);
  8937. bool first_pool = false;
  8938. cg_wlock(&control_lock);
  8939. if (!pools_active) {
  8940. currentpool = pool;
  8941. if (pool->pool_no != 0)
  8942. first_pool = true;
  8943. pools_active = true;
  8944. }
  8945. cg_wunlock(&control_lock);
  8946. if (unlikely(first_pool))
  8947. applog(LOG_NOTICE, "Switching to pool %d %s - first alive pool", pool->pool_no, pool->rpc_url);
  8948. else
  8949. applog(LOG_NOTICE, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  8950. switch_pools(NULL);
  8951. } else
  8952. pool_died(pool);
  8953. pool->testing = false;
  8954. return NULL;
  8955. }
  8956. /* Always returns true that the pool details were added unless we are not
  8957. * live, implying this is the only pool being added, so if no pools are
  8958. * active it returns false. */
  8959. bool add_pool_details(struct pool *pool, bool live, char *url, char *user, char *pass)
  8960. {
  8961. size_t siz;
  8962. pool->rpc_url = url;
  8963. pool->rpc_user = user;
  8964. pool->rpc_pass = pass;
  8965. siz = strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2;
  8966. pool->rpc_userpass = malloc(siz);
  8967. if (!pool->rpc_userpass)
  8968. quit(1, "Failed to malloc userpass");
  8969. snprintf(pool->rpc_userpass, siz, "%s:%s", pool->rpc_user, pool->rpc_pass);
  8970. pool->testing = true;
  8971. pool->idle = true;
  8972. enable_pool(pool);
  8973. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  8974. if (!live) {
  8975. pthread_join(pool->test_thread, NULL);
  8976. return pools_active;
  8977. }
  8978. return true;
  8979. }
  8980. #ifdef HAVE_CURSES
  8981. static bool input_pool(bool live)
  8982. {
  8983. char *url = NULL, *user = NULL, *pass = NULL;
  8984. struct pool *pool;
  8985. bool ret = false;
  8986. immedok(logwin, true);
  8987. wlogprint("Input server details.\n");
  8988. url = curses_input("URL");
  8989. if (!url)
  8990. goto out;
  8991. user = curses_input("Username");
  8992. if (!user)
  8993. goto out;
  8994. pass = curses_input("Password");
  8995. if (!pass)
  8996. pass = calloc(1, 1);
  8997. pool = add_pool();
  8998. if (!detect_stratum(pool, url) && strncmp(url, "http://", 7) &&
  8999. strncmp(url, "https://", 8)) {
  9000. char *httpinput;
  9001. httpinput = malloc(256);
  9002. if (!httpinput)
  9003. quit(1, "Failed to malloc httpinput");
  9004. strcpy(httpinput, "http://");
  9005. strncat(httpinput, url, 248);
  9006. free(url);
  9007. url = httpinput;
  9008. }
  9009. ret = add_pool_details(pool, live, url, user, pass);
  9010. out:
  9011. immedok(logwin, false);
  9012. if (!ret) {
  9013. if (url)
  9014. free(url);
  9015. if (user)
  9016. free(user);
  9017. if (pass)
  9018. free(pass);
  9019. }
  9020. return ret;
  9021. }
  9022. #endif
  9023. #if defined(unix) || defined(__APPLE__)
  9024. static void fork_monitor()
  9025. {
  9026. // Make a pipe: [readFD, writeFD]
  9027. int pfd[2];
  9028. int r = pipe(pfd);
  9029. if (r < 0) {
  9030. perror("pipe - failed to create pipe for --monitor");
  9031. exit(1);
  9032. }
  9033. // Make stderr write end of pipe
  9034. fflush(stderr);
  9035. r = dup2(pfd[1], 2);
  9036. if (r < 0) {
  9037. perror("dup2 - failed to alias stderr to write end of pipe for --monitor");
  9038. exit(1);
  9039. }
  9040. r = close(pfd[1]);
  9041. if (r < 0) {
  9042. perror("close - failed to close write end of pipe for --monitor");
  9043. exit(1);
  9044. }
  9045. // Don't allow a dying monitor to kill the main process
  9046. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  9047. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  9048. if (SIG_ERR == sr0 || SIG_ERR == sr1) {
  9049. perror("signal - failed to edit signal mask for --monitor");
  9050. exit(1);
  9051. }
  9052. // Fork a child process
  9053. forkpid = fork();
  9054. if (forkpid < 0) {
  9055. perror("fork - failed to fork child process for --monitor");
  9056. exit(1);
  9057. }
  9058. // Child: launch monitor command
  9059. if (0 == forkpid) {
  9060. // Make stdin read end of pipe
  9061. r = dup2(pfd[0], 0);
  9062. if (r < 0) {
  9063. perror("dup2 - in child, failed to alias read end of pipe to stdin for --monitor");
  9064. exit(1);
  9065. }
  9066. close(pfd[0]);
  9067. if (r < 0) {
  9068. perror("close - in child, failed to close read end of pipe for --monitor");
  9069. exit(1);
  9070. }
  9071. // Launch user specified command
  9072. execl("/bin/bash", "/bin/bash", "-c", opt_stderr_cmd, (char*)NULL);
  9073. perror("execl - in child failed to exec user specified command for --monitor");
  9074. exit(1);
  9075. }
  9076. // Parent: clean up unused fds and bail
  9077. r = close(pfd[0]);
  9078. if (r < 0) {
  9079. perror("close - failed to close read end of pipe for --monitor");
  9080. exit(1);
  9081. }
  9082. }
  9083. #endif // defined(unix)
  9084. #ifdef HAVE_CURSES
  9085. #ifdef USE_UNICODE
  9086. static
  9087. wchar_t select_unicode_char(const wchar_t *opt)
  9088. {
  9089. for ( ; *opt; ++opt)
  9090. if (iswprint(*opt))
  9091. return *opt;
  9092. return '?';
  9093. }
  9094. #endif
  9095. void enable_curses(void) {
  9096. int x;
  9097. __maybe_unused int y;
  9098. lock_curses();
  9099. if (curses_active) {
  9100. unlock_curses();
  9101. return;
  9102. }
  9103. #ifdef USE_UNICODE
  9104. if (use_unicode)
  9105. {
  9106. setlocale(LC_CTYPE, "");
  9107. if (iswprint(0xb0))
  9108. have_unicode_degrees = true;
  9109. unicode_micro = select_unicode_char(L"\xb5\u03bcu");
  9110. }
  9111. #endif
  9112. mainwin = initscr();
  9113. start_color();
  9114. #if defined(PDCURSES) || defined(NCURSES_VERSION)
  9115. if (ERR != use_default_colors())
  9116. default_bgcolor = -1;
  9117. #endif
  9118. if (has_colors() && ERR != init_pair(1, COLOR_WHITE, COLOR_BLUE))
  9119. {
  9120. menu_attr = COLOR_PAIR(1);
  9121. if (ERR != init_pair(2, COLOR_RED, default_bgcolor))
  9122. attr_bad |= COLOR_PAIR(2);
  9123. }
  9124. keypad(mainwin, true);
  9125. getmaxyx(mainwin, y, x);
  9126. statuswin = newwin(logstart, x, 0, 0);
  9127. leaveok(statuswin, true);
  9128. // For whatever reason, PDCurses crashes if the logwin is initialized to height y-logcursor
  9129. // We resize the window later anyway, so just start it off at 1 :)
  9130. logwin = newwin(1, 0, logcursor, 0);
  9131. idlok(logwin, true);
  9132. scrollok(logwin, true);
  9133. leaveok(logwin, true);
  9134. cbreak();
  9135. noecho();
  9136. nonl();
  9137. curses_active = true;
  9138. statusy = logstart;
  9139. unlock_curses();
  9140. }
  9141. #endif
  9142. /* TODO: fix need a dummy CPU device_drv even if no support for CPU mining */
  9143. #ifndef WANT_CPUMINE
  9144. struct device_drv cpu_drv;
  9145. struct device_drv cpu_drv = {
  9146. .name = "CPU",
  9147. };
  9148. #endif
  9149. static int cgminer_id_count = 0;
  9150. static int device_line_id_count;
  9151. void register_device(struct cgpu_info *cgpu)
  9152. {
  9153. cgpu->deven = DEV_ENABLED;
  9154. wr_lock(&devices_lock);
  9155. devices[cgpu->cgminer_id = cgminer_id_count++] = cgpu;
  9156. wr_unlock(&devices_lock);
  9157. if (!cgpu->proc_id)
  9158. cgpu->device_line_id = device_line_id_count++;
  9159. mining_threads += cgpu->threads ?: 1;
  9160. #ifdef HAVE_CURSES
  9161. adj_width(mining_threads, &dev_width);
  9162. #endif
  9163. rwlock_init(&cgpu->qlock);
  9164. cgpu->queued_work = NULL;
  9165. }
  9166. struct _cgpu_devid_counter {
  9167. char name[4];
  9168. int lastid;
  9169. UT_hash_handle hh;
  9170. };
  9171. void renumber_cgpu(struct cgpu_info *cgpu)
  9172. {
  9173. static struct _cgpu_devid_counter *devids = NULL;
  9174. struct _cgpu_devid_counter *d;
  9175. HASH_FIND_STR(devids, cgpu->drv->name, d);
  9176. if (d)
  9177. cgpu->device_id = ++d->lastid;
  9178. else {
  9179. d = malloc(sizeof(*d));
  9180. memcpy(d->name, cgpu->drv->name, sizeof(d->name));
  9181. cgpu->device_id = d->lastid = 0;
  9182. HASH_ADD_STR(devids, name, d);
  9183. }
  9184. }
  9185. static bool my_blkmaker_sha256_callback(void *digest, const void *buffer, size_t length)
  9186. {
  9187. sha256(buffer, length, digest);
  9188. return true;
  9189. }
  9190. #ifndef HAVE_PTHREAD_CANCEL
  9191. extern void setup_pthread_cancel_workaround();
  9192. extern struct sigaction pcwm_orig_term_handler;
  9193. #endif
  9194. bool bfg_need_detect_rescan;
  9195. extern void probe_device(struct lowlevel_device_info *);
  9196. static void schedule_rescan(const struct timeval *);
  9197. static
  9198. void drv_detect_all()
  9199. {
  9200. const int algomatch = opt_scrypt ? POW_SCRYPT : POW_SHA256D;
  9201. bool rescanning = false;
  9202. rescan:
  9203. bfg_need_detect_rescan = false;
  9204. #ifdef HAVE_BFG_LOWLEVEL
  9205. if (!opt_scrypt)
  9206. {
  9207. struct lowlevel_device_info * const infolist = lowlevel_scan(), *info, *infotmp;
  9208. LL_FOREACH_SAFE(infolist, info, infotmp)
  9209. probe_device(info);
  9210. LL_FOREACH_SAFE(infolist, info, infotmp)
  9211. pthread_join(info->probe_pth, NULL);
  9212. }
  9213. #endif
  9214. struct driver_registration *reg, *tmp;
  9215. BFG_FOREACH_DRIVER_BY_PRIORITY(reg, tmp)
  9216. {
  9217. const struct device_drv * const drv = reg->drv;
  9218. const supported_algos_t algos = drv->supported_algos ?: POW_SHA256D;
  9219. if (0 == (algos & algomatch) || !drv->drv_detect)
  9220. continue;
  9221. drv->drv_detect();
  9222. }
  9223. #ifdef HAVE_BFG_LOWLEVEL
  9224. if (!opt_scrypt)
  9225. lowlevel_scan_free();
  9226. #endif
  9227. if (bfg_need_detect_rescan)
  9228. {
  9229. if (rescanning)
  9230. {
  9231. applog(LOG_DEBUG, "Device rescan requested a second time, delaying");
  9232. struct timeval tv_when;
  9233. timer_set_delay_from_now(&tv_when, rescan_delay_ms * 1000);
  9234. schedule_rescan(&tv_when);
  9235. }
  9236. else
  9237. {
  9238. rescanning = true;
  9239. applog(LOG_DEBUG, "Device rescan requested");
  9240. goto rescan;
  9241. }
  9242. }
  9243. }
  9244. static
  9245. void allocate_cgpu(struct cgpu_info *cgpu, unsigned int *kp)
  9246. {
  9247. struct thr_info *thr;
  9248. int j;
  9249. struct device_drv *api = cgpu->drv;
  9250. if (!cgpu->devtype)
  9251. cgpu->devtype = "PGA";
  9252. cgpu->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  9253. int threadobj = cgpu->threads;
  9254. if (!threadobj)
  9255. // Create a fake thread object to handle hashmeter etc
  9256. threadobj = 1;
  9257. cgpu->thr = calloc(threadobj + 1, sizeof(*cgpu->thr));
  9258. cgpu->thr[threadobj] = NULL;
  9259. cgpu->status = LIFE_INIT;
  9260. if (opt_devices_enabled_list)
  9261. {
  9262. struct string_elist *enablestr_elist;
  9263. cgpu->deven = DEV_DISABLED;
  9264. DL_FOREACH(opt_devices_enabled_list, enablestr_elist)
  9265. {
  9266. const char * const enablestr = enablestr_elist->string;
  9267. if (cgpu_match(enablestr, cgpu))
  9268. {
  9269. cgpu->deven = DEV_ENABLED;
  9270. break;
  9271. }
  9272. }
  9273. }
  9274. cgpu->max_hashes = 0;
  9275. BFGINIT(cgpu->min_nonce_diff, 1);
  9276. // Setup thread structs before starting any of the threads, in case they try to interact
  9277. for (j = 0; j < threadobj; ++j, ++*kp) {
  9278. thr = get_thread(*kp);
  9279. thr->id = *kp;
  9280. thr->cgpu = cgpu;
  9281. thr->device_thread = j;
  9282. thr->work_restart_notifier[1] = INVSOCK;
  9283. thr->mutex_request[1] = INVSOCK;
  9284. thr->_job_transition_in_progress = true;
  9285. timerclear(&thr->tv_morework);
  9286. thr->scanhash_working = true;
  9287. thr->hashes_done = 0;
  9288. timerclear(&thr->tv_hashes_done);
  9289. cgtime(&thr->tv_lastupdate);
  9290. thr->tv_poll.tv_sec = -1;
  9291. thr->_max_nonce = api->can_limit_work ? api->can_limit_work(thr) : 0xffffffff;
  9292. cgpu->thr[j] = thr;
  9293. }
  9294. if (!cgpu->device->threads)
  9295. notifier_init_invalid(cgpu->thr[0]->notifier);
  9296. else
  9297. if (!cgpu->threads)
  9298. memcpy(&cgpu->thr[0]->notifier, &cgpu->device->thr[0]->notifier, sizeof(cgpu->thr[0]->notifier));
  9299. else
  9300. for (j = 0; j < cgpu->threads; ++j)
  9301. {
  9302. thr = cgpu->thr[j];
  9303. notifier_init(thr->notifier);
  9304. }
  9305. }
  9306. static
  9307. void start_cgpu(struct cgpu_info *cgpu)
  9308. {
  9309. struct thr_info *thr;
  9310. int j;
  9311. for (j = 0; j < cgpu->threads; ++j) {
  9312. thr = cgpu->thr[j];
  9313. /* Enable threads for devices set not to mine but disable
  9314. * their queue in case we wish to enable them later */
  9315. if (cgpu->drv->thread_prepare && !cgpu->drv->thread_prepare(thr))
  9316. continue;
  9317. thread_reportout(thr);
  9318. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  9319. quit(1, "thread %d create failed", thr->id);
  9320. notifier_wake(thr->notifier);
  9321. }
  9322. if (cgpu->deven == DEV_ENABLED)
  9323. proc_enable(cgpu);
  9324. }
  9325. static
  9326. void _scan_serial(void *p)
  9327. {
  9328. const char *s = p;
  9329. struct string_elist *iter, *tmp;
  9330. struct string_elist *orig_scan_devices = scan_devices;
  9331. if (s)
  9332. {
  9333. // Make temporary scan_devices list
  9334. scan_devices = NULL;
  9335. string_elist_add("noauto", &scan_devices);
  9336. add_serial(s);
  9337. }
  9338. drv_detect_all();
  9339. if (s)
  9340. {
  9341. DL_FOREACH_SAFE(scan_devices, iter, tmp)
  9342. {
  9343. string_elist_del(&scan_devices, iter);
  9344. }
  9345. scan_devices = orig_scan_devices;
  9346. }
  9347. }
  9348. #ifdef HAVE_BFG_LOWLEVEL
  9349. static
  9350. bool _probe_device_match(const struct lowlevel_device_info * const info, const char * const ser)
  9351. {
  9352. if (!(false
  9353. || (info->serial && !strcasecmp(ser, info->serial))
  9354. || (info->path && !strcasecmp(ser, info->path ))
  9355. || (info->devid && !strcasecmp(ser, info->devid ))
  9356. ))
  9357. {
  9358. char *devid = devpath_to_devid(ser);
  9359. if (!devid)
  9360. return false;
  9361. const bool different = strcmp(info->devid, devid);
  9362. free(devid);
  9363. if (different)
  9364. return false;
  9365. }
  9366. return true;
  9367. }
  9368. static
  9369. const struct device_drv *_probe_device_find_drv(const char * const _dname, const size_t dnamelen)
  9370. {
  9371. struct driver_registration *dreg;
  9372. char dname[dnamelen];
  9373. int i;
  9374. for (i = 0; i < dnamelen; ++i)
  9375. dname[i] = tolower(_dname[i]);
  9376. BFG_FIND_DRV_BY_DNAME(dreg, dname, dnamelen);
  9377. if (!dreg)
  9378. {
  9379. for (i = 0; i < dnamelen; ++i)
  9380. dname[i] = toupper(_dname[i]);
  9381. BFG_FIND_DRV_BY_NAME(dreg, dname, dnamelen);
  9382. if (!dreg)
  9383. return NULL;
  9384. }
  9385. return dreg->drv;
  9386. }
  9387. static
  9388. bool _probe_device_internal(struct lowlevel_device_info * const info, const char * const dname, const size_t dnamelen)
  9389. {
  9390. const struct device_drv * const drv = _probe_device_find_drv(dname, dnamelen);
  9391. if (!(drv && drv->lowl_probe))
  9392. return false;
  9393. return drv->lowl_probe(info);
  9394. }
  9395. static
  9396. void *probe_device_thread(void *p)
  9397. {
  9398. struct lowlevel_device_info * const infolist = p;
  9399. struct lowlevel_device_info *info = infolist;
  9400. {
  9401. char threadname[5 + strlen(info->devid) + 1];
  9402. sprintf(threadname, "probe_%s", info->devid);
  9403. RenameThread(threadname);
  9404. }
  9405. // If already in use, ignore
  9406. if (bfg_claim_any(NULL, NULL, info->devid))
  9407. applogr(NULL, LOG_DEBUG, "%s: \"%s\" already in use",
  9408. __func__, info->product);
  9409. // if lowlevel device matches specific user assignment, probe requested driver(s)
  9410. struct string_elist *sd_iter, *sd_tmp;
  9411. struct driver_registration *dreg, *dreg_tmp;
  9412. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  9413. {
  9414. const char * const dname = sd_iter->string;
  9415. const char * const colon = strpbrk(dname, ":@");
  9416. if (!(colon && colon != dname))
  9417. continue;
  9418. const char * const ser = &colon[1];
  9419. LL_FOREACH2(infolist, info, same_devid_next)
  9420. {
  9421. if (!_probe_device_match(info, ser))
  9422. continue;
  9423. const size_t dnamelen = (colon - dname);
  9424. if (_probe_device_internal(info, dname, dnamelen))
  9425. return NULL;
  9426. else
  9427. bfg_need_detect_rescan = true;
  9428. }
  9429. }
  9430. // probe driver(s) with auto enabled and matching VID/PID/Product/etc of device
  9431. BFG_FOREACH_DRIVER_BY_PRIORITY(dreg, dreg_tmp)
  9432. {
  9433. const struct device_drv * const drv = dreg->drv;
  9434. // Check for "noauto" flag
  9435. // NOTE: driver-specific configuration overrides general
  9436. bool doauto = true;
  9437. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  9438. {
  9439. const char * const dname = sd_iter->string;
  9440. // NOTE: Only checking flags here, NOT path/serial, so @ is unacceptable
  9441. const char *colon = strchr(dname, ':');
  9442. if (!colon)
  9443. colon = &dname[-1];
  9444. if (strcasecmp("noauto", &colon[1]) && strcasecmp("auto", &colon[1]))
  9445. continue;
  9446. const ssize_t dnamelen = (colon - dname);
  9447. if (dnamelen >= 0 && _probe_device_find_drv(dname, dnamelen) != drv)
  9448. continue;
  9449. doauto = (tolower(colon[1]) == 'a');
  9450. if (dnamelen != -1)
  9451. break;
  9452. }
  9453. if (doauto && drv->lowl_match)
  9454. {
  9455. LL_FOREACH2(infolist, info, same_devid_next)
  9456. {
  9457. if (!drv->lowl_match(info))
  9458. continue;
  9459. if (drv->lowl_probe(info))
  9460. return NULL;
  9461. else
  9462. bfg_need_detect_rescan = true;
  9463. }
  9464. }
  9465. }
  9466. // probe driver(s) with 'all' enabled
  9467. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  9468. {
  9469. const char * const dname = sd_iter->string;
  9470. // NOTE: Only checking flags here, NOT path/serial, so @ is unacceptable
  9471. const char * const colon = strchr(dname, ':');
  9472. if (!colon)
  9473. {
  9474. LL_FOREACH2(infolist, info, same_devid_next)
  9475. {
  9476. if (
  9477. #ifdef NEED_BFG_LOWL_VCOM
  9478. (info->lowl == &lowl_vcom && !strcasecmp(dname, "all")) ||
  9479. #endif
  9480. _probe_device_match(info, (dname[0] == '@') ? &dname[1] : dname))
  9481. {
  9482. BFG_FOREACH_DRIVER_BY_PRIORITY(dreg, dreg_tmp)
  9483. {
  9484. const struct device_drv * const drv = dreg->drv;
  9485. if (drv->lowl_probe_by_name_only)
  9486. continue;
  9487. if (!drv->lowl_probe)
  9488. continue;
  9489. if (drv->lowl_probe(info))
  9490. return NULL;
  9491. }
  9492. bfg_need_detect_rescan = true;
  9493. break;
  9494. }
  9495. }
  9496. continue;
  9497. }
  9498. if (strcasecmp(&colon[1], "all"))
  9499. continue;
  9500. const size_t dnamelen = (colon - dname);
  9501. LL_FOREACH2(infolist, info, same_devid_next)
  9502. {
  9503. if (_probe_device_internal(info, dname, dnamelen))
  9504. return NULL;
  9505. }
  9506. }
  9507. return NULL;
  9508. }
  9509. void probe_device(struct lowlevel_device_info * const info)
  9510. {
  9511. pthread_create(&info->probe_pth, NULL, probe_device_thread, info);
  9512. }
  9513. #endif
  9514. int create_new_cgpus(void (*addfunc)(void*), void *arg)
  9515. {
  9516. static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  9517. int devcount, i, mining_threads_new = 0;
  9518. unsigned int k;
  9519. struct cgpu_info *cgpu;
  9520. struct thr_info *thr;
  9521. void *p;
  9522. char *dummy = "\0";
  9523. mutex_lock(&mutex);
  9524. devcount = total_devices;
  9525. addfunc(arg);
  9526. if (!total_devices_new)
  9527. goto out;
  9528. wr_lock(&devices_lock);
  9529. p = realloc(devices, sizeof(struct cgpu_info *) * (total_devices + total_devices_new + 1));
  9530. if (unlikely(!p))
  9531. {
  9532. wr_unlock(&devices_lock);
  9533. applog(LOG_ERR, "scan_serial: realloc failed trying to grow devices array");
  9534. goto out;
  9535. }
  9536. devices = p;
  9537. wr_unlock(&devices_lock);
  9538. for (i = 0; i < total_devices_new; ++i)
  9539. {
  9540. cgpu = devices_new[i];
  9541. mining_threads_new += cgpu->threads ?: 1;
  9542. }
  9543. wr_lock(&mining_thr_lock);
  9544. mining_threads_new += mining_threads;
  9545. p = realloc(mining_thr, sizeof(struct thr_info *) * mining_threads_new);
  9546. if (unlikely(!p))
  9547. {
  9548. wr_unlock(&mining_thr_lock);
  9549. applog(LOG_ERR, "scan_serial: realloc failed trying to grow mining_thr");
  9550. goto out;
  9551. }
  9552. mining_thr = p;
  9553. wr_unlock(&mining_thr_lock);
  9554. for (i = mining_threads; i < mining_threads_new; ++i) {
  9555. mining_thr[i] = calloc(1, sizeof(*thr));
  9556. if (!mining_thr[i])
  9557. {
  9558. applog(LOG_ERR, "scan_serial: Failed to calloc mining_thr[%d]", i);
  9559. for ( ; --i >= mining_threads; )
  9560. free(mining_thr[i]);
  9561. goto out;
  9562. }
  9563. }
  9564. k = mining_threads;
  9565. for (i = 0; i < total_devices_new; ++i)
  9566. {
  9567. cgpu = devices_new[i];
  9568. load_temp_config_cgpu(cgpu, &dummy, &dummy);
  9569. allocate_cgpu(cgpu, &k);
  9570. }
  9571. for (i = 0; i < total_devices_new; ++i)
  9572. {
  9573. cgpu = devices_new[i];
  9574. start_cgpu(cgpu);
  9575. register_device(cgpu);
  9576. ++total_devices;
  9577. }
  9578. #ifdef HAVE_CURSES
  9579. switch_logsize();
  9580. #endif
  9581. out:
  9582. total_devices_new = 0;
  9583. devcount = total_devices - devcount;
  9584. mutex_unlock(&mutex);
  9585. return devcount;
  9586. }
  9587. int scan_serial(const char *s)
  9588. {
  9589. return create_new_cgpus(_scan_serial, (void*)s);
  9590. }
  9591. static pthread_mutex_t rescan_mutex = PTHREAD_MUTEX_INITIALIZER;
  9592. static bool rescan_active;
  9593. static struct timeval tv_rescan;
  9594. static notifier_t rescan_notifier;
  9595. static
  9596. void *rescan_thread(__maybe_unused void *p)
  9597. {
  9598. pthread_detach(pthread_self());
  9599. RenameThread("rescan");
  9600. struct timeval tv_timeout, tv_now;
  9601. fd_set rfds;
  9602. while (true)
  9603. {
  9604. mutex_lock(&rescan_mutex);
  9605. tv_timeout = tv_rescan;
  9606. if (!timer_isset(&tv_timeout))
  9607. {
  9608. rescan_active = false;
  9609. mutex_unlock(&rescan_mutex);
  9610. break;
  9611. }
  9612. mutex_unlock(&rescan_mutex);
  9613. FD_ZERO(&rfds);
  9614. FD_SET(rescan_notifier[0], &rfds);
  9615. const int maxfd = rescan_notifier[0];
  9616. timer_set_now(&tv_now);
  9617. if (select(maxfd+1, &rfds, NULL, NULL, select_timeout(&tv_timeout, &tv_now)) > 0)
  9618. notifier_read(rescan_notifier);
  9619. mutex_lock(&rescan_mutex);
  9620. if (timer_passed(&tv_rescan, NULL))
  9621. {
  9622. timer_unset(&tv_rescan);
  9623. mutex_unlock(&rescan_mutex);
  9624. applog(LOG_DEBUG, "Rescan timer expired, triggering");
  9625. scan_serial(NULL);
  9626. }
  9627. else
  9628. mutex_unlock(&rescan_mutex);
  9629. }
  9630. return NULL;
  9631. }
  9632. static
  9633. void _schedule_rescan(const struct timeval * const tvp_when)
  9634. {
  9635. if (rescan_active)
  9636. {
  9637. if (timercmp(tvp_when, &tv_rescan, <))
  9638. applog(LOG_DEBUG, "schedule_rescan: New schedule is before current, waiting it out");
  9639. else
  9640. {
  9641. applog(LOG_DEBUG, "schedule_rescan: New schedule is after current, delaying rescan");
  9642. tv_rescan = *tvp_when;
  9643. }
  9644. return;
  9645. }
  9646. applog(LOG_DEBUG, "schedule_rescan: Scheduling rescan (no rescans currently pending)");
  9647. tv_rescan = *tvp_when;
  9648. rescan_active = true;
  9649. static pthread_t pth;
  9650. if (unlikely(pthread_create(&pth, NULL, rescan_thread, NULL)))
  9651. applog(LOG_ERR, "Failed to start rescan thread");
  9652. }
  9653. static
  9654. void schedule_rescan(const struct timeval * const tvp_when)
  9655. {
  9656. mutex_lock(&rescan_mutex);
  9657. _schedule_rescan(tvp_when);
  9658. mutex_unlock(&rescan_mutex);
  9659. }
  9660. #ifdef HAVE_BFG_HOTPLUG
  9661. static
  9662. void hotplug_trigger()
  9663. {
  9664. applog(LOG_DEBUG, "%s: Scheduling rescan immediately", __func__);
  9665. struct timeval tv_now;
  9666. timer_set_now(&tv_now);
  9667. schedule_rescan(&tv_now);
  9668. }
  9669. #endif
  9670. #if defined(HAVE_LIBUDEV) && defined(HAVE_SYS_EPOLL_H)
  9671. static
  9672. void *hotplug_thread(__maybe_unused void *p)
  9673. {
  9674. pthread_detach(pthread_self());
  9675. RenameThread("hotplug");
  9676. struct udev * const udev = udev_new();
  9677. if (unlikely(!udev))
  9678. applogfailr(NULL, LOG_ERR, "udev_new");
  9679. struct udev_monitor * const mon = udev_monitor_new_from_netlink(udev, "udev");
  9680. if (unlikely(!mon))
  9681. applogfailr(NULL, LOG_ERR, "udev_monitor_new_from_netlink");
  9682. if (unlikely(udev_monitor_enable_receiving(mon)))
  9683. applogfailr(NULL, LOG_ERR, "udev_monitor_enable_receiving");
  9684. const int epfd = epoll_create(1);
  9685. if (unlikely(epfd == -1))
  9686. applogfailr(NULL, LOG_ERR, "epoll_create");
  9687. {
  9688. const int fd = udev_monitor_get_fd(mon);
  9689. struct epoll_event ev = {
  9690. .events = EPOLLIN | EPOLLPRI,
  9691. .data.fd = fd,
  9692. };
  9693. if (epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev))
  9694. applogfailr(NULL, LOG_ERR, "epoll_ctl");
  9695. }
  9696. struct epoll_event ev;
  9697. int rv;
  9698. bool pending = false;
  9699. while (true)
  9700. {
  9701. rv = epoll_wait(epfd, &ev, 1, pending ? hotplug_delay_ms : -1);
  9702. if (rv == -1)
  9703. {
  9704. if (errno == EAGAIN || errno == EINTR)
  9705. continue;
  9706. break;
  9707. }
  9708. if (!rv)
  9709. {
  9710. hotplug_trigger();
  9711. pending = false;
  9712. continue;
  9713. }
  9714. struct udev_device * const device = udev_monitor_receive_device(mon);
  9715. if (!device)
  9716. continue;
  9717. const char * const action = udev_device_get_action(device);
  9718. applog(LOG_DEBUG, "%s: Received %s event", __func__, action);
  9719. if (strcmp(action, "add"))
  9720. continue;
  9721. pending = true;
  9722. }
  9723. applogfailr(NULL, LOG_ERR, "epoll_wait");
  9724. }
  9725. #elif defined(WIN32)
  9726. static UINT_PTR _hotplug_wintimer_id;
  9727. VOID CALLBACK hotplug_win_timer(HWND hwnd, UINT msg, UINT_PTR idEvent, DWORD dwTime)
  9728. {
  9729. KillTimer(NULL, _hotplug_wintimer_id);
  9730. _hotplug_wintimer_id = 0;
  9731. hotplug_trigger();
  9732. }
  9733. LRESULT CALLBACK hotplug_win_callback(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
  9734. {
  9735. if (msg == WM_DEVICECHANGE && wParam == DBT_DEVNODES_CHANGED)
  9736. {
  9737. applog(LOG_DEBUG, "%s: Received DBT_DEVNODES_CHANGED event", __func__);
  9738. _hotplug_wintimer_id = SetTimer(NULL, _hotplug_wintimer_id, hotplug_delay_ms, hotplug_win_timer);
  9739. }
  9740. return DefWindowProc(hwnd, msg, wParam, lParam);
  9741. }
  9742. static
  9743. void *hotplug_thread(__maybe_unused void *p)
  9744. {
  9745. pthread_detach(pthread_self());
  9746. WNDCLASS DummyWinCls = {
  9747. .lpszClassName = "BFGDummyWinCls",
  9748. .lpfnWndProc = hotplug_win_callback,
  9749. };
  9750. ATOM a = RegisterClass(&DummyWinCls);
  9751. if (unlikely(!a))
  9752. applogfailinfor(NULL, LOG_ERR, "RegisterClass", "%d", (int)GetLastError());
  9753. HWND hwnd = CreateWindow((void*)(intptr_t)a, NULL, WS_OVERLAPPED, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, NULL, NULL);
  9754. if (unlikely(!hwnd))
  9755. applogfailinfor(NULL, LOG_ERR, "CreateWindow", "%d", (int)GetLastError());
  9756. MSG msg;
  9757. while (GetMessage(&msg, NULL, 0, 0))
  9758. {
  9759. TranslateMessage(&msg);
  9760. DispatchMessage(&msg);
  9761. }
  9762. quit(0, "WM_QUIT received");
  9763. return NULL;
  9764. }
  9765. #endif
  9766. #ifdef HAVE_BFG_HOTPLUG
  9767. static
  9768. void hotplug_start()
  9769. {
  9770. pthread_t pth;
  9771. if (unlikely(pthread_create(&pth, NULL, hotplug_thread, NULL)))
  9772. applog(LOG_ERR, "Failed to start hotplug thread");
  9773. }
  9774. #endif
  9775. static void probe_pools(void)
  9776. {
  9777. int i;
  9778. for (i = 0; i < total_pools; i++) {
  9779. struct pool *pool = pools[i];
  9780. pool->testing = true;
  9781. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  9782. }
  9783. }
  9784. static void raise_fd_limits(void)
  9785. {
  9786. #ifdef HAVE_SETRLIMIT
  9787. struct rlimit fdlimit;
  9788. unsigned long old_soft_limit;
  9789. char frombuf[0x10] = "unlimited";
  9790. char hardbuf[0x10] = "unlimited";
  9791. if (getrlimit(RLIMIT_NOFILE, &fdlimit))
  9792. applogr(, LOG_DEBUG, "setrlimit: Failed to getrlimit(RLIMIT_NOFILE)");
  9793. old_soft_limit = fdlimit.rlim_cur;
  9794. if (fdlimit.rlim_max > FD_SETSIZE || fdlimit.rlim_max == RLIM_INFINITY)
  9795. fdlimit.rlim_cur = FD_SETSIZE;
  9796. else
  9797. fdlimit.rlim_cur = fdlimit.rlim_max;
  9798. if (fdlimit.rlim_max != RLIM_INFINITY)
  9799. snprintf(hardbuf, sizeof(hardbuf), "%lu", (unsigned long)fdlimit.rlim_max);
  9800. if (old_soft_limit != RLIM_INFINITY)
  9801. snprintf(frombuf, sizeof(frombuf), "%lu", old_soft_limit);
  9802. if (fdlimit.rlim_cur == old_soft_limit)
  9803. applogr(, LOG_DEBUG, "setrlimit: Soft fd limit not being changed from %lu (FD_SETSIZE=%lu; hard limit=%s)",
  9804. old_soft_limit, (unsigned long)FD_SETSIZE, hardbuf);
  9805. if (setrlimit(RLIMIT_NOFILE, &fdlimit))
  9806. applogr(, LOG_DEBUG, "setrlimit: Failed to change soft fd limit from %s to %lu (FD_SETSIZE=%lu; hard limit=%s)",
  9807. frombuf, (unsigned long)fdlimit.rlim_cur, (unsigned long)FD_SETSIZE, hardbuf);
  9808. applog(LOG_DEBUG, "setrlimit: Changed soft fd limit from %s to %lu (FD_SETSIZE=%lu; hard limit=%s)",
  9809. frombuf, (unsigned long)fdlimit.rlim_cur, (unsigned long)FD_SETSIZE, hardbuf);
  9810. #else
  9811. applog(LOG_DEBUG, "setrlimit: Not supported by platform");
  9812. #endif
  9813. }
  9814. extern void bfg_init_threadlocal();
  9815. extern void stratumsrv_start();
  9816. int main(int argc, char *argv[])
  9817. {
  9818. struct sigaction handler;
  9819. struct thr_info *thr;
  9820. struct block *block;
  9821. unsigned int k;
  9822. int i;
  9823. char *s;
  9824. #ifdef WIN32
  9825. LoadLibrary("backtrace.dll");
  9826. #endif
  9827. blkmk_sha256_impl = my_blkmaker_sha256_callback;
  9828. bfg_init_threadlocal();
  9829. #ifndef HAVE_PTHREAD_CANCEL
  9830. setup_pthread_cancel_workaround();
  9831. #endif
  9832. bfg_init_checksums();
  9833. #ifdef WIN32
  9834. {
  9835. WSADATA wsa;
  9836. i = WSAStartup(MAKEWORD(2, 2), &wsa);
  9837. if (i)
  9838. quit(1, "Failed to initialise Winsock: %s", bfg_strerror(i, BST_SOCKET));
  9839. }
  9840. #endif
  9841. /* This dangerous functions tramples random dynamically allocated
  9842. * variables so do it before anything at all */
  9843. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  9844. quit(1, "Failed to curl_global_init");
  9845. initial_args = malloc(sizeof(char *) * (argc + 1));
  9846. for (i = 0; i < argc; i++)
  9847. initial_args[i] = strdup(argv[i]);
  9848. initial_args[argc] = NULL;
  9849. mutex_init(&hash_lock);
  9850. mutex_init(&console_lock);
  9851. cglock_init(&control_lock);
  9852. mutex_init(&stats_lock);
  9853. mutex_init(&sharelog_lock);
  9854. cglock_init(&ch_lock);
  9855. mutex_init(&sshare_lock);
  9856. rwlock_init(&blk_lock);
  9857. rwlock_init(&netacc_lock);
  9858. rwlock_init(&mining_thr_lock);
  9859. rwlock_init(&devices_lock);
  9860. mutex_init(&lp_lock);
  9861. if (unlikely(pthread_cond_init(&lp_cond, NULL)))
  9862. quit(1, "Failed to pthread_cond_init lp_cond");
  9863. if (unlikely(pthread_cond_init(&gws_cond, NULL)))
  9864. quit(1, "Failed to pthread_cond_init gws_cond");
  9865. notifier_init(submit_waiting_notifier);
  9866. timer_unset(&tv_rescan);
  9867. notifier_init(rescan_notifier);
  9868. snprintf(packagename, sizeof(packagename), "%s %s", PACKAGE, VERSION);
  9869. #ifdef WANT_CPUMINE
  9870. init_max_name_len();
  9871. #endif
  9872. handler.sa_handler = &sighandler;
  9873. handler.sa_flags = 0;
  9874. sigemptyset(&handler.sa_mask);
  9875. #ifdef HAVE_PTHREAD_CANCEL
  9876. sigaction(SIGTERM, &handler, &termhandler);
  9877. #else
  9878. // Need to let pthread_cancel emulation handle SIGTERM first
  9879. termhandler = pcwm_orig_term_handler;
  9880. pcwm_orig_term_handler = handler;
  9881. #endif
  9882. sigaction(SIGINT, &handler, &inthandler);
  9883. #ifndef WIN32
  9884. signal(SIGPIPE, SIG_IGN);
  9885. #else
  9886. timeBeginPeriod(1);
  9887. #endif
  9888. opt_kernel_path = CGMINER_PREFIX;
  9889. cgminer_path = alloca(PATH_MAX);
  9890. s = strdup(argv[0]);
  9891. strcpy(cgminer_path, dirname(s));
  9892. free(s);
  9893. strcat(cgminer_path, "/");
  9894. #ifdef WANT_CPUMINE
  9895. // Hack to make cgminer silent when called recursively on WIN32
  9896. int skip_to_bench = 0;
  9897. #if defined(WIN32)
  9898. char buf[32];
  9899. if (GetEnvironmentVariable("BFGMINER_BENCH_ALGO", buf, 16))
  9900. skip_to_bench = 1;
  9901. if (GetEnvironmentVariable("CGMINER_BENCH_ALGO", buf, 16))
  9902. skip_to_bench = 1;
  9903. #endif // defined(WIN32)
  9904. #endif
  9905. devcursor = 8;
  9906. logstart = devcursor;
  9907. logcursor = logstart;
  9908. block = calloc(sizeof(struct block), 1);
  9909. if (unlikely(!block))
  9910. quit (1, "main OOM");
  9911. for (i = 0; i < 36; i++)
  9912. strcat(block->hash, "0");
  9913. HASH_ADD_STR(blocks, hash, block);
  9914. strcpy(current_block, block->hash);
  9915. mutex_init(&submitting_lock);
  9916. #ifdef HAVE_OPENCL
  9917. memset(gpus, 0, sizeof(gpus));
  9918. for (i = 0; i < MAX_GPUDEVICES; i++)
  9919. gpus[i].dynamic = true;
  9920. #endif
  9921. schedstart.tm.tm_sec = 1;
  9922. schedstop .tm.tm_sec = 1;
  9923. /* parse command line */
  9924. opt_register_table(opt_config_table,
  9925. "Options for both config file and command line");
  9926. opt_register_table(opt_cmdline_table,
  9927. "Options for command line only");
  9928. opt_parse(&argc, argv, applog_and_exit);
  9929. if (argc != 1)
  9930. quit(1, "Unexpected extra commandline arguments");
  9931. if (!config_loaded)
  9932. load_default_config();
  9933. #ifndef HAVE_PTHREAD_CANCEL
  9934. // Can't do this any earlier, or config isn't loaded
  9935. applog(LOG_DEBUG, "pthread_cancel workaround in use");
  9936. #endif
  9937. #ifdef HAVE_PWD_H
  9938. struct passwd *user_info = NULL;
  9939. if (opt_setuid != NULL) {
  9940. if ((user_info = getpwnam(opt_setuid)) == NULL) {
  9941. quit(1, "Unable to find setuid user information");
  9942. }
  9943. }
  9944. #endif
  9945. #ifdef HAVE_CHROOT
  9946. if (chroot_dir != NULL) {
  9947. #ifdef HAVE_PWD_H
  9948. if (user_info == NULL && getuid() == 0) {
  9949. applog(LOG_WARNING, "Running as root inside chroot");
  9950. }
  9951. #endif
  9952. if (chroot(chroot_dir) != 0) {
  9953. quit(1, "Unable to chroot");
  9954. }
  9955. if (chdir("/"))
  9956. quit(1, "Unable to chdir to chroot");
  9957. }
  9958. #endif
  9959. #ifdef HAVE_PWD_H
  9960. if (user_info != NULL) {
  9961. if (setgid((*user_info).pw_gid) != 0)
  9962. quit(1, "Unable to setgid");
  9963. if (setuid((*user_info).pw_uid) != 0)
  9964. quit(1, "Unable to setuid");
  9965. }
  9966. #endif
  9967. raise_fd_limits();
  9968. if (opt_benchmark) {
  9969. struct pool *pool;
  9970. if (opt_scrypt)
  9971. quit(1, "Cannot use benchmark mode with scrypt");
  9972. want_longpoll = false;
  9973. pool = add_pool();
  9974. pool->rpc_url = malloc(255);
  9975. strcpy(pool->rpc_url, "Benchmark");
  9976. pool->rpc_user = pool->rpc_url;
  9977. pool->rpc_pass = pool->rpc_url;
  9978. enable_pool(pool);
  9979. pool->idle = false;
  9980. successful_connect = true;
  9981. }
  9982. if (opt_unittest) {
  9983. test_cgpu_match();
  9984. test_intrange();
  9985. test_decimal_width();
  9986. utf8_test();
  9987. }
  9988. #ifdef HAVE_CURSES
  9989. if (opt_realquiet || opt_display_devs)
  9990. use_curses = false;
  9991. setlocale(LC_ALL, "C");
  9992. if (use_curses)
  9993. enable_curses();
  9994. #endif
  9995. #ifdef HAVE_LIBUSB
  9996. int err = libusb_init(NULL);
  9997. if (err)
  9998. applog(LOG_WARNING, "libusb_init() failed err %d", err);
  9999. else
  10000. have_libusb = true;
  10001. #endif
  10002. applog(LOG_WARNING, "Started %s", packagename);
  10003. if (cnfbuf) {
  10004. applog(LOG_NOTICE, "Loaded configuration file %s", cnfbuf);
  10005. switch (fileconf_load) {
  10006. case 0:
  10007. applog(LOG_WARNING, "Fatal JSON error in configuration file.");
  10008. applog(LOG_WARNING, "Configuration file could not be used.");
  10009. break;
  10010. case -1:
  10011. applog(LOG_WARNING, "Error in configuration file, partially loaded.");
  10012. if (use_curses)
  10013. applog(LOG_WARNING, "Start BFGMiner with -T to see what failed to load.");
  10014. break;
  10015. default:
  10016. break;
  10017. }
  10018. free(cnfbuf);
  10019. cnfbuf = NULL;
  10020. }
  10021. i = strlen(opt_kernel_path) + 2;
  10022. char __kernel_path[i];
  10023. snprintf(__kernel_path, i, "%s/", opt_kernel_path);
  10024. opt_kernel_path = __kernel_path;
  10025. if (want_per_device_stats)
  10026. opt_log_output = true;
  10027. #ifdef WANT_CPUMINE
  10028. #ifdef USE_SCRYPT
  10029. if (opt_scrypt)
  10030. set_scrypt_algo(&opt_algo);
  10031. else
  10032. #endif
  10033. if (0 <= opt_bench_algo) {
  10034. double rate = bench_algo_stage3(opt_bench_algo);
  10035. if (!skip_to_bench)
  10036. printf("%.5f (%s)\n", rate, algo_names[opt_bench_algo]);
  10037. else {
  10038. // Write result to shared memory for parent
  10039. #if defined(WIN32)
  10040. char unique_name[64];
  10041. if (GetEnvironmentVariable("BFGMINER_SHARED_MEM", unique_name, 32) || GetEnvironmentVariable("CGMINER_SHARED_MEM", unique_name, 32)) {
  10042. HANDLE map_handle = CreateFileMapping(
  10043. INVALID_HANDLE_VALUE, // use paging file
  10044. NULL, // default security attributes
  10045. PAGE_READWRITE, // read/write access
  10046. 0, // size: high 32-bits
  10047. 4096, // size: low 32-bits
  10048. unique_name // name of map object
  10049. );
  10050. if (NULL != map_handle) {
  10051. void *shared_mem = MapViewOfFile(
  10052. map_handle, // object to map view of
  10053. FILE_MAP_WRITE, // read/write access
  10054. 0, // high offset: map from
  10055. 0, // low offset: beginning
  10056. 0 // default: map entire file
  10057. );
  10058. if (NULL != shared_mem)
  10059. CopyMemory(shared_mem, &rate, sizeof(rate));
  10060. (void)UnmapViewOfFile(shared_mem);
  10061. }
  10062. (void)CloseHandle(map_handle);
  10063. }
  10064. #endif
  10065. }
  10066. exit(0);
  10067. }
  10068. #endif
  10069. bfg_devapi_init();
  10070. drv_detect_all();
  10071. total_devices = total_devices_new;
  10072. devices = devices_new;
  10073. total_devices_new = 0;
  10074. devices_new = NULL;
  10075. if (opt_display_devs) {
  10076. int devcount = 0;
  10077. applog(LOG_ERR, "Devices detected:");
  10078. for (i = 0; i < total_devices; ++i) {
  10079. struct cgpu_info *cgpu = devices[i];
  10080. char buf[0x100];
  10081. if (cgpu->device != cgpu)
  10082. continue;
  10083. if (cgpu->name)
  10084. snprintf(buf, sizeof(buf), " %s", cgpu->name);
  10085. else
  10086. if (cgpu->dev_manufacturer)
  10087. snprintf(buf, sizeof(buf), " %s by %s", (cgpu->dev_product ?: "Device"), cgpu->dev_manufacturer);
  10088. else
  10089. if (cgpu->dev_product)
  10090. snprintf(buf, sizeof(buf), " %s", cgpu->dev_product);
  10091. else
  10092. strcpy(buf, " Device");
  10093. tailsprintf(buf, sizeof(buf), " (driver=%s; procs=%d", cgpu->drv->dname, cgpu->procs);
  10094. if (cgpu->dev_serial)
  10095. tailsprintf(buf, sizeof(buf), "; serial=%s", cgpu->dev_serial);
  10096. if (cgpu->device_path)
  10097. tailsprintf(buf, sizeof(buf), "; path=%s", cgpu->device_path);
  10098. tailsprintf(buf, sizeof(buf), ")");
  10099. _applog(LOG_NOTICE, buf);
  10100. ++devcount;
  10101. }
  10102. quit(0, "%d devices listed", devcount);
  10103. }
  10104. mining_threads = 0;
  10105. for (i = 0; i < total_devices; ++i)
  10106. register_device(devices[i]);
  10107. if (!total_devices) {
  10108. applog(LOG_WARNING, "No devices detected!");
  10109. if (use_curses)
  10110. applog(LOG_WARNING, "Waiting for devices; press 'M+' to add, or 'Q' to quit");
  10111. else
  10112. applog(LOG_WARNING, "Waiting for devices");
  10113. }
  10114. load_temp_config();
  10115. #ifdef HAVE_CURSES
  10116. switch_logsize();
  10117. #endif
  10118. if (!total_pools) {
  10119. applog(LOG_WARNING, "Need to specify at least one pool server.");
  10120. #ifdef HAVE_CURSES
  10121. if (!use_curses || !input_pool(false))
  10122. #endif
  10123. quit(1, "Pool setup failed");
  10124. }
  10125. for (i = 0; i < total_pools; i++) {
  10126. struct pool *pool = pools[i];
  10127. size_t siz;
  10128. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  10129. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  10130. if (!pool->rpc_url)
  10131. quit(1, "No URI supplied for pool %u", i);
  10132. if (!pool->rpc_userpass) {
  10133. if (!pool->rpc_user || !pool->rpc_pass)
  10134. quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  10135. siz = strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2;
  10136. pool->rpc_userpass = malloc(siz);
  10137. if (!pool->rpc_userpass)
  10138. quit(1, "Failed to malloc userpass");
  10139. snprintf(pool->rpc_userpass, siz, "%s:%s", pool->rpc_user, pool->rpc_pass);
  10140. }
  10141. }
  10142. /* Set the currentpool to pool with priority 0 */
  10143. validate_pool_priorities();
  10144. for (i = 0; i < total_pools; i++) {
  10145. struct pool *pool = pools[i];
  10146. if (!pool->prio)
  10147. currentpool = pool;
  10148. }
  10149. #ifdef HAVE_SYSLOG_H
  10150. if (use_syslog)
  10151. openlog(PACKAGE, LOG_PID, LOG_USER);
  10152. #endif
  10153. #if defined(unix) || defined(__APPLE__)
  10154. if (opt_stderr_cmd)
  10155. fork_monitor();
  10156. #endif // defined(unix)
  10157. mining_thr = calloc(mining_threads, sizeof(thr));
  10158. if (!mining_thr)
  10159. quit(1, "Failed to calloc mining_thr");
  10160. for (i = 0; i < mining_threads; i++) {
  10161. mining_thr[i] = calloc(1, sizeof(*thr));
  10162. if (!mining_thr[i])
  10163. quit(1, "Failed to calloc mining_thr[%d]", i);
  10164. }
  10165. total_control_threads = 6;
  10166. control_thr = calloc(total_control_threads, sizeof(*thr));
  10167. if (!control_thr)
  10168. quit(1, "Failed to calloc control_thr");
  10169. gwsched_thr_id = 0;
  10170. /* Create a unique get work queue */
  10171. getq = tq_new();
  10172. if (!getq)
  10173. quit(1, "Failed to create getq");
  10174. /* We use the getq mutex as the staged lock */
  10175. stgd_lock = &getq->mutex;
  10176. if (opt_benchmark)
  10177. goto begin_bench;
  10178. for (i = 0; i < total_pools; i++) {
  10179. struct pool *pool = pools[i];
  10180. enable_pool(pool);
  10181. pool->idle = true;
  10182. }
  10183. applog(LOG_NOTICE, "Probing for an alive pool");
  10184. do {
  10185. bool still_testing;
  10186. int i;
  10187. /* Look for at least one active pool before starting */
  10188. probe_pools();
  10189. do {
  10190. sleep(1);
  10191. if (pools_active)
  10192. break;
  10193. still_testing = false;
  10194. for (int i = 0; i < total_pools; ++i)
  10195. if (pools[i]->testing)
  10196. still_testing = true;
  10197. } while (still_testing);
  10198. if (!pools_active) {
  10199. applog(LOG_ERR, "No servers were found that could be used to get work from.");
  10200. applog(LOG_ERR, "Please check the details from the list below of the servers you have input");
  10201. applog(LOG_ERR, "Most likely you have input the wrong URL, forgotten to add a port, or have not set up workers");
  10202. for (i = 0; i < total_pools; i++) {
  10203. struct pool *pool;
  10204. pool = pools[i];
  10205. applog(LOG_WARNING, "Pool: %d URL: %s User: %s Password: %s",
  10206. i, pool->rpc_url, pool->rpc_user, pool->rpc_pass);
  10207. }
  10208. #ifdef HAVE_CURSES
  10209. if (use_curses) {
  10210. halfdelay(150);
  10211. applog(LOG_ERR, "Press any key to exit, or BFGMiner will try again in 15s.");
  10212. if (getch() != ERR)
  10213. quit(0, "No servers could be used! Exiting.");
  10214. cbreak();
  10215. } else
  10216. #endif
  10217. quit(0, "No servers could be used! Exiting.");
  10218. }
  10219. } while (!pools_active);
  10220. #ifdef USE_SCRYPT
  10221. if (detect_algo == 1 && !opt_scrypt) {
  10222. applog(LOG_NOTICE, "Detected scrypt algorithm");
  10223. opt_scrypt = true;
  10224. }
  10225. #endif
  10226. detect_algo = 0;
  10227. begin_bench:
  10228. total_mhashes_done = 0;
  10229. for (i = 0; i < total_devices; i++) {
  10230. struct cgpu_info *cgpu = devices[i];
  10231. cgpu->rolling = cgpu->total_mhashes = 0;
  10232. }
  10233. cgtime(&total_tv_start);
  10234. cgtime(&total_tv_end);
  10235. miner_started = total_tv_start;
  10236. time_t miner_start_ts = time(NULL);
  10237. if (schedstart.tm.tm_sec)
  10238. localtime_r(&miner_start_ts, &schedstart.tm);
  10239. if (schedstop.tm.tm_sec)
  10240. localtime_r(&miner_start_ts, &schedstop .tm);
  10241. get_datestamp(datestamp, sizeof(datestamp), miner_start_ts);
  10242. // Initialise processors and threads
  10243. k = 0;
  10244. for (i = 0; i < total_devices; ++i) {
  10245. struct cgpu_info *cgpu = devices[i];
  10246. allocate_cgpu(cgpu, &k);
  10247. }
  10248. // Start threads
  10249. for (i = 0; i < total_devices; ++i) {
  10250. struct cgpu_info *cgpu = devices[i];
  10251. start_cgpu(cgpu);
  10252. }
  10253. #ifdef HAVE_OPENCL
  10254. for (i = 0; i < nDevs; i++)
  10255. pause_dynamic_threads(i);
  10256. #endif
  10257. #ifdef WANT_CPUMINE
  10258. applog(LOG_INFO, "%d cpu miner threads started, "
  10259. "using SHA256 '%s' algorithm.",
  10260. opt_n_threads,
  10261. algo_names[opt_algo]);
  10262. #endif
  10263. cgtime(&total_tv_start);
  10264. cgtime(&total_tv_end);
  10265. {
  10266. pthread_t submit_thread;
  10267. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, NULL)))
  10268. quit(1, "submit_work thread create failed");
  10269. }
  10270. watchpool_thr_id = 1;
  10271. thr = &control_thr[watchpool_thr_id];
  10272. /* start watchpool thread */
  10273. if (thr_info_create(thr, NULL, watchpool_thread, NULL))
  10274. quit(1, "watchpool thread create failed");
  10275. pthread_detach(thr->pth);
  10276. watchdog_thr_id = 2;
  10277. thr = &control_thr[watchdog_thr_id];
  10278. /* start watchdog thread */
  10279. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  10280. quit(1, "watchdog thread create failed");
  10281. pthread_detach(thr->pth);
  10282. #ifdef HAVE_OPENCL
  10283. /* Create reinit gpu thread */
  10284. gpur_thr_id = 3;
  10285. thr = &control_thr[gpur_thr_id];
  10286. thr->q = tq_new();
  10287. if (!thr->q)
  10288. quit(1, "tq_new failed for gpur_thr_id");
  10289. if (thr_info_create(thr, NULL, reinit_gpu, thr))
  10290. quit(1, "reinit_gpu thread create failed");
  10291. #endif
  10292. /* Create API socket thread */
  10293. api_thr_id = 4;
  10294. thr = &control_thr[api_thr_id];
  10295. if (thr_info_create(thr, NULL, api_thread, thr))
  10296. quit(1, "API thread create failed");
  10297. #ifdef USE_LIBMICROHTTPD
  10298. if (httpsrv_port != -1)
  10299. httpsrv_start(httpsrv_port);
  10300. #endif
  10301. #ifdef USE_LIBEVENT
  10302. if (stratumsrv_port != -1)
  10303. stratumsrv_start();
  10304. #endif
  10305. #ifdef HAVE_BFG_HOTPLUG
  10306. if (opt_hotplug && !opt_scrypt)
  10307. hotplug_start();
  10308. #endif
  10309. #ifdef HAVE_CURSES
  10310. /* Create curses input thread for keyboard input. Create this last so
  10311. * that we know all threads are created since this can call kill_work
  10312. * to try and shut down ll previous threads. */
  10313. input_thr_id = 5;
  10314. thr = &control_thr[input_thr_id];
  10315. if (thr_info_create(thr, NULL, input_thread, thr))
  10316. quit(1, "input thread create failed");
  10317. pthread_detach(thr->pth);
  10318. #endif
  10319. /* Just to be sure */
  10320. if (total_control_threads != 6)
  10321. quit(1, "incorrect total_control_threads (%d) should be 7", total_control_threads);
  10322. /* Once everything is set up, main() becomes the getwork scheduler */
  10323. while (42) {
  10324. int ts, max_staged = opt_queue;
  10325. struct pool *pool, *cp;
  10326. bool lagging = false;
  10327. struct curl_ent *ce;
  10328. struct work *work;
  10329. cp = current_pool();
  10330. /* If the primary pool is a getwork pool and cannot roll work,
  10331. * try to stage one extra work per mining thread */
  10332. if (!pool_localgen(cp) && !staged_rollable)
  10333. max_staged += mining_threads;
  10334. mutex_lock(stgd_lock);
  10335. ts = __total_staged();
  10336. if (!pool_localgen(cp) && !ts && !opt_fail_only)
  10337. lagging = true;
  10338. /* Wait until hash_pop tells us we need to create more work */
  10339. if (ts > max_staged) {
  10340. staged_full = true;
  10341. pthread_cond_wait(&gws_cond, stgd_lock);
  10342. ts = __total_staged();
  10343. }
  10344. mutex_unlock(stgd_lock);
  10345. if (ts > max_staged)
  10346. continue;
  10347. work = make_work();
  10348. if (lagging && !pool_tset(cp, &cp->lagging)) {
  10349. applog(LOG_WARNING, "Pool %d not providing work fast enough", cp->pool_no);
  10350. cp->getfail_occasions++;
  10351. total_go++;
  10352. }
  10353. pool = select_pool(lagging);
  10354. retry:
  10355. if (pool->has_stratum) {
  10356. while (!pool->stratum_active || !pool->stratum_notify) {
  10357. struct pool *altpool = select_pool(true);
  10358. if (altpool == pool && pool->has_stratum)
  10359. cgsleep_ms(5000);
  10360. pool = altpool;
  10361. goto retry;
  10362. }
  10363. gen_stratum_work(pool, work);
  10364. applog(LOG_DEBUG, "Generated stratum work");
  10365. stage_work(work);
  10366. continue;
  10367. }
  10368. if (pool->last_work_copy) {
  10369. mutex_lock(&pool->last_work_lock);
  10370. struct work *last_work = pool->last_work_copy;
  10371. if (!last_work)
  10372. {}
  10373. else
  10374. if (can_roll(last_work) && should_roll(last_work)) {
  10375. struct timeval tv_now;
  10376. cgtime(&tv_now);
  10377. free_work(work);
  10378. work = make_clone(pool->last_work_copy);
  10379. mutex_unlock(&pool->last_work_lock);
  10380. roll_work(work);
  10381. applog(LOG_DEBUG, "Generated work from latest GBT job in get_work_thread with %d seconds left", (int)blkmk_time_left(work->tmpl, tv_now.tv_sec));
  10382. stage_work(work);
  10383. continue;
  10384. } else if (last_work->tmpl && pool->proto == PLP_GETBLOCKTEMPLATE && blkmk_work_left(last_work->tmpl) > (unsigned long)mining_threads) {
  10385. // Don't free last_work_copy, since it is used to detect upstream provides plenty of work per template
  10386. } else {
  10387. free_work(last_work);
  10388. pool->last_work_copy = NULL;
  10389. }
  10390. mutex_unlock(&pool->last_work_lock);
  10391. }
  10392. if (clone_available()) {
  10393. applog(LOG_DEBUG, "Cloned getwork work");
  10394. free_work(work);
  10395. continue;
  10396. }
  10397. if (opt_benchmark) {
  10398. get_benchmark_work(work);
  10399. applog(LOG_DEBUG, "Generated benchmark work");
  10400. stage_work(work);
  10401. continue;
  10402. }
  10403. work->pool = pool;
  10404. ce = pop_curl_entry3(pool, 2);
  10405. /* obtain new work from bitcoin via JSON-RPC */
  10406. if (!get_upstream_work(work, ce->curl)) {
  10407. struct pool *next_pool;
  10408. /* Make sure the pool just hasn't stopped serving
  10409. * requests but is up as we'll keep hammering it */
  10410. push_curl_entry(ce, pool);
  10411. ++pool->seq_getfails;
  10412. pool_died(pool);
  10413. next_pool = select_pool(!opt_fail_only);
  10414. if (pool == next_pool) {
  10415. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, retrying in 5s", pool->pool_no);
  10416. cgsleep_ms(5000);
  10417. } else {
  10418. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, failover activated", pool->pool_no);
  10419. pool = next_pool;
  10420. }
  10421. goto retry;
  10422. }
  10423. if (ts >= max_staged)
  10424. pool_tclear(pool, &pool->lagging);
  10425. if (pool_tclear(pool, &pool->idle))
  10426. pool_resus(pool);
  10427. applog(LOG_DEBUG, "Generated getwork work");
  10428. stage_work(work);
  10429. push_curl_entry(ce, pool);
  10430. }
  10431. return 0;
  10432. }