miner.c 316 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374
  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 <float.h>
  22. #include <limits.h>
  23. #include <locale.h>
  24. #include <stdio.h>
  25. #include <stdlib.h>
  26. #include <string.h>
  27. #include <stdbool.h>
  28. #include <stdint.h>
  29. #include <unistd.h>
  30. #include <sys/time.h>
  31. #include <time.h>
  32. #include <math.h>
  33. #include <stdarg.h>
  34. #include <assert.h>
  35. #include <signal.h>
  36. #include <wctype.h>
  37. #include <sys/stat.h>
  38. #include <sys/types.h>
  39. #include <dirent.h>
  40. #ifdef HAVE_PWD_H
  41. #include <pwd.h>
  42. #endif
  43. #ifndef WIN32
  44. #include <sys/resource.h>
  45. #include <sys/socket.h>
  46. #if defined(HAVE_LIBUDEV) && defined(HAVE_SYS_EPOLL_H)
  47. #include <libudev.h>
  48. #include <sys/epoll.h>
  49. #define HAVE_BFG_HOTPLUG
  50. #endif
  51. #else
  52. #include <winsock2.h>
  53. #include <windows.h>
  54. #include <dbt.h>
  55. #define HAVE_BFG_HOTPLUG
  56. #endif
  57. #include <ccan/opt/opt.h>
  58. #include <jansson.h>
  59. #include <curl/curl.h>
  60. #include <libgen.h>
  61. #include <sha2.h>
  62. #include <utlist.h>
  63. #include <blkmaker.h>
  64. #include <blkmaker_jansson.h>
  65. #include <blktemplate.h>
  66. #include "compat.h"
  67. #include "deviceapi.h"
  68. #include "logging.h"
  69. #include "miner.h"
  70. #include "adl.h"
  71. #include "driver-cpu.h"
  72. #include "driver-opencl.h"
  73. #include "scrypt.h"
  74. #ifdef USE_AVALON
  75. #include "driver-avalon.h"
  76. #endif
  77. #ifdef HAVE_BFG_LOWLEVEL
  78. #include "lowlevel.h"
  79. #endif
  80. #if defined(unix) || defined(__APPLE__)
  81. #include <errno.h>
  82. #include <fcntl.h>
  83. #include <sys/wait.h>
  84. #endif
  85. #ifdef USE_SCRYPT
  86. #include "scrypt.h"
  87. #endif
  88. #if defined(USE_AVALON) || defined(USE_BITFORCE) || defined(USE_ICARUS) || defined(USE_MODMINER) || defined(USE_NANOFURY) || defined(USE_X6500) || defined(USE_ZTEX)
  89. # define USE_FPGA
  90. #endif
  91. enum bfg_quit_summary {
  92. BQS_DEFAULT,
  93. BQS_NONE,
  94. BQS_DEVS,
  95. BQS_PROCS,
  96. BQS_DETAILED,
  97. };
  98. struct strategies strategies[] = {
  99. { "Failover" },
  100. { "Round Robin" },
  101. { "Rotate" },
  102. { "Load Balance" },
  103. { "Balance" },
  104. };
  105. static char packagename[256];
  106. bool opt_protocol;
  107. bool opt_dev_protocol;
  108. static bool opt_benchmark;
  109. static bool want_longpoll = true;
  110. static bool want_gbt = true;
  111. static bool want_getwork = true;
  112. #if BLKMAKER_VERSION > 1
  113. struct _cbscript_t {
  114. char *data;
  115. size_t sz;
  116. };
  117. static struct _cbscript_t opt_coinbase_script;
  118. static uint32_t template_nonce;
  119. #endif
  120. #if BLKMAKER_VERSION > 0
  121. char *opt_coinbase_sig;
  122. #endif
  123. static enum bfg_quit_summary opt_quit_summary = BQS_DEFAULT;
  124. static bool include_serial_in_statline;
  125. char *request_target_str;
  126. float request_pdiff = 1.0;
  127. double request_bdiff;
  128. static bool want_stratum = true;
  129. bool have_longpoll;
  130. int opt_skip_checks;
  131. bool want_per_device_stats;
  132. bool use_syslog;
  133. bool opt_quiet_work_updates = true;
  134. bool opt_quiet;
  135. bool opt_realquiet;
  136. int loginput_size;
  137. bool opt_compact;
  138. bool opt_show_procs;
  139. const int opt_cutofftemp = 95;
  140. int opt_hysteresis = 3;
  141. static int opt_retries = -1;
  142. int opt_fail_pause = 5;
  143. int opt_log_interval = 20;
  144. int opt_queue = 1;
  145. int opt_scantime = 60;
  146. int opt_expiry = 120;
  147. int opt_expiry_lp = 3600;
  148. unsigned long long global_hashrate;
  149. static bool opt_unittest = false;
  150. unsigned long global_quota_gcd = 1;
  151. time_t last_getwork;
  152. #ifdef HAVE_OPENCL
  153. int opt_dynamic_interval = 7;
  154. int nDevs;
  155. int opt_g_threads = -1;
  156. #endif
  157. #ifdef USE_SCRYPT
  158. static char detect_algo = 1;
  159. bool opt_scrypt;
  160. #else
  161. static char detect_algo;
  162. #endif
  163. bool opt_restart = true;
  164. #ifdef USE_LIBMICROHTTPD
  165. #include "httpsrv.h"
  166. int httpsrv_port = -1;
  167. #endif
  168. #ifdef USE_LIBEVENT
  169. int stratumsrv_port = -1;
  170. #endif
  171. const
  172. int rescan_delay_ms = 1000;
  173. #ifdef HAVE_BFG_HOTPLUG
  174. bool opt_hotplug = 1;
  175. const
  176. int hotplug_delay_ms = 100;
  177. #else
  178. const bool opt_hotplug;
  179. #endif
  180. struct string_elist *scan_devices;
  181. static struct string_elist *opt_set_device_list;
  182. bool opt_force_dev_init;
  183. static struct string_elist *opt_devices_enabled_list;
  184. static bool opt_display_devs;
  185. int total_devices;
  186. struct cgpu_info **devices;
  187. int total_devices_new;
  188. struct cgpu_info **devices_new;
  189. bool have_opencl;
  190. int opt_n_threads = -1;
  191. int mining_threads;
  192. int num_processors;
  193. #ifdef HAVE_CURSES
  194. bool use_curses = true;
  195. #else
  196. bool use_curses;
  197. #endif
  198. #ifdef HAVE_LIBUSB
  199. bool have_libusb;
  200. #endif
  201. static bool opt_submit_stale = true;
  202. static float opt_shares;
  203. static int opt_submit_threads = 0x40;
  204. bool opt_fail_only;
  205. int opt_fail_switch_delay = 300;
  206. bool opt_autofan;
  207. bool opt_autoengine;
  208. bool opt_noadl;
  209. char *opt_api_allow = NULL;
  210. char *opt_api_groups;
  211. char *opt_api_description = PACKAGE_STRING;
  212. int opt_api_port = 4028;
  213. bool opt_api_listen;
  214. bool opt_api_mcast;
  215. char *opt_api_mcast_addr = API_MCAST_ADDR;
  216. char *opt_api_mcast_code = API_MCAST_CODE;
  217. char *opt_api_mcast_des = "";
  218. int opt_api_mcast_port = 4028;
  219. bool opt_api_network;
  220. bool opt_delaynet;
  221. bool opt_disable_pool;
  222. bool opt_disable_client_reconnect = false;
  223. static bool no_work;
  224. bool opt_worktime;
  225. bool opt_weighed_stats;
  226. char *opt_kernel_path;
  227. char *cgminer_path;
  228. #if defined(USE_BITFORCE)
  229. bool opt_bfl_noncerange;
  230. #endif
  231. #define QUIET (opt_quiet || opt_realquiet)
  232. struct thr_info *control_thr;
  233. struct thr_info **mining_thr;
  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[ALLOC_H2B_SHORTV] = "0";
  324. double current_diff = 0xFFFFFFFFFFFFFFFFULL;
  325. static char block_diff[ALLOC_H2B_SHORTV];
  326. static char net_hashrate[ALLOC_H2B_SHORT];
  327. double 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. pool->sock = INVSOCK;
  934. pool->lp_socket = CURL_SOCKET_BAD;
  935. if (opt_benchmark)
  936. {
  937. // Don't add to pools array, but immediately remove it
  938. remove_pool(pool);
  939. return pool;
  940. }
  941. pools = realloc(pools, sizeof(struct pool *) * (total_pools + 2));
  942. pools[total_pools++] = pool;
  943. adjust_quota_gcd();
  944. return pool;
  945. }
  946. /* Pool variant of test and set */
  947. static bool pool_tset(struct pool *pool, bool *var)
  948. {
  949. bool ret;
  950. mutex_lock(&pool->pool_lock);
  951. ret = *var;
  952. *var = true;
  953. mutex_unlock(&pool->pool_lock);
  954. return ret;
  955. }
  956. bool pool_tclear(struct pool *pool, bool *var)
  957. {
  958. bool ret;
  959. mutex_lock(&pool->pool_lock);
  960. ret = *var;
  961. *var = false;
  962. mutex_unlock(&pool->pool_lock);
  963. return ret;
  964. }
  965. struct pool *current_pool(void)
  966. {
  967. struct pool *pool;
  968. cg_rlock(&control_lock);
  969. pool = currentpool;
  970. cg_runlock(&control_lock);
  971. return pool;
  972. }
  973. // Copied from ccan/opt/helpers.c
  974. static char *arg_bad(const char *fmt, const char *arg)
  975. {
  976. char *str = malloc(strlen(fmt) + strlen(arg));
  977. sprintf(str, fmt, arg);
  978. return str;
  979. }
  980. static
  981. char *opt_set_floatval(const char *arg, float *f)
  982. {
  983. char *endp;
  984. errno = 0;
  985. *f = strtof(arg, &endp);
  986. if (*endp || !arg[0])
  987. return arg_bad("'%s' is not a number", arg);
  988. if (errno)
  989. return arg_bad("'%s' is out of range", arg);
  990. return NULL;
  991. }
  992. static
  993. void opt_show_floatval(char buf[OPT_SHOW_LEN], const float *f)
  994. {
  995. snprintf(buf, OPT_SHOW_LEN, "%.1f", *f);
  996. }
  997. static
  998. char *set_bool_ignore_arg(const char * const arg, bool * const b)
  999. {
  1000. return opt_set_bool(b);
  1001. }
  1002. char *set_int_range(const char *arg, int *i, int min, int max)
  1003. {
  1004. char *err = opt_set_intval(arg, i);
  1005. if (err)
  1006. return err;
  1007. if (*i < min || *i > max)
  1008. return "Value out of range";
  1009. return NULL;
  1010. }
  1011. static char *set_int_0_to_9999(const char *arg, int *i)
  1012. {
  1013. return set_int_range(arg, i, 0, 9999);
  1014. }
  1015. static char *set_int_1_to_65535(const char *arg, int *i)
  1016. {
  1017. return set_int_range(arg, i, 1, 65535);
  1018. }
  1019. static char *set_int_0_to_10(const char *arg, int *i)
  1020. {
  1021. return set_int_range(arg, i, 0, 10);
  1022. }
  1023. static char *set_int_1_to_10(const char *arg, int *i)
  1024. {
  1025. return set_int_range(arg, i, 1, 10);
  1026. }
  1027. char *set_strdup(const char *arg, char **p)
  1028. {
  1029. *p = strdup((char *)arg);
  1030. return NULL;
  1031. }
  1032. #if BLKMAKER_VERSION > 1
  1033. static char *set_b58addr(const char *arg, struct _cbscript_t *p)
  1034. {
  1035. size_t scriptsz = blkmk_address_to_script(NULL, 0, arg);
  1036. if (!scriptsz)
  1037. return "Invalid address";
  1038. char *script = malloc(scriptsz);
  1039. if (blkmk_address_to_script(script, scriptsz, arg) != scriptsz) {
  1040. free(script);
  1041. return "Failed to convert address to script";
  1042. }
  1043. p->data = script;
  1044. p->sz = scriptsz;
  1045. return NULL;
  1046. }
  1047. #endif
  1048. static
  1049. char *set_quit_summary(const char * const arg)
  1050. {
  1051. if (!(strcasecmp(arg, "none") && strcasecmp(arg, "no")))
  1052. opt_quit_summary = BQS_NONE;
  1053. else
  1054. if (!(strcasecmp(arg, "devs") && strcasecmp(arg, "devices")))
  1055. opt_quit_summary = BQS_DEVS;
  1056. else
  1057. if (!(strcasecmp(arg, "procs") && strcasecmp(arg, "processors") && strcasecmp(arg, "chips") && strcasecmp(arg, "cores")))
  1058. opt_quit_summary = BQS_PROCS;
  1059. else
  1060. if (!(strcasecmp(arg, "detailed") && strcasecmp(arg, "detail") && strcasecmp(arg, "all")))
  1061. opt_quit_summary = BQS_DETAILED;
  1062. else
  1063. return "Quit summary must be one of none/devs/procs/detailed";
  1064. return NULL;
  1065. }
  1066. static void pdiff_target_leadzero(void *, double);
  1067. char *set_request_diff(const char *arg, float *p)
  1068. {
  1069. unsigned char target[32];
  1070. char *e = opt_set_floatval(arg, p);
  1071. if (e)
  1072. return e;
  1073. request_bdiff = (double)*p * 0.9999847412109375;
  1074. pdiff_target_leadzero(target, *p);
  1075. request_target_str = malloc(65);
  1076. bin2hex(request_target_str, target, 32);
  1077. return NULL;
  1078. }
  1079. #ifdef NEED_BFG_LOWL_VCOM
  1080. extern struct lowlevel_device_info *_vcom_devinfo_findorcreate(struct lowlevel_device_info **, const char *);
  1081. #ifdef WIN32
  1082. void _vcom_devinfo_scan_querydosdevice(struct lowlevel_device_info ** const devinfo_list)
  1083. {
  1084. char dev[PATH_MAX];
  1085. char *devp = dev;
  1086. size_t bufLen = 0x100;
  1087. tryagain: ;
  1088. char buf[bufLen];
  1089. if (!QueryDosDevice(NULL, buf, bufLen)) {
  1090. if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
  1091. bufLen *= 2;
  1092. applog(LOG_DEBUG, "QueryDosDevice returned insufficent buffer error; enlarging to %lx", (unsigned long)bufLen);
  1093. goto tryagain;
  1094. }
  1095. applogr(, LOG_WARNING, "Error occurred trying to enumerate COM ports with QueryDosDevice");
  1096. }
  1097. size_t tLen;
  1098. memcpy(devp, "\\\\.\\", 4);
  1099. devp = &devp[4];
  1100. for (char *t = buf; *t; t += tLen) {
  1101. tLen = strlen(t) + 1;
  1102. if (strncmp("COM", t, 3))
  1103. continue;
  1104. memcpy(devp, t, tLen);
  1105. // NOTE: We depend on _vcom_devinfo_findorcreate to further check that there's a number (and only a number) on the end
  1106. _vcom_devinfo_findorcreate(devinfo_list, dev);
  1107. }
  1108. }
  1109. #else
  1110. void _vcom_devinfo_scan_lsdev(struct lowlevel_device_info ** const devinfo_list)
  1111. {
  1112. char dev[PATH_MAX];
  1113. char *devp = dev;
  1114. DIR *D;
  1115. struct dirent *de;
  1116. const char devdir[] = "/dev";
  1117. const size_t devdirlen = sizeof(devdir) - 1;
  1118. char *devpath = devp;
  1119. char *devfile = devpath + devdirlen + 1;
  1120. D = opendir(devdir);
  1121. if (!D)
  1122. applogr(, LOG_DEBUG, "No /dev directory to look for VCOM devices in");
  1123. memcpy(devpath, devdir, devdirlen);
  1124. devpath[devdirlen] = '/';
  1125. while ( (de = readdir(D)) ) {
  1126. if (!strncmp(de->d_name, "cu.", 3)
  1127. //don't probe Bluetooth devices - causes bus errors and segfaults
  1128. && strncmp(de->d_name, "cu.Bluetooth", 12))
  1129. goto trydev;
  1130. if (strncmp(de->d_name, "tty", 3))
  1131. continue;
  1132. if (strncmp(&de->d_name[3], "USB", 3) && strncmp(&de->d_name[3], "ACM", 3))
  1133. continue;
  1134. trydev:
  1135. strcpy(devfile, de->d_name);
  1136. _vcom_devinfo_findorcreate(devinfo_list, dev);
  1137. }
  1138. closedir(D);
  1139. }
  1140. #endif
  1141. #endif
  1142. static char *add_serial(const char *arg)
  1143. {
  1144. string_elist_add(arg, &scan_devices);
  1145. return NULL;
  1146. }
  1147. static
  1148. char *opt_string_elist_add(const char *arg, struct string_elist **elist)
  1149. {
  1150. string_elist_add(arg, elist);
  1151. return NULL;
  1152. }
  1153. bool get_intrange(const char *arg, int *val1, int *val2)
  1154. {
  1155. // NOTE: This could be done with sscanf, but its %n is broken in strange ways on Windows
  1156. char *p, *p2;
  1157. *val1 = strtol(arg, &p, 0);
  1158. if (arg == p)
  1159. // Zero-length ending number, invalid
  1160. return false;
  1161. while (true)
  1162. {
  1163. if (!p[0])
  1164. {
  1165. *val2 = *val1;
  1166. return true;
  1167. }
  1168. if (p[0] == '-')
  1169. break;
  1170. if (!isspace(p[0]))
  1171. // Garbage, invalid
  1172. return false;
  1173. ++p;
  1174. }
  1175. p2 = &p[1];
  1176. *val2 = strtol(p2, &p, 0);
  1177. if (p2 == p)
  1178. // Zero-length ending number, invalid
  1179. return false;
  1180. while (true)
  1181. {
  1182. if (!p[0])
  1183. return true;
  1184. if (!isspace(p[0]))
  1185. // Garbage, invalid
  1186. return false;
  1187. ++p;
  1188. }
  1189. }
  1190. static
  1191. void _test_intrange(const char *s, const int v[2])
  1192. {
  1193. int a[2];
  1194. if (!get_intrange(s, &a[0], &a[1]))
  1195. applog(LOG_ERR, "Test \"%s\" failed: returned false", s);
  1196. for (int i = 0; i < 2; ++i)
  1197. if (unlikely(a[i] != v[i]))
  1198. applog(LOG_ERR, "Test \"%s\" failed: value %d should be %d but got %d", s, i, v[i], a[i]);
  1199. }
  1200. #define _test_intrange(s, ...) _test_intrange(s, (int[]){ __VA_ARGS__ })
  1201. static
  1202. void _test_intrange_fail(const char *s)
  1203. {
  1204. int a[2];
  1205. if (get_intrange(s, &a[0], &a[1]))
  1206. applog(LOG_ERR, "Test !\"%s\" failed: returned true with %d and %d", s, a[0], a[1]);
  1207. }
  1208. static
  1209. void test_intrange()
  1210. {
  1211. _test_intrange("-1--2", -1, -2);
  1212. _test_intrange("-1-2", -1, 2);
  1213. _test_intrange("1--2", 1, -2);
  1214. _test_intrange("1-2", 1, 2);
  1215. _test_intrange("111-222", 111, 222);
  1216. _test_intrange(" 11 - 22 ", 11, 22);
  1217. _test_intrange("+11-+22", 11, 22);
  1218. _test_intrange("-1", -1, -1);
  1219. _test_intrange_fail("all");
  1220. _test_intrange_fail("1-");
  1221. _test_intrange_fail("");
  1222. _test_intrange_fail("1-54x");
  1223. }
  1224. static char *set_devices(char *arg)
  1225. {
  1226. if (*arg) {
  1227. if (*arg == '?') {
  1228. opt_display_devs = true;
  1229. return NULL;
  1230. }
  1231. } else
  1232. return "Invalid device parameters";
  1233. string_elist_add(arg, &opt_devices_enabled_list);
  1234. return NULL;
  1235. }
  1236. static char *set_balance(enum pool_strategy *strategy)
  1237. {
  1238. *strategy = POOL_BALANCE;
  1239. return NULL;
  1240. }
  1241. static char *set_loadbalance(enum pool_strategy *strategy)
  1242. {
  1243. *strategy = POOL_LOADBALANCE;
  1244. return NULL;
  1245. }
  1246. static char *set_rotate(const char *arg, int *i)
  1247. {
  1248. pool_strategy = POOL_ROTATE;
  1249. return set_int_range(arg, i, 0, 9999);
  1250. }
  1251. static char *set_rr(enum pool_strategy *strategy)
  1252. {
  1253. *strategy = POOL_ROUNDROBIN;
  1254. return NULL;
  1255. }
  1256. /* Detect that url is for a stratum protocol either via the presence of
  1257. * stratum+tcp or by detecting a stratum server response */
  1258. bool detect_stratum(struct pool *pool, char *url)
  1259. {
  1260. if (!extract_sockaddr(url, &pool->sockaddr_url, &pool->stratum_port))
  1261. return false;
  1262. if (!strncasecmp(url, "stratum+tcp://", 14)) {
  1263. pool->rpc_url = strdup(url);
  1264. pool->has_stratum = true;
  1265. pool->stratum_url = pool->sockaddr_url;
  1266. return true;
  1267. }
  1268. return false;
  1269. }
  1270. static struct pool *add_url(void)
  1271. {
  1272. total_urls++;
  1273. if (total_urls > total_pools)
  1274. add_pool();
  1275. return pools[total_urls - 1];
  1276. }
  1277. static void setup_url(struct pool *pool, char *arg)
  1278. {
  1279. if (detect_stratum(pool, arg))
  1280. return;
  1281. opt_set_charp(arg, &pool->rpc_url);
  1282. if (strncmp(arg, "http://", 7) &&
  1283. strncmp(arg, "https://", 8)) {
  1284. const size_t L = strlen(arg);
  1285. char *httpinput;
  1286. httpinput = malloc(8 + L);
  1287. if (!httpinput)
  1288. quit(1, "Failed to malloc httpinput");
  1289. sprintf(httpinput, "http://%s", arg);
  1290. pool->rpc_url = httpinput;
  1291. }
  1292. }
  1293. static char *set_url(char *arg)
  1294. {
  1295. struct pool *pool = add_url();
  1296. setup_url(pool, arg);
  1297. return NULL;
  1298. }
  1299. static char *set_quota(char *arg)
  1300. {
  1301. char *semicolon = strchr(arg, ';'), *url;
  1302. int len, qlen, quota;
  1303. struct pool *pool;
  1304. if (!semicolon)
  1305. return "No semicolon separated quota;URL pair found";
  1306. len = strlen(arg);
  1307. *semicolon = '\0';
  1308. qlen = strlen(arg);
  1309. if (!qlen)
  1310. return "No parameter for quota found";
  1311. len -= qlen + 1;
  1312. if (len < 1)
  1313. return "No parameter for URL found";
  1314. quota = atoi(arg);
  1315. if (quota < 0)
  1316. return "Invalid negative parameter for quota set";
  1317. url = arg + qlen + 1;
  1318. pool = add_url();
  1319. setup_url(pool, url);
  1320. pool->quota = quota;
  1321. applog(LOG_INFO, "Setting pool %d to quota %d", pool->pool_no, pool->quota);
  1322. adjust_quota_gcd();
  1323. return NULL;
  1324. }
  1325. static char *set_user(const char *arg)
  1326. {
  1327. struct pool *pool;
  1328. total_users++;
  1329. if (total_users > total_pools)
  1330. add_pool();
  1331. pool = pools[total_users - 1];
  1332. opt_set_charp(arg, &pool->rpc_user);
  1333. return NULL;
  1334. }
  1335. static char *set_pass(const char *arg)
  1336. {
  1337. struct pool *pool;
  1338. total_passes++;
  1339. if (total_passes > total_pools)
  1340. add_pool();
  1341. pool = pools[total_passes - 1];
  1342. opt_set_charp(arg, &pool->rpc_pass);
  1343. return NULL;
  1344. }
  1345. static char *set_userpass(const char *arg)
  1346. {
  1347. struct pool *pool;
  1348. char *updup;
  1349. if (total_users != total_passes)
  1350. return "User + pass options must be balanced before userpass";
  1351. ++total_users;
  1352. ++total_passes;
  1353. if (total_users > total_pools)
  1354. add_pool();
  1355. pool = pools[total_users - 1];
  1356. updup = strdup(arg);
  1357. opt_set_charp(arg, &pool->rpc_userpass);
  1358. pool->rpc_user = strtok(updup, ":");
  1359. if (!pool->rpc_user)
  1360. return "Failed to find : delimited user info";
  1361. pool->rpc_pass = strtok(NULL, ":");
  1362. if (!pool->rpc_pass)
  1363. pool->rpc_pass = "";
  1364. return NULL;
  1365. }
  1366. static char *set_pool_priority(const char *arg)
  1367. {
  1368. struct pool *pool;
  1369. if (!total_pools)
  1370. return "Usage of --pool-priority before pools are defined does not make sense";
  1371. pool = pools[total_pools - 1];
  1372. opt_set_intval(arg, &pool->prio);
  1373. return NULL;
  1374. }
  1375. static char *set_pool_proxy(const char *arg)
  1376. {
  1377. struct pool *pool;
  1378. if (!total_pools)
  1379. return "Usage of --pool-proxy before pools are defined does not make sense";
  1380. if (!our_curl_supports_proxy_uris())
  1381. return "Your installed cURL library does not support proxy URIs. At least version 7.21.7 is required.";
  1382. pool = pools[total_pools - 1];
  1383. opt_set_charp(arg, &pool->rpc_proxy);
  1384. return NULL;
  1385. }
  1386. static char *set_pool_force_rollntime(const char *arg)
  1387. {
  1388. struct pool *pool;
  1389. if (!total_pools)
  1390. return "Usage of --force-rollntime before pools are defined does not make sense";
  1391. pool = pools[total_pools - 1];
  1392. opt_set_intval(arg, &pool->force_rollntime);
  1393. return NULL;
  1394. }
  1395. static char *enable_debug(bool *flag)
  1396. {
  1397. *flag = true;
  1398. opt_debug_console = true;
  1399. /* Turn on verbose output, too. */
  1400. opt_log_output = true;
  1401. return NULL;
  1402. }
  1403. static char *set_schedtime(const char *arg, struct schedtime *st)
  1404. {
  1405. if (sscanf(arg, "%d:%d", &st->tm.tm_hour, &st->tm.tm_min) != 2)
  1406. {
  1407. if (strcasecmp(arg, "now"))
  1408. return "Invalid time set, should be HH:MM";
  1409. } else
  1410. schedstop.tm.tm_sec = 0;
  1411. if (st->tm.tm_hour > 23 || st->tm.tm_min > 59 || st->tm.tm_hour < 0 || st->tm.tm_min < 0)
  1412. return "Invalid time set.";
  1413. st->enable = true;
  1414. return NULL;
  1415. }
  1416. static
  1417. char *set_log_file(char *arg)
  1418. {
  1419. char *r = "";
  1420. long int i = strtol(arg, &r, 10);
  1421. int fd, stderr_fd = fileno(stderr);
  1422. if ((!*r) && i >= 0 && i <= INT_MAX)
  1423. fd = i;
  1424. else
  1425. if (!strcmp(arg, "-"))
  1426. {
  1427. fd = fileno(stdout);
  1428. if (unlikely(fd == -1))
  1429. return "Standard output missing for log-file";
  1430. }
  1431. else
  1432. {
  1433. fd = open(arg, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR);
  1434. if (unlikely(fd == -1))
  1435. return "Failed to open log-file";
  1436. }
  1437. close(stderr_fd);
  1438. if (unlikely(-1 == dup2(fd, stderr_fd)))
  1439. return "Failed to dup2 for log-file";
  1440. close(fd);
  1441. return NULL;
  1442. }
  1443. static
  1444. char *_bfgopt_set_file(const char *arg, FILE **F, const char *mode, const char *purpose)
  1445. {
  1446. char *r = "";
  1447. long int i = strtol(arg, &r, 10);
  1448. static char *err = NULL;
  1449. const size_t errbufsz = 0x100;
  1450. free(err);
  1451. err = NULL;
  1452. if ((!*r) && i >= 0 && i <= INT_MAX) {
  1453. *F = fdopen((int)i, mode);
  1454. if (!*F)
  1455. {
  1456. err = malloc(errbufsz);
  1457. snprintf(err, errbufsz, "Failed to open fd %d for %s",
  1458. (int)i, purpose);
  1459. return err;
  1460. }
  1461. } else if (!strcmp(arg, "-")) {
  1462. *F = (mode[0] == 'a') ? stdout : stdin;
  1463. if (!*F)
  1464. {
  1465. err = malloc(errbufsz);
  1466. snprintf(err, errbufsz, "Standard %sput missing for %s",
  1467. (mode[0] == 'a') ? "out" : "in", purpose);
  1468. return err;
  1469. }
  1470. } else {
  1471. *F = fopen(arg, mode);
  1472. if (!*F)
  1473. {
  1474. err = malloc(errbufsz);
  1475. snprintf(err, errbufsz, "Failed to open %s for %s",
  1476. arg, purpose);
  1477. return err;
  1478. }
  1479. }
  1480. return NULL;
  1481. }
  1482. static char *set_noncelog(char *arg)
  1483. {
  1484. return _bfgopt_set_file(arg, &noncelog_file, "a", "nonce log");
  1485. }
  1486. static char *set_sharelog(char *arg)
  1487. {
  1488. return _bfgopt_set_file(arg, &sharelog_file, "a", "share log");
  1489. }
  1490. static
  1491. void _add_set_device_option(const char * const func, const char * const buf)
  1492. {
  1493. applog(LOG_DEBUG, "%s: Using --set-device %s", func, buf);
  1494. string_elist_add(buf, &opt_set_device_list);
  1495. }
  1496. #define add_set_device_option(...) do{ \
  1497. char _tmp1718[0x100]; \
  1498. snprintf(_tmp1718, sizeof(_tmp1718), __VA_ARGS__); \
  1499. _add_set_device_option(__func__, _tmp1718); \
  1500. }while(0)
  1501. char *set_temp_cutoff(char *arg)
  1502. {
  1503. if (strchr(arg, ','))
  1504. return "temp-cutoff no longer supports comma-delimited syntax, use --set-device for better control";
  1505. applog(LOG_WARNING, "temp-cutoff is deprecated! Use --set-device for better control");
  1506. add_set_device_option("all:temp-cutoff=%s", arg);
  1507. return NULL;
  1508. }
  1509. char *set_temp_target(char *arg)
  1510. {
  1511. if (strchr(arg, ','))
  1512. return "temp-target no longer supports comma-delimited syntax, use --set-device for better control";
  1513. applog(LOG_WARNING, "temp-target is deprecated! Use --set-device for better control");
  1514. add_set_device_option("all:temp-target=%s", arg);
  1515. return NULL;
  1516. }
  1517. #ifdef HAVE_OPENCL
  1518. static
  1519. char *set_no_opencl_binaries(__maybe_unused void * const dummy)
  1520. {
  1521. applog(LOG_WARNING, "The --no-opencl-binaries option is deprecated! Use --set-device OCL:binary=no");
  1522. add_set_device_option("OCL:binary=no");
  1523. return NULL;
  1524. }
  1525. #endif
  1526. static
  1527. char *disable_pool_redirect(__maybe_unused void * const dummy)
  1528. {
  1529. opt_disable_client_reconnect = true;
  1530. want_stratum = false;
  1531. return NULL;
  1532. }
  1533. static char *set_api_allow(const char *arg)
  1534. {
  1535. opt_set_charp(arg, &opt_api_allow);
  1536. return NULL;
  1537. }
  1538. static char *set_api_groups(const char *arg)
  1539. {
  1540. opt_set_charp(arg, &opt_api_groups);
  1541. return NULL;
  1542. }
  1543. static char *set_api_description(const char *arg)
  1544. {
  1545. opt_set_charp(arg, &opt_api_description);
  1546. return NULL;
  1547. }
  1548. static char *set_api_mcast_des(const char *arg)
  1549. {
  1550. opt_set_charp(arg, &opt_api_mcast_des);
  1551. return NULL;
  1552. }
  1553. #ifdef USE_ICARUS
  1554. extern const struct bfg_set_device_definition icarus_set_device_funcs[];
  1555. static char *set_icarus_options(const char *arg)
  1556. {
  1557. if (strchr(arg, ','))
  1558. return "icarus-options no longer supports comma-delimited syntax, see README.FPGA for better control";
  1559. applog(LOG_WARNING, "icarus-options is deprecated! See README.FPGA for better control");
  1560. char *opts = strdup(arg), *argdup;
  1561. argdup = opts;
  1562. const struct bfg_set_device_definition *sdf = icarus_set_device_funcs;
  1563. const char *drivers[] = {"antminer", "cairnsmore", "erupter", "icarus"};
  1564. char *saveptr, *opt;
  1565. for (int i = 0; i < 4; ++i, ++sdf)
  1566. {
  1567. opt = strtok_r(opts, ":", &saveptr);
  1568. opts = NULL;
  1569. if (!opt)
  1570. break;
  1571. if (!opt[0])
  1572. continue;
  1573. for (int j = 0; j < 4; ++j)
  1574. add_set_device_option("%s:%s=%s", drivers[j], sdf->optname, opt);
  1575. }
  1576. free(argdup);
  1577. return NULL;
  1578. }
  1579. static char *set_icarus_timing(const char *arg)
  1580. {
  1581. if (strchr(arg, ','))
  1582. return "icarus-timing no longer supports comma-delimited syntax, see README.FPGA for better control";
  1583. applog(LOG_WARNING, "icarus-timing is deprecated! See README.FPGA for better control");
  1584. const char *drivers[] = {"antminer", "cairnsmore", "erupter", "icarus"};
  1585. for (int j = 0; j < 4; ++j)
  1586. add_set_device_option("%s:timing=%s", drivers[j], arg);
  1587. return NULL;
  1588. }
  1589. #endif
  1590. #ifdef USE_AVALON
  1591. extern const struct bfg_set_device_definition avalon_set_device_funcs[];
  1592. static char *set_avalon_options(const char *arg)
  1593. {
  1594. if (strchr(arg, ','))
  1595. return "avalon-options no longer supports comma-delimited syntax, see README.FPGA for better control";
  1596. applog(LOG_WARNING, "avalon-options is deprecated! See README.FPGA for better control");
  1597. char *opts = strdup(arg), *argdup;
  1598. argdup = opts;
  1599. const struct bfg_set_device_definition *sdf = avalon_set_device_funcs;
  1600. char *saveptr, *opt;
  1601. for (int i = 0; i < 5; ++i, ++sdf)
  1602. {
  1603. opt = strtok_r(opts, ":", &saveptr);
  1604. opts = NULL;
  1605. if (!opt)
  1606. break;
  1607. if (!opt[0])
  1608. continue;
  1609. add_set_device_option("avalon:%s=%s", sdf->optname, opt);
  1610. }
  1611. free(argdup);
  1612. return NULL;
  1613. }
  1614. #endif
  1615. #ifdef USE_KLONDIKE
  1616. static char *set_klondike_options(const char *arg)
  1617. {
  1618. int hashclock;
  1619. double temptarget;
  1620. switch (sscanf(arg, "%d:%lf", &hashclock, &temptarget))
  1621. {
  1622. default:
  1623. return "Unrecognised --klondike-options";
  1624. case 2:
  1625. add_set_device_option("klondike:temp-target=%lf", temptarget);
  1626. // fallthru
  1627. case 1:
  1628. add_set_device_option("klondike:clock=%d", hashclock);
  1629. }
  1630. applog(LOG_WARNING, "klondike-options is deprecated! Use --set-device for better control");
  1631. return NULL;
  1632. }
  1633. #endif
  1634. __maybe_unused
  1635. static char *set_null(const char __maybe_unused *arg)
  1636. {
  1637. return NULL;
  1638. }
  1639. /* These options are available from config file or commandline */
  1640. static struct opt_table opt_config_table[] = {
  1641. #ifdef WANT_CPUMINE
  1642. OPT_WITH_ARG("--algo",
  1643. set_algo, show_algo, &opt_algo,
  1644. "Specify sha256 implementation for CPU mining:\n"
  1645. "\tfastauto*\tQuick benchmark at startup to pick a working algorithm\n"
  1646. "\tauto\t\tBenchmark at startup and pick fastest algorithm"
  1647. "\n\tc\t\tLinux kernel sha256, implemented in C"
  1648. #ifdef WANT_SSE2_4WAY
  1649. "\n\t4way\t\ttcatm's 4-way SSE2 implementation"
  1650. #endif
  1651. #ifdef WANT_VIA_PADLOCK
  1652. "\n\tvia\t\tVIA padlock implementation"
  1653. #endif
  1654. "\n\tcryptopp\tCrypto++ C/C++ implementation"
  1655. #ifdef WANT_CRYPTOPP_ASM32
  1656. "\n\tcryptopp_asm32\tCrypto++ 32-bit assembler implementation"
  1657. #endif
  1658. #ifdef WANT_X8632_SSE2
  1659. "\n\tsse2_32\t\tSSE2 32 bit implementation for i386 machines"
  1660. #endif
  1661. #ifdef WANT_X8664_SSE2
  1662. "\n\tsse2_64\t\tSSE2 64 bit implementation for x86_64 machines"
  1663. #endif
  1664. #ifdef WANT_X8664_SSE4
  1665. "\n\tsse4_64\t\tSSE4.1 64 bit implementation for x86_64 machines"
  1666. #endif
  1667. #ifdef WANT_ALTIVEC_4WAY
  1668. "\n\taltivec_4way\tAltivec implementation for PowerPC G4 and G5 machines"
  1669. #endif
  1670. ),
  1671. OPT_WITH_ARG("-a",
  1672. set_algo, show_algo, &opt_algo,
  1673. opt_hidden),
  1674. #endif
  1675. OPT_WITH_ARG("--api-allow",
  1676. set_api_allow, NULL, NULL,
  1677. "Allow API access only to the given list of [G:]IP[/Prefix] addresses[/subnets]"),
  1678. OPT_WITH_ARG("--api-description",
  1679. set_api_description, NULL, NULL,
  1680. "Description placed in the API status header, default: BFGMiner version"),
  1681. OPT_WITH_ARG("--api-groups",
  1682. set_api_groups, NULL, NULL,
  1683. "API one letter groups G:cmd:cmd[,P:cmd:*...] defining the cmds a groups can use"),
  1684. OPT_WITHOUT_ARG("--api-listen",
  1685. opt_set_bool, &opt_api_listen,
  1686. "Enable API, default: disabled"),
  1687. OPT_WITHOUT_ARG("--api-mcast",
  1688. opt_set_bool, &opt_api_mcast,
  1689. "Enable API Multicast listener, default: disabled"),
  1690. OPT_WITH_ARG("--api-mcast-addr",
  1691. opt_set_charp, opt_show_charp, &opt_api_mcast_addr,
  1692. "API Multicast listen address"),
  1693. OPT_WITH_ARG("--api-mcast-code",
  1694. opt_set_charp, opt_show_charp, &opt_api_mcast_code,
  1695. "Code expected in the API Multicast message, don't use '-'"),
  1696. OPT_WITH_ARG("--api-mcast-des",
  1697. set_api_mcast_des, NULL, NULL,
  1698. "Description appended to the API Multicast reply, default: ''"),
  1699. OPT_WITH_ARG("--api-mcast-port",
  1700. set_int_1_to_65535, opt_show_intval, &opt_api_mcast_port,
  1701. "API Multicast listen port"),
  1702. OPT_WITHOUT_ARG("--api-network",
  1703. opt_set_bool, &opt_api_network,
  1704. "Allow API (if enabled) to listen on/for any address, default: only 127.0.0.1"),
  1705. OPT_WITH_ARG("--api-port",
  1706. set_int_1_to_65535, opt_show_intval, &opt_api_port,
  1707. "Port number of miner API"),
  1708. #ifdef HAVE_ADL
  1709. OPT_WITHOUT_ARG("--auto-fan",
  1710. opt_set_bool, &opt_autofan,
  1711. opt_hidden),
  1712. OPT_WITHOUT_ARG("--auto-gpu",
  1713. opt_set_bool, &opt_autoengine,
  1714. opt_hidden),
  1715. #endif
  1716. OPT_WITHOUT_ARG("--balance",
  1717. set_balance, &pool_strategy,
  1718. "Change multipool strategy from failover to even share balance"),
  1719. OPT_WITHOUT_ARG("--benchmark",
  1720. opt_set_bool, &opt_benchmark,
  1721. "Run BFGMiner in benchmark mode - produces no shares"),
  1722. #if defined(USE_BITFORCE)
  1723. OPT_WITHOUT_ARG("--bfl-range",
  1724. opt_set_bool, &opt_bfl_noncerange,
  1725. "Use nonce range on bitforce devices if supported"),
  1726. #endif
  1727. #ifdef HAVE_CHROOT
  1728. OPT_WITH_ARG("--chroot-dir",
  1729. opt_set_charp, NULL, &chroot_dir,
  1730. "Chroot to a directory right after startup"),
  1731. #endif
  1732. OPT_WITH_ARG("--cmd-idle",
  1733. opt_set_charp, NULL, &cmd_idle,
  1734. "Execute a command when a device is allowed to be idle (rest or wait)"),
  1735. OPT_WITH_ARG("--cmd-sick",
  1736. opt_set_charp, NULL, &cmd_sick,
  1737. "Execute a command when a device is declared sick"),
  1738. OPT_WITH_ARG("--cmd-dead",
  1739. opt_set_charp, NULL, &cmd_dead,
  1740. "Execute a command when a device is declared dead"),
  1741. #if BLKMAKER_VERSION > 1
  1742. OPT_WITH_ARG("--coinbase-addr",
  1743. set_b58addr, NULL, &opt_coinbase_script,
  1744. "Set coinbase payout address for solo mining"),
  1745. OPT_WITH_ARG("--coinbase-address|--coinbase-payout|--cbaddress|--cbaddr|--cb-address|--cb-addr|--payout",
  1746. set_b58addr, NULL, &opt_coinbase_script,
  1747. opt_hidden),
  1748. #endif
  1749. #if BLKMAKER_VERSION > 0
  1750. OPT_WITH_ARG("--coinbase-sig",
  1751. set_strdup, NULL, &opt_coinbase_sig,
  1752. "Set coinbase signature when possible"),
  1753. OPT_WITH_ARG("--coinbase|--cbsig|--cb-sig|--cb|--prayer",
  1754. set_strdup, NULL, &opt_coinbase_sig,
  1755. opt_hidden),
  1756. #endif
  1757. #ifdef HAVE_CURSES
  1758. OPT_WITHOUT_ARG("--compact",
  1759. opt_set_bool, &opt_compact,
  1760. "Use compact display without per device statistics"),
  1761. #endif
  1762. #ifdef WANT_CPUMINE
  1763. OPT_WITH_ARG("--cpu-threads",
  1764. force_nthreads_int, opt_show_intval, &opt_n_threads,
  1765. "Number of miner CPU threads"),
  1766. OPT_WITH_ARG("-t",
  1767. force_nthreads_int, opt_show_intval, &opt_n_threads,
  1768. opt_hidden),
  1769. #endif
  1770. OPT_WITHOUT_ARG("--debug|-D",
  1771. enable_debug, &opt_debug,
  1772. "Enable debug output"),
  1773. OPT_WITHOUT_ARG("--debuglog",
  1774. opt_set_bool, &opt_debug,
  1775. "Enable debug logging"),
  1776. OPT_WITHOUT_ARG("--device-protocol-dump",
  1777. opt_set_bool, &opt_dev_protocol,
  1778. "Verbose dump of device protocol-level activities"),
  1779. OPT_WITH_ARG("--device|-d",
  1780. set_devices, NULL, NULL,
  1781. "Enable only devices matching pattern (default: all)"),
  1782. OPT_WITHOUT_ARG("--disable-rejecting",
  1783. opt_set_bool, &opt_disable_pool,
  1784. "Automatically disable pools that continually reject shares"),
  1785. #ifdef USE_LIBMICROHTTPD
  1786. OPT_WITH_ARG("--http-port",
  1787. opt_set_intval, opt_show_intval, &httpsrv_port,
  1788. "Port number to listen on for HTTP getwork miners (-1 means disabled)"),
  1789. #endif
  1790. OPT_WITH_ARG("--expiry",
  1791. set_int_0_to_9999, opt_show_intval, &opt_expiry,
  1792. "Upper bound on how many seconds after getting work we consider a share from it stale (w/o longpoll active)"),
  1793. OPT_WITH_ARG("-E",
  1794. set_int_0_to_9999, opt_show_intval, &opt_expiry,
  1795. opt_hidden),
  1796. OPT_WITH_ARG("--expiry-lp",
  1797. set_int_0_to_9999, opt_show_intval, &opt_expiry_lp,
  1798. "Upper bound on how many seconds after getting work we consider a share from it stale (with longpoll active)"),
  1799. OPT_WITHOUT_ARG("--failover-only",
  1800. opt_set_bool, &opt_fail_only,
  1801. "Don't leak work to backup pools when primary pool is lagging"),
  1802. OPT_WITH_ARG("--failover-switch-delay",
  1803. set_int_1_to_65535, opt_show_intval, &opt_fail_switch_delay,
  1804. "Delay in seconds before switching back to a failed pool"),
  1805. #ifdef USE_FPGA
  1806. OPT_WITHOUT_ARG("--force-dev-init",
  1807. opt_set_bool, &opt_force_dev_init,
  1808. "Always initialize devices when possible (such as bitstream uploads to some FPGAs)"),
  1809. #endif
  1810. #ifdef HAVE_OPENCL
  1811. OPT_WITH_ARG("--gpu-dyninterval",
  1812. set_int_1_to_65535, opt_show_intval, &opt_dynamic_interval,
  1813. opt_hidden),
  1814. OPT_WITH_ARG("--gpu-platform",
  1815. set_int_0_to_9999, opt_show_intval, &opt_platform_id,
  1816. "Select OpenCL platform ID to use for GPU mining"),
  1817. OPT_WITH_ARG("--gpu-threads|-g",
  1818. set_gpu_threads, opt_show_intval, &opt_g_threads,
  1819. opt_hidden),
  1820. #ifdef HAVE_ADL
  1821. OPT_WITH_ARG("--gpu-engine",
  1822. set_gpu_engine, NULL, NULL,
  1823. opt_hidden),
  1824. OPT_WITH_ARG("--gpu-fan",
  1825. set_gpu_fan, NULL, NULL,
  1826. opt_hidden),
  1827. OPT_WITH_ARG("--gpu-map",
  1828. set_gpu_map, NULL, NULL,
  1829. "Map OpenCL to ADL device order manually, paired CSV (e.g. 1:0,2:1 maps OpenCL 1 to ADL 0, 2 to 1)"),
  1830. OPT_WITH_ARG("--gpu-memclock",
  1831. set_gpu_memclock, NULL, NULL,
  1832. opt_hidden),
  1833. OPT_WITH_ARG("--gpu-memdiff",
  1834. set_gpu_memdiff, NULL, NULL,
  1835. opt_hidden),
  1836. OPT_WITH_ARG("--gpu-powertune",
  1837. set_gpu_powertune, NULL, NULL,
  1838. opt_hidden),
  1839. OPT_WITHOUT_ARG("--gpu-reorder",
  1840. opt_set_bool, &opt_reorder,
  1841. "Attempt to reorder GPU devices according to PCI Bus ID"),
  1842. OPT_WITH_ARG("--gpu-vddc",
  1843. set_gpu_vddc, NULL, NULL,
  1844. opt_hidden),
  1845. #endif
  1846. #ifdef USE_SCRYPT
  1847. OPT_WITH_ARG("--lookup-gap",
  1848. set_lookup_gap, NULL, NULL,
  1849. opt_hidden),
  1850. #endif
  1851. OPT_WITH_ARG("--intensity|-I",
  1852. set_intensity, NULL, NULL,
  1853. opt_hidden),
  1854. #endif
  1855. #if defined(HAVE_OPENCL) || defined(USE_MODMINER) || defined(USE_X6500) || defined(USE_ZTEX)
  1856. OPT_WITH_ARG("--kernel-path",
  1857. opt_set_charp, opt_show_charp, &opt_kernel_path,
  1858. "Specify a path to where bitstream and kernel files are"),
  1859. OPT_WITH_ARG("-K",
  1860. opt_set_charp, opt_show_charp, &opt_kernel_path,
  1861. opt_hidden),
  1862. #endif
  1863. #ifdef HAVE_OPENCL
  1864. OPT_WITH_ARG("--kernel|-k",
  1865. set_kernel, NULL, NULL,
  1866. opt_hidden),
  1867. #endif
  1868. #ifdef USE_ICARUS
  1869. OPT_WITH_ARG("--icarus-options",
  1870. set_icarus_options, NULL, NULL,
  1871. opt_hidden),
  1872. OPT_WITH_ARG("--icarus-timing",
  1873. set_icarus_timing, NULL, NULL,
  1874. opt_hidden),
  1875. #endif
  1876. #ifdef USE_AVALON
  1877. OPT_WITH_ARG("--avalon-options",
  1878. set_avalon_options, NULL, NULL,
  1879. opt_hidden),
  1880. #endif
  1881. #ifdef USE_KLONDIKE
  1882. OPT_WITH_ARG("--klondike-options",
  1883. set_klondike_options, NULL, NULL,
  1884. "Set klondike options clock:temptarget"),
  1885. #endif
  1886. OPT_WITHOUT_ARG("--load-balance",
  1887. set_loadbalance, &pool_strategy,
  1888. "Change multipool strategy from failover to quota based balance"),
  1889. OPT_WITH_ARG("--log|-l",
  1890. set_int_0_to_9999, opt_show_intval, &opt_log_interval,
  1891. "Interval in seconds between log output"),
  1892. OPT_WITH_ARG("--log-file|-L",
  1893. set_log_file, NULL, NULL,
  1894. "Append log file for output messages"),
  1895. OPT_WITH_ARG("--logfile",
  1896. set_log_file, NULL, NULL,
  1897. opt_hidden),
  1898. OPT_WITHOUT_ARG("--log-microseconds",
  1899. opt_set_bool, &opt_log_microseconds,
  1900. "Include microseconds in log output"),
  1901. #if defined(unix) || defined(__APPLE__)
  1902. OPT_WITH_ARG("--monitor|-m",
  1903. opt_set_charp, NULL, &opt_stderr_cmd,
  1904. "Use custom pipe cmd for output messages"),
  1905. #endif // defined(unix)
  1906. OPT_WITHOUT_ARG("--net-delay",
  1907. opt_set_bool, &opt_delaynet,
  1908. "Impose small delays in networking to avoid overloading slow routers"),
  1909. OPT_WITHOUT_ARG("--no-adl",
  1910. opt_set_bool, &opt_noadl,
  1911. #ifdef HAVE_ADL
  1912. "Disable the ATI display library used for monitoring and setting GPU parameters"
  1913. #else
  1914. opt_hidden
  1915. #endif
  1916. ),
  1917. OPT_WITHOUT_ARG("--no-gbt",
  1918. opt_set_invbool, &want_gbt,
  1919. "Disable getblocktemplate support"),
  1920. OPT_WITHOUT_ARG("--no-getwork",
  1921. opt_set_invbool, &want_getwork,
  1922. "Disable getwork support"),
  1923. OPT_WITHOUT_ARG("--no-hotplug",
  1924. #ifdef HAVE_BFG_HOTPLUG
  1925. opt_set_invbool, &opt_hotplug,
  1926. "Disable hotplug detection"
  1927. #else
  1928. set_null, &opt_hotplug,
  1929. opt_hidden
  1930. #endif
  1931. ),
  1932. OPT_WITHOUT_ARG("--no-longpoll",
  1933. opt_set_invbool, &want_longpoll,
  1934. "Disable X-Long-Polling support"),
  1935. OPT_WITHOUT_ARG("--no-pool-disable",
  1936. opt_set_invbool, &opt_disable_pool,
  1937. opt_hidden),
  1938. OPT_WITHOUT_ARG("--no-client-reconnect",
  1939. opt_set_invbool, &opt_disable_client_reconnect,
  1940. opt_hidden),
  1941. OPT_WITHOUT_ARG("--no-pool-redirect",
  1942. disable_pool_redirect, NULL,
  1943. "Ignore pool requests to redirect to another server"),
  1944. OPT_WITHOUT_ARG("--no-restart",
  1945. opt_set_invbool, &opt_restart,
  1946. "Do not attempt to restart devices that hang"
  1947. ),
  1948. OPT_WITHOUT_ARG("--no-show-processors",
  1949. opt_set_invbool, &opt_show_procs,
  1950. opt_hidden),
  1951. OPT_WITHOUT_ARG("--no-show-procs",
  1952. opt_set_invbool, &opt_show_procs,
  1953. opt_hidden),
  1954. OPT_WITHOUT_ARG("--no-stratum",
  1955. opt_set_invbool, &want_stratum,
  1956. "Disable Stratum detection"),
  1957. OPT_WITHOUT_ARG("--no-submit-stale",
  1958. opt_set_invbool, &opt_submit_stale,
  1959. "Don't submit shares if they are detected as stale"),
  1960. #ifdef HAVE_OPENCL
  1961. OPT_WITHOUT_ARG("--no-opencl-binaries",
  1962. set_no_opencl_binaries, NULL,
  1963. opt_hidden),
  1964. #endif
  1965. OPT_WITHOUT_ARG("--no-unicode",
  1966. #ifdef USE_UNICODE
  1967. opt_set_invbool, &use_unicode,
  1968. "Don't use Unicode characters in TUI"
  1969. #else
  1970. set_null, &use_unicode,
  1971. opt_hidden
  1972. #endif
  1973. ),
  1974. OPT_WITH_ARG("--noncelog",
  1975. set_noncelog, NULL, NULL,
  1976. "Create log of all nonces found"),
  1977. OPT_WITH_ARG("--pass|-p",
  1978. set_pass, NULL, NULL,
  1979. "Password for bitcoin JSON-RPC server"),
  1980. OPT_WITHOUT_ARG("--per-device-stats",
  1981. opt_set_bool, &want_per_device_stats,
  1982. "Force verbose mode and output per-device statistics"),
  1983. OPT_WITH_ARG("--userpass|-O", // duplicate to ensure config loads it before pool-priority
  1984. set_userpass, NULL, NULL,
  1985. opt_hidden),
  1986. OPT_WITH_ARG("--pool-priority",
  1987. set_pool_priority, NULL, NULL,
  1988. "Priority for just the previous-defined pool"),
  1989. OPT_WITH_ARG("--pool-proxy|-x",
  1990. set_pool_proxy, NULL, NULL,
  1991. "Proxy URI to use for connecting to just the previous-defined pool"),
  1992. OPT_WITH_ARG("--force-rollntime", // NOTE: must be after --pass for config file ordering
  1993. set_pool_force_rollntime, NULL, NULL,
  1994. opt_hidden),
  1995. OPT_WITHOUT_ARG("--protocol-dump|-P",
  1996. opt_set_bool, &opt_protocol,
  1997. "Verbose dump of protocol-level activities"),
  1998. OPT_WITH_ARG("--queue|-Q",
  1999. set_int_0_to_9999, opt_show_intval, &opt_queue,
  2000. "Minimum number of work items to have queued (0+)"),
  2001. OPT_WITHOUT_ARG("--quiet|-q",
  2002. opt_set_bool, &opt_quiet,
  2003. "Disable logging output, display status and errors"),
  2004. OPT_WITHOUT_ARG("--quiet-work-updates|--quiet-work-update",
  2005. opt_set_bool, &opt_quiet_work_updates,
  2006. opt_hidden),
  2007. OPT_WITH_ARG("--quit-summary",
  2008. set_quit_summary, NULL, NULL,
  2009. "Summary printed when you quit: none/devs/procs/detailed"),
  2010. OPT_WITH_ARG("--quota|-U",
  2011. set_quota, NULL, NULL,
  2012. "quota;URL combination for server with load-balance strategy quotas"),
  2013. OPT_WITHOUT_ARG("--real-quiet",
  2014. opt_set_bool, &opt_realquiet,
  2015. "Disable all output"),
  2016. OPT_WITH_ARG("--request-diff",
  2017. set_request_diff, opt_show_floatval, &request_pdiff,
  2018. "Request a specific difficulty from pools"),
  2019. OPT_WITH_ARG("--retries",
  2020. opt_set_intval, opt_show_intval, &opt_retries,
  2021. "Number of times to retry failed submissions before giving up (-1 means never)"),
  2022. OPT_WITH_ARG("--retry-pause",
  2023. set_null, NULL, NULL,
  2024. opt_hidden),
  2025. OPT_WITH_ARG("--rotate",
  2026. set_rotate, opt_show_intval, &opt_rotate_period,
  2027. "Change multipool strategy from failover to regularly rotate at N minutes"),
  2028. OPT_WITHOUT_ARG("--round-robin",
  2029. set_rr, &pool_strategy,
  2030. "Change multipool strategy from failover to round robin on failure"),
  2031. OPT_WITH_ARG("--scan|-S",
  2032. add_serial, NULL, NULL,
  2033. "Configure how to scan for mining devices"),
  2034. OPT_WITH_ARG("--scan-device|--scan-serial|--devscan",
  2035. add_serial, NULL, NULL,
  2036. opt_hidden),
  2037. OPT_WITH_ARG("--scan-time",
  2038. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  2039. "Upper bound on time spent scanning current work, in seconds"),
  2040. OPT_WITH_ARG("-s",
  2041. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  2042. opt_hidden),
  2043. OPT_WITH_ARG("--scantime",
  2044. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  2045. opt_hidden),
  2046. OPT_WITH_ARG("--sched-start",
  2047. set_schedtime, NULL, &schedstart,
  2048. "Set a time of day in HH:MM to start mining (a once off without a stop time)"),
  2049. OPT_WITH_ARG("--sched-stop",
  2050. set_schedtime, NULL, &schedstop,
  2051. "Set a time of day in HH:MM to stop mining (will quit without a start time)"),
  2052. #ifdef USE_SCRYPT
  2053. OPT_WITHOUT_ARG("--scrypt",
  2054. opt_set_bool, &opt_scrypt,
  2055. "Use the scrypt algorithm for mining (non-bitcoin)"),
  2056. #endif
  2057. OPT_WITH_ARG("--set-device|--set",
  2058. opt_string_elist_add, NULL, &opt_set_device_list,
  2059. "Set default parameters on devices; eg, NFY:osc6_bits=50"),
  2060. #if defined(USE_SCRYPT) && defined(HAVE_OPENCL)
  2061. OPT_WITH_ARG("--shaders",
  2062. set_shaders, NULL, NULL,
  2063. opt_hidden),
  2064. #endif
  2065. #ifdef HAVE_PWD_H
  2066. OPT_WITH_ARG("--setuid",
  2067. opt_set_charp, NULL, &opt_setuid,
  2068. "Username of an unprivileged user to run as"),
  2069. #endif
  2070. OPT_WITH_ARG("--sharelog",
  2071. set_sharelog, NULL, NULL,
  2072. "Append share log to file"),
  2073. OPT_WITH_ARG("--shares",
  2074. opt_set_floatval, NULL, &opt_shares,
  2075. "Quit after mining 2^32 * N hashes worth of shares (default: unlimited)"),
  2076. OPT_WITHOUT_ARG("--show-processors",
  2077. opt_set_bool, &opt_show_procs,
  2078. "Show per processor statistics in summary"),
  2079. OPT_WITHOUT_ARG("--show-procs",
  2080. opt_set_bool, &opt_show_procs,
  2081. opt_hidden),
  2082. OPT_WITH_ARG("--skip-security-checks",
  2083. set_int_0_to_9999, NULL, &opt_skip_checks,
  2084. "Skip security checks sometimes to save bandwidth; only check 1/<arg>th of the time (default: never skip)"),
  2085. OPT_WITH_ARG("--socks-proxy",
  2086. opt_set_charp, NULL, &opt_socks_proxy,
  2087. "Set socks proxy (host:port)"),
  2088. #ifdef USE_LIBEVENT
  2089. OPT_WITH_ARG("--stratum-port",
  2090. opt_set_intval, opt_show_intval, &stratumsrv_port,
  2091. "Port number to listen on for stratum miners (-1 means disabled)"),
  2092. #endif
  2093. OPT_WITHOUT_ARG("--submit-stale",
  2094. opt_set_bool, &opt_submit_stale,
  2095. opt_hidden),
  2096. OPT_WITH_ARG("--submit-threads",
  2097. opt_set_intval, opt_show_intval, &opt_submit_threads,
  2098. "Minimum number of concurrent share submissions (default: 64)"),
  2099. #ifdef HAVE_SYSLOG_H
  2100. OPT_WITHOUT_ARG("--syslog",
  2101. opt_set_bool, &use_syslog,
  2102. "Use system log for output messages (default: standard error)"),
  2103. #endif
  2104. OPT_WITH_ARG("--temp-cutoff",
  2105. set_temp_cutoff, NULL, &opt_cutofftemp,
  2106. opt_hidden),
  2107. OPT_WITH_ARG("--temp-hysteresis",
  2108. set_int_1_to_10, opt_show_intval, &opt_hysteresis,
  2109. "Set how much the temperature can fluctuate outside limits when automanaging speeds"),
  2110. #ifdef HAVE_ADL
  2111. OPT_WITH_ARG("--temp-overheat",
  2112. set_temp_overheat, opt_show_intval, &opt_overheattemp,
  2113. opt_hidden),
  2114. #endif
  2115. OPT_WITH_ARG("--temp-target",
  2116. set_temp_target, NULL, NULL,
  2117. opt_hidden),
  2118. OPT_WITHOUT_ARG("--text-only|-T",
  2119. opt_set_invbool, &use_curses,
  2120. #ifdef HAVE_CURSES
  2121. "Disable ncurses formatted screen output"
  2122. #else
  2123. opt_hidden
  2124. #endif
  2125. ),
  2126. #if defined(USE_SCRYPT) && defined(HAVE_OPENCL)
  2127. OPT_WITH_ARG("--thread-concurrency",
  2128. set_thread_concurrency, NULL, NULL,
  2129. opt_hidden),
  2130. #endif
  2131. #ifdef USE_UNICODE
  2132. OPT_WITHOUT_ARG("--unicode",
  2133. opt_set_bool, &use_unicode,
  2134. "Use Unicode characters in TUI"),
  2135. #endif
  2136. OPT_WITH_ARG("--url|-o",
  2137. set_url, NULL, NULL,
  2138. "URL for bitcoin JSON-RPC server"),
  2139. OPT_WITH_ARG("--user|-u",
  2140. set_user, NULL, NULL,
  2141. "Username for bitcoin JSON-RPC server"),
  2142. #ifdef HAVE_OPENCL
  2143. OPT_WITH_ARG("--vectors|-v",
  2144. set_vector, NULL, NULL,
  2145. opt_hidden),
  2146. #endif
  2147. OPT_WITHOUT_ARG("--verbose",
  2148. opt_set_bool, &opt_log_output,
  2149. "Log verbose output to stderr as well as status output"),
  2150. OPT_WITHOUT_ARG("--verbose-work-updates|--verbose-work-update",
  2151. opt_set_invbool, &opt_quiet_work_updates,
  2152. opt_hidden),
  2153. OPT_WITHOUT_ARG("--weighed-stats",
  2154. opt_set_bool, &opt_weighed_stats,
  2155. "Display statistics weighed to difficulty 1"),
  2156. #ifdef HAVE_OPENCL
  2157. OPT_WITH_ARG("--worksize|-w",
  2158. set_worksize, NULL, NULL,
  2159. opt_hidden),
  2160. #endif
  2161. OPT_WITHOUT_ARG("--unittest",
  2162. opt_set_bool, &opt_unittest, opt_hidden),
  2163. OPT_WITH_ARG("--userpass|-O",
  2164. set_userpass, NULL, NULL,
  2165. "Username:Password pair for bitcoin JSON-RPC server"),
  2166. OPT_WITHOUT_ARG("--worktime",
  2167. opt_set_bool, &opt_worktime,
  2168. "Display extra work time debug information"),
  2169. OPT_WITH_ARG("--pools",
  2170. opt_set_bool, NULL, NULL, opt_hidden),
  2171. OPT_ENDTABLE
  2172. };
  2173. static char *load_config(const char *arg, void __maybe_unused *unused);
  2174. static int fileconf_load;
  2175. static char *parse_config(json_t *config, bool fileconf)
  2176. {
  2177. static char err_buf[200];
  2178. struct opt_table *opt;
  2179. json_t *val;
  2180. if (fileconf && !fileconf_load)
  2181. fileconf_load = 1;
  2182. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  2183. char *p, *name, *sp;
  2184. /* We don't handle subtables. */
  2185. assert(!(opt->type & OPT_SUBTABLE));
  2186. if (!opt->names)
  2187. continue;
  2188. /* Pull apart the option name(s). */
  2189. name = strdup(opt->names);
  2190. for (p = strtok_r(name, "|", &sp); p; p = strtok_r(NULL, "|", &sp)) {
  2191. char *err = "Invalid value";
  2192. /* Ignore short options. */
  2193. if (p[1] != '-')
  2194. continue;
  2195. val = json_object_get(config, p+2);
  2196. if (!val)
  2197. continue;
  2198. if (opt->type & OPT_HASARG) {
  2199. if (json_is_string(val)) {
  2200. err = opt->cb_arg(json_string_value(val),
  2201. opt->u.arg);
  2202. } else if (json_is_number(val)) {
  2203. char buf[256], *p, *q;
  2204. snprintf(buf, 256, "%f", json_number_value(val));
  2205. if ( (p = strchr(buf, '.')) ) {
  2206. // Trim /\.0*$/ to work properly with integer-only arguments
  2207. q = p;
  2208. while (*(++q) == '0') {}
  2209. if (*q == '\0')
  2210. *p = '\0';
  2211. }
  2212. err = opt->cb_arg(buf, opt->u.arg);
  2213. } else if (json_is_array(val)) {
  2214. int n, size = json_array_size(val);
  2215. err = NULL;
  2216. for (n = 0; n < size && !err; n++) {
  2217. if (json_is_string(json_array_get(val, n)))
  2218. err = opt->cb_arg(json_string_value(json_array_get(val, n)), opt->u.arg);
  2219. else if (json_is_object(json_array_get(val, n)))
  2220. err = parse_config(json_array_get(val, n), false);
  2221. }
  2222. }
  2223. } else if (opt->type & OPT_NOARG) {
  2224. if (json_is_true(val))
  2225. err = opt->cb(opt->u.arg);
  2226. else if (json_is_boolean(val)) {
  2227. if (opt->cb == (void*)opt_set_bool)
  2228. err = opt_set_invbool(opt->u.arg);
  2229. else if (opt->cb == (void*)opt_set_invbool)
  2230. err = opt_set_bool(opt->u.arg);
  2231. }
  2232. }
  2233. if (err) {
  2234. /* Allow invalid values to be in configuration
  2235. * file, just skipping over them provided the
  2236. * JSON is still valid after that. */
  2237. if (fileconf) {
  2238. applog(LOG_ERR, "Invalid config option %s: %s", p, err);
  2239. fileconf_load = -1;
  2240. } else {
  2241. snprintf(err_buf, sizeof(err_buf), "Parsing JSON option %s: %s",
  2242. p, err);
  2243. return err_buf;
  2244. }
  2245. }
  2246. }
  2247. free(name);
  2248. }
  2249. val = json_object_get(config, JSON_INCLUDE_CONF);
  2250. if (val && json_is_string(val))
  2251. return load_config(json_string_value(val), NULL);
  2252. return NULL;
  2253. }
  2254. char *cnfbuf = NULL;
  2255. static char *load_config(const char *arg, void __maybe_unused *unused)
  2256. {
  2257. json_error_t err;
  2258. json_t *config;
  2259. char *json_error;
  2260. size_t siz;
  2261. if (!cnfbuf)
  2262. cnfbuf = strdup(arg);
  2263. if (++include_count > JSON_MAX_DEPTH)
  2264. return JSON_MAX_DEPTH_ERR;
  2265. #if JANSSON_MAJOR_VERSION > 1
  2266. config = json_load_file(arg, 0, &err);
  2267. #else
  2268. config = json_load_file(arg, &err);
  2269. #endif
  2270. if (!json_is_object(config)) {
  2271. siz = JSON_LOAD_ERROR_LEN + strlen(arg) + strlen(err.text);
  2272. json_error = malloc(siz);
  2273. if (!json_error)
  2274. quit(1, "Malloc failure in json error");
  2275. snprintf(json_error, siz, JSON_LOAD_ERROR, arg, err.text);
  2276. return json_error;
  2277. }
  2278. config_loaded = true;
  2279. /* Parse the config now, so we can override it. That can keep pointers
  2280. * so don't free config object. */
  2281. return parse_config(config, true);
  2282. }
  2283. static void load_default_config(void)
  2284. {
  2285. cnfbuf = malloc(PATH_MAX);
  2286. #if defined(unix)
  2287. if (getenv("HOME") && *getenv("HOME")) {
  2288. strcpy(cnfbuf, getenv("HOME"));
  2289. strcat(cnfbuf, "/");
  2290. } else
  2291. strcpy(cnfbuf, "");
  2292. char *dirp = cnfbuf + strlen(cnfbuf);
  2293. strcpy(dirp, ".bfgminer/");
  2294. strcat(dirp, def_conf);
  2295. if (access(cnfbuf, R_OK))
  2296. // No BFGMiner config, try Cgminer's...
  2297. strcpy(dirp, ".cgminer/cgminer.conf");
  2298. #else
  2299. strcpy(cnfbuf, "");
  2300. strcat(cnfbuf, def_conf);
  2301. #endif
  2302. if (!access(cnfbuf, R_OK))
  2303. load_config(cnfbuf, NULL);
  2304. else {
  2305. free(cnfbuf);
  2306. cnfbuf = NULL;
  2307. }
  2308. }
  2309. extern const char *opt_argv0;
  2310. static char *opt_verusage_and_exit(const char *extra)
  2311. {
  2312. puts(packagename);
  2313. printf(" Lowlevel:%s\n", BFG_LOWLLIST);
  2314. printf(" Drivers:%s\n", BFG_DRIVERLIST);
  2315. printf(" Algorithms:%s\n", BFG_ALGOLIST);
  2316. printf(" Options:%s\n", BFG_OPTLIST);
  2317. printf("%s", opt_usage(opt_argv0, extra));
  2318. fflush(stdout);
  2319. exit(0);
  2320. }
  2321. /* These options are parsed before anything else */
  2322. static struct opt_table opt_early_table[] = {
  2323. OPT_EARLY_WITH_ARG("--config|-c",
  2324. set_bool_ignore_arg, NULL, &config_loaded,
  2325. opt_hidden),
  2326. OPT_EARLY_WITHOUT_ARG("--no-config",
  2327. opt_set_bool, &config_loaded,
  2328. "Inhibit loading default config file"),
  2329. OPT_ENDTABLE
  2330. };
  2331. /* These options are available from commandline only */
  2332. static struct opt_table opt_cmdline_table[] = {
  2333. OPT_WITH_ARG("--config|-c",
  2334. load_config, NULL, NULL,
  2335. "Load a JSON-format configuration file\n"
  2336. "See example.conf for an example configuration."),
  2337. OPT_EARLY_WITHOUT_ARG("--no-config",
  2338. opt_set_bool, &config_loaded,
  2339. "Inhibit loading default config file"),
  2340. OPT_WITHOUT_ARG("--help|-h",
  2341. opt_verusage_and_exit, NULL,
  2342. "Print this message"),
  2343. #ifdef HAVE_OPENCL
  2344. OPT_WITHOUT_ARG("--ndevs|-n",
  2345. print_ndevs_and_exit, &nDevs,
  2346. opt_hidden),
  2347. #endif
  2348. OPT_WITHOUT_ARG("--version|-V",
  2349. opt_version_and_exit, packagename,
  2350. "Display version and exit"),
  2351. OPT_ENDTABLE
  2352. };
  2353. static bool jobj_binary(const json_t *obj, const char *key,
  2354. void *buf, size_t buflen, bool required)
  2355. {
  2356. const char *hexstr;
  2357. json_t *tmp;
  2358. tmp = json_object_get(obj, key);
  2359. if (unlikely(!tmp)) {
  2360. if (unlikely(required))
  2361. applog(LOG_ERR, "JSON key '%s' not found", key);
  2362. return false;
  2363. }
  2364. hexstr = json_string_value(tmp);
  2365. if (unlikely(!hexstr)) {
  2366. applog(LOG_ERR, "JSON key '%s' is not a string", key);
  2367. return false;
  2368. }
  2369. if (!hex2bin(buf, hexstr, buflen))
  2370. return false;
  2371. return true;
  2372. }
  2373. static void calc_midstate(struct work *work)
  2374. {
  2375. union {
  2376. unsigned char c[64];
  2377. uint32_t i[16];
  2378. } data;
  2379. swap32yes(&data.i[0], work->data, 16);
  2380. sha256_ctx ctx;
  2381. sha256_init(&ctx);
  2382. sha256_update(&ctx, data.c, 64);
  2383. memcpy(work->midstate, ctx.h, sizeof(work->midstate));
  2384. swap32tole(work->midstate, work->midstate, 8);
  2385. }
  2386. static
  2387. struct bfg_tmpl_ref *tmpl_makeref(blktemplate_t * const tmpl)
  2388. {
  2389. struct bfg_tmpl_ref * const tr = malloc(sizeof(*tr));
  2390. *tr = (struct bfg_tmpl_ref){
  2391. .tmpl = tmpl,
  2392. .refcount = 1,
  2393. };
  2394. mutex_init(&tr->mutex);
  2395. return tr;
  2396. }
  2397. static
  2398. void tmpl_incref(struct bfg_tmpl_ref * const tr)
  2399. {
  2400. mutex_lock(&tr->mutex);
  2401. ++tr->refcount;
  2402. mutex_unlock(&tr->mutex);
  2403. }
  2404. void tmpl_decref(struct bfg_tmpl_ref * const tr)
  2405. {
  2406. mutex_lock(&tr->mutex);
  2407. bool free_tmpl = !--tr->refcount;
  2408. mutex_unlock(&tr->mutex);
  2409. if (free_tmpl)
  2410. {
  2411. blktmpl_free(tr->tmpl);
  2412. mutex_destroy(&tr->mutex);
  2413. free(tr);
  2414. }
  2415. }
  2416. static struct work *make_work(void)
  2417. {
  2418. struct work *work = calloc(1, sizeof(struct work));
  2419. if (unlikely(!work))
  2420. quit(1, "Failed to calloc work in make_work");
  2421. cg_wlock(&control_lock);
  2422. work->id = total_work++;
  2423. cg_wunlock(&control_lock);
  2424. return work;
  2425. }
  2426. /* This is the central place all work that is about to be retired should be
  2427. * cleaned to remove any dynamically allocated arrays within the struct */
  2428. void clean_work(struct work *work)
  2429. {
  2430. free(work->job_id);
  2431. bytes_free(&work->nonce2);
  2432. free(work->nonce1);
  2433. if (work->device_data_free_func)
  2434. work->device_data_free_func(work);
  2435. if (work->tr)
  2436. tmpl_decref(work->tr);
  2437. memset(work, 0, sizeof(struct work));
  2438. }
  2439. /* All dynamically allocated work structs should be freed here to not leak any
  2440. * ram from arrays allocated within the work struct */
  2441. void free_work(struct work *work)
  2442. {
  2443. clean_work(work);
  2444. free(work);
  2445. }
  2446. 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";
  2447. // Must only be called with ch_lock held!
  2448. static
  2449. void __update_block_title(const unsigned char *hash_swap)
  2450. {
  2451. if (hash_swap) {
  2452. char tmp[17];
  2453. // Only provided when the block has actually changed
  2454. free(current_hash);
  2455. current_hash = malloc(3 /* ... */ + 16 /* block hash segment */ + 1);
  2456. bin2hex(tmp, &hash_swap[24], 8);
  2457. memset(current_hash, '.', 3);
  2458. memcpy(&current_hash[3], tmp, 17);
  2459. known_blkheight_current = false;
  2460. } else if (likely(known_blkheight_current)) {
  2461. return;
  2462. }
  2463. if (current_block_id == known_blkheight_blkid) {
  2464. // FIXME: The block number will overflow this sometime around AD 2025-2027
  2465. if (known_blkheight < 1000000) {
  2466. memmove(&current_hash[3], &current_hash[11], 8);
  2467. snprintf(&current_hash[11], 20-11, " #%6u", known_blkheight);
  2468. }
  2469. known_blkheight_current = true;
  2470. }
  2471. }
  2472. static
  2473. void have_block_height(uint32_t block_id, uint32_t blkheight)
  2474. {
  2475. if (known_blkheight == blkheight)
  2476. return;
  2477. applog(LOG_DEBUG, "Learned that block id %08" PRIx32 " is height %" PRIu32, (uint32_t)be32toh(block_id), blkheight);
  2478. cg_wlock(&ch_lock);
  2479. known_blkheight = blkheight;
  2480. known_blkheight_blkid = block_id;
  2481. block_subsidy = 5000000000LL >> (blkheight / 210000);
  2482. if (block_id == current_block_id)
  2483. __update_block_title(NULL);
  2484. cg_wunlock(&ch_lock);
  2485. }
  2486. static
  2487. void pool_set_opaque(struct pool *pool, bool opaque)
  2488. {
  2489. if (pool->swork.opaque == opaque)
  2490. return;
  2491. pool->swork.opaque = opaque;
  2492. if (opaque)
  2493. applog(LOG_WARNING, "Pool %u is hiding block contents from us",
  2494. pool->pool_no);
  2495. else
  2496. applog(LOG_NOTICE, "Pool %u now providing block contents to us",
  2497. pool->pool_no);
  2498. }
  2499. bool pool_may_redirect_to(struct pool * const pool, const char * const uri)
  2500. {
  2501. const char *p = strchr(pool->rpc_url, '#');
  2502. if (unlikely(p && strstr(&p[1], "redirect")))
  2503. return true;
  2504. return match_domains(pool->rpc_url, strlen(pool->rpc_url), uri, strlen(uri));
  2505. }
  2506. void set_simple_ntime_roll_limit(struct ntime_roll_limits * const nrl, const uint32_t ntime_base, const int ntime_roll)
  2507. {
  2508. *nrl = (struct ntime_roll_limits){
  2509. .min = ntime_base,
  2510. .max = ntime_base + ntime_roll,
  2511. .minoff = -ntime_roll,
  2512. .maxoff = ntime_roll,
  2513. };
  2514. }
  2515. void work_set_simple_ntime_roll_limit(struct work * const work, const int ntime_roll)
  2516. {
  2517. set_simple_ntime_roll_limit(&work->ntime_roll_limits, upk_u32be(work->data, 0x44), ntime_roll);
  2518. }
  2519. static double target_diff(const unsigned char *);
  2520. #define GBT_XNONCESZ (sizeof(uint32_t))
  2521. #if BLKMAKER_VERSION > 4
  2522. #define blkmk_append_coinbase_safe(tmpl, append, appendsz) \
  2523. blkmk_append_coinbase_safe2(tmpl, append, appendsz, GBT_XNONCESZ, false)
  2524. #endif
  2525. static bool work_decode(struct pool *pool, struct work *work, json_t *val)
  2526. {
  2527. json_t *res_val = json_object_get(val, "result");
  2528. json_t *tmp_val;
  2529. bool ret = false;
  2530. struct timeval tv_now;
  2531. if (unlikely(detect_algo == 1)) {
  2532. json_t *tmp = json_object_get(res_val, "algorithm");
  2533. const char *v = tmp ? json_string_value(tmp) : "";
  2534. if (strncasecmp(v, "scrypt", 6))
  2535. detect_algo = 2;
  2536. }
  2537. timer_set_now(&tv_now);
  2538. if (work->tr)
  2539. {
  2540. blktemplate_t * const tmpl = work->tr->tmpl;
  2541. const char *err = blktmpl_add_jansson(tmpl, res_val, tv_now.tv_sec);
  2542. if (err) {
  2543. applog(LOG_ERR, "blktmpl error: %s", err);
  2544. return false;
  2545. }
  2546. work->rolltime = blkmk_time_left(tmpl, tv_now.tv_sec);
  2547. #if BLKMAKER_VERSION > 1
  2548. if (opt_coinbase_script.sz)
  2549. {
  2550. bool newcb;
  2551. #if BLKMAKER_VERSION > 2
  2552. blkmk_init_generation2(tmpl, opt_coinbase_script.data, opt_coinbase_script.sz, &newcb);
  2553. #else
  2554. newcb = !tmpl->cbtxn;
  2555. blkmk_init_generation(tmpl, opt_coinbase_script.data, opt_coinbase_script.sz);
  2556. #endif
  2557. if (newcb)
  2558. {
  2559. ssize_t ae = blkmk_append_coinbase_safe(tmpl, &template_nonce, sizeof(template_nonce));
  2560. if (ae < (ssize_t)sizeof(template_nonce))
  2561. 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);
  2562. ++template_nonce;
  2563. }
  2564. }
  2565. #endif
  2566. #if BLKMAKER_VERSION > 0
  2567. {
  2568. ssize_t ae = blkmk_append_coinbase_safe(tmpl, opt_coinbase_sig, 101);
  2569. static bool appenderr = false;
  2570. if (ae <= 0) {
  2571. if (opt_coinbase_sig) {
  2572. applog((appenderr ? LOG_DEBUG : LOG_WARNING), "Cannot append coinbase signature at all on pool %u (%"PRId64")", pool->pool_no, (int64_t)ae);
  2573. appenderr = true;
  2574. }
  2575. } else if (ae >= 3 || opt_coinbase_sig) {
  2576. const char *cbappend = opt_coinbase_sig;
  2577. const char full[] = PACKAGE " " VERSION;
  2578. if (!cbappend) {
  2579. if ((size_t)ae >= sizeof(full) - 1)
  2580. cbappend = full;
  2581. else if ((size_t)ae >= sizeof(PACKAGE) - 1)
  2582. cbappend = PACKAGE;
  2583. else
  2584. cbappend = "BFG";
  2585. }
  2586. size_t cbappendsz = strlen(cbappend);
  2587. static bool truncatewarning = false;
  2588. if (cbappendsz <= (size_t)ae) {
  2589. if (cbappendsz < (size_t)ae)
  2590. // If we have space, include the trailing \0
  2591. ++cbappendsz;
  2592. ae = cbappendsz;
  2593. truncatewarning = false;
  2594. } else {
  2595. char *tmp = malloc(ae + 1);
  2596. memcpy(tmp, opt_coinbase_sig, ae);
  2597. tmp[ae] = '\0';
  2598. applog((truncatewarning ? LOG_DEBUG : LOG_WARNING),
  2599. "Pool %u truncating appended coinbase signature at %"PRId64" bytes: %s(%s)",
  2600. pool->pool_no, (int64_t)ae, tmp, &opt_coinbase_sig[ae]);
  2601. free(tmp);
  2602. truncatewarning = true;
  2603. }
  2604. ae = blkmk_append_coinbase_safe(tmpl, cbappend, ae);
  2605. if (ae <= 0) {
  2606. applog((appenderr ? LOG_DEBUG : LOG_WARNING), "Error appending coinbase signature (%"PRId64")", (int64_t)ae);
  2607. appenderr = true;
  2608. } else
  2609. appenderr = false;
  2610. }
  2611. }
  2612. #endif
  2613. if (blkmk_get_data(tmpl, work->data, 80, tv_now.tv_sec, NULL, &work->dataid) < 76)
  2614. return false;
  2615. swap32yes(work->data, work->data, 80 / 4);
  2616. memcpy(&work->data[80], workpadding_bin, 48);
  2617. work->ntime_roll_limits = (struct ntime_roll_limits){
  2618. .min = tmpl->mintime,
  2619. .max = tmpl->maxtime,
  2620. .minoff = tmpl->mintimeoff,
  2621. .maxoff = tmpl->maxtimeoff,
  2622. };
  2623. const struct blktmpl_longpoll_req *lp;
  2624. if ((lp = blktmpl_get_longpoll(tmpl)) && ((!pool->lp_id) || strcmp(lp->id, pool->lp_id))) {
  2625. free(pool->lp_id);
  2626. pool->lp_id = strdup(lp->id);
  2627. #if 0 /* This just doesn't work :( */
  2628. curl_socket_t sock = pool->lp_socket;
  2629. if (sock != CURL_SOCKET_BAD) {
  2630. pool->lp_socket = CURL_SOCKET_BAD;
  2631. applog(LOG_WARNING, "Pool %u long poll request hanging, reconnecting", pool->pool_no);
  2632. shutdown(sock, SHUT_RDWR);
  2633. }
  2634. #endif
  2635. }
  2636. }
  2637. else
  2638. if (unlikely(!jobj_binary(res_val, "data", work->data, sizeof(work->data), true))) {
  2639. applog(LOG_ERR, "JSON inval data");
  2640. return false;
  2641. }
  2642. else
  2643. work_set_simple_ntime_roll_limit(work, 0);
  2644. if (!jobj_binary(res_val, "midstate", work->midstate, sizeof(work->midstate), false)) {
  2645. // Calculate it ourselves
  2646. applog(LOG_DEBUG, "Calculating midstate locally");
  2647. calc_midstate(work);
  2648. }
  2649. if (unlikely(!jobj_binary(res_val, "target", work->target, sizeof(work->target), true))) {
  2650. applog(LOG_ERR, "JSON inval target");
  2651. return false;
  2652. }
  2653. if (work->tr)
  2654. {
  2655. for (size_t i = 0; i < sizeof(work->target) / 2; ++i)
  2656. {
  2657. int p = (sizeof(work->target) - 1) - i;
  2658. unsigned char c = work->target[i];
  2659. work->target[i] = work->target[p];
  2660. work->target[p] = c;
  2661. }
  2662. }
  2663. if ( (tmp_val = json_object_get(res_val, "height")) ) {
  2664. uint32_t blkheight = json_number_value(tmp_val);
  2665. uint32_t block_id = ((uint32_t*)work->data)[1];
  2666. have_block_height(block_id, blkheight);
  2667. }
  2668. memset(work->hash, 0, sizeof(work->hash));
  2669. work->tv_staged = tv_now;
  2670. #if BLKMAKER_VERSION > 4
  2671. if (work->tr)
  2672. {
  2673. blktemplate_t * const tmpl = work->tr->tmpl;
  2674. uint8_t buf[80];
  2675. int16_t expire;
  2676. uint8_t *cbtxn;
  2677. size_t cbtxnsz;
  2678. size_t cbextranonceoffset;
  2679. int branchcount;
  2680. libblkmaker_hash_t *branches;
  2681. if (blkmk_get_mdata(tmpl, buf, sizeof(buf), tv_now.tv_sec, &expire, &cbtxn, &cbtxnsz, &cbextranonceoffset, &branchcount, &branches, GBT_XNONCESZ, false))
  2682. {
  2683. struct stratum_work * const swork = &pool->swork;
  2684. const size_t branchdatasz = branchcount * 0x20;
  2685. cg_wlock(&pool->data_lock);
  2686. swork->tr = work->tr;
  2687. bytes_assimilate_raw(&swork->coinbase, cbtxn, cbtxnsz, cbtxnsz);
  2688. swork->nonce2_offset = cbextranonceoffset;
  2689. bytes_assimilate_raw(&swork->merkle_bin, branches, branchdatasz, branchdatasz);
  2690. swork->merkles = branchcount;
  2691. memcpy(swork->header1, &buf[0], 36);
  2692. swork->ntime = le32toh(*(uint32_t *)(&buf[68]));
  2693. swork->tv_received = tv_now;
  2694. memcpy(swork->diffbits, &buf[72], 4);
  2695. memcpy(swork->target, work->target, sizeof(swork->target));
  2696. free(swork->job_id);
  2697. swork->job_id = NULL;
  2698. swork->clean = true;
  2699. // FIXME: Do something with expire
  2700. pool->nonce2sz = pool->n2size = GBT_XNONCESZ;
  2701. pool->nonce2 = 0;
  2702. cg_wunlock(&pool->data_lock);
  2703. }
  2704. else
  2705. applog(LOG_DEBUG, "blkmk_get_mdata failed for pool %u", pool->pool_no);
  2706. }
  2707. #endif // BLKMAKER_VERSION > 4
  2708. pool_set_opaque(pool, !work->tr);
  2709. ret = true;
  2710. return ret;
  2711. }
  2712. /* Returns whether the pool supports local work generation or not. */
  2713. static bool pool_localgen(struct pool *pool)
  2714. {
  2715. return (pool->last_work_copy || pool->has_stratum);
  2716. }
  2717. int dev_from_id(int thr_id)
  2718. {
  2719. struct cgpu_info *cgpu = get_thr_cgpu(thr_id);
  2720. return cgpu->device_id;
  2721. }
  2722. /* Create an exponentially decaying average over the opt_log_interval */
  2723. void decay_time(double *f, double fadd, double fsecs)
  2724. {
  2725. double ftotal, fprop;
  2726. fprop = 1.0 - 1 / (exp(fsecs / (double)opt_log_interval));
  2727. ftotal = 1.0 + fprop;
  2728. *f += (fadd * fprop);
  2729. *f /= ftotal;
  2730. }
  2731. static int __total_staged(void)
  2732. {
  2733. return HASH_COUNT(staged_work);
  2734. }
  2735. static int total_staged(void)
  2736. {
  2737. int ret;
  2738. mutex_lock(stgd_lock);
  2739. ret = __total_staged();
  2740. mutex_unlock(stgd_lock);
  2741. return ret;
  2742. }
  2743. #ifdef HAVE_CURSES
  2744. WINDOW *mainwin, *statuswin, *logwin;
  2745. #endif
  2746. double total_secs = 1.0;
  2747. static char statusline[256];
  2748. /* logstart is where the log window should start */
  2749. static int devcursor, logstart, logcursor;
  2750. #ifdef HAVE_CURSES
  2751. /* statusy is where the status window goes up to in cases where it won't fit at startup */
  2752. static int statusy;
  2753. static int devsummaryYOffset;
  2754. static int total_lines;
  2755. #endif
  2756. #ifdef HAVE_OPENCL
  2757. struct cgpu_info gpus[MAX_GPUDEVICES]; /* Maximum number apparently possible */
  2758. #endif
  2759. struct cgpu_info *cpus;
  2760. bool _bfg_console_cancel_disabled;
  2761. int _bfg_console_prev_cancelstate;
  2762. #ifdef HAVE_CURSES
  2763. #define lock_curses() bfg_console_lock()
  2764. #define unlock_curses() bfg_console_unlock()
  2765. static bool curses_active_locked(void)
  2766. {
  2767. bool ret;
  2768. lock_curses();
  2769. ret = curses_active;
  2770. if (!ret)
  2771. unlock_curses();
  2772. return ret;
  2773. }
  2774. // Cancellable getch
  2775. int my_cancellable_getch(void)
  2776. {
  2777. // This only works because the macro only hits direct getch() calls
  2778. typedef int (*real_getch_t)(void);
  2779. const real_getch_t real_getch = __real_getch;
  2780. int type, rv;
  2781. bool sct;
  2782. sct = !pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &type);
  2783. rv = real_getch();
  2784. if (sct)
  2785. pthread_setcanceltype(type, &type);
  2786. return rv;
  2787. }
  2788. #ifdef PDCURSES
  2789. static
  2790. int bfg_wresize(WINDOW *win, int lines, int columns)
  2791. {
  2792. int rv = wresize(win, lines, columns);
  2793. int x, y;
  2794. getyx(win, y, x);
  2795. if (unlikely(y >= lines || x >= columns))
  2796. {
  2797. if (y >= lines)
  2798. y = lines - 1;
  2799. if (x >= columns)
  2800. x = columns - 1;
  2801. wmove(win, y, x);
  2802. }
  2803. return rv;
  2804. }
  2805. #else
  2806. # define bfg_wresize wresize
  2807. #endif
  2808. #endif
  2809. void tailsprintf(char *buf, size_t bufsz, const char *fmt, ...)
  2810. {
  2811. va_list ap;
  2812. size_t presz = strlen(buf);
  2813. va_start(ap, fmt);
  2814. vsnprintf(&buf[presz], bufsz - presz, fmt, ap);
  2815. va_end(ap);
  2816. }
  2817. double stats_elapsed(struct cgminer_stats *stats)
  2818. {
  2819. struct timeval now;
  2820. double elapsed;
  2821. if (stats->start_tv.tv_sec == 0)
  2822. elapsed = total_secs;
  2823. else {
  2824. cgtime(&now);
  2825. elapsed = tdiff(&now, &stats->start_tv);
  2826. }
  2827. if (elapsed < 1.0)
  2828. elapsed = 1.0;
  2829. return elapsed;
  2830. }
  2831. bool drv_ready(struct cgpu_info *cgpu)
  2832. {
  2833. switch (cgpu->status) {
  2834. case LIFE_INIT:
  2835. case LIFE_DEAD2:
  2836. return false;
  2837. default:
  2838. return true;
  2839. }
  2840. }
  2841. double cgpu_utility(struct cgpu_info *cgpu)
  2842. {
  2843. double dev_runtime = cgpu_runtime(cgpu);
  2844. return cgpu->utility = cgpu->accepted / dev_runtime * 60;
  2845. }
  2846. #define suffix_string(val, buf, bufsiz, sigdigits) do{ \
  2847. _Static_assert(sigdigits == 0, "suffix_string only supported with sigdigits==0"); \
  2848. format_unit3(buf, bufsiz, FUP_DIFF, "", H2B_SHORTV, val, -1); \
  2849. }while(0)
  2850. static float
  2851. utility_to_hashrate(double utility)
  2852. {
  2853. return utility * 0x4444444;
  2854. }
  2855. static const char*_unitchar = "pn\xb5m kMGTPEZY?";
  2856. static const int _unitbase = 4;
  2857. static
  2858. void pick_unit(float hashrate, unsigned char *unit)
  2859. {
  2860. unsigned char i;
  2861. if (hashrate == 0)
  2862. {
  2863. if (*unit < _unitbase)
  2864. *unit = _unitbase;
  2865. return;
  2866. }
  2867. hashrate *= 1e12;
  2868. for (i = 0; i < *unit; ++i)
  2869. hashrate /= 1e3;
  2870. // 1000 but with tolerance for floating-point rounding, avoid showing "1000.0"
  2871. while (hashrate >= 999.95)
  2872. {
  2873. hashrate /= 1e3;
  2874. if (likely(_unitchar[*unit] != '?'))
  2875. ++*unit;
  2876. }
  2877. }
  2878. #define hashrate_pick_unit(hashrate, unit) pick_unit(hashrate, unit)
  2879. enum h2bs_fmt {
  2880. H2B_NOUNIT, // "xxx.x"
  2881. H2B_SHORT, // "xxx.xMH/s"
  2882. H2B_SPACED, // "xxx.x MH/s"
  2883. H2B_SHORTV, // Like H2B_SHORT, but omit space for base unit
  2884. };
  2885. enum bfu_floatprec {
  2886. FUP_INTEGER,
  2887. FUP_HASHES,
  2888. FUP_BTC,
  2889. FUP_DIFF,
  2890. };
  2891. static
  2892. int format_unit3(char *buf, size_t sz, enum bfu_floatprec fprec, const char *measurement, enum h2bs_fmt fmt, float hashrate, signed char unitin)
  2893. {
  2894. char *s = buf;
  2895. unsigned char prec, i, unit;
  2896. int rv = 0;
  2897. if (unitin == -1)
  2898. {
  2899. unit = 0;
  2900. hashrate_pick_unit(hashrate, &unit);
  2901. }
  2902. else
  2903. unit = unitin;
  2904. hashrate *= 1e12;
  2905. for (i = 0; i < unit; ++i)
  2906. hashrate /= 1000;
  2907. switch (fprec)
  2908. {
  2909. case FUP_HASHES:
  2910. // 100 but with tolerance for floating-point rounding, max "99.99" then "100.0"
  2911. if (hashrate >= 99.995 || unit < 6)
  2912. prec = 1;
  2913. else
  2914. prec = 2;
  2915. _SNP("%5.*f", prec, hashrate);
  2916. break;
  2917. case FUP_INTEGER:
  2918. _SNP("%3d", (int)hashrate);
  2919. break;
  2920. case FUP_BTC:
  2921. if (hashrate >= 99.995)
  2922. prec = 0;
  2923. else
  2924. prec = 2;
  2925. _SNP("%5.*f", prec, hashrate);
  2926. break;
  2927. case FUP_DIFF:
  2928. if (unit > _unitbase)
  2929. _SNP("%.3g", hashrate);
  2930. else
  2931. _SNP("%u", (unsigned int)hashrate);
  2932. }
  2933. if (fmt != H2B_NOUNIT)
  2934. {
  2935. char uc[3] = {_unitchar[unit], '\0'};
  2936. switch (fmt) {
  2937. case H2B_SPACED:
  2938. _SNP(" ");
  2939. default:
  2940. break;
  2941. case H2B_SHORTV:
  2942. if (isspace(uc[0]))
  2943. uc[0] = '\0';
  2944. }
  2945. if (uc[0] == '\xb5')
  2946. // Convert to UTF-8
  2947. snprintf(uc, sizeof(uc), "%s", U8_MICRO);
  2948. _SNP("%s%s", uc, measurement);
  2949. }
  2950. return rv;
  2951. }
  2952. #define format_unit2(buf, sz, floatprec, measurement, fmt, n, unit) \
  2953. format_unit3(buf, sz, floatprec ? FUP_HASHES : FUP_INTEGER, measurement, fmt, n, unit)
  2954. static
  2955. 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)
  2956. {
  2957. unsigned char unit = 0;
  2958. bool allzero = true;
  2959. int i;
  2960. size_t delimsz = 0;
  2961. char *buf = buflist[0];
  2962. size_t bufsz = bufszlist[0];
  2963. size_t itemwidth = (floatprec ? 5 : 3);
  2964. if (!isarray)
  2965. delimsz = strlen(delim);
  2966. for (i = 0; i < count; ++i)
  2967. if (numbers[i] != 0)
  2968. {
  2969. pick_unit(numbers[i], &unit);
  2970. allzero = false;
  2971. }
  2972. if (allzero)
  2973. unit = _unitbase;
  2974. --count;
  2975. for (i = 0; i < count; ++i)
  2976. {
  2977. format_unit2(buf, bufsz, floatprec, NULL, H2B_NOUNIT, numbers[i], unit);
  2978. if (isarray)
  2979. {
  2980. buf = buflist[i + 1];
  2981. bufsz = bufszlist[i + 1];
  2982. }
  2983. else
  2984. {
  2985. buf += itemwidth;
  2986. bufsz -= itemwidth;
  2987. if (delimsz > bufsz)
  2988. delimsz = bufsz;
  2989. memcpy(buf, delim, delimsz);
  2990. buf += delimsz;
  2991. bufsz -= delimsz;
  2992. }
  2993. }
  2994. // Last entry has the unit
  2995. format_unit2(buf, bufsz, floatprec, measurement, fmt, numbers[count], unit);
  2996. return buflist[0];
  2997. }
  2998. #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)
  2999. #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)
  3000. static
  3001. int percentf3(char * const buf, size_t sz, double p, const double t)
  3002. {
  3003. char *s = buf;
  3004. int rv = 0;
  3005. if (!p)
  3006. _SNP("none");
  3007. else
  3008. if (t <= p)
  3009. _SNP("100%%");
  3010. else
  3011. {
  3012. p /= t;
  3013. if (p < 0.00995) // 0.01 but with tolerance for floating-point rounding, max ".99%"
  3014. _SNP(".%02.0f%%", p * 10000); // ".01%"
  3015. else
  3016. if (p < 0.0995) // 0.1 but with tolerance for floating-point rounding, max "9.9%"
  3017. _SNP("%.1f%%", p * 100); // "9.1%"
  3018. else
  3019. _SNP("%3.0f%%", p * 100); // " 99%"
  3020. }
  3021. return rv;
  3022. }
  3023. #define percentf4(buf, bufsz, p, t) percentf3(buf, bufsz, p, p + t)
  3024. static
  3025. void test_decimal_width()
  3026. {
  3027. // The pipe character at end of each line should perfectly line up
  3028. char printbuf[512];
  3029. char testbuf1[64];
  3030. char testbuf2[64];
  3031. char testbuf3[64];
  3032. char testbuf4[64];
  3033. double testn;
  3034. int width;
  3035. int saved;
  3036. // Hotspots around 0.1 and 0.01
  3037. saved = -1;
  3038. for (testn = 0.09; testn <= 0.11; testn += 0.000001) {
  3039. percentf3(testbuf1, sizeof(testbuf1), testn, 1.0);
  3040. percentf3(testbuf2, sizeof(testbuf2), testn, 10.0);
  3041. width = snprintf(printbuf, sizeof(printbuf), "%10g %s %s |", testn, testbuf1, testbuf2);
  3042. if (unlikely((saved != -1) && (width != saved))) {
  3043. applog(LOG_ERR, "Test width mismatch in percentf3! %d not %d at %10g", width, saved, testn);
  3044. applog(LOG_ERR, "%s", printbuf);
  3045. }
  3046. saved = width;
  3047. }
  3048. // Hotspot around 100 (but test this in several units because format_unit2 also has unit<2 check)
  3049. saved = -1;
  3050. for (testn = 99.0; testn <= 101.0; testn += 0.0001) {
  3051. format_unit2(testbuf1, sizeof(testbuf1), true, "x", H2B_SHORT, testn , -1);
  3052. format_unit2(testbuf2, sizeof(testbuf2), true, "x", H2B_SHORT, testn * 1e3, -1);
  3053. format_unit2(testbuf3, sizeof(testbuf3), true, "x", H2B_SHORT, testn * 1e6, -1);
  3054. snprintf(printbuf, sizeof(printbuf), "%10g %s %s %s |", testn, testbuf1, testbuf2, testbuf3);
  3055. width = utf8_strlen(printbuf);
  3056. if (unlikely((saved != -1) && (width != saved))) {
  3057. applog(LOG_ERR, "Test width mismatch in format_unit2! %d not %d at %10g", width, saved, testn);
  3058. applog(LOG_ERR, "%s", printbuf);
  3059. }
  3060. saved = width;
  3061. }
  3062. // Hotspot around unit transition boundary in pick_unit
  3063. saved = -1;
  3064. for (testn = 999.0; testn <= 1001.0; testn += 0.0001) {
  3065. format_unit2(testbuf1, sizeof(testbuf1), true, "x", H2B_SHORT, testn , -1);
  3066. format_unit2(testbuf2, sizeof(testbuf2), true, "x", H2B_SHORT, testn * 1e3, -1);
  3067. format_unit2(testbuf3, sizeof(testbuf3), true, "x", H2B_SHORT, testn * 1e6, -1);
  3068. format_unit2(testbuf4, sizeof(testbuf4), true, "x", H2B_SHORT, testn * 1e9, -1);
  3069. snprintf(printbuf, sizeof(printbuf), "%10g %s %s %s %s |", testn, testbuf1, testbuf2, testbuf3, testbuf4);
  3070. width = utf8_strlen(printbuf);
  3071. if (unlikely((saved != -1) && (width != saved))) {
  3072. applog(LOG_ERR, "Test width mismatch in pick_unit! %d not %d at %10g", width, saved, testn);
  3073. applog(LOG_ERR, "%s", printbuf);
  3074. }
  3075. saved = width;
  3076. }
  3077. }
  3078. #ifdef HAVE_CURSES
  3079. static void adj_width(int var, int *length);
  3080. #endif
  3081. #ifdef HAVE_CURSES
  3082. static int awidth = 1, rwidth = 1, swidth = 1, hwwidth = 1;
  3083. static
  3084. 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)
  3085. {
  3086. char rejpcbuf[6];
  3087. char bnbuf[6];
  3088. adj_width(accepted, &awidth);
  3089. adj_width(rejected, &rwidth);
  3090. adj_width(stale, &swidth);
  3091. adj_width(hwerrs, &hwwidth);
  3092. percentf4(rejpcbuf, sizeof(rejpcbuf), wnotaccepted, waccepted);
  3093. percentf3(bnbuf, sizeof(bnbuf), bad_diff1, allnonces);
  3094. tailsprintf(buf, bufsz, "%s/%s/%s | A:%*d R:%*d+%*d(%s) HW:%*d/%s",
  3095. cHr, aHr, uHr,
  3096. awidth, accepted,
  3097. rwidth, rejected,
  3098. swidth, stale,
  3099. rejpcbuf,
  3100. hwwidth, hwerrs,
  3101. bnbuf
  3102. );
  3103. }
  3104. static
  3105. const char *pool_proto_str(const struct pool * const pool)
  3106. {
  3107. if (pool->idle)
  3108. return "Dead ";
  3109. if (pool->has_stratum)
  3110. return "Strtm";
  3111. if (pool->lp_url && pool->proto != pool->lp_proto)
  3112. return "Mixed";
  3113. switch (pool->proto)
  3114. {
  3115. case PLP_GETBLOCKTEMPLATE:
  3116. return " GBT ";
  3117. case PLP_GETWORK:
  3118. return "GWork";
  3119. default:
  3120. return "Alive";
  3121. }
  3122. }
  3123. #endif
  3124. static inline
  3125. void temperature_column(char *buf, size_t bufsz, bool maybe_unicode, const float * const temp)
  3126. {
  3127. if (!(use_unicode && have_unicode_degrees))
  3128. maybe_unicode = false;
  3129. if (temp && *temp > 0.)
  3130. if (maybe_unicode)
  3131. snprintf(buf, bufsz, "%4.1f"U8_DEGREE"C", *temp);
  3132. else
  3133. snprintf(buf, bufsz, "%4.1fC", *temp);
  3134. else
  3135. {
  3136. if (temp)
  3137. snprintf(buf, bufsz, " ");
  3138. if (maybe_unicode)
  3139. tailsprintf(buf, bufsz, " ");
  3140. }
  3141. tailsprintf(buf, bufsz, " | ");
  3142. }
  3143. void get_statline3(char *buf, size_t bufsz, struct cgpu_info *cgpu, bool for_curses, bool opt_show_procs)
  3144. {
  3145. #ifndef HAVE_CURSES
  3146. assert(for_curses == false);
  3147. #endif
  3148. struct device_drv *drv = cgpu->drv;
  3149. enum h2bs_fmt hashrate_style = for_curses ? H2B_SHORT : H2B_SPACED;
  3150. char cHr[ALLOC_H2B_NOUNIT+1], aHr[ALLOC_H2B_NOUNIT+1], uHr[max(ALLOC_H2B_SHORT, ALLOC_H2B_SPACED)+3+1];
  3151. char rejpcbuf[6];
  3152. char bnbuf[6];
  3153. double dev_runtime;
  3154. if (!opt_show_procs)
  3155. cgpu = cgpu->device;
  3156. dev_runtime = cgpu_runtime(cgpu);
  3157. double rolling, mhashes;
  3158. int accepted, rejected, stale;
  3159. double waccepted;
  3160. double wnotaccepted;
  3161. int hwerrs;
  3162. double bad_diff1, good_diff1;
  3163. rolling = mhashes = waccepted = wnotaccepted = 0;
  3164. accepted = rejected = stale = hwerrs = bad_diff1 = good_diff1 = 0;
  3165. {
  3166. struct cgpu_info *slave = cgpu;
  3167. for (int i = 0; i < cgpu->procs; ++i, (slave = slave->next_proc))
  3168. {
  3169. slave->utility = slave->accepted / dev_runtime * 60;
  3170. slave->utility_diff1 = slave->diff_accepted / dev_runtime * 60;
  3171. rolling += slave->rolling;
  3172. mhashes += slave->total_mhashes;
  3173. if (opt_weighed_stats)
  3174. {
  3175. accepted += slave->diff_accepted;
  3176. rejected += slave->diff_rejected;
  3177. stale += slave->diff_stale;
  3178. }
  3179. else
  3180. {
  3181. accepted += slave->accepted;
  3182. rejected += slave->rejected;
  3183. stale += slave->stale;
  3184. }
  3185. waccepted += slave->diff_accepted;
  3186. wnotaccepted += slave->diff_rejected + slave->diff_stale;
  3187. hwerrs += slave->hw_errors;
  3188. bad_diff1 += slave->bad_diff1;
  3189. good_diff1 += slave->diff1;
  3190. if (opt_show_procs)
  3191. break;
  3192. }
  3193. }
  3194. double wtotal = (waccepted + wnotaccepted);
  3195. multi_format_unit_array2(
  3196. ((char*[]){cHr, aHr, uHr}),
  3197. ((size_t[]){sizeof(cHr), sizeof(aHr), sizeof(uHr)}),
  3198. true, "h/s", hashrate_style,
  3199. 3,
  3200. 1e6*rolling,
  3201. 1e6*mhashes / dev_runtime,
  3202. utility_to_hashrate(good_diff1 * (wtotal ? (waccepted / wtotal) : 1) * 60 / dev_runtime));
  3203. // Processor representation
  3204. #ifdef HAVE_CURSES
  3205. if (for_curses)
  3206. {
  3207. if (opt_show_procs)
  3208. snprintf(buf, bufsz, " %"PRIprepr": ", cgpu->proc_repr);
  3209. else
  3210. snprintf(buf, bufsz, " %s: ", cgpu->dev_repr);
  3211. }
  3212. else
  3213. #endif
  3214. snprintf(buf, bufsz, "%s ", opt_show_procs ? cgpu->proc_repr_ns : cgpu->dev_repr_ns);
  3215. if (include_serial_in_statline && cgpu->dev_serial)
  3216. tailsprintf(buf, bufsz, "[serial=%s] ", cgpu->dev_serial);
  3217. if (unlikely(cgpu->status == LIFE_INIT))
  3218. {
  3219. tailsprintf(buf, bufsz, "Initializing...");
  3220. return;
  3221. }
  3222. {
  3223. const size_t bufln = strlen(buf);
  3224. const size_t abufsz = (bufln >= bufsz) ? 0 : (bufsz - bufln);
  3225. if (likely(cgpu->status != LIFE_DEAD2) && drv->override_statline_temp2 && drv->override_statline_temp2(buf, bufsz, cgpu, opt_show_procs))
  3226. temperature_column(&buf[bufln], abufsz, for_curses, NULL);
  3227. else
  3228. {
  3229. float temp = cgpu->temp;
  3230. if (!opt_show_procs)
  3231. {
  3232. // Find the highest temperature of all processors
  3233. struct cgpu_info *proc = cgpu;
  3234. for (int i = 0; i < cgpu->procs; ++i, (proc = proc->next_proc))
  3235. if (proc->temp > temp)
  3236. temp = proc->temp;
  3237. }
  3238. temperature_column(&buf[bufln], abufsz, for_curses, &temp);
  3239. }
  3240. }
  3241. #ifdef HAVE_CURSES
  3242. if (for_curses)
  3243. {
  3244. const char *cHrStatsOpt[] = {AS_BAD("DEAD "), AS_BAD("SICK "), "OFF ", AS_BAD("REST "), AS_BAD(" ERR "), AS_BAD("WAIT "), cHr};
  3245. const char *cHrStats;
  3246. int cHrStatsI = (sizeof(cHrStatsOpt) / sizeof(*cHrStatsOpt)) - 1;
  3247. bool all_dead = true, all_off = true, all_rdrv = true;
  3248. struct cgpu_info *proc = cgpu;
  3249. for (int i = 0; i < cgpu->procs; ++i, (proc = proc->next_proc))
  3250. {
  3251. switch (cHrStatsI) {
  3252. default:
  3253. if (proc->status == LIFE_WAIT)
  3254. cHrStatsI = 5;
  3255. case 5:
  3256. if (proc->deven == DEV_RECOVER_ERR)
  3257. cHrStatsI = 4;
  3258. case 4:
  3259. if (proc->deven == DEV_RECOVER)
  3260. cHrStatsI = 3;
  3261. case 3:
  3262. if (proc->status == LIFE_SICK || proc->status == LIFE_DEAD || proc->status == LIFE_DEAD2)
  3263. {
  3264. cHrStatsI = 1;
  3265. all_off = false;
  3266. }
  3267. else
  3268. {
  3269. if (likely(proc->deven == DEV_ENABLED))
  3270. all_off = false;
  3271. if (proc->deven != DEV_RECOVER_DRV)
  3272. all_rdrv = false;
  3273. }
  3274. case 1:
  3275. break;
  3276. }
  3277. if (likely(proc->status != LIFE_DEAD && proc->status != LIFE_DEAD2))
  3278. all_dead = false;
  3279. if (opt_show_procs)
  3280. break;
  3281. }
  3282. if (unlikely(all_dead))
  3283. cHrStatsI = 0;
  3284. else
  3285. if (unlikely(all_off))
  3286. cHrStatsI = 2;
  3287. cHrStats = cHrStatsOpt[cHrStatsI];
  3288. if (cHrStatsI == 2 && all_rdrv)
  3289. cHrStats = " RST ";
  3290. format_statline(buf, bufsz,
  3291. cHrStats,
  3292. aHr, uHr,
  3293. accepted, rejected, stale,
  3294. wnotaccepted, waccepted,
  3295. hwerrs,
  3296. bad_diff1, bad_diff1 + good_diff1);
  3297. }
  3298. else
  3299. #endif
  3300. {
  3301. percentf4(rejpcbuf, sizeof(rejpcbuf), wnotaccepted, waccepted);
  3302. percentf4(bnbuf, sizeof(bnbuf), bad_diff1, good_diff1);
  3303. tailsprintf(buf, bufsz, "%ds:%s avg:%s u:%s | A:%d R:%d+%d(%s) HW:%d/%s",
  3304. opt_log_interval,
  3305. cHr, aHr, uHr,
  3306. accepted,
  3307. rejected,
  3308. stale,
  3309. rejpcbuf,
  3310. hwerrs,
  3311. bnbuf
  3312. );
  3313. }
  3314. }
  3315. #define get_statline(buf, bufsz, cgpu) get_statline3(buf, bufsz, cgpu, false, opt_show_procs)
  3316. #define get_statline2(buf, bufsz, cgpu, for_curses) get_statline3(buf, bufsz, cgpu, for_curses, opt_show_procs)
  3317. static void text_print_status(int thr_id)
  3318. {
  3319. struct cgpu_info *cgpu;
  3320. char logline[256];
  3321. cgpu = get_thr_cgpu(thr_id);
  3322. if (cgpu) {
  3323. get_statline(logline, sizeof(logline), cgpu);
  3324. printf("%s\n", logline);
  3325. }
  3326. }
  3327. #ifdef HAVE_CURSES
  3328. static int attr_bad = A_BOLD;
  3329. #ifdef WIN32
  3330. #define swprintf snwprintf
  3331. #endif
  3332. static
  3333. void bfg_waddstr(WINDOW *win, const char *s)
  3334. {
  3335. const char *p = s;
  3336. int32_t w;
  3337. int wlen;
  3338. unsigned char stop_ascii = (use_unicode ? '|' : 0x80);
  3339. while (true)
  3340. {
  3341. while (likely(p[0] == '\n' || (p[0] >= 0x20 && p[0] < stop_ascii)))
  3342. {
  3343. // Printable ASCII
  3344. ++p;
  3345. }
  3346. if (p != s)
  3347. waddnstr(win, s, p - s);
  3348. w = utf8_decode(p, &wlen);
  3349. s = p += wlen;
  3350. switch(w)
  3351. {
  3352. // NOTE: U+F000-U+F7FF are reserved for font hacks
  3353. case '\0':
  3354. return;
  3355. case 0xb5: // micro symbol
  3356. w = unicode_micro;
  3357. goto default_addch;
  3358. case 0xf000: // "bad" off
  3359. wattroff(win, attr_bad);
  3360. break;
  3361. case 0xf001: // "bad" on
  3362. wattron(win, attr_bad);
  3363. break;
  3364. #ifdef USE_UNICODE
  3365. case '|':
  3366. wadd_wch(win, WACS_VLINE);
  3367. break;
  3368. #endif
  3369. case 0x2500: // BOX DRAWINGS LIGHT HORIZONTAL
  3370. case 0x2534: // BOX DRAWINGS LIGHT UP AND HORIZONTAL
  3371. if (!use_unicode)
  3372. {
  3373. waddch(win, '-');
  3374. break;
  3375. }
  3376. #ifdef USE_UNICODE
  3377. wadd_wch(win, (w == 0x2500) ? WACS_HLINE : WACS_BTEE);
  3378. break;
  3379. #endif
  3380. case 0x2022:
  3381. if (w > WCHAR_MAX || !iswprint(w))
  3382. w = '*';
  3383. default:
  3384. default_addch:
  3385. if (w > WCHAR_MAX || !(iswprint(w) || w == '\n'))
  3386. {
  3387. #if REPLACEMENT_CHAR <= WCHAR_MAX
  3388. if (iswprint(REPLACEMENT_CHAR))
  3389. w = REPLACEMENT_CHAR;
  3390. else
  3391. #endif
  3392. w = '?';
  3393. }
  3394. {
  3395. #ifdef USE_UNICODE
  3396. wchar_t wbuf[0x10];
  3397. int wbuflen = sizeof(wbuf) / sizeof(*wbuf);
  3398. wbuflen = swprintf(wbuf, wbuflen, L"%lc", (wint_t)w);
  3399. waddnwstr(win, wbuf, wbuflen);
  3400. #else
  3401. wprintw(win, "%lc", (wint_t)w);
  3402. #endif
  3403. }
  3404. }
  3405. }
  3406. }
  3407. static inline
  3408. void bfg_hline(WINDOW *win, int y)
  3409. {
  3410. int maxx, __maybe_unused maxy;
  3411. getmaxyx(win, maxy, maxx);
  3412. #ifdef USE_UNICODE
  3413. if (use_unicode)
  3414. mvwhline_set(win, y, 0, WACS_HLINE, maxx);
  3415. else
  3416. #endif
  3417. mvwhline(win, y, 0, '-', maxx);
  3418. }
  3419. // Spaces until end of line, using current attributes (ie, not completely clear)
  3420. static
  3421. void bfg_wspctoeol(WINDOW * const win, const int offset)
  3422. {
  3423. int x, maxx;
  3424. int __maybe_unused y;
  3425. getmaxyx(win, y, maxx);
  3426. getyx(win, y, x);
  3427. const int space_count = (maxx - x) - offset;
  3428. // Check for negative - terminal too narrow
  3429. if (space_count <= 0)
  3430. return;
  3431. char buf[space_count];
  3432. memset(buf, ' ', space_count);
  3433. waddnstr(win, buf, space_count);
  3434. }
  3435. static int menu_attr = A_REVERSE;
  3436. #define CURBUFSIZ 256
  3437. #define cg_mvwprintw(win, y, x, fmt, ...) do { \
  3438. char tmp42[CURBUFSIZ]; \
  3439. snprintf(tmp42, sizeof(tmp42), fmt, ##__VA_ARGS__); \
  3440. wmove(win, y, x); \
  3441. bfg_waddstr(win, tmp42); \
  3442. } while (0)
  3443. #define cg_wprintw(win, fmt, ...) do { \
  3444. char tmp42[CURBUFSIZ]; \
  3445. snprintf(tmp42, sizeof(tmp42), fmt, ##__VA_ARGS__); \
  3446. bfg_waddstr(win, tmp42); \
  3447. } while (0)
  3448. static bool pool_unworkable(const struct pool *);
  3449. /* Must be called with curses mutex lock held and curses_active */
  3450. static void curses_print_status(const int ts)
  3451. {
  3452. struct pool *pool = currentpool;
  3453. struct timeval now, tv;
  3454. float efficiency;
  3455. double income;
  3456. int logdiv;
  3457. efficiency = total_bytes_xfer ? total_diff_accepted * 2048. / total_bytes_xfer : 0.0;
  3458. wattron(statuswin, attr_title);
  3459. cg_mvwprintw(statuswin, 0, 0, " " PACKAGE " version " VERSION " - Started: %s", datestamp);
  3460. timer_set_now(&now);
  3461. {
  3462. unsigned int days, hours;
  3463. div_t d;
  3464. timersub(&now, &miner_started, &tv);
  3465. d = div(tv.tv_sec, 86400);
  3466. days = d.quot;
  3467. d = div(d.rem, 3600);
  3468. hours = d.quot;
  3469. d = div(d.rem, 60);
  3470. cg_wprintw(statuswin, " - [%3u day%c %02d:%02d:%02d]"
  3471. , days
  3472. , (days == 1) ? ' ' : 's'
  3473. , hours
  3474. , d.quot
  3475. , d.rem
  3476. );
  3477. }
  3478. bfg_wspctoeol(statuswin, 0);
  3479. wattroff(statuswin, attr_title);
  3480. wattron(statuswin, menu_attr);
  3481. wmove(statuswin, 1, 0);
  3482. bfg_waddstr(statuswin, " [M]anage devices [P]ool management [S]ettings [D]isplay options ");
  3483. bfg_wspctoeol(statuswin, 14);
  3484. bfg_waddstr(statuswin, "[H]elp [Q]uit ");
  3485. wattroff(statuswin, menu_attr);
  3486. if ((pool_strategy == POOL_LOADBALANCE || pool_strategy == POOL_BALANCE) && enabled_pools > 1) {
  3487. char poolinfo[20], poolinfo2[20];
  3488. int poolinfooff = 0, poolinfo2off, workable_pools = 0;
  3489. double lowdiff = DBL_MAX, highdiff = -1;
  3490. struct pool *lowdiff_pool = pools[0], *highdiff_pool = pools[0];
  3491. time_t oldest_work_restart = time(NULL) + 1;
  3492. struct pool *oldest_work_restart_pool = pools[0];
  3493. for (int i = 0; i < total_pools; ++i)
  3494. {
  3495. if (pool_unworkable(pools[i]))
  3496. continue;
  3497. // NOTE: Only set pool var when it's workable; if only one is, it gets used by single-pool code
  3498. pool = pools[i];
  3499. ++workable_pools;
  3500. if (poolinfooff < sizeof(poolinfo))
  3501. poolinfooff += snprintf(&poolinfo[poolinfooff], sizeof(poolinfo) - poolinfooff, "%u,", pool->pool_no);
  3502. struct cgminer_pool_stats * const pool_stats = &pool->cgminer_pool_stats;
  3503. if (pool_stats->last_diff < lowdiff)
  3504. {
  3505. lowdiff = pool_stats->last_diff;
  3506. lowdiff_pool = pool;
  3507. }
  3508. if (pool_stats->last_diff > highdiff)
  3509. {
  3510. highdiff = pool_stats->last_diff;
  3511. highdiff_pool = pool;
  3512. }
  3513. if (oldest_work_restart >= pool->work_restart_time)
  3514. {
  3515. oldest_work_restart = pool->work_restart_time;
  3516. oldest_work_restart_pool = pool;
  3517. }
  3518. }
  3519. if (workable_pools == 1)
  3520. goto one_workable_pool;
  3521. poolinfo2off = snprintf(poolinfo2, sizeof(poolinfo2), "%u (", workable_pools);
  3522. if (poolinfooff > sizeof(poolinfo2) - poolinfo2off - 1)
  3523. snprintf(&poolinfo2[poolinfo2off], sizeof(poolinfo2) - poolinfo2off, "%.*s...)", (int)(sizeof(poolinfo2) - poolinfo2off - 5), poolinfo);
  3524. else
  3525. snprintf(&poolinfo2[poolinfo2off], sizeof(poolinfo2) - poolinfo2off, "%.*s)%*s", (int)(poolinfooff - 1), poolinfo, (int)(sizeof(poolinfo2)), "");
  3526. cg_mvwprintw(statuswin, 2, 0, " Pools: %s Diff:%s%s%s %c LU:%s",
  3527. poolinfo2,
  3528. lowdiff_pool->diff,
  3529. (lowdiff == highdiff) ? "" : "-",
  3530. (lowdiff == highdiff) ? "" : highdiff_pool->diff,
  3531. have_longpoll ? '+' : '-',
  3532. oldest_work_restart_pool->work_restart_timestamp);
  3533. }
  3534. else
  3535. {
  3536. one_workable_pool: ;
  3537. char pooladdr[19];
  3538. {
  3539. const char *rawaddr = pool->sockaddr_url;
  3540. BFGINIT(rawaddr, pool->rpc_url);
  3541. size_t pooladdrlen = strlen(rawaddr);
  3542. if (pooladdrlen > 20)
  3543. snprintf(pooladdr, sizeof(pooladdr), "...%s", &rawaddr[pooladdrlen - (sizeof(pooladdr) - 4)]);
  3544. else
  3545. snprintf(pooladdr, sizeof(pooladdr), "%*s", -(int)(sizeof(pooladdr) - 1), rawaddr);
  3546. }
  3547. cg_mvwprintw(statuswin, 2, 0, " Pool%2u: %s Diff:%s %c%s LU:%s User:%s",
  3548. pool->pool_no, pooladdr, pool->diff,
  3549. have_longpoll ? '+' : '-', pool_proto_str(pool),
  3550. pool->work_restart_timestamp,
  3551. pool->rpc_user);
  3552. }
  3553. wclrtoeol(statuswin);
  3554. cg_mvwprintw(statuswin, 3, 0, " Block: %s Diff:%s (%s) Started: %s",
  3555. current_hash, block_diff, net_hashrate, blocktime);
  3556. income = total_diff_accepted * 3600 * block_subsidy / total_secs / current_diff;
  3557. char bwstr[(ALLOC_H2B_SHORT*2)+3+1], incomestr[ALLOC_H2B_SHORT+6+1];
  3558. format_unit3(incomestr, sizeof(incomestr), FUP_BTC, "BTC/hr", H2B_SHORT, income/1e8, -1);
  3559. cg_mvwprintw(statuswin, 4, 0, " ST:%d F:%d NB:%d AS:%d BW:[%s] E:%.2f I:%s BS:%s",
  3560. ts,
  3561. total_go + total_ro,
  3562. new_blocks,
  3563. total_submitting,
  3564. multi_format_unit2(bwstr, sizeof(bwstr),
  3565. false, "B/s", H2B_SHORT, "/", 2,
  3566. (float)(total_bytes_rcvd / total_secs),
  3567. (float)(total_bytes_sent / total_secs)),
  3568. efficiency,
  3569. incomestr,
  3570. best_share);
  3571. wclrtoeol(statuswin);
  3572. mvwaddstr(statuswin, 5, 0, " ");
  3573. bfg_waddstr(statuswin, statusline);
  3574. wclrtoeol(statuswin);
  3575. logdiv = statusy - 1;
  3576. bfg_hline(statuswin, 6);
  3577. bfg_hline(statuswin, logdiv);
  3578. #ifdef USE_UNICODE
  3579. if (use_unicode)
  3580. {
  3581. int offset = 8 /* device */ + 5 /* temperature */ + 1 /* padding space */;
  3582. if (opt_show_procs && !opt_compact)
  3583. ++offset; // proc letter
  3584. if (have_unicode_degrees)
  3585. ++offset; // degrees symbol
  3586. mvwadd_wch(statuswin, 6, offset, WACS_PLUS);
  3587. mvwadd_wch(statuswin, logdiv, offset, WACS_BTEE);
  3588. offset += 24; // hashrates etc
  3589. mvwadd_wch(statuswin, 6, offset, WACS_PLUS);
  3590. mvwadd_wch(statuswin, logdiv, offset, WACS_BTEE);
  3591. }
  3592. #endif
  3593. }
  3594. static void adj_width(int var, int *length)
  3595. {
  3596. if ((int)(log10(var) + 1) > *length)
  3597. (*length)++;
  3598. }
  3599. static int dev_width;
  3600. static void curses_print_devstatus(struct cgpu_info *cgpu)
  3601. {
  3602. char logline[256];
  3603. int ypos;
  3604. if (opt_compact)
  3605. return;
  3606. /* Check this isn't out of the window size */
  3607. if (opt_show_procs)
  3608. ypos = cgpu->cgminer_id;
  3609. else
  3610. {
  3611. if (cgpu->proc_id)
  3612. return;
  3613. ypos = cgpu->device_line_id;
  3614. }
  3615. ypos += devsummaryYOffset;
  3616. if (ypos < 0)
  3617. return;
  3618. ypos += devcursor - 1;
  3619. if (ypos >= statusy - 1)
  3620. return;
  3621. if (wmove(statuswin, ypos, 0) == ERR)
  3622. return;
  3623. get_statline2(logline, sizeof(logline), cgpu, true);
  3624. if (selecting_device && (opt_show_procs ? (selected_device == cgpu->cgminer_id) : (devices[selected_device]->device == cgpu)))
  3625. wattron(statuswin, A_REVERSE);
  3626. bfg_waddstr(statuswin, logline);
  3627. wattroff(statuswin, A_REVERSE);
  3628. wclrtoeol(statuswin);
  3629. }
  3630. static
  3631. void _refresh_devstatus(const bool already_have_lock) {
  3632. if ((!opt_compact) && (already_have_lock || curses_active_locked())) {
  3633. int i;
  3634. if (unlikely(!total_devices))
  3635. {
  3636. const int ypos = devcursor - 1;
  3637. if (ypos < statusy - 1 && wmove(statuswin, ypos, 0) != ERR)
  3638. {
  3639. wattron(statuswin, attr_bad);
  3640. bfg_waddstr(statuswin, "NO DEVICES FOUND: Press 'M' and '+' to add");
  3641. wclrtoeol(statuswin);
  3642. wattroff(statuswin, attr_bad);
  3643. }
  3644. }
  3645. for (i = 0; i < total_devices; i++)
  3646. curses_print_devstatus(get_devices(i));
  3647. touchwin(statuswin);
  3648. wrefresh(statuswin);
  3649. if (!already_have_lock)
  3650. unlock_curses();
  3651. }
  3652. }
  3653. #define refresh_devstatus() _refresh_devstatus(false)
  3654. #endif
  3655. static void print_status(int thr_id)
  3656. {
  3657. if (!curses_active)
  3658. text_print_status(thr_id);
  3659. }
  3660. #ifdef HAVE_CURSES
  3661. static
  3662. bool set_statusy(int maxy)
  3663. {
  3664. if (loginput_size)
  3665. {
  3666. maxy -= loginput_size;
  3667. if (maxy < 0)
  3668. maxy = 0;
  3669. }
  3670. if (logstart < maxy)
  3671. maxy = logstart;
  3672. if (statusy == maxy)
  3673. return false;
  3674. statusy = maxy;
  3675. logcursor = statusy;
  3676. return true;
  3677. }
  3678. /* Check for window resize. Called with curses mutex locked */
  3679. static inline void change_logwinsize(void)
  3680. {
  3681. int x, y, logx, logy;
  3682. getmaxyx(mainwin, y, x);
  3683. if (x < 80 || y < 25)
  3684. return;
  3685. if (y > statusy + 2 && statusy < logstart) {
  3686. set_statusy(y - 2);
  3687. mvwin(logwin, logcursor, 0);
  3688. bfg_wresize(statuswin, statusy, x);
  3689. }
  3690. y -= logcursor;
  3691. getmaxyx(logwin, logy, logx);
  3692. /* Detect screen size change */
  3693. if (x != logx || y != logy)
  3694. bfg_wresize(logwin, y, x);
  3695. }
  3696. static void check_winsizes(void)
  3697. {
  3698. if (!use_curses)
  3699. return;
  3700. if (curses_active_locked()) {
  3701. int y, x;
  3702. x = getmaxx(statuswin);
  3703. if (set_statusy(LINES - 2))
  3704. {
  3705. erase();
  3706. bfg_wresize(statuswin, statusy, x);
  3707. getmaxyx(mainwin, y, x);
  3708. y -= logcursor;
  3709. bfg_wresize(logwin, y, x);
  3710. mvwin(logwin, logcursor, 0);
  3711. }
  3712. unlock_curses();
  3713. }
  3714. }
  3715. static int device_line_id_count;
  3716. static void switch_logsize(void)
  3717. {
  3718. if (curses_active_locked()) {
  3719. if (opt_compact) {
  3720. logstart = devcursor - 1;
  3721. logcursor = logstart + 1;
  3722. } else {
  3723. total_lines = (opt_show_procs ? total_devices : device_line_id_count) ?: 1;
  3724. logstart = devcursor + total_lines;
  3725. logcursor = logstart;
  3726. }
  3727. unlock_curses();
  3728. }
  3729. check_winsizes();
  3730. }
  3731. /* For mandatory printing when mutex is already locked */
  3732. void _wlog(const char *str)
  3733. {
  3734. static bool newline;
  3735. size_t end = strlen(str) - 1;
  3736. if (newline)
  3737. bfg_waddstr(logwin, "\n");
  3738. if (str[end] == '\n')
  3739. {
  3740. char *s;
  3741. newline = true;
  3742. s = alloca(end + 1);
  3743. memcpy(s, str, end);
  3744. s[end] = '\0';
  3745. str = s;
  3746. }
  3747. else
  3748. newline = false;
  3749. bfg_waddstr(logwin, str);
  3750. }
  3751. /* Mandatory printing */
  3752. void _wlogprint(const char *str)
  3753. {
  3754. if (curses_active_locked()) {
  3755. _wlog(str);
  3756. unlock_curses();
  3757. }
  3758. }
  3759. #endif
  3760. #ifdef HAVE_CURSES
  3761. bool _log_curses_only(int prio, const char *datetime, const char *str)
  3762. {
  3763. bool high_prio;
  3764. high_prio = (prio == LOG_WARNING || prio == LOG_ERR);
  3765. if (curses_active)
  3766. {
  3767. if (!loginput_size || high_prio) {
  3768. wlog(" %s %s\n", datetime, str);
  3769. if (high_prio) {
  3770. touchwin(logwin);
  3771. wrefresh(logwin);
  3772. }
  3773. }
  3774. return true;
  3775. }
  3776. return false;
  3777. }
  3778. void clear_logwin(void)
  3779. {
  3780. if (curses_active_locked()) {
  3781. wclear(logwin);
  3782. unlock_curses();
  3783. }
  3784. }
  3785. void logwin_update(void)
  3786. {
  3787. if (curses_active_locked()) {
  3788. touchwin(logwin);
  3789. wrefresh(logwin);
  3790. unlock_curses();
  3791. }
  3792. }
  3793. #endif
  3794. static void enable_pool(struct pool *pool)
  3795. {
  3796. if (pool->enabled != POOL_ENABLED) {
  3797. enabled_pools++;
  3798. pool->enabled = POOL_ENABLED;
  3799. }
  3800. }
  3801. #ifdef HAVE_CURSES
  3802. static void disable_pool(struct pool *pool)
  3803. {
  3804. if (pool->enabled == POOL_ENABLED)
  3805. enabled_pools--;
  3806. pool->enabled = POOL_DISABLED;
  3807. }
  3808. #endif
  3809. static void reject_pool(struct pool *pool)
  3810. {
  3811. if (pool->enabled == POOL_ENABLED)
  3812. enabled_pools--;
  3813. pool->enabled = POOL_REJECTING;
  3814. }
  3815. static double share_diff(const struct work *);
  3816. static
  3817. void share_result_msg(const struct work *work, const char *disp, const char *reason, bool resubmit, const char *worktime) {
  3818. struct cgpu_info *cgpu;
  3819. const unsigned char *hashpart = &work->hash[opt_scrypt ? 26 : 24];
  3820. char shrdiffdisp[ALLOC_H2B_SHORTV];
  3821. const double tgtdiff = work->work_difficulty;
  3822. char tgtdiffdisp[ALLOC_H2B_SHORTV];
  3823. char where[20];
  3824. cgpu = get_thr_cgpu(work->thr_id);
  3825. suffix_string(work->share_diff, shrdiffdisp, sizeof(shrdiffdisp), 0);
  3826. suffix_string(tgtdiff, tgtdiffdisp, sizeof(tgtdiffdisp), 0);
  3827. if (total_pools > 1)
  3828. snprintf(where, sizeof(where), " pool %d", work->pool->pool_no);
  3829. else
  3830. where[0] = '\0';
  3831. applog(LOG_NOTICE, "%s %02x%02x%02x%02x %"PRIprepr"%s Diff %s/%s%s %s%s",
  3832. disp,
  3833. (unsigned)hashpart[3], (unsigned)hashpart[2], (unsigned)hashpart[1], (unsigned)hashpart[0],
  3834. cgpu->proc_repr,
  3835. where,
  3836. shrdiffdisp, tgtdiffdisp,
  3837. reason,
  3838. resubmit ? "(resubmit)" : "",
  3839. worktime
  3840. );
  3841. }
  3842. static bool test_work_current(struct work *);
  3843. static void _submit_work_async(struct work *);
  3844. static
  3845. void maybe_local_submit(const struct work *work)
  3846. {
  3847. #if BLKMAKER_VERSION > 3
  3848. if (unlikely(work->block && work->tr))
  3849. {
  3850. // This is a block with a full template (GBT)
  3851. // Regardless of the result, submit to local bitcoind(s) as well
  3852. struct work *work_cp;
  3853. char *p;
  3854. for (int i = 0; i < total_pools; ++i)
  3855. {
  3856. p = strchr(pools[i]->rpc_url, '#');
  3857. if (likely(!(p && strstr(&p[1], "allblocks"))))
  3858. continue;
  3859. applog(LOG_DEBUG, "Attempting submission of full block to pool %d", pools[i]->pool_no);
  3860. work_cp = copy_work(work);
  3861. work_cp->pool = pools[i];
  3862. work_cp->do_foreign_submit = true;
  3863. _submit_work_async(work_cp);
  3864. }
  3865. }
  3866. #endif
  3867. }
  3868. /* Theoretically threads could race when modifying accepted and
  3869. * rejected values but the chance of two submits completing at the
  3870. * same time is zero so there is no point adding extra locking */
  3871. static void
  3872. share_result(json_t *val, json_t *res, json_t *err, const struct work *work,
  3873. /*char *hashshow,*/ bool resubmit, char *worktime)
  3874. {
  3875. struct pool *pool = work->pool;
  3876. struct cgpu_info *cgpu;
  3877. cgpu = get_thr_cgpu(work->thr_id);
  3878. if ((json_is_null(err) || !err) && (json_is_null(res) || json_is_true(res))) {
  3879. mutex_lock(&stats_lock);
  3880. cgpu->accepted++;
  3881. total_accepted++;
  3882. pool->accepted++;
  3883. cgpu->diff_accepted += work->work_difficulty;
  3884. total_diff_accepted += work->work_difficulty;
  3885. pool->diff_accepted += work->work_difficulty;
  3886. mutex_unlock(&stats_lock);
  3887. pool->seq_rejects = 0;
  3888. cgpu->last_share_pool = pool->pool_no;
  3889. cgpu->last_share_pool_time = time(NULL);
  3890. cgpu->last_share_diff = work->work_difficulty;
  3891. pool->last_share_time = cgpu->last_share_pool_time;
  3892. pool->last_share_diff = work->work_difficulty;
  3893. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  3894. if (!QUIET) {
  3895. share_result_msg(work, "Accepted", "", resubmit, worktime);
  3896. }
  3897. sharelog("accept", work);
  3898. if (opt_shares && total_diff_accepted >= opt_shares) {
  3899. applog(LOG_WARNING, "Successfully mined %g accepted shares as requested and exiting.", opt_shares);
  3900. kill_work();
  3901. return;
  3902. }
  3903. /* Detect if a pool that has been temporarily disabled for
  3904. * continually rejecting shares has started accepting shares.
  3905. * This will only happen with the work returned from a
  3906. * longpoll */
  3907. if (unlikely(pool->enabled == POOL_REJECTING)) {
  3908. applog(LOG_WARNING, "Rejecting pool %d now accepting shares, re-enabling!", pool->pool_no);
  3909. enable_pool(pool);
  3910. switch_pools(NULL);
  3911. }
  3912. if (unlikely(work->block)) {
  3913. // Force moving on to this new block :)
  3914. struct work fakework;
  3915. memset(&fakework, 0, sizeof(fakework));
  3916. fakework.pool = work->pool;
  3917. // Copy block version, bits, and time from share
  3918. memcpy(&fakework.data[ 0], &work->data[ 0], 4);
  3919. memcpy(&fakework.data[68], &work->data[68], 8);
  3920. // Set prevblock to winning hash (swap32'd)
  3921. swap32yes(&fakework.data[4], &work->hash[0], 32 / 4);
  3922. test_work_current(&fakework);
  3923. }
  3924. } else {
  3925. mutex_lock(&stats_lock);
  3926. cgpu->rejected++;
  3927. total_rejected++;
  3928. pool->rejected++;
  3929. cgpu->diff_rejected += work->work_difficulty;
  3930. total_diff_rejected += work->work_difficulty;
  3931. pool->diff_rejected += work->work_difficulty;
  3932. pool->seq_rejects++;
  3933. mutex_unlock(&stats_lock);
  3934. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  3935. if (!QUIET) {
  3936. char where[20];
  3937. char disposition[36] = "reject";
  3938. char reason[32];
  3939. strcpy(reason, "");
  3940. if (total_pools > 1)
  3941. snprintf(where, sizeof(where), "pool %d", work->pool->pool_no);
  3942. else
  3943. strcpy(where, "");
  3944. if (!json_is_string(res))
  3945. res = json_object_get(val, "reject-reason");
  3946. if (res) {
  3947. const char *reasontmp = json_string_value(res);
  3948. size_t reasonLen = strlen(reasontmp);
  3949. if (reasonLen > 28)
  3950. reasonLen = 28;
  3951. reason[0] = ' '; reason[1] = '(';
  3952. memcpy(2 + reason, reasontmp, reasonLen);
  3953. reason[reasonLen + 2] = ')'; reason[reasonLen + 3] = '\0';
  3954. memcpy(disposition + 7, reasontmp, reasonLen);
  3955. disposition[6] = ':'; disposition[reasonLen + 7] = '\0';
  3956. } else if (work->stratum && err && json_is_array(err)) {
  3957. json_t *reason_val = json_array_get(err, 1);
  3958. char *reason_str;
  3959. if (reason_val && json_is_string(reason_val)) {
  3960. reason_str = (char *)json_string_value(reason_val);
  3961. snprintf(reason, 31, " (%s)", reason_str);
  3962. }
  3963. }
  3964. share_result_msg(work, "Rejected", reason, resubmit, worktime);
  3965. sharelog(disposition, work);
  3966. }
  3967. /* Once we have more than a nominal amount of sequential rejects,
  3968. * at least 10 and more than 3 mins at the current utility,
  3969. * disable the pool because some pool error is likely to have
  3970. * ensued. Do not do this if we know the share just happened to
  3971. * be stale due to networking delays.
  3972. */
  3973. if (pool->seq_rejects > 10 && !work->stale && opt_disable_pool && enabled_pools > 1) {
  3974. double utility = total_accepted / total_secs * 60;
  3975. if (pool->seq_rejects > utility * 3) {
  3976. applog(LOG_WARNING, "Pool %d rejected %d sequential shares, disabling!",
  3977. pool->pool_no, pool->seq_rejects);
  3978. reject_pool(pool);
  3979. if (pool == current_pool())
  3980. switch_pools(NULL);
  3981. pool->seq_rejects = 0;
  3982. }
  3983. }
  3984. }
  3985. maybe_local_submit(work);
  3986. }
  3987. static char *submit_upstream_work_request(struct work *work)
  3988. {
  3989. char *hexstr = NULL;
  3990. char *s, *sd;
  3991. struct pool *pool = work->pool;
  3992. if (work->tr)
  3993. {
  3994. blktemplate_t * const tmpl = work->tr->tmpl;
  3995. json_t *req;
  3996. unsigned char data[80];
  3997. swap32yes(data, work->data, 80 / 4);
  3998. #if BLKMAKER_VERSION > 3
  3999. if (work->do_foreign_submit)
  4000. req = blkmk_submit_foreign_jansson(tmpl, data, work->dataid, le32toh(*((uint32_t*)&work->data[76])));
  4001. else
  4002. #endif
  4003. req = blkmk_submit_jansson(tmpl, data, work->dataid, le32toh(*((uint32_t*)&work->data[76])));
  4004. s = json_dumps(req, 0);
  4005. json_decref(req);
  4006. sd = malloc(161);
  4007. bin2hex(sd, data, 80);
  4008. } else {
  4009. /* build hex string */
  4010. hexstr = malloc((sizeof(work->data) * 2) + 1);
  4011. bin2hex(hexstr, work->data, sizeof(work->data));
  4012. /* build JSON-RPC request */
  4013. s = strdup("{\"method\": \"getwork\", \"params\": [ \"");
  4014. s = realloc_strcat(s, hexstr);
  4015. s = realloc_strcat(s, "\" ], \"id\":1}");
  4016. free(hexstr);
  4017. sd = s;
  4018. }
  4019. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->rpc_url, sd);
  4020. if (work->tr)
  4021. free(sd);
  4022. else
  4023. s = realloc_strcat(s, "\n");
  4024. return s;
  4025. }
  4026. static bool submit_upstream_work_completed(struct work *work, bool resubmit, struct timeval *ptv_submit, json_t *val) {
  4027. json_t *res, *err;
  4028. bool rc = false;
  4029. int thr_id = work->thr_id;
  4030. struct pool *pool = work->pool;
  4031. struct timeval tv_submit_reply;
  4032. time_t ts_submit_reply;
  4033. char worktime[200] = "";
  4034. cgtime(&tv_submit_reply);
  4035. ts_submit_reply = time(NULL);
  4036. if (unlikely(!val)) {
  4037. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  4038. if (!pool_tset(pool, &pool->submit_fail)) {
  4039. total_ro++;
  4040. pool->remotefail_occasions++;
  4041. applog(LOG_WARNING, "Pool %d communication failure, caching submissions", pool->pool_no);
  4042. }
  4043. goto out;
  4044. } else if (pool_tclear(pool, &pool->submit_fail))
  4045. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  4046. res = json_object_get(val, "result");
  4047. err = json_object_get(val, "error");
  4048. if (!QUIET) {
  4049. if (opt_worktime) {
  4050. char workclone[20];
  4051. struct tm _tm;
  4052. struct tm *tm, tm_getwork, tm_submit_reply;
  4053. tm = &_tm;
  4054. double getwork_time = tdiff((struct timeval *)&(work->tv_getwork_reply),
  4055. (struct timeval *)&(work->tv_getwork));
  4056. double getwork_to_work = tdiff((struct timeval *)&(work->tv_work_start),
  4057. (struct timeval *)&(work->tv_getwork_reply));
  4058. double work_time = tdiff((struct timeval *)&(work->tv_work_found),
  4059. (struct timeval *)&(work->tv_work_start));
  4060. double work_to_submit = tdiff(ptv_submit,
  4061. (struct timeval *)&(work->tv_work_found));
  4062. double submit_time = tdiff(&tv_submit_reply, ptv_submit);
  4063. int diffplaces = 3;
  4064. localtime_r(&work->ts_getwork, tm);
  4065. memcpy(&tm_getwork, tm, sizeof(struct tm));
  4066. localtime_r(&ts_submit_reply, tm);
  4067. memcpy(&tm_submit_reply, tm, sizeof(struct tm));
  4068. if (work->clone) {
  4069. snprintf(workclone, sizeof(workclone), "C:%1.3f",
  4070. tdiff((struct timeval *)&(work->tv_cloned),
  4071. (struct timeval *)&(work->tv_getwork_reply)));
  4072. }
  4073. else
  4074. strcpy(workclone, "O");
  4075. if (work->work_difficulty < 1)
  4076. diffplaces = 6;
  4077. snprintf(worktime, sizeof(worktime),
  4078. " <-%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",
  4079. (unsigned long)be32toh(*(uint32_t *)&(work->data[opt_scrypt ? 32 : 28])),
  4080. (unsigned long)be32toh(*(uint32_t *)&(work->data[opt_scrypt ? 28 : 24])),
  4081. work->getwork_mode, diffplaces, work->work_difficulty,
  4082. tm_getwork.tm_hour, tm_getwork.tm_min,
  4083. tm_getwork.tm_sec, getwork_time, workclone,
  4084. getwork_to_work, work_time, work_to_submit, submit_time,
  4085. tm_submit_reply.tm_hour, tm_submit_reply.tm_min,
  4086. tm_submit_reply.tm_sec);
  4087. }
  4088. }
  4089. share_result(val, res, err, work, resubmit, worktime);
  4090. if (!opt_realquiet)
  4091. print_status(thr_id);
  4092. if (!want_per_device_stats) {
  4093. char logline[256];
  4094. struct cgpu_info *cgpu;
  4095. cgpu = get_thr_cgpu(thr_id);
  4096. get_statline(logline, sizeof(logline), cgpu);
  4097. applog(LOG_INFO, "%s", logline);
  4098. }
  4099. json_decref(val);
  4100. rc = true;
  4101. out:
  4102. return rc;
  4103. }
  4104. /* Specifies whether we can use this pool for work or not. */
  4105. static bool pool_unworkable(const struct pool * const pool)
  4106. {
  4107. if (pool->idle)
  4108. return true;
  4109. if (pool->enabled != POOL_ENABLED)
  4110. return true;
  4111. if (pool->has_stratum && !pool->stratum_active)
  4112. return true;
  4113. return false;
  4114. }
  4115. static
  4116. bool pool_actively_desired(const struct pool * const pool, const struct pool *cp)
  4117. {
  4118. if (pool->enabled != POOL_ENABLED)
  4119. return false;
  4120. if (pool_strategy == POOL_LOADBALANCE || pool_strategy == POOL_BALANCE)
  4121. return true;
  4122. if (!cp)
  4123. cp = current_pool();
  4124. return (pool == cp);
  4125. }
  4126. static
  4127. bool pool_actively_in_use(const struct pool * const pool, const struct pool *cp)
  4128. {
  4129. return (!pool_unworkable(pool)) && pool_actively_desired(pool, cp);
  4130. }
  4131. /* In balanced mode, the amount of diff1 solutions per pool is monitored as a
  4132. * rolling average per 10 minutes and if pools start getting more, it biases
  4133. * away from them to distribute work evenly. The share count is reset to the
  4134. * rolling average every 10 minutes to not send all work to one pool after it
  4135. * has been disabled/out for an extended period. */
  4136. static struct pool *select_balanced(struct pool *cp)
  4137. {
  4138. int i, lowest = cp->shares;
  4139. struct pool *ret = cp;
  4140. for (i = 0; i < total_pools; i++) {
  4141. struct pool *pool = pools[i];
  4142. if (pool_unworkable(pool))
  4143. continue;
  4144. if (pool->shares < lowest) {
  4145. lowest = pool->shares;
  4146. ret = pool;
  4147. }
  4148. }
  4149. ret->shares++;
  4150. return ret;
  4151. }
  4152. static bool pool_active(struct pool *, bool pinging);
  4153. static void pool_died(struct pool *);
  4154. static struct pool *priority_pool(int choice);
  4155. static bool pool_unusable(struct pool *pool);
  4156. /* Select any active pool in a rotating fashion when loadbalance is chosen if
  4157. * it has any quota left. */
  4158. static inline struct pool *select_pool(bool lagging)
  4159. {
  4160. static int rotating_pool = 0;
  4161. struct pool *pool, *cp;
  4162. bool avail = false;
  4163. int tested, i;
  4164. cp = current_pool();
  4165. retry:
  4166. if (pool_strategy == POOL_BALANCE) {
  4167. pool = select_balanced(cp);
  4168. goto out;
  4169. }
  4170. if (pool_strategy != POOL_LOADBALANCE && (!lagging || opt_fail_only)) {
  4171. pool = cp;
  4172. goto out;
  4173. } else
  4174. pool = NULL;
  4175. for (i = 0; i < total_pools; i++) {
  4176. struct pool *tp = pools[i];
  4177. if (tp->quota_used < tp->quota_gcd) {
  4178. avail = true;
  4179. break;
  4180. }
  4181. }
  4182. /* There are no pools with quota, so reset them. */
  4183. if (!avail) {
  4184. for (i = 0; i < total_pools; i++)
  4185. pools[i]->quota_used = 0;
  4186. if (++rotating_pool >= total_pools)
  4187. rotating_pool = 0;
  4188. }
  4189. /* Try to find the first pool in the rotation that is usable */
  4190. tested = 0;
  4191. while (!pool && tested++ < total_pools) {
  4192. pool = pools[rotating_pool];
  4193. if (pool->quota_used++ < pool->quota_gcd) {
  4194. if (!pool_unworkable(pool))
  4195. break;
  4196. /* Failover-only flag for load-balance means distribute
  4197. * unused quota to priority pool 0. */
  4198. if (opt_fail_only)
  4199. priority_pool(0)->quota_used--;
  4200. }
  4201. pool = NULL;
  4202. if (++rotating_pool >= total_pools)
  4203. rotating_pool = 0;
  4204. }
  4205. /* If there are no alive pools with quota, choose according to
  4206. * priority. */
  4207. if (!pool) {
  4208. for (i = 0; i < total_pools; i++) {
  4209. struct pool *tp = priority_pool(i);
  4210. if (!pool_unusable(tp)) {
  4211. pool = tp;
  4212. break;
  4213. }
  4214. }
  4215. }
  4216. /* If still nothing is usable, use the current pool */
  4217. if (!pool)
  4218. pool = cp;
  4219. out:
  4220. if (!pool_actively_in_use(pool, cp))
  4221. {
  4222. if (!pool_active(pool, false))
  4223. {
  4224. pool_died(pool);
  4225. goto retry;
  4226. }
  4227. pool_tclear(pool, &pool->idle);
  4228. }
  4229. applog(LOG_DEBUG, "Selecting pool %d for work", pool->pool_no);
  4230. return pool;
  4231. }
  4232. static double DIFFEXACTONE = 26959946667150639794667015087019630673637144422540572481103610249215.0;
  4233. static const uint64_t diffone = 0xFFFF000000000000ull;
  4234. static double target_diff(const unsigned char *target)
  4235. {
  4236. double targ = 0;
  4237. signed int i;
  4238. for (i = 31; i >= 0; --i)
  4239. targ = (targ * 0x100) + target[i];
  4240. return DIFFEXACTONE / (targ ?: 1);
  4241. }
  4242. /*
  4243. * Calculate the work share difficulty
  4244. */
  4245. static void calc_diff(struct work *work, int known)
  4246. {
  4247. struct cgminer_pool_stats *pool_stats = &(work->pool->cgminer_pool_stats);
  4248. double difficulty;
  4249. if (!known) {
  4250. work->work_difficulty = target_diff(work->target);
  4251. } else
  4252. work->work_difficulty = known;
  4253. difficulty = work->work_difficulty;
  4254. pool_stats->last_diff = difficulty;
  4255. suffix_string(difficulty, work->pool->diff, sizeof(work->pool->diff), 0);
  4256. if (difficulty == pool_stats->min_diff)
  4257. pool_stats->min_diff_count++;
  4258. else if (difficulty < pool_stats->min_diff || pool_stats->min_diff == 0) {
  4259. pool_stats->min_diff = difficulty;
  4260. pool_stats->min_diff_count = 1;
  4261. }
  4262. if (difficulty == pool_stats->max_diff)
  4263. pool_stats->max_diff_count++;
  4264. else if (difficulty > pool_stats->max_diff) {
  4265. pool_stats->max_diff = difficulty;
  4266. pool_stats->max_diff_count = 1;
  4267. }
  4268. }
  4269. static
  4270. void setup_benchmark_pool()
  4271. {
  4272. struct pool *pool;
  4273. want_longpoll = false;
  4274. // Temporarily disable opt_benchmark to avoid auto-removal
  4275. opt_benchmark = false;
  4276. pool = add_pool();
  4277. opt_benchmark = true;
  4278. pool->rpc_url = malloc(255);
  4279. strcpy(pool->rpc_url, "Benchmark");
  4280. pool->rpc_user = pool->rpc_url;
  4281. pool->rpc_pass = pool->rpc_url;
  4282. enable_pool(pool);
  4283. pool->idle = false;
  4284. successful_connect = true;
  4285. }
  4286. void get_benchmark_work(struct work *work)
  4287. {
  4288. static uint32_t blkhdr[20];
  4289. for (int i = 18; i >= 0; --i)
  4290. if (++blkhdr[i])
  4291. break;
  4292. memcpy(&work->data[ 0], blkhdr, 80);
  4293. memcpy(&work->data[80], workpadding_bin, 48);
  4294. calc_midstate(work);
  4295. set_target_to_pdiff(work->target, 1.0);
  4296. work->mandatory = true;
  4297. work->pool = pools[0];
  4298. cgtime(&work->tv_getwork);
  4299. copy_time(&work->tv_getwork_reply, &work->tv_getwork);
  4300. copy_time(&work->tv_staged, &work->tv_getwork);
  4301. work->getwork_mode = GETWORK_MODE_BENCHMARK;
  4302. calc_diff(work, 0);
  4303. work_set_simple_ntime_roll_limit(work, 60);
  4304. }
  4305. static void wake_gws(void);
  4306. static void update_last_work(struct work *work)
  4307. {
  4308. if (!work->tr)
  4309. // Only save GBT jobs, since rollntime isn't coordinated well yet
  4310. return;
  4311. struct pool *pool = work->pool;
  4312. mutex_lock(&pool->last_work_lock);
  4313. if (pool->last_work_copy)
  4314. free_work(pool->last_work_copy);
  4315. pool->last_work_copy = copy_work(work);
  4316. pool->last_work_copy->work_restart_id = pool->work_restart_id;
  4317. mutex_unlock(&pool->last_work_lock);
  4318. }
  4319. static
  4320. void gbt_req_target(json_t *req)
  4321. {
  4322. json_t *j;
  4323. json_t *n;
  4324. if (!request_target_str)
  4325. return;
  4326. j = json_object_get(req, "params");
  4327. if (!j)
  4328. {
  4329. n = json_array();
  4330. if (!n)
  4331. return;
  4332. if (json_object_set_new(req, "params", n))
  4333. goto erradd;
  4334. j = n;
  4335. }
  4336. n = json_array_get(j, 0);
  4337. if (!n)
  4338. {
  4339. n = json_object();
  4340. if (!n)
  4341. return;
  4342. if (json_array_append_new(j, n))
  4343. goto erradd;
  4344. }
  4345. j = n;
  4346. n = json_string(request_target_str);
  4347. if (!n)
  4348. return;
  4349. if (json_object_set_new(j, "target", n))
  4350. goto erradd;
  4351. return;
  4352. erradd:
  4353. json_decref(n);
  4354. }
  4355. static char *prepare_rpc_req2(struct work *work, enum pool_protocol proto, const char *lpid, bool probe)
  4356. {
  4357. char *rpc_req;
  4358. clean_work(work);
  4359. switch (proto) {
  4360. case PLP_GETWORK:
  4361. work->getwork_mode = GETWORK_MODE_POOL;
  4362. return strdup(getwork_req);
  4363. case PLP_GETBLOCKTEMPLATE:
  4364. work->getwork_mode = GETWORK_MODE_GBT;
  4365. blktemplate_t * const tmpl = blktmpl_create();
  4366. if (!tmpl)
  4367. goto gbtfail2;
  4368. work->tr = tmpl_makeref(tmpl);
  4369. gbt_capabilities_t caps = blktmpl_addcaps(tmpl);
  4370. if (!caps)
  4371. goto gbtfail;
  4372. caps |= GBT_LONGPOLL;
  4373. #if BLKMAKER_VERSION > 1
  4374. if (opt_coinbase_script.sz)
  4375. caps |= GBT_CBVALUE;
  4376. #endif
  4377. json_t *req = blktmpl_request_jansson(caps, lpid);
  4378. if (!req)
  4379. goto gbtfail;
  4380. if (probe)
  4381. gbt_req_target(req);
  4382. rpc_req = json_dumps(req, 0);
  4383. if (!rpc_req)
  4384. goto gbtfail;
  4385. json_decref(req);
  4386. return rpc_req;
  4387. default:
  4388. return NULL;
  4389. }
  4390. return NULL;
  4391. gbtfail:
  4392. tmpl_decref(work->tr);
  4393. work->tr = NULL;
  4394. gbtfail2:
  4395. return NULL;
  4396. }
  4397. #define prepare_rpc_req(work, proto, lpid) prepare_rpc_req2(work, proto, lpid, false)
  4398. #define prepare_rpc_req_probe(work, proto, lpid) prepare_rpc_req2(work, proto, lpid, true)
  4399. static const char *pool_protocol_name(enum pool_protocol proto)
  4400. {
  4401. switch (proto) {
  4402. case PLP_GETBLOCKTEMPLATE:
  4403. return "getblocktemplate";
  4404. case PLP_GETWORK:
  4405. return "getwork";
  4406. default:
  4407. return "UNKNOWN";
  4408. }
  4409. }
  4410. static enum pool_protocol pool_protocol_fallback(enum pool_protocol proto)
  4411. {
  4412. switch (proto) {
  4413. case PLP_GETBLOCKTEMPLATE:
  4414. if (want_getwork)
  4415. return PLP_GETWORK;
  4416. default:
  4417. return PLP_NONE;
  4418. }
  4419. }
  4420. static bool get_upstream_work(struct work *work, CURL *curl)
  4421. {
  4422. struct pool *pool = work->pool;
  4423. struct cgminer_pool_stats *pool_stats = &(pool->cgminer_pool_stats);
  4424. struct timeval tv_elapsed;
  4425. json_t *val = NULL;
  4426. bool rc = false;
  4427. char *url;
  4428. enum pool_protocol proto;
  4429. char *rpc_req;
  4430. if (pool->proto == PLP_NONE)
  4431. pool->proto = PLP_GETBLOCKTEMPLATE;
  4432. tryagain:
  4433. rpc_req = prepare_rpc_req(work, pool->proto, NULL);
  4434. work->pool = pool;
  4435. if (!rpc_req)
  4436. return false;
  4437. applog(LOG_DEBUG, "DBG: sending %s get RPC call: %s", pool->rpc_url, rpc_req);
  4438. url = pool->rpc_url;
  4439. cgtime(&work->tv_getwork);
  4440. val = json_rpc_call(curl, url, pool->rpc_userpass, rpc_req, false,
  4441. false, &work->rolltime, pool, false);
  4442. pool_stats->getwork_attempts++;
  4443. free(rpc_req);
  4444. if (likely(val)) {
  4445. rc = work_decode(pool, work, val);
  4446. if (unlikely(!rc))
  4447. applog(LOG_DEBUG, "Failed to decode work in get_upstream_work");
  4448. } else if (PLP_NONE != (proto = pool_protocol_fallback(pool->proto))) {
  4449. applog(LOG_WARNING, "Pool %u failed getblocktemplate request; falling back to getwork protocol", pool->pool_no);
  4450. pool->proto = proto;
  4451. goto tryagain;
  4452. } else
  4453. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  4454. cgtime(&work->tv_getwork_reply);
  4455. timersub(&(work->tv_getwork_reply), &(work->tv_getwork), &tv_elapsed);
  4456. pool_stats->getwork_wait_rolling += ((double)tv_elapsed.tv_sec + ((double)tv_elapsed.tv_usec / 1000000)) * 0.63;
  4457. pool_stats->getwork_wait_rolling /= 1.63;
  4458. timeradd(&tv_elapsed, &(pool_stats->getwork_wait), &(pool_stats->getwork_wait));
  4459. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_max), >)) {
  4460. pool_stats->getwork_wait_max.tv_sec = tv_elapsed.tv_sec;
  4461. pool_stats->getwork_wait_max.tv_usec = tv_elapsed.tv_usec;
  4462. }
  4463. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_min), <)) {
  4464. pool_stats->getwork_wait_min.tv_sec = tv_elapsed.tv_sec;
  4465. pool_stats->getwork_wait_min.tv_usec = tv_elapsed.tv_usec;
  4466. }
  4467. pool_stats->getwork_calls++;
  4468. work->pool = pool;
  4469. work->longpoll = false;
  4470. calc_diff(work, 0);
  4471. total_getworks++;
  4472. pool->getwork_requested++;
  4473. if (rc)
  4474. update_last_work(work);
  4475. if (likely(val))
  4476. json_decref(val);
  4477. return rc;
  4478. }
  4479. #ifdef HAVE_CURSES
  4480. static void disable_curses(void)
  4481. {
  4482. if (curses_active_locked()) {
  4483. use_curses = false;
  4484. curses_active = false;
  4485. leaveok(logwin, false);
  4486. leaveok(statuswin, false);
  4487. leaveok(mainwin, false);
  4488. nocbreak();
  4489. echo();
  4490. delwin(logwin);
  4491. delwin(statuswin);
  4492. delwin(mainwin);
  4493. endwin();
  4494. #ifdef WIN32
  4495. // Move the cursor to after curses output.
  4496. HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
  4497. CONSOLE_SCREEN_BUFFER_INFO csbi;
  4498. COORD coord;
  4499. if (GetConsoleScreenBufferInfo(hout, &csbi)) {
  4500. coord.X = 0;
  4501. coord.Y = csbi.dwSize.Y - 1;
  4502. SetConsoleCursorPosition(hout, coord);
  4503. }
  4504. #endif
  4505. unlock_curses();
  4506. }
  4507. }
  4508. #endif
  4509. static void __kill_work(void)
  4510. {
  4511. struct cgpu_info *cgpu;
  4512. struct thr_info *thr;
  4513. int i;
  4514. if (!successful_connect)
  4515. return;
  4516. applog(LOG_INFO, "Received kill message");
  4517. shutting_down = true;
  4518. applog(LOG_DEBUG, "Prompting submit_work thread to finish");
  4519. notifier_wake(submit_waiting_notifier);
  4520. #ifdef USE_LIBMICROHTTPD
  4521. httpsrv_stop();
  4522. #endif
  4523. applog(LOG_DEBUG, "Killing off watchpool thread");
  4524. /* Kill the watchpool thread */
  4525. thr = &control_thr[watchpool_thr_id];
  4526. thr_info_cancel(thr);
  4527. applog(LOG_DEBUG, "Killing off watchdog thread");
  4528. /* Kill the watchdog thread */
  4529. thr = &control_thr[watchdog_thr_id];
  4530. thr_info_cancel(thr);
  4531. applog(LOG_DEBUG, "Shutting down mining threads");
  4532. for (i = 0; i < mining_threads; i++) {
  4533. thr = get_thread(i);
  4534. if (!thr)
  4535. continue;
  4536. cgpu = thr->cgpu;
  4537. if (!cgpu)
  4538. continue;
  4539. if (!cgpu->threads)
  4540. continue;
  4541. cgpu->shutdown = true;
  4542. thr->work_restart = true;
  4543. notifier_wake(thr->notifier);
  4544. notifier_wake(thr->work_restart_notifier);
  4545. }
  4546. sleep(1);
  4547. applog(LOG_DEBUG, "Killing off mining threads");
  4548. /* Kill the mining threads*/
  4549. for (i = 0; i < mining_threads; i++) {
  4550. thr = get_thread(i);
  4551. if (!thr)
  4552. continue;
  4553. cgpu = thr->cgpu;
  4554. if (cgpu->threads)
  4555. {
  4556. applog(LOG_WARNING, "Killing %"PRIpreprv, thr->cgpu->proc_repr);
  4557. thr_info_cancel(thr);
  4558. }
  4559. cgpu->status = LIFE_DEAD2;
  4560. }
  4561. /* Stop the others */
  4562. applog(LOG_DEBUG, "Killing off API thread");
  4563. thr = &control_thr[api_thr_id];
  4564. thr_info_cancel(thr);
  4565. }
  4566. /* This should be the common exit path */
  4567. void kill_work(void)
  4568. {
  4569. __kill_work();
  4570. quit(0, "Shutdown signal received.");
  4571. }
  4572. static
  4573. #ifdef WIN32
  4574. #ifndef _WIN64
  4575. const
  4576. #endif
  4577. #endif
  4578. char **initial_args;
  4579. void _bfg_clean_up(bool);
  4580. void app_restart(void)
  4581. {
  4582. applog(LOG_WARNING, "Attempting to restart %s", packagename);
  4583. __kill_work();
  4584. _bfg_clean_up(true);
  4585. #if defined(unix) || defined(__APPLE__)
  4586. if (forkpid > 0) {
  4587. kill(forkpid, SIGTERM);
  4588. forkpid = 0;
  4589. }
  4590. #endif
  4591. execv(initial_args[0], initial_args);
  4592. applog(LOG_WARNING, "Failed to restart application");
  4593. }
  4594. static void sighandler(int __maybe_unused sig)
  4595. {
  4596. /* Restore signal handlers so we can still quit if kill_work fails */
  4597. sigaction(SIGTERM, &termhandler, NULL);
  4598. sigaction(SIGINT, &inthandler, NULL);
  4599. kill_work();
  4600. }
  4601. static void start_longpoll(void);
  4602. static void stop_longpoll(void);
  4603. /* Called with pool_lock held. Recruit an extra curl if none are available for
  4604. * this pool. */
  4605. static void recruit_curl(struct pool *pool)
  4606. {
  4607. struct curl_ent *ce = calloc(sizeof(struct curl_ent), 1);
  4608. if (unlikely(!ce))
  4609. quit(1, "Failed to calloc in recruit_curl");
  4610. ce->curl = curl_easy_init();
  4611. if (unlikely(!ce->curl))
  4612. quit(1, "Failed to init in recruit_curl");
  4613. LL_PREPEND(pool->curllist, ce);
  4614. pool->curls++;
  4615. }
  4616. /* Grab an available curl if there is one. If not, then recruit extra curls
  4617. * unless we are in a submit_fail situation, or we have opt_delaynet enabled
  4618. * and there are already 5 curls in circulation. Limit total number to the
  4619. * number of mining threads per pool as well to prevent blasting a pool during
  4620. * network delays/outages. */
  4621. static struct curl_ent *pop_curl_entry3(struct pool *pool, int blocking)
  4622. {
  4623. int curl_limit = opt_delaynet ? 5 : (mining_threads + opt_queue) * 2;
  4624. bool recruited = false;
  4625. struct curl_ent *ce;
  4626. mutex_lock(&pool->pool_lock);
  4627. retry:
  4628. if (!pool->curls) {
  4629. recruit_curl(pool);
  4630. recruited = true;
  4631. } else if (!pool->curllist) {
  4632. if (blocking < 2 && pool->curls >= curl_limit && (blocking || pool->curls >= opt_submit_threads)) {
  4633. if (!blocking) {
  4634. mutex_unlock(&pool->pool_lock);
  4635. return NULL;
  4636. }
  4637. pthread_cond_wait(&pool->cr_cond, &pool->pool_lock);
  4638. goto retry;
  4639. } else {
  4640. recruit_curl(pool);
  4641. recruited = true;
  4642. }
  4643. }
  4644. ce = pool->curllist;
  4645. LL_DELETE(pool->curllist, ce);
  4646. mutex_unlock(&pool->pool_lock);
  4647. if (recruited)
  4648. applog(LOG_DEBUG, "Recruited curl for pool %d", pool->pool_no);
  4649. return ce;
  4650. }
  4651. static struct curl_ent *pop_curl_entry2(struct pool *pool, bool blocking)
  4652. {
  4653. return pop_curl_entry3(pool, blocking ? 1 : 0);
  4654. }
  4655. __maybe_unused
  4656. static struct curl_ent *pop_curl_entry(struct pool *pool)
  4657. {
  4658. return pop_curl_entry3(pool, 1);
  4659. }
  4660. static void push_curl_entry(struct curl_ent *ce, struct pool *pool)
  4661. {
  4662. mutex_lock(&pool->pool_lock);
  4663. if (!ce || !ce->curl)
  4664. quithere(1, "Attempted to add NULL");
  4665. LL_PREPEND(pool->curllist, ce);
  4666. cgtime(&ce->tv);
  4667. pthread_cond_broadcast(&pool->cr_cond);
  4668. mutex_unlock(&pool->pool_lock);
  4669. }
  4670. bool stale_work(struct work *work, bool share);
  4671. static inline bool should_roll(struct work *work)
  4672. {
  4673. struct timeval now;
  4674. time_t expiry;
  4675. if (!pool_actively_in_use(work->pool, NULL))
  4676. return false;
  4677. if (stale_work(work, false))
  4678. return false;
  4679. if (work->rolltime > opt_scantime)
  4680. expiry = work->rolltime;
  4681. else
  4682. expiry = opt_scantime;
  4683. expiry = expiry * 2 / 3;
  4684. /* We shouldn't roll if we're unlikely to get one shares' duration
  4685. * work out of doing so */
  4686. cgtime(&now);
  4687. if (now.tv_sec - work->tv_staged.tv_sec > expiry)
  4688. return false;
  4689. return true;
  4690. }
  4691. /* Limit rolls to 7000 to not beyond 2 hours in the future where bitcoind will
  4692. * reject blocks as invalid. */
  4693. static inline bool can_roll(struct work *work)
  4694. {
  4695. if (work->stratum)
  4696. return false;
  4697. if (!(work->pool && !work->clone))
  4698. return false;
  4699. if (work->tr)
  4700. {
  4701. if (stale_work(work, false))
  4702. return false;
  4703. return blkmk_work_left(work->tr->tmpl);
  4704. }
  4705. return (work->rolltime &&
  4706. work->rolls < 7000 && !stale_work(work, false));
  4707. }
  4708. static void roll_work(struct work *work)
  4709. {
  4710. if (work->tr)
  4711. {
  4712. struct timeval tv_now;
  4713. cgtime(&tv_now);
  4714. if (blkmk_get_data(work->tr->tmpl, work->data, 80, tv_now.tv_sec, NULL, &work->dataid) < 76)
  4715. applog(LOG_ERR, "Failed to get next data from template; spinning wheels!");
  4716. swap32yes(work->data, work->data, 80 / 4);
  4717. calc_midstate(work);
  4718. applog(LOG_DEBUG, "Successfully rolled extranonce to dataid %u", work->dataid);
  4719. } else {
  4720. uint32_t *work_ntime;
  4721. uint32_t ntime;
  4722. work_ntime = (uint32_t *)(work->data + 68);
  4723. ntime = be32toh(*work_ntime);
  4724. ntime++;
  4725. *work_ntime = htobe32(ntime);
  4726. work_set_simple_ntime_roll_limit(work, 0);
  4727. applog(LOG_DEBUG, "Successfully rolled time header in work");
  4728. }
  4729. local_work++;
  4730. work->rolls++;
  4731. work->blk.nonce = 0;
  4732. /* This is now a different work item so it needs a different ID for the
  4733. * hashtable */
  4734. work->id = total_work++;
  4735. }
  4736. /* Duplicates any dynamically allocated arrays within the work struct to
  4737. * prevent a copied work struct from freeing ram belonging to another struct */
  4738. static void _copy_work(struct work *work, const struct work *base_work, int noffset)
  4739. {
  4740. int id = work->id;
  4741. clean_work(work);
  4742. memcpy(work, base_work, sizeof(struct work));
  4743. /* Keep the unique new id assigned during make_work to prevent copied
  4744. * work from having the same id. */
  4745. work->id = id;
  4746. if (base_work->job_id)
  4747. work->job_id = strdup(base_work->job_id);
  4748. if (base_work->nonce1)
  4749. work->nonce1 = strdup(base_work->nonce1);
  4750. bytes_cpy(&work->nonce2, &base_work->nonce2);
  4751. if (base_work->tr)
  4752. tmpl_incref(base_work->tr);
  4753. if (noffset)
  4754. {
  4755. uint32_t *work_ntime = (uint32_t *)(work->data + 68);
  4756. uint32_t ntime = be32toh(*work_ntime);
  4757. ntime += noffset;
  4758. *work_ntime = htobe32(ntime);
  4759. }
  4760. if (work->device_data_dup_func)
  4761. work->device_data = work->device_data_dup_func(work);
  4762. }
  4763. /* Generates a copy of an existing work struct, creating fresh heap allocations
  4764. * for all dynamically allocated arrays within the struct */
  4765. struct work *copy_work(const struct work *base_work)
  4766. {
  4767. struct work *work = make_work();
  4768. _copy_work(work, base_work, 0);
  4769. return work;
  4770. }
  4771. void __copy_work(struct work *work, const struct work *base_work)
  4772. {
  4773. _copy_work(work, base_work, 0);
  4774. }
  4775. static struct work *make_clone(struct work *work)
  4776. {
  4777. struct work *work_clone = copy_work(work);
  4778. work_clone->clone = true;
  4779. cgtime((struct timeval *)&(work_clone->tv_cloned));
  4780. work_clone->longpoll = false;
  4781. work_clone->mandatory = false;
  4782. /* Make cloned work appear slightly older to bias towards keeping the
  4783. * master work item which can be further rolled */
  4784. work_clone->tv_staged.tv_sec -= 1;
  4785. return work_clone;
  4786. }
  4787. static void stage_work(struct work *work);
  4788. static bool clone_available(void)
  4789. {
  4790. struct work *work_clone = NULL, *work, *tmp;
  4791. bool cloned = false;
  4792. mutex_lock(stgd_lock);
  4793. if (!staged_rollable)
  4794. goto out_unlock;
  4795. HASH_ITER(hh, staged_work, work, tmp) {
  4796. if (can_roll(work) && should_roll(work)) {
  4797. roll_work(work);
  4798. work_clone = make_clone(work);
  4799. applog(LOG_DEBUG, "%s: Rolling work %d to %d", __func__, work->id, work_clone->id);
  4800. roll_work(work);
  4801. cloned = true;
  4802. break;
  4803. }
  4804. }
  4805. out_unlock:
  4806. mutex_unlock(stgd_lock);
  4807. if (cloned) {
  4808. applog(LOG_DEBUG, "Pushing cloned available work to stage thread");
  4809. stage_work(work_clone);
  4810. }
  4811. return cloned;
  4812. }
  4813. static void pool_died(struct pool *pool)
  4814. {
  4815. if (!pool_tset(pool, &pool->idle)) {
  4816. cgtime(&pool->tv_idle);
  4817. if (pool == current_pool()) {
  4818. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  4819. switch_pools(NULL);
  4820. } else
  4821. applog(LOG_INFO, "Pool %d %s failed to return work", pool->pool_no, pool->rpc_url);
  4822. }
  4823. }
  4824. bool stale_work(struct work *work, bool share)
  4825. {
  4826. unsigned work_expiry;
  4827. struct pool *pool;
  4828. uint32_t block_id;
  4829. unsigned getwork_delay;
  4830. if (opt_benchmark)
  4831. return false;
  4832. block_id = ((uint32_t*)work->data)[1];
  4833. pool = work->pool;
  4834. /* Technically the rolltime should be correct but some pools
  4835. * advertise a broken expire= that is lower than a meaningful
  4836. * scantime */
  4837. if (work->rolltime >= opt_scantime || work->tr)
  4838. work_expiry = work->rolltime;
  4839. else
  4840. work_expiry = opt_expiry;
  4841. unsigned max_expiry = (have_longpoll ? opt_expiry_lp : opt_expiry);
  4842. if (work_expiry > max_expiry)
  4843. work_expiry = max_expiry;
  4844. if (share) {
  4845. /* If the share isn't on this pool's latest block, it's stale */
  4846. if (pool->block_id && pool->block_id != block_id)
  4847. {
  4848. applog(LOG_DEBUG, "Share stale due to block mismatch (%08lx != %08lx)", (long)block_id, (long)pool->block_id);
  4849. return true;
  4850. }
  4851. /* If the pool doesn't want old shares, then any found in work before
  4852. * the most recent longpoll is stale */
  4853. if ((!pool->submit_old) && work->work_restart_id != pool->work_restart_id)
  4854. {
  4855. applog(LOG_DEBUG, "Share stale due to mandatory work update (%02x != %02x)", work->work_restart_id, pool->work_restart_id);
  4856. return true;
  4857. }
  4858. } else {
  4859. /* If this work isn't for the latest Bitcoin block, it's stale */
  4860. /* But only care about the current pool if failover-only */
  4861. if (enabled_pools <= 1 || opt_fail_only) {
  4862. if (pool->block_id && block_id != pool->block_id)
  4863. {
  4864. applog(LOG_DEBUG, "Work stale due to block mismatch (%08lx != 1 ? %08lx : %08lx)", (long)block_id, (long)pool->block_id, (long)current_block_id);
  4865. return true;
  4866. }
  4867. } else {
  4868. if (block_id != current_block_id)
  4869. {
  4870. applog(LOG_DEBUG, "Work stale due to block mismatch (%08lx != 0 ? %08lx : %08lx)", (long)block_id, (long)pool->block_id, (long)current_block_id);
  4871. return true;
  4872. }
  4873. }
  4874. /* If the pool has asked us to restart since this work, it's stale */
  4875. if (work->work_restart_id != pool->work_restart_id)
  4876. {
  4877. applog(LOG_DEBUG, "Work stale due to work update (%02x != %02x)", work->work_restart_id, pool->work_restart_id);
  4878. return true;
  4879. }
  4880. if (pool->has_stratum && work->job_id) {
  4881. bool same_job;
  4882. if (!pool->stratum_active || !pool->stratum_notify) {
  4883. applog(LOG_DEBUG, "Work stale due to stratum inactive");
  4884. return true;
  4885. }
  4886. same_job = true;
  4887. cg_rlock(&pool->data_lock);
  4888. if (strcmp(work->job_id, pool->swork.job_id))
  4889. same_job = false;
  4890. cg_runlock(&pool->data_lock);
  4891. if (!same_job) {
  4892. applog(LOG_DEBUG, "Work stale due to stratum job_id mismatch");
  4893. return true;
  4894. }
  4895. }
  4896. /* Factor in the average getwork delay of this pool, rounding it up to
  4897. * the nearest second */
  4898. getwork_delay = pool->cgminer_pool_stats.getwork_wait_rolling * 5 + 1;
  4899. if (unlikely(work_expiry <= getwork_delay + 5))
  4900. work_expiry = 5;
  4901. else
  4902. work_expiry -= getwork_delay;
  4903. }
  4904. int elapsed_since_staged = timer_elapsed(&work->tv_staged, NULL);
  4905. if (elapsed_since_staged > work_expiry) {
  4906. applog(LOG_DEBUG, "%s stale due to expiry (%d >= %u)", share?"Share":"Work", elapsed_since_staged, work_expiry);
  4907. return true;
  4908. }
  4909. /* If the user only wants strict failover, any work from a pool other than
  4910. * the current one is always considered stale */
  4911. if (opt_fail_only && !share && !work->mandatory && !pool_actively_in_use(pool, NULL))
  4912. {
  4913. applog(LOG_DEBUG, "Work stale due to fail only pool mismatch (pool %u vs %u)", pool->pool_no, current_pool()->pool_no);
  4914. return true;
  4915. }
  4916. return false;
  4917. }
  4918. static double share_diff(const struct work *work)
  4919. {
  4920. double ret;
  4921. bool new_best = false;
  4922. ret = target_diff(work->hash);
  4923. cg_wlock(&control_lock);
  4924. if (unlikely(ret > best_diff)) {
  4925. new_best = true;
  4926. best_diff = ret;
  4927. suffix_string(best_diff, best_share, sizeof(best_share), 0);
  4928. }
  4929. if (unlikely(ret > work->pool->best_diff))
  4930. work->pool->best_diff = ret;
  4931. cg_wunlock(&control_lock);
  4932. if (unlikely(new_best))
  4933. applog(LOG_INFO, "New best share: %s", best_share);
  4934. return ret;
  4935. }
  4936. static void regen_hash(struct work *work)
  4937. {
  4938. hash_data(work->hash, work->data);
  4939. }
  4940. static void rebuild_hash(struct work *work)
  4941. {
  4942. if (opt_scrypt)
  4943. scrypt_regenhash(work);
  4944. else
  4945. regen_hash(work);
  4946. work->share_diff = share_diff(work);
  4947. if (unlikely(work->share_diff >= current_diff)) {
  4948. work->block = true;
  4949. work->pool->solved++;
  4950. found_blocks++;
  4951. work->mandatory = true;
  4952. applog(LOG_NOTICE, "Found block for pool %d!", work->pool->pool_no);
  4953. }
  4954. }
  4955. static void submit_discard_share2(const char *reason, struct work *work)
  4956. {
  4957. struct cgpu_info *cgpu = get_thr_cgpu(work->thr_id);
  4958. sharelog(reason, work);
  4959. mutex_lock(&stats_lock);
  4960. ++total_stale;
  4961. ++cgpu->stale;
  4962. ++(work->pool->stale_shares);
  4963. total_diff_stale += work->work_difficulty;
  4964. cgpu->diff_stale += work->work_difficulty;
  4965. work->pool->diff_stale += work->work_difficulty;
  4966. mutex_unlock(&stats_lock);
  4967. }
  4968. static void submit_discard_share(struct work *work)
  4969. {
  4970. submit_discard_share2("discard", work);
  4971. }
  4972. struct submit_work_state {
  4973. struct work *work;
  4974. bool resubmit;
  4975. struct curl_ent *ce;
  4976. int failures;
  4977. struct timeval tv_staleexpire;
  4978. char *s;
  4979. struct timeval tv_submit;
  4980. struct submit_work_state *next;
  4981. };
  4982. static int my_curl_timer_set(__maybe_unused CURLM *curlm, long timeout_ms, void *userp)
  4983. {
  4984. long *p_timeout_us = userp;
  4985. const long max_ms = LONG_MAX / 1000;
  4986. if (max_ms < timeout_ms)
  4987. timeout_ms = max_ms;
  4988. *p_timeout_us = timeout_ms * 1000;
  4989. return 0;
  4990. }
  4991. static void sws_has_ce(struct submit_work_state *sws)
  4992. {
  4993. struct pool *pool = sws->work->pool;
  4994. sws->s = submit_upstream_work_request(sws->work);
  4995. cgtime(&sws->tv_submit);
  4996. json_rpc_call_async(sws->ce->curl, pool->rpc_url, pool->rpc_userpass, sws->s, false, pool, true, sws);
  4997. }
  4998. static struct submit_work_state *begin_submission(struct work *work)
  4999. {
  5000. struct pool *pool;
  5001. struct submit_work_state *sws = NULL;
  5002. pool = work->pool;
  5003. sws = malloc(sizeof(*sws));
  5004. *sws = (struct submit_work_state){
  5005. .work = work,
  5006. };
  5007. rebuild_hash(work);
  5008. if (stale_work(work, true)) {
  5009. work->stale = true;
  5010. if (opt_submit_stale)
  5011. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as user requested", pool->pool_no);
  5012. else if (pool->submit_old)
  5013. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as pool requested", pool->pool_no);
  5014. else {
  5015. applog(LOG_NOTICE, "Pool %d stale share detected, discarding", pool->pool_no);
  5016. submit_discard_share(work);
  5017. goto out;
  5018. }
  5019. timer_set_delay_from_now(&sws->tv_staleexpire, 300000000);
  5020. }
  5021. if (work->stratum) {
  5022. char *s;
  5023. s = malloc(1024);
  5024. sws->s = s;
  5025. } else {
  5026. /* submit solution to bitcoin via JSON-RPC */
  5027. sws->ce = pop_curl_entry2(pool, false);
  5028. if (sws->ce) {
  5029. sws_has_ce(sws);
  5030. } else {
  5031. sws->next = pool->sws_waiting_on_curl;
  5032. pool->sws_waiting_on_curl = sws;
  5033. if (sws->next)
  5034. applog(LOG_DEBUG, "submit_thread queuing submission");
  5035. else
  5036. applog(LOG_WARNING, "submit_thread queuing submissions (see --submit-threads)");
  5037. }
  5038. }
  5039. return sws;
  5040. out:
  5041. free(sws);
  5042. return NULL;
  5043. }
  5044. static bool retry_submission(struct submit_work_state *sws)
  5045. {
  5046. struct work *work = sws->work;
  5047. struct pool *pool = work->pool;
  5048. sws->resubmit = true;
  5049. if ((!work->stale) && stale_work(work, true)) {
  5050. work->stale = true;
  5051. if (opt_submit_stale)
  5052. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, will retry as user requested", pool->pool_no);
  5053. else if (pool->submit_old)
  5054. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, will retry as pool requested", pool->pool_no);
  5055. else {
  5056. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, discarding", pool->pool_no);
  5057. submit_discard_share(work);
  5058. return false;
  5059. }
  5060. timer_set_delay_from_now(&sws->tv_staleexpire, 300000000);
  5061. }
  5062. if (unlikely((opt_retries >= 0) && (++sws->failures > opt_retries))) {
  5063. applog(LOG_ERR, "Pool %d failed %d submission retries, discarding", pool->pool_no, opt_retries);
  5064. submit_discard_share(work);
  5065. return false;
  5066. }
  5067. else if (work->stale) {
  5068. if (unlikely(opt_retries < 0 && timer_passed(&sws->tv_staleexpire, NULL)))
  5069. {
  5070. applog(LOG_NOTICE, "Pool %d stale share failed to submit for 5 minutes, discarding", pool->pool_no);
  5071. submit_discard_share(work);
  5072. return false;
  5073. }
  5074. }
  5075. /* pause, then restart work-request loop */
  5076. applog(LOG_INFO, "json_rpc_call failed on submit_work, retrying");
  5077. cgtime(&sws->tv_submit);
  5078. json_rpc_call_async(sws->ce->curl, pool->rpc_url, pool->rpc_userpass, sws->s, false, pool, true, sws);
  5079. return true;
  5080. }
  5081. static void free_sws(struct submit_work_state *sws)
  5082. {
  5083. free(sws->s);
  5084. free_work(sws->work);
  5085. free(sws);
  5086. }
  5087. static void *submit_work_thread(__maybe_unused void *userdata)
  5088. {
  5089. int wip = 0;
  5090. CURLM *curlm;
  5091. long curlm_timeout_us = -1;
  5092. struct timeval curlm_timer;
  5093. struct submit_work_state *sws, **swsp;
  5094. struct submit_work_state *write_sws = NULL;
  5095. unsigned tsreduce = 0;
  5096. pthread_detach(pthread_self());
  5097. RenameThread("submit_work");
  5098. applog(LOG_DEBUG, "Creating extra submit work thread");
  5099. curlm = curl_multi_init();
  5100. curlm_timeout_us = -1;
  5101. curl_multi_setopt(curlm, CURLMOPT_TIMERDATA, &curlm_timeout_us);
  5102. curl_multi_setopt(curlm, CURLMOPT_TIMERFUNCTION, my_curl_timer_set);
  5103. fd_set rfds, wfds, efds;
  5104. int maxfd;
  5105. struct timeval tv_timeout, tv_now;
  5106. int n;
  5107. CURLMsg *cm;
  5108. FD_ZERO(&rfds);
  5109. while (1) {
  5110. mutex_lock(&submitting_lock);
  5111. total_submitting -= tsreduce;
  5112. tsreduce = 0;
  5113. if (FD_ISSET(submit_waiting_notifier[0], &rfds)) {
  5114. notifier_read(submit_waiting_notifier);
  5115. }
  5116. // Receive any new submissions
  5117. while (submit_waiting) {
  5118. struct work *work = submit_waiting;
  5119. DL_DELETE(submit_waiting, work);
  5120. if ( (sws = begin_submission(work)) ) {
  5121. if (sws->ce)
  5122. curl_multi_add_handle(curlm, sws->ce->curl);
  5123. else if (sws->s) {
  5124. sws->next = write_sws;
  5125. write_sws = sws;
  5126. }
  5127. ++wip;
  5128. }
  5129. else {
  5130. --total_submitting;
  5131. free_work(work);
  5132. }
  5133. }
  5134. if (unlikely(shutting_down && !wip))
  5135. break;
  5136. mutex_unlock(&submitting_lock);
  5137. FD_ZERO(&rfds);
  5138. FD_ZERO(&wfds);
  5139. FD_ZERO(&efds);
  5140. tv_timeout.tv_sec = -1;
  5141. // Setup cURL with select
  5142. // Need to call perform to ensure the timeout gets updated
  5143. curl_multi_perform(curlm, &n);
  5144. curl_multi_fdset(curlm, &rfds, &wfds, &efds, &maxfd);
  5145. if (curlm_timeout_us >= 0)
  5146. {
  5147. timer_set_delay_from_now(&curlm_timer, curlm_timeout_us);
  5148. reduce_timeout_to(&tv_timeout, &curlm_timer);
  5149. }
  5150. // Setup waiting stratum submissions with select
  5151. for (sws = write_sws; sws; sws = sws->next)
  5152. {
  5153. struct pool *pool = sws->work->pool;
  5154. int fd = pool->sock;
  5155. if (fd == INVSOCK || (!pool->stratum_init) || !pool->stratum_notify)
  5156. continue;
  5157. FD_SET(fd, &wfds);
  5158. set_maxfd(&maxfd, fd);
  5159. }
  5160. // Setup "submit waiting" notifier with select
  5161. FD_SET(submit_waiting_notifier[0], &rfds);
  5162. set_maxfd(&maxfd, submit_waiting_notifier[0]);
  5163. // Wait for something interesting to happen :)
  5164. cgtime(&tv_now);
  5165. if (select(maxfd+1, &rfds, &wfds, &efds, select_timeout(&tv_timeout, &tv_now)) < 0) {
  5166. FD_ZERO(&rfds);
  5167. continue;
  5168. }
  5169. // Handle any stratum ready-to-write results
  5170. for (swsp = &write_sws; (sws = *swsp); ) {
  5171. struct work *work = sws->work;
  5172. struct pool *pool = work->pool;
  5173. int fd = pool->sock;
  5174. bool sessionid_match;
  5175. if (fd == INVSOCK || (!pool->stratum_init) || (!pool->stratum_notify) || !FD_ISSET(fd, &wfds)) {
  5176. next_write_sws:
  5177. // TODO: Check if stale, possibly discard etc
  5178. swsp = &sws->next;
  5179. continue;
  5180. }
  5181. cg_rlock(&pool->data_lock);
  5182. // 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
  5183. // NOTE: Worst case scenario for a false positive: the pool rejects it as H-not-zero
  5184. sessionid_match = (!pool->nonce1) || !strcmp(work->nonce1, pool->nonce1);
  5185. cg_runlock(&pool->data_lock);
  5186. if (!sessionid_match)
  5187. {
  5188. applog(LOG_DEBUG, "No matching session id for resubmitting stratum share");
  5189. submit_discard_share2("disconnect", work);
  5190. ++tsreduce;
  5191. next_write_sws_del:
  5192. // Clear the fd from wfds, to avoid potentially blocking on other submissions to the same socket
  5193. FD_CLR(fd, &wfds);
  5194. // Delete sws for this submission, since we're done with it
  5195. *swsp = sws->next;
  5196. free_sws(sws);
  5197. --wip;
  5198. continue;
  5199. }
  5200. char *s = sws->s;
  5201. struct stratum_share *sshare = calloc(sizeof(struct stratum_share), 1);
  5202. int sshare_id;
  5203. uint32_t nonce;
  5204. char nonce2hex[(bytes_len(&work->nonce2) * 2) + 1];
  5205. char noncehex[9];
  5206. char ntimehex[9];
  5207. sshare->work = copy_work(work);
  5208. bin2hex(nonce2hex, bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  5209. nonce = *((uint32_t *)(work->data + 76));
  5210. bin2hex(noncehex, (const unsigned char *)&nonce, 4);
  5211. bin2hex(ntimehex, (void *)&work->data[68], 4);
  5212. mutex_lock(&sshare_lock);
  5213. /* Give the stratum share a unique id */
  5214. sshare_id =
  5215. sshare->id = swork_id++;
  5216. HASH_ADD_INT(stratum_shares, id, sshare);
  5217. snprintf(s, 1024, "{\"params\": [\"%s\", \"%s\", \"%s\", \"%s\", \"%s\"], \"id\": %d, \"method\": \"mining.submit\"}",
  5218. pool->rpc_user, work->job_id, nonce2hex, ntimehex, noncehex, sshare->id);
  5219. mutex_unlock(&sshare_lock);
  5220. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->stratum_url, s);
  5221. if (likely(stratum_send(pool, s, strlen(s)))) {
  5222. if (pool_tclear(pool, &pool->submit_fail))
  5223. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  5224. applog(LOG_DEBUG, "Successfully submitted, adding to stratum_shares db");
  5225. goto next_write_sws_del;
  5226. } else if (!pool_tset(pool, &pool->submit_fail)) {
  5227. // Undo stuff
  5228. mutex_lock(&sshare_lock);
  5229. // NOTE: Need to find it again in case something else has consumed it already (like the stratum-disconnect resubmitter...)
  5230. HASH_FIND_INT(stratum_shares, &sshare_id, sshare);
  5231. if (sshare)
  5232. HASH_DEL(stratum_shares, sshare);
  5233. mutex_unlock(&sshare_lock);
  5234. if (sshare)
  5235. {
  5236. free_work(sshare->work);
  5237. free(sshare);
  5238. }
  5239. applog(LOG_WARNING, "Pool %d stratum share submission failure", pool->pool_no);
  5240. total_ro++;
  5241. pool->remotefail_occasions++;
  5242. if (!sshare)
  5243. goto next_write_sws_del;
  5244. goto next_write_sws;
  5245. }
  5246. }
  5247. // Handle any cURL activities
  5248. curl_multi_perform(curlm, &n);
  5249. while( (cm = curl_multi_info_read(curlm, &n)) ) {
  5250. if (cm->msg == CURLMSG_DONE)
  5251. {
  5252. bool finished;
  5253. json_t *val = json_rpc_call_completed(cm->easy_handle, cm->data.result, false, NULL, &sws);
  5254. curl_multi_remove_handle(curlm, cm->easy_handle);
  5255. finished = submit_upstream_work_completed(sws->work, sws->resubmit, &sws->tv_submit, val);
  5256. if (!finished) {
  5257. if (retry_submission(sws))
  5258. curl_multi_add_handle(curlm, sws->ce->curl);
  5259. else
  5260. finished = true;
  5261. }
  5262. if (finished) {
  5263. --wip;
  5264. ++tsreduce;
  5265. struct pool *pool = sws->work->pool;
  5266. if (pool->sws_waiting_on_curl) {
  5267. pool->sws_waiting_on_curl->ce = sws->ce;
  5268. sws_has_ce(pool->sws_waiting_on_curl);
  5269. pool->sws_waiting_on_curl = pool->sws_waiting_on_curl->next;
  5270. curl_multi_add_handle(curlm, sws->ce->curl);
  5271. } else {
  5272. push_curl_entry(sws->ce, sws->work->pool);
  5273. }
  5274. free_sws(sws);
  5275. }
  5276. }
  5277. }
  5278. }
  5279. assert(!write_sws);
  5280. mutex_unlock(&submitting_lock);
  5281. curl_multi_cleanup(curlm);
  5282. applog(LOG_DEBUG, "submit_work thread exiting");
  5283. return NULL;
  5284. }
  5285. /* Find the pool that currently has the highest priority */
  5286. static struct pool *priority_pool(int choice)
  5287. {
  5288. struct pool *ret = NULL;
  5289. int i;
  5290. for (i = 0; i < total_pools; i++) {
  5291. struct pool *pool = pools[i];
  5292. if (pool->prio == choice) {
  5293. ret = pool;
  5294. break;
  5295. }
  5296. }
  5297. if (unlikely(!ret)) {
  5298. applog(LOG_ERR, "WTF No pool %d found!", choice);
  5299. return pools[choice];
  5300. }
  5301. return ret;
  5302. }
  5303. int prioritize_pools(char *param, int *pid)
  5304. {
  5305. char *ptr, *next;
  5306. int i, pr, prio = 0;
  5307. if (total_pools == 0) {
  5308. return MSG_NOPOOL;
  5309. }
  5310. if (param == NULL || *param == '\0') {
  5311. return MSG_MISPID;
  5312. }
  5313. bool pools_changed[total_pools];
  5314. int new_prio[total_pools];
  5315. for (i = 0; i < total_pools; ++i)
  5316. pools_changed[i] = false;
  5317. next = param;
  5318. while (next && *next) {
  5319. ptr = next;
  5320. next = strchr(ptr, ',');
  5321. if (next)
  5322. *(next++) = '\0';
  5323. i = atoi(ptr);
  5324. if (i < 0 || i >= total_pools) {
  5325. *pid = i;
  5326. return MSG_INVPID;
  5327. }
  5328. if (pools_changed[i]) {
  5329. *pid = i;
  5330. return MSG_DUPPID;
  5331. }
  5332. pools_changed[i] = true;
  5333. new_prio[i] = prio++;
  5334. }
  5335. // Only change them if no errors
  5336. for (i = 0; i < total_pools; i++) {
  5337. if (pools_changed[i])
  5338. pools[i]->prio = new_prio[i];
  5339. }
  5340. // In priority order, cycle through the unchanged pools and append them
  5341. for (pr = 0; pr < total_pools; pr++)
  5342. for (i = 0; i < total_pools; i++) {
  5343. if (!pools_changed[i] && pools[i]->prio == pr) {
  5344. pools[i]->prio = prio++;
  5345. pools_changed[i] = true;
  5346. break;
  5347. }
  5348. }
  5349. if (current_pool()->prio)
  5350. switch_pools(NULL);
  5351. return MSG_POOLPRIO;
  5352. }
  5353. void validate_pool_priorities(void)
  5354. {
  5355. // TODO: this should probably do some sort of logging
  5356. int i, j;
  5357. bool used[total_pools];
  5358. bool valid[total_pools];
  5359. for (i = 0; i < total_pools; i++)
  5360. used[i] = valid[i] = false;
  5361. for (i = 0; i < total_pools; i++) {
  5362. if (pools[i]->prio >=0 && pools[i]->prio < total_pools) {
  5363. if (!used[pools[i]->prio]) {
  5364. valid[i] = true;
  5365. used[pools[i]->prio] = true;
  5366. }
  5367. }
  5368. }
  5369. for (i = 0; i < total_pools; i++) {
  5370. if (!valid[i]) {
  5371. for (j = 0; j < total_pools; j++) {
  5372. if (!used[j]) {
  5373. applog(LOG_WARNING, "Pool %d priority changed from %d to %d", i, pools[i]->prio, j);
  5374. pools[i]->prio = j;
  5375. used[j] = true;
  5376. break;
  5377. }
  5378. }
  5379. }
  5380. }
  5381. }
  5382. static void clear_pool_work(struct pool *pool);
  5383. /* Specifies whether we can switch to this pool or not. */
  5384. static bool pool_unusable(struct pool *pool)
  5385. {
  5386. if (pool->idle)
  5387. return true;
  5388. if (pool->enabled != POOL_ENABLED)
  5389. return true;
  5390. return false;
  5391. }
  5392. void switch_pools(struct pool *selected)
  5393. {
  5394. struct pool *pool, *last_pool;
  5395. int i, pool_no, next_pool;
  5396. cg_wlock(&control_lock);
  5397. last_pool = currentpool;
  5398. pool_no = currentpool->pool_no;
  5399. /* Switch selected to pool number 0 and move the rest down */
  5400. if (selected) {
  5401. if (selected->prio != 0) {
  5402. for (i = 0; i < total_pools; i++) {
  5403. pool = pools[i];
  5404. if (pool->prio < selected->prio)
  5405. pool->prio++;
  5406. }
  5407. selected->prio = 0;
  5408. }
  5409. }
  5410. switch (pool_strategy) {
  5411. /* All of these set to the master pool */
  5412. case POOL_BALANCE:
  5413. case POOL_FAILOVER:
  5414. case POOL_LOADBALANCE:
  5415. for (i = 0; i < total_pools; i++) {
  5416. pool = priority_pool(i);
  5417. if (pool_unusable(pool))
  5418. continue;
  5419. pool_no = pool->pool_no;
  5420. break;
  5421. }
  5422. break;
  5423. /* Both of these simply increment and cycle */
  5424. case POOL_ROUNDROBIN:
  5425. case POOL_ROTATE:
  5426. if (selected && !selected->idle) {
  5427. pool_no = selected->pool_no;
  5428. break;
  5429. }
  5430. next_pool = pool_no;
  5431. /* Select the next alive pool */
  5432. for (i = 1; i < total_pools; i++) {
  5433. next_pool++;
  5434. if (next_pool >= total_pools)
  5435. next_pool = 0;
  5436. pool = pools[next_pool];
  5437. if (pool_unusable(pool))
  5438. continue;
  5439. pool_no = next_pool;
  5440. break;
  5441. }
  5442. break;
  5443. default:
  5444. break;
  5445. }
  5446. currentpool = pools[pool_no];
  5447. pool = currentpool;
  5448. cg_wunlock(&control_lock);
  5449. /* Set the lagging flag to avoid pool not providing work fast enough
  5450. * messages in failover only mode since we have to get all fresh work
  5451. * as in restart_threads */
  5452. if (opt_fail_only)
  5453. pool_tset(pool, &pool->lagging);
  5454. if (pool != last_pool)
  5455. {
  5456. pool->block_id = 0;
  5457. if (pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  5458. applog(LOG_WARNING, "Switching to pool %d %s", pool->pool_no, pool->rpc_url);
  5459. if (pool_localgen(pool) || opt_fail_only)
  5460. clear_pool_work(last_pool);
  5461. }
  5462. }
  5463. mutex_lock(&lp_lock);
  5464. pthread_cond_broadcast(&lp_cond);
  5465. mutex_unlock(&lp_lock);
  5466. }
  5467. static void discard_work(struct work *work)
  5468. {
  5469. if (!work->clone && !work->rolls && !work->mined) {
  5470. if (work->pool) {
  5471. work->pool->discarded_work++;
  5472. work->pool->quota_used--;
  5473. work->pool->works--;
  5474. }
  5475. total_discarded++;
  5476. applog(LOG_DEBUG, "Discarded work");
  5477. } else
  5478. applog(LOG_DEBUG, "Discarded cloned or rolled work");
  5479. free_work(work);
  5480. }
  5481. static void wake_gws(void)
  5482. {
  5483. mutex_lock(stgd_lock);
  5484. pthread_cond_signal(&gws_cond);
  5485. mutex_unlock(stgd_lock);
  5486. }
  5487. static void discard_stale(void)
  5488. {
  5489. struct work *work, *tmp;
  5490. int stale = 0;
  5491. mutex_lock(stgd_lock);
  5492. HASH_ITER(hh, staged_work, work, tmp) {
  5493. if (stale_work(work, false)) {
  5494. HASH_DEL(staged_work, work);
  5495. discard_work(work);
  5496. stale++;
  5497. staged_full = false;
  5498. }
  5499. }
  5500. pthread_cond_signal(&gws_cond);
  5501. mutex_unlock(stgd_lock);
  5502. if (stale)
  5503. applog(LOG_DEBUG, "Discarded %d stales that didn't match current hash", stale);
  5504. }
  5505. bool stale_work_future(struct work *work, bool share, unsigned long ustime)
  5506. {
  5507. bool rv;
  5508. struct timeval tv, orig;
  5509. ldiv_t d;
  5510. d = ldiv(ustime, 1000000);
  5511. tv = (struct timeval){
  5512. .tv_sec = d.quot,
  5513. .tv_usec = d.rem,
  5514. };
  5515. orig = work->tv_staged;
  5516. timersub(&orig, &tv, &work->tv_staged);
  5517. rv = stale_work(work, share);
  5518. work->tv_staged = orig;
  5519. return rv;
  5520. }
  5521. static
  5522. void pool_update_work_restart_time(struct pool * const pool)
  5523. {
  5524. pool->work_restart_time = time(NULL);
  5525. get_timestamp(pool->work_restart_timestamp, sizeof(pool->work_restart_timestamp), pool->work_restart_time);
  5526. }
  5527. static void restart_threads(void)
  5528. {
  5529. struct pool *cp = current_pool();
  5530. int i;
  5531. struct thr_info *thr;
  5532. /* Artificially set the lagging flag to avoid pool not providing work
  5533. * fast enough messages after every long poll */
  5534. pool_tset(cp, &cp->lagging);
  5535. /* Discard staged work that is now stale */
  5536. discard_stale();
  5537. rd_lock(&mining_thr_lock);
  5538. for (i = 0; i < mining_threads; i++)
  5539. {
  5540. thr = mining_thr[i];
  5541. thr->work_restart = true;
  5542. }
  5543. for (i = 0; i < mining_threads; i++)
  5544. {
  5545. thr = mining_thr[i];
  5546. notifier_wake(thr->work_restart_notifier);
  5547. }
  5548. rd_unlock(&mining_thr_lock);
  5549. }
  5550. static
  5551. void blkhashstr(char *rv, const unsigned char *hash)
  5552. {
  5553. unsigned char hash_swap[32];
  5554. swap256(hash_swap, hash);
  5555. swap32tole(hash_swap, hash_swap, 32 / 4);
  5556. bin2hex(rv, hash_swap, 32);
  5557. }
  5558. static void set_curblock(char *hexstr, unsigned char *hash)
  5559. {
  5560. unsigned char hash_swap[32];
  5561. current_block_id = ((uint32_t*)hash)[0];
  5562. strcpy(current_block, hexstr);
  5563. swap256(hash_swap, hash);
  5564. swap32tole(hash_swap, hash_swap, 32 / 4);
  5565. cg_wlock(&ch_lock);
  5566. block_time = time(NULL);
  5567. __update_block_title(hash_swap);
  5568. free(current_fullhash);
  5569. current_fullhash = malloc(65);
  5570. bin2hex(current_fullhash, hash_swap, 32);
  5571. get_timestamp(blocktime, sizeof(blocktime), block_time);
  5572. cg_wunlock(&ch_lock);
  5573. applog(LOG_INFO, "New block: %s diff %s (%s)", current_hash, block_diff, net_hashrate);
  5574. }
  5575. /* Search to see if this string is from a block that has been seen before */
  5576. static bool block_exists(char *hexstr)
  5577. {
  5578. struct block *s;
  5579. rd_lock(&blk_lock);
  5580. HASH_FIND_STR(blocks, hexstr, s);
  5581. rd_unlock(&blk_lock);
  5582. if (s)
  5583. return true;
  5584. return false;
  5585. }
  5586. /* Tests if this work is from a block that has been seen before */
  5587. static inline bool from_existing_block(struct work *work)
  5588. {
  5589. char hexstr[37];
  5590. bool ret;
  5591. bin2hex(hexstr, work->data + 8, 18);
  5592. ret = block_exists(hexstr);
  5593. return ret;
  5594. }
  5595. static int block_sort(struct block *blocka, struct block *blockb)
  5596. {
  5597. return blocka->block_no - blockb->block_no;
  5598. }
  5599. static void set_blockdiff(const struct work *work)
  5600. {
  5601. unsigned char target[32];
  5602. double diff;
  5603. uint64_t diff64;
  5604. real_block_target(target, work->data);
  5605. diff = target_diff(target);
  5606. diff64 = diff;
  5607. suffix_string(diff64, block_diff, sizeof(block_diff), 0);
  5608. format_unit2(net_hashrate, sizeof(net_hashrate),
  5609. true, "h/s", H2B_SHORT, diff * 7158278, -1);
  5610. if (unlikely(current_diff != diff))
  5611. applog(LOG_NOTICE, "Network difficulty changed to %s (%s)", block_diff, net_hashrate);
  5612. current_diff = diff;
  5613. }
  5614. static bool test_work_current(struct work *work)
  5615. {
  5616. bool ret = true;
  5617. char hexstr[65];
  5618. if (work->mandatory)
  5619. return ret;
  5620. uint32_t block_id = ((uint32_t*)(work->data))[1];
  5621. /* Hack to work around dud work sneaking into test */
  5622. bin2hex(hexstr, work->data + 8, 18);
  5623. if (!strncmp(hexstr, "000000000000000000000000000000000000", 36))
  5624. goto out_free;
  5625. struct pool * const pool = work->pool;
  5626. /* Search to see if this block exists yet and if not, consider it a
  5627. * new block and set the current block details to this one */
  5628. if (!block_exists(hexstr))
  5629. {
  5630. struct block *s = calloc(sizeof(struct block), 1);
  5631. int deleted_block = 0;
  5632. ret = false;
  5633. if (unlikely(!s))
  5634. quit (1, "test_work_current OOM");
  5635. strcpy(s->hash, hexstr);
  5636. s->block_no = new_blocks++;
  5637. wr_lock(&blk_lock);
  5638. /* Only keep the last hour's worth of blocks in memory since
  5639. * work from blocks before this is virtually impossible and we
  5640. * want to prevent memory usage from continually rising */
  5641. if (HASH_COUNT(blocks) > 6)
  5642. {
  5643. struct block *oldblock;
  5644. HASH_SORT(blocks, block_sort);
  5645. oldblock = blocks;
  5646. deleted_block = oldblock->block_no;
  5647. HASH_DEL(blocks, oldblock);
  5648. free(oldblock);
  5649. }
  5650. HASH_ADD_STR(blocks, hash, s);
  5651. set_blockdiff(work);
  5652. wr_unlock(&blk_lock);
  5653. pool->block_id = block_id;
  5654. pool_update_work_restart_time(pool);
  5655. if (deleted_block)
  5656. applog(LOG_DEBUG, "Deleted block %d from database", deleted_block);
  5657. #if BLKMAKER_VERSION > 1
  5658. template_nonce = 0;
  5659. #endif
  5660. set_curblock(hexstr, &work->data[4]);
  5661. if (unlikely(new_blocks == 1))
  5662. goto out_free;
  5663. if (!work->stratum)
  5664. {
  5665. if (work->longpoll)
  5666. {
  5667. applog(LOG_NOTICE, "Longpoll from pool %d detected new block",
  5668. pool->pool_no);
  5669. }
  5670. else
  5671. if (have_longpoll)
  5672. applog(LOG_NOTICE, "New block detected on network before longpoll");
  5673. else
  5674. applog(LOG_NOTICE, "New block detected on network");
  5675. }
  5676. restart_threads();
  5677. }
  5678. else
  5679. {
  5680. bool restart = false;
  5681. if (unlikely(pool->block_id != block_id))
  5682. {
  5683. bool was_active = pool->block_id != 0;
  5684. pool->block_id = block_id;
  5685. pool_update_work_restart_time(pool);
  5686. if (!work->longpoll)
  5687. update_last_work(work);
  5688. if (was_active)
  5689. {
  5690. // Pool actively changed block
  5691. if (pool == current_pool())
  5692. restart = true;
  5693. if (block_id == current_block_id)
  5694. {
  5695. // Caught up, only announce if this pool is the one in use
  5696. if (restart)
  5697. applog(LOG_NOTICE, "%s %d caught up to new block",
  5698. work->longpoll ? "Longpoll from pool" : "Pool",
  5699. pool->pool_no);
  5700. }
  5701. else
  5702. {
  5703. // Switched to a block we know, but not the latest... why?
  5704. // This might detect pools trying to double-spend or 51%,
  5705. // but let's not make any accusations until it's had time
  5706. // in the real world.
  5707. blkhashstr(hexstr, &work->data[4]);
  5708. applog(LOG_WARNING, "%s %d is issuing work for an old block: %s",
  5709. work->longpoll ? "Longpoll from pool" : "Pool",
  5710. pool->pool_no,
  5711. hexstr);
  5712. }
  5713. }
  5714. }
  5715. if (work->longpoll)
  5716. {
  5717. struct pool * const cp = current_pool();
  5718. ++pool->work_restart_id;
  5719. update_last_work(work);
  5720. pool_update_work_restart_time(pool);
  5721. applog(
  5722. ((!opt_quiet_work_updates) && pool_actively_in_use(pool, cp) ? LOG_NOTICE : LOG_DEBUG),
  5723. "Longpoll from pool %d requested work update",
  5724. pool->pool_no);
  5725. if ((!restart) && pool == cp)
  5726. restart = true;
  5727. }
  5728. if (restart)
  5729. restart_threads();
  5730. }
  5731. work->longpoll = false;
  5732. out_free:
  5733. return ret;
  5734. }
  5735. static int tv_sort(struct work *worka, struct work *workb)
  5736. {
  5737. return worka->tv_staged.tv_sec - workb->tv_staged.tv_sec;
  5738. }
  5739. static bool work_rollable(struct work *work)
  5740. {
  5741. return (!work->clone && work->rolltime);
  5742. }
  5743. static bool hash_push(struct work *work)
  5744. {
  5745. bool rc = true;
  5746. mutex_lock(stgd_lock);
  5747. if (work_rollable(work))
  5748. staged_rollable++;
  5749. if (likely(!getq->frozen)) {
  5750. HASH_ADD_INT(staged_work, id, work);
  5751. HASH_SORT(staged_work, tv_sort);
  5752. } else
  5753. rc = false;
  5754. pthread_cond_broadcast(&getq->cond);
  5755. mutex_unlock(stgd_lock);
  5756. return rc;
  5757. }
  5758. static void stage_work(struct work *work)
  5759. {
  5760. applog(LOG_DEBUG, "Pushing work %d from pool %d to hash queue",
  5761. work->id, work->pool->pool_no);
  5762. work->work_restart_id = work->pool->work_restart_id;
  5763. work->pool->last_work_time = time(NULL);
  5764. cgtime(&work->pool->tv_last_work_time);
  5765. test_work_current(work);
  5766. work->pool->works++;
  5767. hash_push(work);
  5768. }
  5769. #ifdef HAVE_CURSES
  5770. int curses_int(const char *query)
  5771. {
  5772. int ret;
  5773. char *cvar;
  5774. cvar = curses_input(query);
  5775. if (unlikely(!cvar))
  5776. return -1;
  5777. ret = atoi(cvar);
  5778. free(cvar);
  5779. return ret;
  5780. }
  5781. #endif
  5782. #ifdef HAVE_CURSES
  5783. static bool input_pool(bool live);
  5784. #endif
  5785. #ifdef HAVE_CURSES
  5786. static void display_pool_summary(struct pool *pool)
  5787. {
  5788. double efficiency = 0.0;
  5789. char xfer[ALLOC_H2B_NOUNIT+ALLOC_H2B_SPACED+4+1], bw[ALLOC_H2B_NOUNIT+ALLOC_H2B_SPACED+6+1];
  5790. int pool_secs;
  5791. if (curses_active_locked()) {
  5792. wlog("Pool: %s\n", pool->rpc_url);
  5793. if (pool->solved)
  5794. wlog("SOLVED %d BLOCK%s!\n", pool->solved, pool->solved > 1 ? "S" : "");
  5795. if (!pool->has_stratum)
  5796. wlog("%s own long-poll support\n", pool->lp_url ? "Has" : "Does not have");
  5797. wlog(" Queued work requests: %d\n", pool->getwork_requested);
  5798. wlog(" Share submissions: %d\n", pool->accepted + pool->rejected);
  5799. wlog(" Accepted shares: %d\n", pool->accepted);
  5800. wlog(" Rejected shares: %d + %d stale (%.2f%%)\n",
  5801. pool->rejected, pool->stale_shares,
  5802. (float)(pool->rejected + pool->stale_shares) / (float)(pool->rejected + pool->stale_shares + pool->accepted)
  5803. );
  5804. wlog(" Accepted difficulty shares: %1.f\n", pool->diff_accepted);
  5805. wlog(" Rejected difficulty shares: %1.f\n", pool->diff_rejected);
  5806. pool_secs = timer_elapsed(&pool->cgminer_stats.start_tv, NULL);
  5807. wlog(" Network transfer: %s (%s)\n",
  5808. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  5809. (float)pool->cgminer_pool_stats.net_bytes_received,
  5810. (float)pool->cgminer_pool_stats.net_bytes_sent),
  5811. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  5812. (float)(pool->cgminer_pool_stats.net_bytes_received / pool_secs),
  5813. (float)(pool->cgminer_pool_stats.net_bytes_sent / pool_secs)));
  5814. uint64_t pool_bytes_xfer = pool->cgminer_pool_stats.net_bytes_received + pool->cgminer_pool_stats.net_bytes_sent;
  5815. efficiency = pool_bytes_xfer ? pool->diff_accepted * 2048. / pool_bytes_xfer : 0.0;
  5816. wlog(" Efficiency (accepted * difficulty / 2 KB): %.2f\n", efficiency);
  5817. wlog(" Items worked on: %d\n", pool->works);
  5818. wlog(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  5819. wlog(" Unable to get work from server occasions: %d\n", pool->getfail_occasions);
  5820. wlog(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  5821. unlock_curses();
  5822. }
  5823. }
  5824. #endif
  5825. /* We can't remove the memory used for this struct pool because there may
  5826. * still be work referencing it. We just remove it from the pools list */
  5827. void remove_pool(struct pool *pool)
  5828. {
  5829. int i, last_pool = total_pools - 1;
  5830. struct pool *other;
  5831. /* Boost priority of any lower prio than this one */
  5832. for (i = 0; i < total_pools; i++) {
  5833. other = pools[i];
  5834. if (other->prio > pool->prio)
  5835. other->prio--;
  5836. }
  5837. if (pool->pool_no < last_pool) {
  5838. /* Swap the last pool for this one */
  5839. (pools[last_pool])->pool_no = pool->pool_no;
  5840. pools[pool->pool_no] = pools[last_pool];
  5841. }
  5842. /* Give it an invalid number */
  5843. pool->pool_no = total_pools;
  5844. pool->removed = true;
  5845. pool->has_stratum = false;
  5846. total_pools--;
  5847. }
  5848. /* add a mutex if this needs to be thread safe in the future */
  5849. static struct JE {
  5850. char *buf;
  5851. struct JE *next;
  5852. } *jedata = NULL;
  5853. static void json_escape_free()
  5854. {
  5855. struct JE *jeptr = jedata;
  5856. struct JE *jenext;
  5857. jedata = NULL;
  5858. while (jeptr) {
  5859. jenext = jeptr->next;
  5860. free(jeptr->buf);
  5861. free(jeptr);
  5862. jeptr = jenext;
  5863. }
  5864. }
  5865. static
  5866. char *json_escape(const char *str)
  5867. {
  5868. struct JE *jeptr;
  5869. char *buf, *ptr;
  5870. /* 2x is the max, may as well just allocate that */
  5871. ptr = buf = malloc(strlen(str) * 2 + 1);
  5872. jeptr = malloc(sizeof(*jeptr));
  5873. jeptr->buf = buf;
  5874. jeptr->next = jedata;
  5875. jedata = jeptr;
  5876. while (*str) {
  5877. if (*str == '\\' || *str == '"')
  5878. *(ptr++) = '\\';
  5879. *(ptr++) = *(str++);
  5880. }
  5881. *ptr = '\0';
  5882. return buf;
  5883. }
  5884. static
  5885. void _write_config_string_elist(FILE *fcfg, const char *configname, struct string_elist * const elist)
  5886. {
  5887. if (!elist)
  5888. return;
  5889. static struct string_elist *entry;
  5890. fprintf(fcfg, ",\n\"%s\" : [", configname);
  5891. bool first = true;
  5892. DL_FOREACH(elist, entry)
  5893. {
  5894. const char * const s = entry->string;
  5895. fprintf(fcfg, "%s\n\t\"%s\"", first ? "" : ",", json_escape(s));
  5896. first = false;
  5897. }
  5898. fprintf(fcfg, "\n]");
  5899. }
  5900. void write_config(FILE *fcfg)
  5901. {
  5902. int i;
  5903. /* Write pool values */
  5904. fputs("{\n\"pools\" : [", fcfg);
  5905. for(i = 0; i < total_pools; i++) {
  5906. struct pool *pool = pools[i];
  5907. if (pool->quota != 1) {
  5908. fprintf(fcfg, "%s\n\t{\n\t\t\"quota\" : \"%d;%s\",", i > 0 ? "," : "",
  5909. pool->quota,
  5910. json_escape(pool->rpc_url));
  5911. } else {
  5912. fprintf(fcfg, "%s\n\t{\n\t\t\"url\" : \"%s\",", i > 0 ? "," : "",
  5913. json_escape(pool->rpc_url));
  5914. }
  5915. if (pool->rpc_proxy)
  5916. fprintf(fcfg, "\n\t\t\"pool-proxy\" : \"%s\",", json_escape(pool->rpc_proxy));
  5917. fprintf(fcfg, "\n\t\t\"user\" : \"%s\",", json_escape(pool->rpc_user));
  5918. fprintf(fcfg, "\n\t\t\"pass\" : \"%s\",", json_escape(pool->rpc_pass));
  5919. fprintf(fcfg, "\n\t\t\"pool-priority\" : \"%d\"", pool->prio);
  5920. if (pool->force_rollntime)
  5921. fprintf(fcfg, ",\n\t\t\"force-rollntime\" : %d", pool->force_rollntime);
  5922. fprintf(fcfg, "\n\t}");
  5923. }
  5924. fputs("\n]\n", fcfg);
  5925. #ifdef HAVE_OPENCL
  5926. write_config_opencl(fcfg);
  5927. #endif
  5928. #ifdef WANT_CPUMINE
  5929. fprintf(fcfg, ",\n\"algo\" : \"%s\"", algo_names[opt_algo]);
  5930. #endif
  5931. /* Simple bool and int options */
  5932. struct opt_table *opt;
  5933. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  5934. char *p, *name = strdup(opt->names);
  5935. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  5936. if (p[1] != '-')
  5937. continue;
  5938. if (opt->type & OPT_NOARG &&
  5939. ((void *)opt->cb == (void *)opt_set_bool || (void *)opt->cb == (void *)opt_set_invbool) &&
  5940. (*(bool *)opt->u.arg == ((void *)opt->cb == (void *)opt_set_bool)))
  5941. fprintf(fcfg, ",\n\"%s\" : true", p+2);
  5942. if (opt->type & OPT_HASARG &&
  5943. ((void *)opt->cb_arg == (void *)set_int_0_to_9999 ||
  5944. (void *)opt->cb_arg == (void *)set_int_1_to_65535 ||
  5945. (void *)opt->cb_arg == (void *)set_int_0_to_10 ||
  5946. (void *)opt->cb_arg == (void *)set_int_1_to_10) &&
  5947. opt->desc != opt_hidden &&
  5948. 0 <= *(int *)opt->u.arg)
  5949. fprintf(fcfg, ",\n\"%s\" : \"%d\"", p+2, *(int *)opt->u.arg);
  5950. }
  5951. }
  5952. /* Special case options */
  5953. if (request_target_str)
  5954. {
  5955. if (request_pdiff == (long)request_pdiff)
  5956. fprintf(fcfg, ",\n\"request-diff\" : %ld", (long)request_pdiff);
  5957. else
  5958. fprintf(fcfg, ",\n\"request-diff\" : %f", request_pdiff);
  5959. }
  5960. fprintf(fcfg, ",\n\"shares\" : %g", opt_shares);
  5961. if (pool_strategy == POOL_BALANCE)
  5962. fputs(",\n\"balance\" : true", fcfg);
  5963. if (pool_strategy == POOL_LOADBALANCE)
  5964. fputs(",\n\"load-balance\" : true", fcfg);
  5965. if (pool_strategy == POOL_ROUNDROBIN)
  5966. fputs(",\n\"round-robin\" : true", fcfg);
  5967. if (pool_strategy == POOL_ROTATE)
  5968. fprintf(fcfg, ",\n\"rotate\" : \"%d\"", opt_rotate_period);
  5969. #if defined(unix) || defined(__APPLE__)
  5970. if (opt_stderr_cmd && *opt_stderr_cmd)
  5971. fprintf(fcfg, ",\n\"monitor\" : \"%s\"", json_escape(opt_stderr_cmd));
  5972. #endif // defined(unix)
  5973. if (opt_kernel_path && *opt_kernel_path) {
  5974. char *kpath = strdup(opt_kernel_path);
  5975. if (kpath[strlen(kpath)-1] == '/')
  5976. kpath[strlen(kpath)-1] = 0;
  5977. fprintf(fcfg, ",\n\"kernel-path\" : \"%s\"", json_escape(kpath));
  5978. free(kpath);
  5979. }
  5980. if (schedstart.enable)
  5981. fprintf(fcfg, ",\n\"sched-time\" : \"%d:%d\"", schedstart.tm.tm_hour, schedstart.tm.tm_min);
  5982. if (schedstop.enable)
  5983. fprintf(fcfg, ",\n\"stop-time\" : \"%d:%d\"", schedstop.tm.tm_hour, schedstop.tm.tm_min);
  5984. if (opt_socks_proxy && *opt_socks_proxy)
  5985. fprintf(fcfg, ",\n\"socks-proxy\" : \"%s\"", json_escape(opt_socks_proxy));
  5986. _write_config_string_elist(fcfg, "scan", scan_devices);
  5987. #ifdef USE_LIBMICROHTTPD
  5988. if (httpsrv_port != -1)
  5989. fprintf(fcfg, ",\n\"http-port\" : %d", httpsrv_port);
  5990. #endif
  5991. #ifdef USE_LIBEVENT
  5992. if (stratumsrv_port != -1)
  5993. fprintf(fcfg, ",\n\"stratum-port\" : %d", stratumsrv_port);
  5994. #endif
  5995. _write_config_string_elist(fcfg, "device", opt_devices_enabled_list);
  5996. _write_config_string_elist(fcfg, "set-device", opt_set_device_list);
  5997. if (opt_api_allow)
  5998. fprintf(fcfg, ",\n\"api-allow\" : \"%s\"", json_escape(opt_api_allow));
  5999. if (strcmp(opt_api_mcast_addr, API_MCAST_ADDR) != 0)
  6000. fprintf(fcfg, ",\n\"api-mcast-addr\" : \"%s\"", json_escape(opt_api_mcast_addr));
  6001. if (strcmp(opt_api_mcast_code, API_MCAST_CODE) != 0)
  6002. fprintf(fcfg, ",\n\"api-mcast-code\" : \"%s\"", json_escape(opt_api_mcast_code));
  6003. if (*opt_api_mcast_des)
  6004. fprintf(fcfg, ",\n\"api-mcast-des\" : \"%s\"", json_escape(opt_api_mcast_des));
  6005. if (strcmp(opt_api_description, PACKAGE_STRING) != 0)
  6006. fprintf(fcfg, ",\n\"api-description\" : \"%s\"", json_escape(opt_api_description));
  6007. if (opt_api_groups)
  6008. fprintf(fcfg, ",\n\"api-groups\" : \"%s\"", json_escape(opt_api_groups));
  6009. fputs("\n}\n", fcfg);
  6010. json_escape_free();
  6011. }
  6012. void zero_bestshare(void)
  6013. {
  6014. int i;
  6015. best_diff = 0;
  6016. suffix_string(best_diff, best_share, sizeof(best_share), 0);
  6017. for (i = 0; i < total_pools; i++) {
  6018. struct pool *pool = pools[i];
  6019. pool->best_diff = 0;
  6020. }
  6021. }
  6022. void zero_stats(void)
  6023. {
  6024. int i;
  6025. applog(LOG_DEBUG, "Zeroing stats");
  6026. cgtime(&total_tv_start);
  6027. miner_started = total_tv_start;
  6028. total_rolling = 0;
  6029. total_mhashes_done = 0;
  6030. total_getworks = 0;
  6031. total_accepted = 0;
  6032. total_rejected = 0;
  6033. hw_errors = 0;
  6034. total_stale = 0;
  6035. total_discarded = 0;
  6036. total_bytes_rcvd = total_bytes_sent = 0;
  6037. new_blocks = 0;
  6038. local_work = 0;
  6039. total_go = 0;
  6040. total_ro = 0;
  6041. total_secs = 1.0;
  6042. total_diff1 = 0;
  6043. total_bad_diff1 = 0;
  6044. found_blocks = 0;
  6045. total_diff_accepted = 0;
  6046. total_diff_rejected = 0;
  6047. total_diff_stale = 0;
  6048. #ifdef HAVE_CURSES
  6049. awidth = rwidth = swidth = hwwidth = 1;
  6050. #endif
  6051. for (i = 0; i < total_pools; i++) {
  6052. struct pool *pool = pools[i];
  6053. pool->getwork_requested = 0;
  6054. pool->accepted = 0;
  6055. pool->rejected = 0;
  6056. pool->solved = 0;
  6057. pool->getwork_requested = 0;
  6058. pool->stale_shares = 0;
  6059. pool->discarded_work = 0;
  6060. pool->getfail_occasions = 0;
  6061. pool->remotefail_occasions = 0;
  6062. pool->last_share_time = 0;
  6063. pool->diff1 = 0;
  6064. pool->diff_accepted = 0;
  6065. pool->diff_rejected = 0;
  6066. pool->diff_stale = 0;
  6067. pool->last_share_diff = 0;
  6068. pool->cgminer_stats.start_tv = total_tv_start;
  6069. pool->cgminer_stats.getwork_calls = 0;
  6070. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6071. pool->cgminer_stats.getwork_wait_max.tv_sec = 0;
  6072. pool->cgminer_stats.getwork_wait_max.tv_usec = 0;
  6073. pool->cgminer_pool_stats.getwork_calls = 0;
  6074. pool->cgminer_pool_stats.getwork_attempts = 0;
  6075. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6076. pool->cgminer_pool_stats.getwork_wait_max.tv_sec = 0;
  6077. pool->cgminer_pool_stats.getwork_wait_max.tv_usec = 0;
  6078. pool->cgminer_pool_stats.min_diff = 0;
  6079. pool->cgminer_pool_stats.max_diff = 0;
  6080. pool->cgminer_pool_stats.min_diff_count = 0;
  6081. pool->cgminer_pool_stats.max_diff_count = 0;
  6082. pool->cgminer_pool_stats.times_sent = 0;
  6083. pool->cgminer_pool_stats.bytes_sent = 0;
  6084. pool->cgminer_pool_stats.net_bytes_sent = 0;
  6085. pool->cgminer_pool_stats.times_received = 0;
  6086. pool->cgminer_pool_stats.bytes_received = 0;
  6087. pool->cgminer_pool_stats.net_bytes_received = 0;
  6088. }
  6089. zero_bestshare();
  6090. for (i = 0; i < total_devices; ++i) {
  6091. struct cgpu_info *cgpu = get_devices(i);
  6092. mutex_lock(&hash_lock);
  6093. cgpu->total_mhashes = 0;
  6094. cgpu->accepted = 0;
  6095. cgpu->rejected = 0;
  6096. cgpu->stale = 0;
  6097. cgpu->hw_errors = 0;
  6098. cgpu->utility = 0.0;
  6099. cgpu->utility_diff1 = 0;
  6100. cgpu->last_share_pool_time = 0;
  6101. cgpu->bad_diff1 = 0;
  6102. cgpu->diff1 = 0;
  6103. cgpu->diff_accepted = 0;
  6104. cgpu->diff_rejected = 0;
  6105. cgpu->diff_stale = 0;
  6106. cgpu->last_share_diff = 0;
  6107. cgpu->thread_fail_init_count = 0;
  6108. cgpu->thread_zero_hash_count = 0;
  6109. cgpu->thread_fail_queue_count = 0;
  6110. cgpu->dev_sick_idle_60_count = 0;
  6111. cgpu->dev_dead_idle_600_count = 0;
  6112. cgpu->dev_nostart_count = 0;
  6113. cgpu->dev_over_heat_count = 0;
  6114. cgpu->dev_thermal_cutoff_count = 0;
  6115. cgpu->dev_comms_error_count = 0;
  6116. cgpu->dev_throttle_count = 0;
  6117. cgpu->cgminer_stats.start_tv = total_tv_start;
  6118. cgpu->cgminer_stats.getwork_calls = 0;
  6119. cgpu->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6120. cgpu->cgminer_stats.getwork_wait_max.tv_sec = 0;
  6121. cgpu->cgminer_stats.getwork_wait_max.tv_usec = 0;
  6122. mutex_unlock(&hash_lock);
  6123. }
  6124. }
  6125. #ifdef HAVE_CURSES
  6126. static
  6127. void loginput_mode(const int size)
  6128. {
  6129. clear_logwin();
  6130. loginput_size = size;
  6131. check_winsizes();
  6132. }
  6133. static void display_pools(void)
  6134. {
  6135. struct pool *pool;
  6136. int selected, i, j;
  6137. char input;
  6138. loginput_mode(7 + total_pools);
  6139. immedok(logwin, true);
  6140. updated:
  6141. for (j = 0; j < total_pools; j++) {
  6142. for (i = 0; i < total_pools; i++) {
  6143. pool = pools[i];
  6144. if (pool->prio != j)
  6145. continue;
  6146. if (pool == current_pool())
  6147. wattron(logwin, A_BOLD);
  6148. if (pool->enabled != POOL_ENABLED)
  6149. wattron(logwin, A_DIM);
  6150. wlogprint("%d: ", pool->prio);
  6151. switch (pool->enabled) {
  6152. case POOL_ENABLED:
  6153. wlogprint("Enabled ");
  6154. break;
  6155. case POOL_DISABLED:
  6156. wlogprint("Disabled ");
  6157. break;
  6158. case POOL_REJECTING:
  6159. wlogprint("Rejectin ");
  6160. break;
  6161. }
  6162. _wlogprint(pool_proto_str(pool));
  6163. wlogprint(" Quota %d Pool %d: %s User:%s\n",
  6164. pool->quota,
  6165. pool->pool_no,
  6166. pool->rpc_url, pool->rpc_user);
  6167. wattroff(logwin, A_BOLD | A_DIM);
  6168. break; //for (i = 0; i < total_pools; i++)
  6169. }
  6170. }
  6171. retry:
  6172. wlogprint("\nCurrent pool management strategy: %s\n",
  6173. strategies[pool_strategy].s);
  6174. if (pool_strategy == POOL_ROTATE)
  6175. wlogprint("Set to rotate every %d minutes\n", opt_rotate_period);
  6176. wlogprint("[F]ailover only %s\n", opt_fail_only ? "enabled" : "disabled");
  6177. wlogprint("Pool [A]dd [R]emove [D]isable [E]nable [P]rioritize [Q]uota change\n");
  6178. wlogprint("[C]hange management strategy [S]witch pool [I]nformation\n");
  6179. wlogprint("Or press any other key to continue\n");
  6180. logwin_update();
  6181. input = getch();
  6182. if (!strncasecmp(&input, "a", 1)) {
  6183. if (opt_benchmark)
  6184. {
  6185. wlogprint("Cannot add pools in benchmark mode");
  6186. goto retry;
  6187. }
  6188. input_pool(true);
  6189. goto updated;
  6190. } else if (!strncasecmp(&input, "r", 1)) {
  6191. if (total_pools <= 1) {
  6192. wlogprint("Cannot remove last pool");
  6193. goto retry;
  6194. }
  6195. selected = curses_int("Select pool number");
  6196. if (selected < 0 || selected >= total_pools) {
  6197. wlogprint("Invalid selection\n");
  6198. goto retry;
  6199. }
  6200. pool = pools[selected];
  6201. if (pool == current_pool())
  6202. switch_pools(NULL);
  6203. if (pool == current_pool()) {
  6204. wlogprint("Unable to remove pool due to activity\n");
  6205. goto retry;
  6206. }
  6207. disable_pool(pool);
  6208. remove_pool(pool);
  6209. goto updated;
  6210. } else if (!strncasecmp(&input, "s", 1)) {
  6211. selected = curses_int("Select pool number");
  6212. if (selected < 0 || selected >= total_pools) {
  6213. wlogprint("Invalid selection\n");
  6214. goto retry;
  6215. }
  6216. pool = pools[selected];
  6217. enable_pool(pool);
  6218. switch_pools(pool);
  6219. goto updated;
  6220. } else if (!strncasecmp(&input, "d", 1)) {
  6221. if (enabled_pools <= 1) {
  6222. wlogprint("Cannot disable last pool");
  6223. goto retry;
  6224. }
  6225. selected = curses_int("Select pool number");
  6226. if (selected < 0 || selected >= total_pools) {
  6227. wlogprint("Invalid selection\n");
  6228. goto retry;
  6229. }
  6230. pool = pools[selected];
  6231. disable_pool(pool);
  6232. if (pool == current_pool())
  6233. switch_pools(NULL);
  6234. goto updated;
  6235. } else if (!strncasecmp(&input, "e", 1)) {
  6236. selected = curses_int("Select pool number");
  6237. if (selected < 0 || selected >= total_pools) {
  6238. wlogprint("Invalid selection\n");
  6239. goto retry;
  6240. }
  6241. pool = pools[selected];
  6242. enable_pool(pool);
  6243. if (pool->prio < current_pool()->prio)
  6244. switch_pools(pool);
  6245. goto updated;
  6246. } else if (!strncasecmp(&input, "c", 1)) {
  6247. for (i = 0; i <= TOP_STRATEGY; i++)
  6248. wlogprint("%d: %s\n", i, strategies[i].s);
  6249. selected = curses_int("Select strategy number type");
  6250. if (selected < 0 || selected > TOP_STRATEGY) {
  6251. wlogprint("Invalid selection\n");
  6252. goto retry;
  6253. }
  6254. if (selected == POOL_ROTATE) {
  6255. opt_rotate_period = curses_int("Select interval in minutes");
  6256. if (opt_rotate_period < 0 || opt_rotate_period > 9999) {
  6257. opt_rotate_period = 0;
  6258. wlogprint("Invalid selection\n");
  6259. goto retry;
  6260. }
  6261. }
  6262. pool_strategy = selected;
  6263. switch_pools(NULL);
  6264. goto updated;
  6265. } else if (!strncasecmp(&input, "i", 1)) {
  6266. selected = curses_int("Select pool number");
  6267. if (selected < 0 || selected >= total_pools) {
  6268. wlogprint("Invalid selection\n");
  6269. goto retry;
  6270. }
  6271. pool = pools[selected];
  6272. display_pool_summary(pool);
  6273. goto retry;
  6274. } else if (!strncasecmp(&input, "q", 1)) {
  6275. selected = curses_int("Select pool number");
  6276. if (selected < 0 || selected >= total_pools) {
  6277. wlogprint("Invalid selection\n");
  6278. goto retry;
  6279. }
  6280. pool = pools[selected];
  6281. selected = curses_int("Set quota");
  6282. if (selected < 0) {
  6283. wlogprint("Invalid negative quota\n");
  6284. goto retry;
  6285. }
  6286. pool->quota = selected;
  6287. adjust_quota_gcd();
  6288. goto updated;
  6289. } else if (!strncasecmp(&input, "f", 1)) {
  6290. opt_fail_only ^= true;
  6291. goto updated;
  6292. } else if (!strncasecmp(&input, "p", 1)) {
  6293. char *prilist = curses_input("Enter new pool priority (comma separated list)");
  6294. if (!prilist)
  6295. {
  6296. wlogprint("Not changing priorities\n");
  6297. goto retry;
  6298. }
  6299. int res = prioritize_pools(prilist, &i);
  6300. free(prilist);
  6301. switch (res) {
  6302. case MSG_NOPOOL:
  6303. wlogprint("No pools\n");
  6304. goto retry;
  6305. case MSG_MISPID:
  6306. wlogprint("Missing pool id parameter\n");
  6307. goto retry;
  6308. case MSG_INVPID:
  6309. wlogprint("Invalid pool id %d - range is 0 - %d\n", i, total_pools - 1);
  6310. goto retry;
  6311. case MSG_DUPPID:
  6312. wlogprint("Duplicate pool specified %d\n", i);
  6313. goto retry;
  6314. case MSG_POOLPRIO:
  6315. default:
  6316. goto updated;
  6317. }
  6318. }
  6319. immedok(logwin, false);
  6320. loginput_mode(0);
  6321. }
  6322. static const char *summary_detail_level_str(void)
  6323. {
  6324. if (opt_compact)
  6325. return "compact";
  6326. if (opt_show_procs)
  6327. return "processors";
  6328. return "devices";
  6329. }
  6330. static void display_options(void)
  6331. {
  6332. int selected;
  6333. char input;
  6334. immedok(logwin, true);
  6335. loginput_mode(12);
  6336. retry:
  6337. clear_logwin();
  6338. wlogprint("[N]ormal [C]lear [S]ilent mode (disable all output)\n");
  6339. wlogprint("[D]ebug:%s\n[P]er-device:%s\n[Q]uiet:%s\n[V]erbose:%s\n"
  6340. "[R]PC debug:%s\n[W]orkTime details:%s\nsu[M]mary detail level:%s\n"
  6341. "[L]og interval:%d\nS[T]atistical counts: %s\n[Z]ero statistics\n",
  6342. opt_debug_console ? "on" : "off",
  6343. want_per_device_stats? "on" : "off",
  6344. opt_quiet ? "on" : "off",
  6345. opt_log_output ? "on" : "off",
  6346. opt_protocol ? "on" : "off",
  6347. opt_worktime ? "on" : "off",
  6348. summary_detail_level_str(),
  6349. opt_log_interval,
  6350. opt_weighed_stats ? "weighed" : "absolute");
  6351. wlogprint("Select an option or any other key to return\n");
  6352. logwin_update();
  6353. input = getch();
  6354. if (!strncasecmp(&input, "q", 1)) {
  6355. opt_quiet ^= true;
  6356. wlogprint("Quiet mode %s\n", opt_quiet ? "enabled" : "disabled");
  6357. goto retry;
  6358. } else if (!strncasecmp(&input, "v", 1)) {
  6359. opt_log_output ^= true;
  6360. if (opt_log_output)
  6361. opt_quiet = false;
  6362. wlogprint("Verbose mode %s\n", opt_log_output ? "enabled" : "disabled");
  6363. goto retry;
  6364. } else if (!strncasecmp(&input, "n", 1)) {
  6365. opt_log_output = false;
  6366. opt_debug_console = false;
  6367. opt_quiet = false;
  6368. opt_protocol = false;
  6369. opt_compact = false;
  6370. opt_show_procs = false;
  6371. devsummaryYOffset = 0;
  6372. want_per_device_stats = false;
  6373. wlogprint("Output mode reset to normal\n");
  6374. switch_logsize();
  6375. goto retry;
  6376. } else if (!strncasecmp(&input, "d", 1)) {
  6377. opt_debug = true;
  6378. opt_debug_console ^= true;
  6379. opt_log_output = opt_debug_console;
  6380. if (opt_debug_console)
  6381. opt_quiet = false;
  6382. wlogprint("Debug mode %s\n", opt_debug_console ? "enabled" : "disabled");
  6383. goto retry;
  6384. } else if (!strncasecmp(&input, "m", 1)) {
  6385. if (opt_compact)
  6386. opt_compact = false;
  6387. else
  6388. if (!opt_show_procs)
  6389. opt_show_procs = true;
  6390. else
  6391. {
  6392. opt_compact = true;
  6393. opt_show_procs = false;
  6394. devsummaryYOffset = 0;
  6395. }
  6396. wlogprint("su[M]mary detail level changed to: %s\n", summary_detail_level_str());
  6397. switch_logsize();
  6398. goto retry;
  6399. } else if (!strncasecmp(&input, "p", 1)) {
  6400. want_per_device_stats ^= true;
  6401. opt_log_output = want_per_device_stats;
  6402. wlogprint("Per-device stats %s\n", want_per_device_stats ? "enabled" : "disabled");
  6403. goto retry;
  6404. } else if (!strncasecmp(&input, "r", 1)) {
  6405. opt_protocol ^= true;
  6406. if (opt_protocol)
  6407. opt_quiet = false;
  6408. wlogprint("RPC protocol debugging %s\n", opt_protocol ? "enabled" : "disabled");
  6409. goto retry;
  6410. } else if (!strncasecmp(&input, "c", 1))
  6411. clear_logwin();
  6412. else if (!strncasecmp(&input, "l", 1)) {
  6413. selected = curses_int("Interval in seconds");
  6414. if (selected < 0 || selected > 9999) {
  6415. wlogprint("Invalid selection\n");
  6416. goto retry;
  6417. }
  6418. opt_log_interval = selected;
  6419. wlogprint("Log interval set to %d seconds\n", opt_log_interval);
  6420. goto retry;
  6421. } else if (!strncasecmp(&input, "s", 1)) {
  6422. opt_realquiet = true;
  6423. } else if (!strncasecmp(&input, "w", 1)) {
  6424. opt_worktime ^= true;
  6425. wlogprint("WorkTime details %s\n", opt_worktime ? "enabled" : "disabled");
  6426. goto retry;
  6427. } else if (!strncasecmp(&input, "t", 1)) {
  6428. opt_weighed_stats ^= true;
  6429. wlogprint("Now displaying %s statistics\n", opt_weighed_stats ? "weighed" : "absolute");
  6430. goto retry;
  6431. } else if (!strncasecmp(&input, "z", 1)) {
  6432. zero_stats();
  6433. goto retry;
  6434. }
  6435. immedok(logwin, false);
  6436. loginput_mode(0);
  6437. }
  6438. #endif
  6439. void default_save_file(char *filename)
  6440. {
  6441. #if defined(unix) || defined(__APPLE__)
  6442. if (getenv("HOME") && *getenv("HOME")) {
  6443. strcpy(filename, getenv("HOME"));
  6444. strcat(filename, "/");
  6445. }
  6446. else
  6447. strcpy(filename, "");
  6448. strcat(filename, ".bfgminer/");
  6449. mkdir(filename, 0777);
  6450. #else
  6451. strcpy(filename, "");
  6452. #endif
  6453. strcat(filename, def_conf);
  6454. }
  6455. #ifdef HAVE_CURSES
  6456. static void set_options(void)
  6457. {
  6458. int selected;
  6459. char input;
  6460. immedok(logwin, true);
  6461. loginput_mode(8);
  6462. retry:
  6463. wlogprint("\n[L]ongpoll: %s\n", want_longpoll ? "On" : "Off");
  6464. wlogprint("[Q]ueue: %d\n[S]cantime: %d\n[E]xpiry: %d\n[R]etries: %d\n"
  6465. "[W]rite config file\n[B]FGMiner restart\n",
  6466. opt_queue, opt_scantime, opt_expiry, opt_retries);
  6467. wlogprint("Select an option or any other key to return\n");
  6468. logwin_update();
  6469. input = getch();
  6470. if (!strncasecmp(&input, "q", 1)) {
  6471. selected = curses_int("Extra work items to queue");
  6472. if (selected < 0 || selected > 9999) {
  6473. wlogprint("Invalid selection\n");
  6474. goto retry;
  6475. }
  6476. opt_queue = selected;
  6477. goto retry;
  6478. } else if (!strncasecmp(&input, "l", 1)) {
  6479. if (want_longpoll)
  6480. stop_longpoll();
  6481. else
  6482. start_longpoll();
  6483. applog(LOG_WARNING, "Longpoll %s", want_longpoll ? "enabled" : "disabled");
  6484. goto retry;
  6485. } else if (!strncasecmp(&input, "s", 1)) {
  6486. selected = curses_int("Set scantime in seconds");
  6487. if (selected < 0 || selected > 9999) {
  6488. wlogprint("Invalid selection\n");
  6489. goto retry;
  6490. }
  6491. opt_scantime = selected;
  6492. goto retry;
  6493. } else if (!strncasecmp(&input, "e", 1)) {
  6494. selected = curses_int("Set expiry time in seconds");
  6495. if (selected < 0 || selected > 9999) {
  6496. wlogprint("Invalid selection\n");
  6497. goto retry;
  6498. }
  6499. opt_expiry = selected;
  6500. goto retry;
  6501. } else if (!strncasecmp(&input, "r", 1)) {
  6502. selected = curses_int("Retries before failing (-1 infinite)");
  6503. if (selected < -1 || selected > 9999) {
  6504. wlogprint("Invalid selection\n");
  6505. goto retry;
  6506. }
  6507. opt_retries = selected;
  6508. goto retry;
  6509. } else if (!strncasecmp(&input, "w", 1)) {
  6510. FILE *fcfg;
  6511. char *str, filename[PATH_MAX], prompt[PATH_MAX + 50];
  6512. default_save_file(filename);
  6513. snprintf(prompt, sizeof(prompt), "Config filename to write (Enter for default) [%s]", filename);
  6514. str = curses_input(prompt);
  6515. if (str) {
  6516. struct stat statbuf;
  6517. strcpy(filename, str);
  6518. free(str);
  6519. if (!stat(filename, &statbuf)) {
  6520. wlogprint("File exists, overwrite?\n");
  6521. input = getch();
  6522. if (strncasecmp(&input, "y", 1))
  6523. goto retry;
  6524. }
  6525. }
  6526. fcfg = fopen(filename, "w");
  6527. if (!fcfg) {
  6528. wlogprint("Cannot open or create file\n");
  6529. goto retry;
  6530. }
  6531. write_config(fcfg);
  6532. fclose(fcfg);
  6533. goto retry;
  6534. } else if (!strncasecmp(&input, "b", 1)) {
  6535. wlogprint("Are you sure?\n");
  6536. input = getch();
  6537. if (!strncasecmp(&input, "y", 1))
  6538. app_restart();
  6539. else
  6540. clear_logwin();
  6541. } else
  6542. clear_logwin();
  6543. loginput_mode(0);
  6544. immedok(logwin, false);
  6545. }
  6546. int scan_serial(const char *);
  6547. static
  6548. void _managetui_msg(const char *repr, const char **msg)
  6549. {
  6550. if (*msg)
  6551. {
  6552. applog(LOG_DEBUG, "ManageTUI: %"PRIpreprv": %s", repr, *msg);
  6553. wattron(logwin, A_BOLD);
  6554. wlogprint("%s", *msg);
  6555. wattroff(logwin, A_BOLD);
  6556. *msg = NULL;
  6557. }
  6558. logwin_update();
  6559. }
  6560. void manage_device(void)
  6561. {
  6562. char logline[256];
  6563. const char *msg = NULL;
  6564. struct cgpu_info *cgpu;
  6565. const struct device_drv *drv;
  6566. selecting_device = true;
  6567. immedok(logwin, true);
  6568. loginput_mode(12);
  6569. devchange:
  6570. if (unlikely(!total_devices))
  6571. {
  6572. clear_logwin();
  6573. wlogprint("(no devices)\n");
  6574. wlogprint("[Plus] Add device(s) [Enter] Close device manager\n");
  6575. _managetui_msg("(none)", &msg);
  6576. int input = getch();
  6577. switch (input)
  6578. {
  6579. case '+': case '=': // add new device
  6580. goto addnew;
  6581. default:
  6582. goto out;
  6583. }
  6584. }
  6585. cgpu = devices[selected_device];
  6586. drv = cgpu->drv;
  6587. refresh_devstatus();
  6588. refresh:
  6589. clear_logwin();
  6590. wlogprint("Select processor to manage using up/down arrow keys\n");
  6591. get_statline3(logline, sizeof(logline), cgpu, true, true);
  6592. wattron(logwin, A_BOLD);
  6593. wlogprint("%s", logline);
  6594. wattroff(logwin, A_BOLD);
  6595. wlogprint("\n");
  6596. if (cgpu->dev_manufacturer)
  6597. wlogprint(" %s from %s\n", (cgpu->dev_product ?: "Device"), cgpu->dev_manufacturer);
  6598. else
  6599. if (cgpu->dev_product)
  6600. wlogprint(" %s\n", cgpu->dev_product);
  6601. if (cgpu->dev_serial)
  6602. wlogprint("Serial: %s\n", cgpu->dev_serial);
  6603. if (cgpu->kname)
  6604. wlogprint("Kernel: %s\n", cgpu->kname);
  6605. if (drv->proc_wlogprint_status && likely(cgpu->status != LIFE_INIT))
  6606. drv->proc_wlogprint_status(cgpu);
  6607. wlogprint("\n");
  6608. // TODO: Last share at TIMESTAMP on pool N
  6609. // TODO: Custom device info/commands
  6610. if (cgpu->deven != DEV_ENABLED)
  6611. wlogprint("[E]nable ");
  6612. if (cgpu->deven != DEV_DISABLED)
  6613. wlogprint("[D]isable ");
  6614. if (drv->identify_device)
  6615. wlogprint("[I]dentify ");
  6616. if (drv->proc_tui_wlogprint_choices && likely(cgpu->status != LIFE_INIT))
  6617. drv->proc_tui_wlogprint_choices(cgpu);
  6618. wlogprint("\n");
  6619. wlogprint("[Slash] Find processor [Plus] Add device(s) [Enter] Close device manager\n");
  6620. _managetui_msg(cgpu->proc_repr, &msg);
  6621. while (true)
  6622. {
  6623. int input = getch();
  6624. applog(LOG_DEBUG, "ManageTUI: %"PRIpreprv": (choice %d)", cgpu->proc_repr, input);
  6625. switch (input) {
  6626. case 'd': case 'D':
  6627. if (cgpu->deven == DEV_DISABLED)
  6628. msg = "Processor already disabled\n";
  6629. else
  6630. {
  6631. cgpu->deven = DEV_DISABLED;
  6632. msg = "Processor being disabled\n";
  6633. }
  6634. goto refresh;
  6635. case 'e': case 'E':
  6636. if (cgpu->deven == DEV_ENABLED)
  6637. msg = "Processor already enabled\n";
  6638. else
  6639. {
  6640. proc_enable(cgpu);
  6641. msg = "Processor being enabled\n";
  6642. }
  6643. goto refresh;
  6644. case 'i': case 'I':
  6645. if (drv->identify_device && drv->identify_device(cgpu))
  6646. msg = "Identify command sent\n";
  6647. else
  6648. goto key_default;
  6649. goto refresh;
  6650. case KEY_DOWN:
  6651. if (selected_device >= total_devices - 1)
  6652. break;
  6653. ++selected_device;
  6654. goto devchange;
  6655. case KEY_UP:
  6656. if (selected_device <= 0)
  6657. break;
  6658. --selected_device;
  6659. goto devchange;
  6660. case KEY_NPAGE:
  6661. {
  6662. if (selected_device >= total_devices - 1)
  6663. break;
  6664. struct cgpu_info *mdev = devices[selected_device]->device;
  6665. do {
  6666. ++selected_device;
  6667. } while (devices[selected_device]->device == mdev && selected_device < total_devices - 1);
  6668. goto devchange;
  6669. }
  6670. case KEY_PPAGE:
  6671. {
  6672. if (selected_device <= 0)
  6673. break;
  6674. struct cgpu_info *mdev = devices[selected_device]->device;
  6675. do {
  6676. --selected_device;
  6677. } while (devices[selected_device]->device == mdev && selected_device > 0);
  6678. goto devchange;
  6679. }
  6680. case '/': case '?': // find device
  6681. {
  6682. static char *pattern = NULL;
  6683. char *newpattern = curses_input("Enter pattern");
  6684. if (newpattern)
  6685. {
  6686. free(pattern);
  6687. pattern = newpattern;
  6688. }
  6689. else
  6690. if (!pattern)
  6691. pattern = calloc(1, 1);
  6692. int match = cgpu_search(pattern, selected_device + 1);
  6693. if (match == -1)
  6694. {
  6695. msg = "Couldn't find device\n";
  6696. goto refresh;
  6697. }
  6698. selected_device = match;
  6699. goto devchange;
  6700. }
  6701. case '+': case '=': // add new device
  6702. {
  6703. addnew:
  6704. clear_logwin();
  6705. _wlogprint(
  6706. "Enter \"auto\", \"all\", or a serial port to probe for mining devices.\n"
  6707. "Prefix by a driver name and colon to only probe a specific driver.\n"
  6708. "For example: erupter:"
  6709. #ifdef WIN32
  6710. "\\\\.\\COM40"
  6711. #elif defined(__APPLE__)
  6712. "/dev/cu.SLAB_USBtoUART"
  6713. #else
  6714. "/dev/ttyUSB39"
  6715. #endif
  6716. "\n"
  6717. );
  6718. char *scanser = curses_input("Enter target");
  6719. if (scan_serial(scanser))
  6720. {
  6721. selected_device = total_devices - 1;
  6722. msg = "Device scan succeeded\n";
  6723. }
  6724. else
  6725. msg = "No new devices found\n";
  6726. goto devchange;
  6727. }
  6728. case 'Q': case 'q':
  6729. case KEY_BREAK: case KEY_BACKSPACE: case KEY_CANCEL: case KEY_CLOSE: case KEY_EXIT:
  6730. case '\x1b': // ESC
  6731. case KEY_ENTER:
  6732. case '\r': // Ctrl-M on Windows, with nonl
  6733. #ifdef PADENTER
  6734. case PADENTER: // pdcurses, used by Enter key on Windows with nonl
  6735. #endif
  6736. case '\n':
  6737. goto out;
  6738. default:
  6739. ;
  6740. key_default:
  6741. if (drv->proc_tui_handle_choice && likely(drv_ready(cgpu)))
  6742. {
  6743. msg = drv->proc_tui_handle_choice(cgpu, input);
  6744. if (msg)
  6745. goto refresh;
  6746. }
  6747. }
  6748. }
  6749. out:
  6750. selecting_device = false;
  6751. loginput_mode(0);
  6752. immedok(logwin, false);
  6753. }
  6754. void show_help(void)
  6755. {
  6756. loginput_mode(11);
  6757. // NOTE: wlogprint is a macro with a buffer limit
  6758. _wlogprint(
  6759. "LU: oldest explicit work update currently being used for new work\n"
  6760. "ST: work in queue | F: network fails | NB: new blocks detected\n"
  6761. "AS: shares being submitted | BW: bandwidth (up/down)\n"
  6762. "E: # shares * diff per 2kB bw | I: expected income | BS: best share ever found\n"
  6763. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6764. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6765. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6766. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_BTEE
  6767. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6768. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6769. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_BTEE U8_HLINE U8_HLINE U8_HLINE
  6770. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6771. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6772. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6773. "\n"
  6774. "devices/processors hashing (only for totals line), hottest temperature\n"
  6775. );
  6776. wlogprint(
  6777. "hashrates: %ds decaying / all-time average / all-time average (effective)\n"
  6778. , opt_log_interval);
  6779. _wlogprint(
  6780. "A: accepted shares | R: rejected+discarded(% of total)\n"
  6781. "HW: hardware errors / % nonces invalid\n"
  6782. "\n"
  6783. "Press any key to clear"
  6784. );
  6785. logwin_update();
  6786. getch();
  6787. loginput_mode(0);
  6788. }
  6789. static void *input_thread(void __maybe_unused *userdata)
  6790. {
  6791. RenameThread("input");
  6792. if (!curses_active)
  6793. return NULL;
  6794. while (1) {
  6795. int input;
  6796. input = getch();
  6797. switch (input) {
  6798. case 'h': case 'H': case '?':
  6799. case KEY_F(1):
  6800. show_help();
  6801. break;
  6802. case 'q': case 'Q':
  6803. kill_work();
  6804. return NULL;
  6805. case 'd': case 'D':
  6806. display_options();
  6807. break;
  6808. case 'm': case 'M':
  6809. manage_device();
  6810. break;
  6811. case 'p': case 'P':
  6812. display_pools();
  6813. break;
  6814. case 's': case 'S':
  6815. set_options();
  6816. break;
  6817. #ifdef HAVE_CURSES
  6818. case KEY_DOWN:
  6819. {
  6820. const int visible_lines = logcursor - devcursor;
  6821. const int invisible_lines = total_lines - visible_lines;
  6822. if (devsummaryYOffset <= -invisible_lines)
  6823. break;
  6824. devsummaryYOffset -= 2;
  6825. }
  6826. case KEY_UP:
  6827. if (devsummaryYOffset == 0)
  6828. break;
  6829. ++devsummaryYOffset;
  6830. refresh_devstatus();
  6831. break;
  6832. case KEY_NPAGE:
  6833. {
  6834. const int visible_lines = logcursor - devcursor;
  6835. const int invisible_lines = total_lines - visible_lines;
  6836. if (devsummaryYOffset - visible_lines <= -invisible_lines)
  6837. devsummaryYOffset = -invisible_lines;
  6838. else
  6839. devsummaryYOffset -= visible_lines;
  6840. refresh_devstatus();
  6841. break;
  6842. }
  6843. case KEY_PPAGE:
  6844. {
  6845. const int visible_lines = logcursor - devcursor;
  6846. if (devsummaryYOffset + visible_lines >= 0)
  6847. devsummaryYOffset = 0;
  6848. else
  6849. devsummaryYOffset += visible_lines;
  6850. refresh_devstatus();
  6851. break;
  6852. }
  6853. #endif
  6854. }
  6855. if (opt_realquiet) {
  6856. disable_curses();
  6857. break;
  6858. }
  6859. }
  6860. return NULL;
  6861. }
  6862. #endif
  6863. static void *api_thread(void *userdata)
  6864. {
  6865. struct thr_info *mythr = userdata;
  6866. pthread_detach(pthread_self());
  6867. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  6868. RenameThread("rpc");
  6869. api(api_thr_id);
  6870. mythr->has_pth = false;
  6871. return NULL;
  6872. }
  6873. void thread_reportin(struct thr_info *thr)
  6874. {
  6875. cgtime(&thr->last);
  6876. thr->cgpu->status = LIFE_WELL;
  6877. thr->getwork = 0;
  6878. thr->cgpu->device_last_well = time(NULL);
  6879. }
  6880. void thread_reportout(struct thr_info *thr)
  6881. {
  6882. thr->getwork = time(NULL);
  6883. }
  6884. static void hashmeter(int thr_id, struct timeval *diff,
  6885. uint64_t hashes_done)
  6886. {
  6887. char logstatusline[256];
  6888. struct timeval temp_tv_end, total_diff;
  6889. double secs;
  6890. double local_secs;
  6891. static double local_mhashes_done = 0;
  6892. double local_mhashes = (double)hashes_done / 1000000.0;
  6893. bool showlog = false;
  6894. char cHr[ALLOC_H2B_NOUNIT+1], aHr[ALLOC_H2B_NOUNIT+1], uHr[ALLOC_H2B_SPACED+3+1];
  6895. char rejpcbuf[6];
  6896. char bnbuf[6];
  6897. struct thr_info *thr;
  6898. /* Update the last time this thread reported in */
  6899. if (thr_id >= 0) {
  6900. thr = get_thread(thr_id);
  6901. cgtime(&(thr->last));
  6902. thr->cgpu->device_last_well = time(NULL);
  6903. }
  6904. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  6905. /* So we can call hashmeter from a non worker thread */
  6906. if (thr_id >= 0) {
  6907. struct cgpu_info *cgpu = thr->cgpu;
  6908. int threadobj = cgpu->threads ?: 1;
  6909. double thread_rolling = 0.0;
  6910. int i;
  6911. applog(LOG_DEBUG, "[thread %d: %"PRIu64" hashes, %.1f khash/sec]",
  6912. thr_id, hashes_done, hashes_done / 1000 / secs);
  6913. /* Rolling average for each thread and each device */
  6914. decay_time(&thr->rolling, local_mhashes / secs, secs);
  6915. for (i = 0; i < threadobj; i++)
  6916. thread_rolling += cgpu->thr[i]->rolling;
  6917. mutex_lock(&hash_lock);
  6918. decay_time(&cgpu->rolling, thread_rolling, secs);
  6919. cgpu->total_mhashes += local_mhashes;
  6920. mutex_unlock(&hash_lock);
  6921. // If needed, output detailed, per-device stats
  6922. if (want_per_device_stats) {
  6923. struct timeval now;
  6924. struct timeval elapsed;
  6925. struct timeval *last_msg_tv = opt_show_procs ? &thr->cgpu->last_message_tv : &thr->cgpu->device->last_message_tv;
  6926. cgtime(&now);
  6927. timersub(&now, last_msg_tv, &elapsed);
  6928. if (opt_log_interval <= elapsed.tv_sec) {
  6929. struct cgpu_info *cgpu = thr->cgpu;
  6930. char logline[255];
  6931. *last_msg_tv = now;
  6932. get_statline(logline, sizeof(logline), cgpu);
  6933. if (!curses_active) {
  6934. printf("%s \r", logline);
  6935. fflush(stdout);
  6936. } else
  6937. applog(LOG_INFO, "%s", logline);
  6938. }
  6939. }
  6940. }
  6941. /* Totals are updated by all threads so can race without locking */
  6942. mutex_lock(&hash_lock);
  6943. cgtime(&temp_tv_end);
  6944. timersub(&temp_tv_end, &total_tv_end, &total_diff);
  6945. total_mhashes_done += local_mhashes;
  6946. local_mhashes_done += local_mhashes;
  6947. /* Only update with opt_log_interval */
  6948. if (total_diff.tv_sec < opt_log_interval)
  6949. goto out_unlock;
  6950. showlog = true;
  6951. cgtime(&total_tv_end);
  6952. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  6953. decay_time(&total_rolling, local_mhashes_done / local_secs, local_secs);
  6954. global_hashrate = ((unsigned long long)lround(total_rolling)) * 1000000;
  6955. timersub(&total_tv_end, &total_tv_start, &total_diff);
  6956. total_secs = (double)total_diff.tv_sec +
  6957. ((double)total_diff.tv_usec / 1000000.0);
  6958. double wtotal = (total_diff_accepted + total_diff_rejected + total_diff_stale);
  6959. multi_format_unit_array2(
  6960. ((char*[]){cHr, aHr, uHr}),
  6961. ((size_t[]){sizeof(cHr), sizeof(aHr), sizeof(uHr)}),
  6962. true, "h/s", H2B_SHORT,
  6963. 3,
  6964. 1e6*total_rolling,
  6965. 1e6*total_mhashes_done / total_secs,
  6966. utility_to_hashrate(total_diff1 * (wtotal ? (total_diff_accepted / wtotal) : 1) * 60 / total_secs));
  6967. int ui_accepted, ui_rejected, ui_stale;
  6968. if (opt_weighed_stats)
  6969. {
  6970. ui_accepted = total_diff_accepted;
  6971. ui_rejected = total_diff_rejected;
  6972. ui_stale = total_diff_stale;
  6973. }
  6974. else
  6975. {
  6976. ui_accepted = total_accepted;
  6977. ui_rejected = total_rejected;
  6978. ui_stale = total_stale;
  6979. }
  6980. #ifdef HAVE_CURSES
  6981. if (curses_active_locked()) {
  6982. float temp = 0;
  6983. struct cgpu_info *proc, *last_working_dev = NULL;
  6984. int i, working_devs = 0, working_procs = 0;
  6985. int divx;
  6986. bool bad = false;
  6987. // Find the highest temperature of all processors
  6988. for (i = 0; i < total_devices; ++i)
  6989. {
  6990. proc = get_devices(i);
  6991. if (proc->temp > temp)
  6992. temp = proc->temp;
  6993. if (unlikely(proc->deven == DEV_DISABLED))
  6994. ; // Just need to block it off from both conditions
  6995. else
  6996. if (likely(proc->status == LIFE_WELL && proc->deven == DEV_ENABLED))
  6997. {
  6998. if (proc->rolling > .1)
  6999. {
  7000. ++working_procs;
  7001. if (proc->device != last_working_dev)
  7002. {
  7003. ++working_devs;
  7004. last_working_dev = proc->device;
  7005. }
  7006. }
  7007. }
  7008. else
  7009. bad = true;
  7010. }
  7011. if (working_devs == working_procs)
  7012. snprintf(statusline, sizeof(statusline), "%s%d ", bad ? U8_BAD_START : "", working_devs);
  7013. else
  7014. snprintf(statusline, sizeof(statusline), "%s%d/%d ", bad ? U8_BAD_START : "", working_devs, working_procs);
  7015. divx = 7;
  7016. if (opt_show_procs && !opt_compact)
  7017. ++divx;
  7018. if (bad)
  7019. {
  7020. divx += sizeof(U8_BAD_START)-1;
  7021. strcpy(&statusline[divx], U8_BAD_END);
  7022. divx += sizeof(U8_BAD_END)-1;
  7023. }
  7024. temperature_column(&statusline[divx], sizeof(statusline)-divx, true, &temp);
  7025. format_statline(statusline, sizeof(statusline),
  7026. cHr, aHr,
  7027. uHr,
  7028. ui_accepted,
  7029. ui_rejected,
  7030. ui_stale,
  7031. total_diff_rejected + total_diff_stale, total_diff_accepted,
  7032. hw_errors,
  7033. total_bad_diff1, total_bad_diff1 + total_diff1);
  7034. unlock_curses();
  7035. }
  7036. #endif
  7037. // Add a space
  7038. memmove(&uHr[6], &uHr[5], strlen(&uHr[5]) + 1);
  7039. uHr[5] = ' ';
  7040. percentf4(rejpcbuf, sizeof(rejpcbuf), total_diff_rejected + total_diff_stale, total_diff_accepted);
  7041. percentf4(bnbuf, sizeof(bnbuf), total_bad_diff1, total_diff1);
  7042. snprintf(logstatusline, sizeof(logstatusline),
  7043. "%s%ds:%s avg:%s u:%s | A:%d R:%d+%d(%s) HW:%d/%s",
  7044. want_per_device_stats ? "ALL " : "",
  7045. opt_log_interval,
  7046. cHr, aHr,
  7047. uHr,
  7048. ui_accepted,
  7049. ui_rejected,
  7050. ui_stale,
  7051. rejpcbuf,
  7052. hw_errors,
  7053. bnbuf
  7054. );
  7055. local_mhashes_done = 0;
  7056. out_unlock:
  7057. mutex_unlock(&hash_lock);
  7058. if (showlog) {
  7059. if (!curses_active) {
  7060. printf("%s \r", logstatusline);
  7061. fflush(stdout);
  7062. } else
  7063. applog(LOG_INFO, "%s", logstatusline);
  7064. }
  7065. }
  7066. void hashmeter2(struct thr_info *thr)
  7067. {
  7068. struct timeval tv_now, tv_elapsed;
  7069. timerclear(&thr->tv_hashes_done);
  7070. cgtime(&tv_now);
  7071. timersub(&tv_now, &thr->tv_lastupdate, &tv_elapsed);
  7072. /* Update the hashmeter at most 5 times per second */
  7073. if ((thr->hashes_done && (tv_elapsed.tv_sec > 0 || tv_elapsed.tv_usec > 200000)) ||
  7074. tv_elapsed.tv_sec >= opt_log_interval) {
  7075. hashmeter(thr->id, &tv_elapsed, thr->hashes_done);
  7076. thr->hashes_done = 0;
  7077. thr->tv_lastupdate = tv_now;
  7078. }
  7079. }
  7080. static void stratum_share_result(json_t *val, json_t *res_val, json_t *err_val,
  7081. struct stratum_share *sshare)
  7082. {
  7083. struct work *work = sshare->work;
  7084. share_result(val, res_val, err_val, work, false, "");
  7085. }
  7086. /* Parses stratum json responses and tries to find the id that the request
  7087. * matched to and treat it accordingly. */
  7088. bool parse_stratum_response(struct pool *pool, char *s)
  7089. {
  7090. json_t *val = NULL, *err_val, *res_val, *id_val;
  7091. struct stratum_share *sshare;
  7092. json_error_t err;
  7093. bool ret = false;
  7094. int id;
  7095. val = JSON_LOADS(s, &err);
  7096. if (!val) {
  7097. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  7098. goto out;
  7099. }
  7100. res_val = json_object_get(val, "result");
  7101. err_val = json_object_get(val, "error");
  7102. id_val = json_object_get(val, "id");
  7103. if (json_is_null(id_val) || !id_val) {
  7104. char *ss;
  7105. if (err_val)
  7106. ss = json_dumps(err_val, JSON_INDENT(3));
  7107. else
  7108. ss = strdup("(unknown reason)");
  7109. applog(LOG_INFO, "JSON-RPC non method decode failed: %s", ss);
  7110. free(ss);
  7111. goto out;
  7112. }
  7113. if (!json_is_integer(id_val)) {
  7114. if (json_is_string(id_val)
  7115. && !strncmp(json_string_value(id_val), "txlist", 6))
  7116. {
  7117. const bool is_array = json_is_array(res_val);
  7118. applog(LOG_DEBUG, "Received %s for pool %u job %s",
  7119. is_array ? "transaction list" : "no-transaction-list response",
  7120. pool->pool_no, &json_string_value(id_val)[6]);
  7121. if (!is_array)
  7122. {
  7123. // No need to wait for a timeout
  7124. timer_unset(&pool->swork.tv_transparency);
  7125. pool_set_opaque(pool, true);
  7126. goto fishy;
  7127. }
  7128. if (strcmp(json_string_value(id_val) + 6, pool->swork.job_id))
  7129. // We only care about a transaction list for the current job id
  7130. goto fishy;
  7131. // Check that the transactions actually hash to the merkle links
  7132. {
  7133. unsigned maxtx = 1 << pool->swork.merkles;
  7134. unsigned mintx = maxtx >> 1;
  7135. --maxtx;
  7136. unsigned acttx = (unsigned)json_array_size(res_val);
  7137. if (acttx < mintx || acttx > maxtx) {
  7138. applog(LOG_WARNING, "Pool %u is sending mismatched block contents to us (%u is not %u-%u)",
  7139. pool->pool_no, acttx, mintx, maxtx);
  7140. goto fishy;
  7141. }
  7142. // TODO: Check hashes match actual merkle links
  7143. }
  7144. pool_set_opaque(pool, false);
  7145. timer_unset(&pool->swork.tv_transparency);
  7146. fishy:
  7147. ret = true;
  7148. }
  7149. goto out;
  7150. }
  7151. id = json_integer_value(id_val);
  7152. mutex_lock(&sshare_lock);
  7153. HASH_FIND_INT(stratum_shares, &id, sshare);
  7154. if (sshare)
  7155. HASH_DEL(stratum_shares, sshare);
  7156. mutex_unlock(&sshare_lock);
  7157. if (!sshare) {
  7158. double pool_diff;
  7159. /* Since the share is untracked, we can only guess at what the
  7160. * work difficulty is based on the current pool diff. */
  7161. cg_rlock(&pool->data_lock);
  7162. pool_diff = target_diff(pool->swork.target);
  7163. cg_runlock(&pool->data_lock);
  7164. if (json_is_true(res_val)) {
  7165. applog(LOG_NOTICE, "Accepted untracked stratum share from pool %d", pool->pool_no);
  7166. /* We don't know what device this came from so we can't
  7167. * attribute the work to the relevant cgpu */
  7168. mutex_lock(&stats_lock);
  7169. total_accepted++;
  7170. pool->accepted++;
  7171. total_diff_accepted += pool_diff;
  7172. pool->diff_accepted += pool_diff;
  7173. mutex_unlock(&stats_lock);
  7174. } else {
  7175. applog(LOG_NOTICE, "Rejected untracked stratum share from pool %d", pool->pool_no);
  7176. mutex_lock(&stats_lock);
  7177. total_rejected++;
  7178. pool->rejected++;
  7179. total_diff_rejected += pool_diff;
  7180. pool->diff_rejected += pool_diff;
  7181. mutex_unlock(&stats_lock);
  7182. }
  7183. goto out;
  7184. }
  7185. else {
  7186. mutex_lock(&submitting_lock);
  7187. --total_submitting;
  7188. mutex_unlock(&submitting_lock);
  7189. }
  7190. stratum_share_result(val, res_val, err_val, sshare);
  7191. free_work(sshare->work);
  7192. free(sshare);
  7193. ret = true;
  7194. out:
  7195. if (val)
  7196. json_decref(val);
  7197. return ret;
  7198. }
  7199. static void shutdown_stratum(struct pool *pool)
  7200. {
  7201. // Shut down Stratum as if we never had it
  7202. pool->stratum_active = false;
  7203. pool->stratum_init = false;
  7204. pool->has_stratum = false;
  7205. shutdown(pool->sock, SHUT_RDWR);
  7206. free(pool->stratum_url);
  7207. if (pool->sockaddr_url == pool->stratum_url)
  7208. pool->sockaddr_url = NULL;
  7209. pool->stratum_url = NULL;
  7210. }
  7211. void clear_stratum_shares(struct pool *pool)
  7212. {
  7213. int my_mining_threads = mining_threads; // Cached outside of locking
  7214. struct stratum_share *sshare, *tmpshare;
  7215. struct work *work;
  7216. struct cgpu_info *cgpu;
  7217. double diff_cleared = 0;
  7218. double thr_diff_cleared[my_mining_threads];
  7219. int cleared = 0;
  7220. int thr_cleared[my_mining_threads];
  7221. // NOTE: This is per-thread rather than per-device to avoid getting devices lock in stratum_shares loop
  7222. for (int i = 0; i < my_mining_threads; ++i)
  7223. {
  7224. thr_diff_cleared[i] = 0;
  7225. thr_cleared[i] = 0;
  7226. }
  7227. mutex_lock(&sshare_lock);
  7228. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  7229. work = sshare->work;
  7230. if (sshare->work->pool == pool && work->thr_id < my_mining_threads) {
  7231. HASH_DEL(stratum_shares, sshare);
  7232. sharelog("disconnect", work);
  7233. diff_cleared += sshare->work->work_difficulty;
  7234. thr_diff_cleared[work->thr_id] += work->work_difficulty;
  7235. ++thr_cleared[work->thr_id];
  7236. free_work(sshare->work);
  7237. free(sshare);
  7238. cleared++;
  7239. }
  7240. }
  7241. mutex_unlock(&sshare_lock);
  7242. if (cleared) {
  7243. applog(LOG_WARNING, "Lost %d shares due to stratum disconnect on pool %d", cleared, pool->pool_no);
  7244. mutex_lock(&stats_lock);
  7245. pool->stale_shares += cleared;
  7246. total_stale += cleared;
  7247. pool->diff_stale += diff_cleared;
  7248. total_diff_stale += diff_cleared;
  7249. for (int i = 0; i < my_mining_threads; ++i)
  7250. if (thr_cleared[i])
  7251. {
  7252. cgpu = get_thr_cgpu(i);
  7253. cgpu->diff_stale += thr_diff_cleared[i];
  7254. cgpu->stale += thr_cleared[i];
  7255. }
  7256. mutex_unlock(&stats_lock);
  7257. mutex_lock(&submitting_lock);
  7258. total_submitting -= cleared;
  7259. mutex_unlock(&submitting_lock);
  7260. }
  7261. }
  7262. static void resubmit_stratum_shares(struct pool *pool)
  7263. {
  7264. struct stratum_share *sshare, *tmpshare;
  7265. struct work *work;
  7266. unsigned resubmitted = 0;
  7267. mutex_lock(&sshare_lock);
  7268. mutex_lock(&submitting_lock);
  7269. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  7270. if (sshare->work->pool != pool)
  7271. continue;
  7272. HASH_DEL(stratum_shares, sshare);
  7273. work = sshare->work;
  7274. DL_APPEND(submit_waiting, work);
  7275. free(sshare);
  7276. ++resubmitted;
  7277. }
  7278. mutex_unlock(&submitting_lock);
  7279. mutex_unlock(&sshare_lock);
  7280. if (resubmitted) {
  7281. notifier_wake(submit_waiting_notifier);
  7282. applog(LOG_DEBUG, "Resubmitting %u shares due to stratum disconnect on pool %u", resubmitted, pool->pool_no);
  7283. }
  7284. }
  7285. static void clear_pool_work(struct pool *pool)
  7286. {
  7287. struct work *work, *tmp;
  7288. int cleared = 0;
  7289. mutex_lock(stgd_lock);
  7290. HASH_ITER(hh, staged_work, work, tmp) {
  7291. if (work->pool == pool) {
  7292. HASH_DEL(staged_work, work);
  7293. free_work(work);
  7294. cleared++;
  7295. staged_full = false;
  7296. }
  7297. }
  7298. mutex_unlock(stgd_lock);
  7299. }
  7300. static int cp_prio(void)
  7301. {
  7302. int prio;
  7303. cg_rlock(&control_lock);
  7304. prio = currentpool->prio;
  7305. cg_runlock(&control_lock);
  7306. return prio;
  7307. }
  7308. /* We only need to maintain a secondary pool connection when we need the
  7309. * capacity to get work from the backup pools while still on the primary */
  7310. static bool cnx_needed(struct pool *pool)
  7311. {
  7312. struct pool *cp;
  7313. if (pool->enabled != POOL_ENABLED)
  7314. return false;
  7315. /* Idle stratum pool needs something to kick it alive again */
  7316. if (pool->has_stratum && pool->idle)
  7317. return true;
  7318. /* Getwork pools without opt_fail_only need backup pools up to be able
  7319. * to leak shares */
  7320. cp = current_pool();
  7321. if (pool_actively_desired(pool, cp))
  7322. return true;
  7323. if (!pool_localgen(cp) && (!opt_fail_only || !cp->hdr_path))
  7324. return true;
  7325. /* Keep the connection open to allow any stray shares to be submitted
  7326. * on switching pools for 2 minutes. */
  7327. if (timer_elapsed(&pool->tv_last_work_time, NULL) < 120)
  7328. return true;
  7329. /* If the pool has only just come to life and is higher priority than
  7330. * the current pool keep the connection open so we can fail back to
  7331. * it. */
  7332. if (pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  7333. return true;
  7334. if (pool_unworkable(cp))
  7335. return true;
  7336. /* We've run out of work, bring anything back to life. */
  7337. if (no_work)
  7338. return true;
  7339. return false;
  7340. }
  7341. static void wait_lpcurrent(struct pool *pool);
  7342. static void pool_resus(struct pool *pool);
  7343. static void gen_stratum_work(struct pool *pool, struct work *work);
  7344. static void stratum_resumed(struct pool *pool)
  7345. {
  7346. if (!pool->stratum_notify)
  7347. return;
  7348. if (pool_tclear(pool, &pool->idle)) {
  7349. applog(LOG_INFO, "Stratum connection to pool %d resumed", pool->pool_no);
  7350. pool_resus(pool);
  7351. }
  7352. }
  7353. static bool supports_resume(struct pool *pool)
  7354. {
  7355. bool ret;
  7356. cg_rlock(&pool->data_lock);
  7357. ret = (pool->sessionid != NULL);
  7358. cg_runlock(&pool->data_lock);
  7359. return ret;
  7360. }
  7361. /* One stratum thread per pool that has stratum waits on the socket checking
  7362. * for new messages and for the integrity of the socket connection. We reset
  7363. * the connection based on the integrity of the receive side only as the send
  7364. * side will eventually expire data it fails to send. */
  7365. static void *stratum_thread(void *userdata)
  7366. {
  7367. struct pool *pool = (struct pool *)userdata;
  7368. pthread_detach(pthread_self());
  7369. char threadname[20];
  7370. snprintf(threadname, 20, "stratum%u", pool->pool_no);
  7371. RenameThread(threadname);
  7372. srand(time(NULL) + (intptr_t)userdata);
  7373. while (42) {
  7374. struct timeval timeout;
  7375. int sel_ret;
  7376. fd_set rd;
  7377. char *s;
  7378. int sock;
  7379. if (unlikely(!pool->has_stratum))
  7380. break;
  7381. /* Check to see whether we need to maintain this connection
  7382. * indefinitely or just bring it up when we switch to this
  7383. * pool */
  7384. while (true)
  7385. {
  7386. sock = pool->sock;
  7387. if (sock == INVSOCK)
  7388. applog(LOG_DEBUG, "Pool %u: Invalid socket, suspending",
  7389. pool->pool_no);
  7390. else
  7391. if (!sock_full(pool) && !cnx_needed(pool))
  7392. applog(LOG_DEBUG, "Pool %u: Connection not needed, suspending",
  7393. pool->pool_no);
  7394. else
  7395. break;
  7396. suspend_stratum(pool);
  7397. clear_stratum_shares(pool);
  7398. clear_pool_work(pool);
  7399. wait_lpcurrent(pool);
  7400. if (!restart_stratum(pool)) {
  7401. pool_died(pool);
  7402. while (!restart_stratum(pool)) {
  7403. if (pool->removed)
  7404. goto out;
  7405. cgsleep_ms(30000);
  7406. }
  7407. }
  7408. }
  7409. FD_ZERO(&rd);
  7410. FD_SET(sock, &rd);
  7411. timeout.tv_sec = 120;
  7412. timeout.tv_usec = 0;
  7413. /* If we fail to receive any notify messages for 2 minutes we
  7414. * assume the connection has been dropped and treat this pool
  7415. * as dead */
  7416. if (!sock_full(pool) && (sel_ret = select(sock + 1, &rd, NULL, NULL, &timeout)) < 1) {
  7417. applog(LOG_DEBUG, "Stratum select failed on pool %d with value %d", pool->pool_no, sel_ret);
  7418. s = NULL;
  7419. } else
  7420. s = recv_line(pool);
  7421. if (!s) {
  7422. if (!pool->has_stratum)
  7423. break;
  7424. applog(LOG_NOTICE, "Stratum connection to pool %d interrupted", pool->pool_no);
  7425. pool->getfail_occasions++;
  7426. total_go++;
  7427. mutex_lock(&pool->stratum_lock);
  7428. pool->stratum_active = pool->stratum_notify = false;
  7429. pool->sock = INVSOCK;
  7430. mutex_unlock(&pool->stratum_lock);
  7431. /* If the socket to our stratum pool disconnects, all
  7432. * submissions need to be discarded or resent. */
  7433. if (!supports_resume(pool))
  7434. clear_stratum_shares(pool);
  7435. else
  7436. resubmit_stratum_shares(pool);
  7437. clear_pool_work(pool);
  7438. if (pool == current_pool())
  7439. restart_threads();
  7440. if (restart_stratum(pool))
  7441. continue;
  7442. shutdown_stratum(pool);
  7443. pool_died(pool);
  7444. break;
  7445. }
  7446. /* Check this pool hasn't died while being a backup pool and
  7447. * has not had its idle flag cleared */
  7448. stratum_resumed(pool);
  7449. if (!parse_method(pool, s) && !parse_stratum_response(pool, s))
  7450. applog(LOG_INFO, "Unknown stratum msg: %s", s);
  7451. free(s);
  7452. if (pool->swork.clean) {
  7453. struct work *work = make_work();
  7454. /* Generate a single work item to update the current
  7455. * block database */
  7456. pool->swork.clean = false;
  7457. gen_stratum_work(pool, work);
  7458. /* Try to extract block height from coinbase scriptSig */
  7459. uint8_t *bin_height = &bytes_buf(&pool->swork.coinbase)[4 /*version*/ + 1 /*txin count*/ + 36 /*prevout*/ + 1 /*scriptSig len*/ + 1 /*push opcode*/];
  7460. unsigned char cb_height_sz;
  7461. cb_height_sz = bin_height[-1];
  7462. if (cb_height_sz == 3) {
  7463. // FIXME: The block number will overflow this by AD 2173
  7464. uint32_t block_id = ((uint32_t*)work->data)[1];
  7465. uint32_t height = 0;
  7466. memcpy(&height, bin_height, 3);
  7467. height = le32toh(height);
  7468. have_block_height(block_id, height);
  7469. }
  7470. ++pool->work_restart_id;
  7471. pool_update_work_restart_time(pool);
  7472. if (test_work_current(work)) {
  7473. /* Only accept a work update if this stratum
  7474. * connection is from the current pool */
  7475. struct pool * const cp = current_pool();
  7476. if (pool == cp)
  7477. restart_threads();
  7478. applog(
  7479. ((!opt_quiet_work_updates) && pool_actively_in_use(pool, cp) ? LOG_NOTICE : LOG_DEBUG),
  7480. "Stratum from pool %d requested work update", pool->pool_no);
  7481. } else
  7482. applog(LOG_NOTICE, "Stratum from pool %d detected new block", pool->pool_no);
  7483. free_work(work);
  7484. }
  7485. if (timer_passed(&pool->swork.tv_transparency, NULL)) {
  7486. // More than 4 timmills past since requested transactions
  7487. timer_unset(&pool->swork.tv_transparency);
  7488. pool_set_opaque(pool, true);
  7489. }
  7490. }
  7491. out:
  7492. return NULL;
  7493. }
  7494. static void init_stratum_thread(struct pool *pool)
  7495. {
  7496. have_longpoll = true;
  7497. if (unlikely(pthread_create(&pool->stratum_thread, NULL, stratum_thread, (void *)pool)))
  7498. quit(1, "Failed to create stratum thread");
  7499. }
  7500. static void *longpoll_thread(void *userdata);
  7501. static bool stratum_works(struct pool *pool)
  7502. {
  7503. applog(LOG_INFO, "Testing pool %d stratum %s", pool->pool_no, pool->stratum_url);
  7504. if (!extract_sockaddr(pool->stratum_url, &pool->sockaddr_url, &pool->stratum_port))
  7505. return false;
  7506. if (pool->stratum_active)
  7507. return true;
  7508. if (!initiate_stratum(pool))
  7509. return false;
  7510. return true;
  7511. }
  7512. static bool pool_active(struct pool *pool, bool pinging)
  7513. {
  7514. struct timeval tv_now, tv_getwork, tv_getwork_reply;
  7515. bool ret = false;
  7516. json_t *val;
  7517. CURL *curl;
  7518. int rolltime;
  7519. char *rpc_req;
  7520. struct work *work;
  7521. enum pool_protocol proto;
  7522. if (pool->stratum_init)
  7523. return pool->stratum_active;
  7524. timer_set_now(&tv_now);
  7525. if (timer_isset(&pool->tv_last_work_time) && timer_elapsed(&pool->tv_last_work_time, &tv_now) < 60)
  7526. return true;
  7527. if (pool->idle && timer_elapsed(&pool->tv_idle, &tv_now) < 30)
  7528. return false;
  7529. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  7530. /* This is the central point we activate stratum when we can */
  7531. curl = curl_easy_init();
  7532. if (unlikely(!curl)) {
  7533. applog(LOG_ERR, "CURL initialisation failed");
  7534. return false;
  7535. }
  7536. if (!(want_gbt || want_getwork))
  7537. goto nohttp;
  7538. work = make_work();
  7539. /* Probe for GBT support on first pass */
  7540. proto = want_gbt ? PLP_GETBLOCKTEMPLATE : PLP_GETWORK;
  7541. tryagain:
  7542. rpc_req = prepare_rpc_req_probe(work, proto, NULL);
  7543. work->pool = pool;
  7544. if (!rpc_req)
  7545. goto out;
  7546. pool->probed = false;
  7547. cgtime(&tv_getwork);
  7548. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  7549. true, false, &rolltime, pool, false);
  7550. cgtime(&tv_getwork_reply);
  7551. free(rpc_req);
  7552. /* Detect if a http getwork pool has an X-Stratum header at startup,
  7553. * and if so, switch to that in preference to getwork if it works */
  7554. if (pool->stratum_url && want_stratum && pool_may_redirect_to(pool, pool->stratum_url) && (pool->has_stratum || stratum_works(pool))) {
  7555. if (!pool->has_stratum) {
  7556. applog(LOG_NOTICE, "Switching pool %d %s to %s", pool->pool_no, pool->rpc_url, pool->stratum_url);
  7557. if (!pool->rpc_url)
  7558. pool->rpc_url = strdup(pool->stratum_url);
  7559. pool->has_stratum = true;
  7560. }
  7561. free_work(work);
  7562. if (val)
  7563. json_decref(val);
  7564. retry_stratum:
  7565. curl_easy_cleanup(curl);
  7566. /* We create the stratum thread for each pool just after
  7567. * successful authorisation. Once the init flag has been set
  7568. * we never unset it and the stratum thread is responsible for
  7569. * setting/unsetting the active flag */
  7570. bool init = pool_tset(pool, &pool->stratum_init);
  7571. if (!init) {
  7572. bool ret = initiate_stratum(pool) && auth_stratum(pool);
  7573. if (ret)
  7574. {
  7575. detect_algo = 2;
  7576. init_stratum_thread(pool);
  7577. }
  7578. else
  7579. pool_tclear(pool, &pool->stratum_init);
  7580. return ret;
  7581. }
  7582. return pool->stratum_active;
  7583. }
  7584. else if (pool->has_stratum)
  7585. shutdown_stratum(pool);
  7586. if (val) {
  7587. bool rc;
  7588. json_t *res;
  7589. res = json_object_get(val, "result");
  7590. if ((!json_is_object(res)) || (proto == PLP_GETBLOCKTEMPLATE && !json_object_get(res, "bits")))
  7591. goto badwork;
  7592. work->rolltime = rolltime;
  7593. rc = work_decode(pool, work, val);
  7594. if (rc) {
  7595. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  7596. pool->pool_no, pool->rpc_url);
  7597. work->pool = pool;
  7598. copy_time(&work->tv_getwork, &tv_getwork);
  7599. copy_time(&work->tv_getwork_reply, &tv_getwork_reply);
  7600. work->getwork_mode = GETWORK_MODE_TESTPOOL;
  7601. calc_diff(work, 0);
  7602. update_last_work(work);
  7603. applog(LOG_DEBUG, "Pushing pooltest work to base pool");
  7604. stage_work(work);
  7605. total_getworks++;
  7606. pool->getwork_requested++;
  7607. ret = true;
  7608. cgtime(&pool->tv_idle);
  7609. } else {
  7610. badwork:
  7611. json_decref(val);
  7612. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher work from pool %u %s",
  7613. pool->pool_no, pool->rpc_url);
  7614. pool->proto = proto = pool_protocol_fallback(proto);
  7615. if (PLP_NONE != proto)
  7616. goto tryagain;
  7617. free_work(work);
  7618. goto out;
  7619. }
  7620. json_decref(val);
  7621. if (proto != pool->proto) {
  7622. pool->proto = proto;
  7623. applog(LOG_INFO, "Selected %s protocol for pool %u", pool_protocol_name(proto), pool->pool_no);
  7624. }
  7625. if (pool->lp_url)
  7626. goto out;
  7627. /* Decipher the longpoll URL, if any, and store it in ->lp_url */
  7628. const struct blktmpl_longpoll_req *lp;
  7629. if (work->tr && (lp = blktmpl_get_longpoll(work->tr->tmpl))) {
  7630. // NOTE: work_decode takes care of lp id
  7631. pool->lp_url = lp->uri ? absolute_uri(lp->uri, pool->rpc_url) : pool->rpc_url;
  7632. if (!pool->lp_url)
  7633. {
  7634. ret = false;
  7635. goto out;
  7636. }
  7637. pool->lp_proto = PLP_GETBLOCKTEMPLATE;
  7638. }
  7639. else
  7640. if (pool->hdr_path && want_getwork) {
  7641. pool->lp_url = absolute_uri(pool->hdr_path, pool->rpc_url);
  7642. if (!pool->lp_url)
  7643. {
  7644. ret = false;
  7645. goto out;
  7646. }
  7647. pool->lp_proto = PLP_GETWORK;
  7648. } else
  7649. pool->lp_url = NULL;
  7650. if (want_longpoll && !pool->lp_started) {
  7651. pool->lp_started = true;
  7652. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  7653. quit(1, "Failed to create pool longpoll thread");
  7654. }
  7655. } else if (PLP_NONE != (proto = pool_protocol_fallback(proto))) {
  7656. pool->proto = proto;
  7657. goto tryagain;
  7658. } else {
  7659. free_work(work);
  7660. nohttp:
  7661. /* If we failed to parse a getwork, this could be a stratum
  7662. * url without the prefix stratum+tcp:// so let's check it */
  7663. if (extract_sockaddr(pool->rpc_url, &pool->sockaddr_url, &pool->stratum_port) && initiate_stratum(pool)) {
  7664. pool->has_stratum = true;
  7665. goto retry_stratum;
  7666. }
  7667. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  7668. pool->pool_no, pool->rpc_url);
  7669. if (!pinging)
  7670. applog(LOG_WARNING, "Pool %u slow/down or URL or credentials invalid", pool->pool_no);
  7671. }
  7672. out:
  7673. curl_easy_cleanup(curl);
  7674. return ret;
  7675. }
  7676. static void pool_resus(struct pool *pool)
  7677. {
  7678. if (pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  7679. applog(LOG_WARNING, "Pool %d %s alive, testing stability", pool->pool_no, pool->rpc_url);
  7680. else
  7681. applog(LOG_INFO, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  7682. }
  7683. static struct work *hash_pop(void)
  7684. {
  7685. struct work *work = NULL, *tmp;
  7686. int hc;
  7687. struct timespec ts;
  7688. retry:
  7689. mutex_lock(stgd_lock);
  7690. while (!HASH_COUNT(staged_work))
  7691. {
  7692. if (unlikely(staged_full))
  7693. {
  7694. if (likely(opt_queue < 10 + mining_threads))
  7695. {
  7696. ++opt_queue;
  7697. applog(LOG_WARNING, "Staged work underrun; increasing queue minimum to %d", opt_queue);
  7698. }
  7699. else
  7700. applog(LOG_WARNING, "Staged work underrun; not automatically increasing above %d", opt_queue);
  7701. staged_full = false; // Let it fill up before triggering an underrun again
  7702. no_work = true;
  7703. }
  7704. ts = (struct timespec){ .tv_sec = opt_log_interval, };
  7705. pthread_cond_signal(&gws_cond);
  7706. if (ETIMEDOUT == pthread_cond_timedwait(&getq->cond, stgd_lock, &ts))
  7707. {
  7708. run_cmd(cmd_idle);
  7709. pthread_cond_signal(&gws_cond);
  7710. pthread_cond_wait(&getq->cond, stgd_lock);
  7711. }
  7712. }
  7713. no_work = false;
  7714. hc = HASH_COUNT(staged_work);
  7715. /* Find clone work if possible, to allow masters to be reused */
  7716. if (hc > staged_rollable) {
  7717. HASH_ITER(hh, staged_work, work, tmp) {
  7718. if (!work_rollable(work))
  7719. break;
  7720. }
  7721. } else
  7722. work = staged_work;
  7723. if (can_roll(work) && should_roll(work))
  7724. {
  7725. // Instead of consuming it, force it to be cloned and grab the clone
  7726. mutex_unlock(stgd_lock);
  7727. clone_available();
  7728. goto retry;
  7729. }
  7730. HASH_DEL(staged_work, work);
  7731. if (work_rollable(work))
  7732. staged_rollable--;
  7733. /* Signal the getwork scheduler to look for more work */
  7734. pthread_cond_signal(&gws_cond);
  7735. /* Signal hash_pop again in case there are mutliple hash_pop waiters */
  7736. pthread_cond_signal(&getq->cond);
  7737. mutex_unlock(stgd_lock);
  7738. work->pool->last_work_time = time(NULL);
  7739. cgtime(&work->pool->tv_last_work_time);
  7740. return work;
  7741. }
  7742. /* Clones work by rolling it if possible, and returning a clone instead of the
  7743. * original work item which gets staged again to possibly be rolled again in
  7744. * the future */
  7745. static struct work *clone_work(struct work *work)
  7746. {
  7747. int mrs = mining_threads + opt_queue - total_staged();
  7748. struct work *work_clone;
  7749. bool cloned;
  7750. if (mrs < 1)
  7751. return work;
  7752. cloned = false;
  7753. work_clone = make_clone(work);
  7754. while (mrs-- > 0 && can_roll(work) && should_roll(work)) {
  7755. applog(LOG_DEBUG, "Pushing rolled converted work to stage thread");
  7756. stage_work(work_clone);
  7757. roll_work(work);
  7758. work_clone = make_clone(work);
  7759. /* Roll it again to prevent duplicates should this be used
  7760. * directly later on */
  7761. roll_work(work);
  7762. cloned = true;
  7763. }
  7764. if (cloned) {
  7765. stage_work(work);
  7766. return work_clone;
  7767. }
  7768. free_work(work_clone);
  7769. return work;
  7770. }
  7771. void gen_hash(unsigned char *data, unsigned char *hash, int len)
  7772. {
  7773. unsigned char hash1[32];
  7774. sha256(data, len, hash1);
  7775. sha256(hash1, 32, hash);
  7776. }
  7777. /* PDiff 1 is a 256 bit unsigned integer of
  7778. * 0x00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff
  7779. * so we use a big endian 32 bit unsigned integer positioned at the Nth byte to
  7780. * cover a huge range of difficulty targets, though not all 256 bits' worth */
  7781. static void pdiff_target_leadzero(void * const target_p, double diff)
  7782. {
  7783. uint8_t *target = target_p;
  7784. diff *= 0x100000000;
  7785. int skip = log2(diff) / 8;
  7786. if (skip)
  7787. {
  7788. if (skip > 0x1c)
  7789. skip = 0x1c;
  7790. diff /= pow(0x100, skip);
  7791. memset(target, 0, skip);
  7792. }
  7793. uint32_t n = 0xffffffff;
  7794. n = (double)n / diff;
  7795. n = htobe32(n);
  7796. memcpy(&target[skip], &n, sizeof(n));
  7797. memset(&target[skip + sizeof(n)], 0xff, 32 - (skip + sizeof(n)));
  7798. }
  7799. void set_target_to_pdiff(void * const dest_target, const double pdiff)
  7800. {
  7801. unsigned char rtarget[32];
  7802. pdiff_target_leadzero(rtarget, pdiff);
  7803. swab256(dest_target, rtarget);
  7804. if (opt_debug) {
  7805. char htarget[65];
  7806. bin2hex(htarget, rtarget, 32);
  7807. applog(LOG_DEBUG, "Generated target %s", htarget);
  7808. }
  7809. }
  7810. void set_target_to_bdiff(void * const dest_target, const double bdiff)
  7811. {
  7812. set_target_to_pdiff(dest_target, bdiff_to_pdiff(bdiff));
  7813. }
  7814. void _test_target(void * const funcp, const char * const funcname, const bool little_endian, const void * const expectp, const double diff)
  7815. {
  7816. uint8_t bufr[32], buf[32], expectr[32], expect[32];
  7817. int off;
  7818. void (*func)(void *, double) = funcp;
  7819. func(little_endian ? bufr : buf, diff);
  7820. if (little_endian)
  7821. swab256(buf, bufr);
  7822. swap32tobe(expect, expectp, 256/32);
  7823. // Fuzzy comparison: the first 32 bits set must match, and the actual target must be >= the expected
  7824. for (off = 0; off < 28 && !buf[off]; ++off)
  7825. {}
  7826. if (memcmp(&buf[off], &expect[off], 4))
  7827. {
  7828. testfail: ;
  7829. char hexbuf[65], expectbuf[65];
  7830. bin2hex(hexbuf, buf, 32);
  7831. bin2hex(expectbuf, expect, 32);
  7832. applogr(, LOG_WARNING, "%s test failed: diff %g got %s (expected %s)",
  7833. funcname, diff, hexbuf, expectbuf);
  7834. }
  7835. if (!little_endian)
  7836. swab256(bufr, buf);
  7837. swab256(expectr, expect);
  7838. if (!hash_target_check(expectr, bufr))
  7839. goto testfail;
  7840. }
  7841. #define TEST_TARGET(func, le, expect, diff) \
  7842. _test_target(func, #func, le, expect, diff)
  7843. void test_target()
  7844. {
  7845. uint32_t expect[8] = {0};
  7846. // bdiff 1 should be exactly 00000000ffff0000000006f29cfd29510a6caee84634e86a57257cf03152537f due to floating-point imprecision (pdiff1 / 1.0000152590218966)
  7847. expect[0] = 0x0000ffff;
  7848. TEST_TARGET(set_target_to_bdiff, true, expect, 1./0x10000);
  7849. expect[0] = 0;
  7850. expect[1] = 0xffff0000;
  7851. TEST_TARGET(set_target_to_bdiff, true, expect, 1);
  7852. expect[1] >>= 1;
  7853. TEST_TARGET(set_target_to_bdiff, true, expect, 2);
  7854. expect[1] >>= 3;
  7855. TEST_TARGET(set_target_to_bdiff, true, expect, 0x10);
  7856. expect[1] >>= 4;
  7857. TEST_TARGET(set_target_to_bdiff, true, expect, 0x100);
  7858. memset(&expect[1], '\xff', 28);
  7859. expect[0] = 0x0000ffff;
  7860. TEST_TARGET(set_target_to_pdiff, true, expect, 1./0x10000);
  7861. expect[0] = 0;
  7862. TEST_TARGET(set_target_to_pdiff, true, expect, 1);
  7863. expect[1] >>= 1;
  7864. TEST_TARGET(set_target_to_pdiff, true, expect, 2);
  7865. expect[1] >>= 3;
  7866. TEST_TARGET(set_target_to_pdiff, true, expect, 0x10);
  7867. expect[1] >>= 4;
  7868. TEST_TARGET(set_target_to_pdiff, true, expect, 0x100);
  7869. }
  7870. void stratum_work_cpy(struct stratum_work * const dst, const struct stratum_work * const src)
  7871. {
  7872. *dst = *src;
  7873. if (dst->tr)
  7874. tmpl_incref(dst->tr);
  7875. dst->job_id = maybe_strdup(src->job_id);
  7876. bytes_cpy(&dst->coinbase, &src->coinbase);
  7877. bytes_cpy(&dst->merkle_bin, &src->merkle_bin);
  7878. }
  7879. void stratum_work_clean(struct stratum_work * const swork)
  7880. {
  7881. if (swork->tr)
  7882. tmpl_decref(swork->tr);
  7883. free(swork->job_id);
  7884. bytes_free(&swork->coinbase);
  7885. bytes_free(&swork->merkle_bin);
  7886. }
  7887. bool pool_has_usable_swork(const struct pool * const pool)
  7888. {
  7889. if (pool->swork.tr)
  7890. {
  7891. // GBT
  7892. struct timeval tv_now;
  7893. timer_set_now(&tv_now);
  7894. return blkmk_time_left(pool->swork.tr->tmpl, tv_now.tv_sec);
  7895. }
  7896. return pool->stratum_notify;
  7897. }
  7898. /* Generates stratum based work based on the most recent notify information
  7899. * from the pool. This will keep generating work while a pool is down so we use
  7900. * other means to detect when the pool has died in stratum_thread */
  7901. static void gen_stratum_work(struct pool *pool, struct work *work)
  7902. {
  7903. clean_work(work);
  7904. cg_wlock(&pool->data_lock);
  7905. pool->swork.data_lock_p = &pool->data_lock;
  7906. bytes_resize(&work->nonce2, pool->n2size);
  7907. if (pool->nonce2sz < pool->n2size)
  7908. memset(&bytes_buf(&work->nonce2)[pool->nonce2sz], 0, pool->n2size - pool->nonce2sz);
  7909. memcpy(bytes_buf(&work->nonce2),
  7910. #ifdef WORDS_BIGENDIAN
  7911. // NOTE: On big endian, the most significant bits are stored at the end, so skip the LSBs
  7912. &((char*)&pool->nonce2)[pool->nonce2off],
  7913. #else
  7914. &pool->nonce2,
  7915. #endif
  7916. pool->nonce2sz);
  7917. pool->nonce2++;
  7918. work->pool = pool;
  7919. work->work_restart_id = work->pool->work_restart_id;
  7920. gen_stratum_work2(work, &pool->swork, pool->nonce1);
  7921. cgtime(&work->tv_staged);
  7922. }
  7923. void gen_stratum_work2(struct work *work, struct stratum_work *swork, const char *nonce1)
  7924. {
  7925. unsigned char *coinbase, merkle_root[32], merkle_sha[64];
  7926. uint8_t *merkle_bin;
  7927. uint32_t *data32, *swap32;
  7928. int i;
  7929. /* Generate coinbase */
  7930. coinbase = bytes_buf(&swork->coinbase);
  7931. memcpy(&coinbase[swork->nonce2_offset], bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  7932. /* Downgrade to a read lock to read off the variables */
  7933. if (swork->data_lock_p)
  7934. cg_dwlock(swork->data_lock_p);
  7935. /* Generate merkle root */
  7936. gen_hash(coinbase, merkle_root, bytes_len(&swork->coinbase));
  7937. memcpy(merkle_sha, merkle_root, 32);
  7938. merkle_bin = bytes_buf(&swork->merkle_bin);
  7939. for (i = 0; i < swork->merkles; ++i, merkle_bin += 32) {
  7940. memcpy(merkle_sha + 32, merkle_bin, 32);
  7941. gen_hash(merkle_sha, merkle_root, 64);
  7942. memcpy(merkle_sha, merkle_root, 32);
  7943. }
  7944. data32 = (uint32_t *)merkle_sha;
  7945. swap32 = (uint32_t *)merkle_root;
  7946. flip32(swap32, data32);
  7947. memcpy(&work->data[0], swork->header1, 36);
  7948. memcpy(&work->data[36], merkle_root, 32);
  7949. *((uint32_t*)&work->data[68]) = htobe32(swork->ntime + timer_elapsed(&swork->tv_received, NULL));
  7950. memcpy(&work->data[72], swork->diffbits, 4);
  7951. memset(&work->data[76], 0, 4); // nonce
  7952. memcpy(&work->data[80], workpadding_bin, 48);
  7953. work->ntime_roll_limits = swork->ntime_roll_limits;
  7954. /* Copy parameters required for share submission */
  7955. memcpy(work->target, swork->target, sizeof(work->target));
  7956. work->job_id = maybe_strdup(swork->job_id);
  7957. work->nonce1 = maybe_strdup(nonce1);
  7958. if (swork->data_lock_p)
  7959. cg_runlock(swork->data_lock_p);
  7960. if (opt_debug)
  7961. {
  7962. char header[161];
  7963. char nonce2hex[(bytes_len(&work->nonce2) * 2) + 1];
  7964. bin2hex(header, work->data, 80);
  7965. bin2hex(nonce2hex, bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  7966. applog(LOG_DEBUG, "Generated stratum header %s", header);
  7967. applog(LOG_DEBUG, "Work job_id %s nonce2 %s", work->job_id, nonce2hex);
  7968. }
  7969. calc_midstate(work);
  7970. local_work++;
  7971. work->stratum = true;
  7972. work->blk.nonce = 0;
  7973. work->id = total_work++;
  7974. work->longpoll = false;
  7975. work->getwork_mode = GETWORK_MODE_STRATUM;
  7976. calc_diff(work, 0);
  7977. }
  7978. void request_work(struct thr_info *thr)
  7979. {
  7980. struct cgpu_info *cgpu = thr->cgpu;
  7981. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  7982. /* Tell the watchdog thread this thread is waiting on getwork and
  7983. * should not be restarted */
  7984. thread_reportout(thr);
  7985. // HACK: Since get_work still blocks, reportout all processors dependent on this thread
  7986. for (struct cgpu_info *proc = thr->cgpu->next_proc; proc; proc = proc->next_proc)
  7987. {
  7988. if (proc->threads)
  7989. break;
  7990. thread_reportout(proc->thr[0]);
  7991. }
  7992. cgtime(&dev_stats->_get_start);
  7993. }
  7994. // FIXME: Make this non-blocking (and remove HACK above)
  7995. struct work *get_work(struct thr_info *thr)
  7996. {
  7997. const int thr_id = thr->id;
  7998. struct cgpu_info *cgpu = thr->cgpu;
  7999. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  8000. struct cgminer_stats *pool_stats;
  8001. struct timeval tv_get;
  8002. struct work *work = NULL;
  8003. applog(LOG_DEBUG, "%"PRIpreprv": Popping work from get queue to get work", cgpu->proc_repr);
  8004. while (!work) {
  8005. work = hash_pop();
  8006. if (stale_work(work, false)) {
  8007. staged_full = false; // It wasn't really full, since it was stale :(
  8008. discard_work(work);
  8009. work = NULL;
  8010. wake_gws();
  8011. }
  8012. }
  8013. last_getwork = time(NULL);
  8014. applog(LOG_DEBUG, "%"PRIpreprv": Got work %d from get queue to get work for thread %d",
  8015. cgpu->proc_repr, work->id, thr_id);
  8016. work->thr_id = thr_id;
  8017. thread_reportin(thr);
  8018. // HACK: Since get_work still blocks, reportin all processors dependent on this thread
  8019. for (struct cgpu_info *proc = thr->cgpu->next_proc; proc; proc = proc->next_proc)
  8020. {
  8021. if (proc->threads)
  8022. break;
  8023. thread_reportin(proc->thr[0]);
  8024. }
  8025. work->mined = true;
  8026. work->blk.nonce = 0;
  8027. cgtime(&tv_get);
  8028. timersub(&tv_get, &dev_stats->_get_start, &tv_get);
  8029. timeradd(&tv_get, &dev_stats->getwork_wait, &dev_stats->getwork_wait);
  8030. if (timercmp(&tv_get, &dev_stats->getwork_wait_max, >))
  8031. dev_stats->getwork_wait_max = tv_get;
  8032. if (timercmp(&tv_get, &dev_stats->getwork_wait_min, <))
  8033. dev_stats->getwork_wait_min = tv_get;
  8034. ++dev_stats->getwork_calls;
  8035. pool_stats = &(work->pool->cgminer_stats);
  8036. timeradd(&tv_get, &pool_stats->getwork_wait, &pool_stats->getwork_wait);
  8037. if (timercmp(&tv_get, &pool_stats->getwork_wait_max, >))
  8038. pool_stats->getwork_wait_max = tv_get;
  8039. if (timercmp(&tv_get, &pool_stats->getwork_wait_min, <))
  8040. pool_stats->getwork_wait_min = tv_get;
  8041. ++pool_stats->getwork_calls;
  8042. if (work->work_difficulty < 1)
  8043. {
  8044. if (unlikely(work->work_difficulty < cgpu->min_nonce_diff))
  8045. {
  8046. applog(LOG_WARNING, "%"PRIpreprv": Using work with lower difficulty than device supports",
  8047. cgpu->proc_repr);
  8048. work->nonce_diff = cgpu->min_nonce_diff;
  8049. }
  8050. else
  8051. work->nonce_diff = work->work_difficulty;
  8052. }
  8053. else
  8054. work->nonce_diff = 1;
  8055. return work;
  8056. }
  8057. static
  8058. void _submit_work_async(struct work *work)
  8059. {
  8060. applog(LOG_DEBUG, "Pushing submit work to work thread");
  8061. if (opt_benchmark)
  8062. {
  8063. json_t * const jn = json_null();
  8064. rebuild_hash(work);
  8065. share_result(jn, jn, jn, work, false, "");
  8066. free_work(work);
  8067. return;
  8068. }
  8069. mutex_lock(&submitting_lock);
  8070. ++total_submitting;
  8071. DL_APPEND(submit_waiting, work);
  8072. mutex_unlock(&submitting_lock);
  8073. notifier_wake(submit_waiting_notifier);
  8074. }
  8075. /* Submit a copy of the tested, statistic recorded work item asynchronously */
  8076. static void submit_work_async2(struct work *work, struct timeval *tv_work_found)
  8077. {
  8078. if (tv_work_found)
  8079. copy_time(&work->tv_work_found, tv_work_found);
  8080. _submit_work_async(work);
  8081. }
  8082. void inc_hw_errors3(struct thr_info *thr, const struct work *work, const uint32_t *bad_nonce_p, float nonce_diff)
  8083. {
  8084. struct cgpu_info * const cgpu = thr->cgpu;
  8085. if (bad_nonce_p)
  8086. {
  8087. if (bad_nonce_p == UNKNOWN_NONCE)
  8088. applog(LOG_DEBUG, "%"PRIpreprv": invalid nonce - HW error",
  8089. cgpu->proc_repr);
  8090. else
  8091. applog(LOG_DEBUG, "%"PRIpreprv": invalid nonce (%08lx) - HW error",
  8092. cgpu->proc_repr, (unsigned long)be32toh(*bad_nonce_p));
  8093. }
  8094. mutex_lock(&stats_lock);
  8095. hw_errors++;
  8096. ++cgpu->hw_errors;
  8097. if (bad_nonce_p)
  8098. {
  8099. total_bad_diff1 += nonce_diff;
  8100. cgpu->bad_diff1 += nonce_diff;
  8101. }
  8102. mutex_unlock(&stats_lock);
  8103. if (thr->cgpu->drv->hw_error)
  8104. thr->cgpu->drv->hw_error(thr);
  8105. }
  8106. enum test_nonce2_result hashtest2(struct work *work, bool checktarget)
  8107. {
  8108. uint32_t *hash2_32 = (uint32_t *)&work->hash[0];
  8109. hash_data(work->hash, work->data);
  8110. if (hash2_32[7] != 0)
  8111. return TNR_BAD;
  8112. if (!checktarget)
  8113. return TNR_GOOD;
  8114. if (!hash_target_check_v(work->hash, work->target))
  8115. {
  8116. bool high_hash = true;
  8117. struct pool * const pool = work->pool;
  8118. if (pool->stratum_active)
  8119. {
  8120. // Some stratum pools are buggy and expect difficulty changes to be immediate retroactively, so if the target has changed, check and submit just in case
  8121. if (memcmp(pool->swork.target, work->target, sizeof(work->target)))
  8122. {
  8123. applog(LOG_DEBUG, "Stratum pool %u target has changed since work job issued, checking that too",
  8124. pool->pool_no);
  8125. if (hash_target_check_v(work->hash, pool->swork.target))
  8126. high_hash = false;
  8127. }
  8128. }
  8129. if (high_hash)
  8130. return TNR_HIGH;
  8131. }
  8132. return TNR_GOOD;
  8133. }
  8134. enum test_nonce2_result _test_nonce2(struct work *work, uint32_t nonce, bool checktarget)
  8135. {
  8136. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  8137. *work_nonce = htole32(nonce);
  8138. #ifdef USE_SCRYPT
  8139. if (opt_scrypt)
  8140. // NOTE: Depends on scrypt_test return matching enum values
  8141. return scrypt_test(work->data, work->target, nonce);
  8142. #endif
  8143. return hashtest2(work, checktarget);
  8144. }
  8145. /* Returns true if nonce for work was a valid share */
  8146. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  8147. {
  8148. return submit_noffset_nonce(thr, work, nonce, 0);
  8149. }
  8150. /* Allows drivers to submit work items where the driver has changed the ntime
  8151. * value by noffset. Must be only used with a work protocol that does not ntime
  8152. * roll itself intrinsically to generate work (eg stratum). We do not touch
  8153. * the original work struct, but the copy of it only. */
  8154. bool submit_noffset_nonce(struct thr_info *thr, struct work *work_in, uint32_t nonce,
  8155. int noffset)
  8156. {
  8157. struct work *work = make_work();
  8158. _copy_work(work, work_in, noffset);
  8159. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  8160. struct timeval tv_work_found;
  8161. enum test_nonce2_result res;
  8162. bool ret = true;
  8163. thread_reportout(thr);
  8164. cgtime(&tv_work_found);
  8165. *work_nonce = htole32(nonce);
  8166. work->thr_id = thr->id;
  8167. /* Do one last check before attempting to submit the work */
  8168. /* Side effect: sets work->data for us */
  8169. res = test_nonce2(work, nonce);
  8170. if (unlikely(res == TNR_BAD))
  8171. {
  8172. inc_hw_errors(thr, work, nonce);
  8173. ret = false;
  8174. goto out;
  8175. }
  8176. mutex_lock(&stats_lock);
  8177. total_diff1 += work->nonce_diff;
  8178. thr ->cgpu->diff1 += work->nonce_diff;
  8179. work->pool->diff1 += work->nonce_diff;
  8180. thr->cgpu->last_device_valid_work = time(NULL);
  8181. mutex_unlock(&stats_lock);
  8182. if (noncelog_file)
  8183. noncelog(work);
  8184. if (res == TNR_HIGH)
  8185. {
  8186. // Share above target, normal
  8187. /* Check the diff of the share, even if it didn't reach the
  8188. * target, just to set the best share value if it's higher. */
  8189. share_diff(work);
  8190. goto out;
  8191. }
  8192. submit_work_async2(work, &tv_work_found);
  8193. work = NULL; // Taken by submit_work_async2
  8194. out:
  8195. if (work)
  8196. free_work(work);
  8197. thread_reportin(thr);
  8198. return ret;
  8199. }
  8200. bool abandon_work(struct work *work, struct timeval *wdiff, uint64_t hashes)
  8201. {
  8202. if (wdiff->tv_sec > opt_scantime ||
  8203. work->blk.nonce >= 0xfffffffe - hashes ||
  8204. hashes >= 0xfffffffe ||
  8205. stale_work(work, false))
  8206. return true;
  8207. return false;
  8208. }
  8209. void __thr_being_msg(int prio, struct thr_info *thr, const char *being)
  8210. {
  8211. struct cgpu_info *proc = thr->cgpu;
  8212. if (proc->threads > 1)
  8213. applog(prio, "%"PRIpreprv" (thread %d) %s", proc->proc_repr, thr->id, being);
  8214. else
  8215. applog(prio, "%"PRIpreprv" %s", proc->proc_repr, being);
  8216. }
  8217. // Called by asynchronous minerloops, when they find their processor should be disabled
  8218. void mt_disable_start(struct thr_info *mythr)
  8219. {
  8220. struct cgpu_info *cgpu = mythr->cgpu;
  8221. struct device_drv *drv = cgpu->drv;
  8222. if (drv->thread_disable)
  8223. drv->thread_disable(mythr);
  8224. hashmeter2(mythr);
  8225. __thr_being_msg(LOG_WARNING, mythr, "being disabled");
  8226. mythr->rolling = mythr->cgpu->rolling = 0;
  8227. thread_reportout(mythr);
  8228. mythr->_mt_disable_called = true;
  8229. }
  8230. /* Put a new unqueued work item in cgpu->unqueued_work under cgpu->qlock till
  8231. * the driver tells us it's full so that it may extract the work item using
  8232. * the get_queued() function which adds it to the hashtable on
  8233. * cgpu->queued_work. */
  8234. static void fill_queue(struct thr_info *mythr, struct cgpu_info *cgpu, struct device_drv *drv, const int thr_id)
  8235. {
  8236. thread_reportout(mythr);
  8237. do {
  8238. bool need_work;
  8239. /* Do this lockless just to know if we need more unqueued work. */
  8240. need_work = (!cgpu->unqueued_work);
  8241. /* get_work is a blocking function so do it outside of lock
  8242. * to prevent deadlocks with other locks. */
  8243. if (need_work) {
  8244. struct work *work = get_work(mythr);
  8245. wr_lock(&cgpu->qlock);
  8246. /* Check we haven't grabbed work somehow between
  8247. * checking and picking up the lock. */
  8248. if (likely(!cgpu->unqueued_work))
  8249. cgpu->unqueued_work = work;
  8250. else
  8251. need_work = false;
  8252. wr_unlock(&cgpu->qlock);
  8253. if (unlikely(!need_work))
  8254. discard_work(work);
  8255. }
  8256. /* The queue_full function should be used by the driver to
  8257. * actually place work items on the physical device if it
  8258. * does have a queue. */
  8259. } while (drv->queue_full && !drv->queue_full(cgpu));
  8260. }
  8261. /* Add a work item to a cgpu's queued hashlist */
  8262. void __add_queued(struct cgpu_info *cgpu, struct work *work)
  8263. {
  8264. cgpu->queued_count++;
  8265. HASH_ADD_INT(cgpu->queued_work, id, work);
  8266. }
  8267. /* This function is for retrieving one work item from the unqueued pointer and
  8268. * adding it to the hashtable of queued work. Code using this function must be
  8269. * able to handle NULL as a return which implies there is no work available. */
  8270. struct work *get_queued(struct cgpu_info *cgpu)
  8271. {
  8272. struct work *work = NULL;
  8273. wr_lock(&cgpu->qlock);
  8274. if (cgpu->unqueued_work) {
  8275. work = cgpu->unqueued_work;
  8276. if (unlikely(stale_work(work, false))) {
  8277. discard_work(work);
  8278. work = NULL;
  8279. wake_gws();
  8280. } else
  8281. __add_queued(cgpu, work);
  8282. cgpu->unqueued_work = NULL;
  8283. }
  8284. wr_unlock(&cgpu->qlock);
  8285. return work;
  8286. }
  8287. void add_queued(struct cgpu_info *cgpu, struct work *work)
  8288. {
  8289. wr_lock(&cgpu->qlock);
  8290. __add_queued(cgpu, work);
  8291. wr_unlock(&cgpu->qlock);
  8292. }
  8293. /* Get fresh work and add it to cgpu's queued hashlist */
  8294. struct work *get_queue_work(struct thr_info *thr, struct cgpu_info *cgpu, int thr_id)
  8295. {
  8296. struct work *work = get_work(thr);
  8297. add_queued(cgpu, work);
  8298. return work;
  8299. }
  8300. /* This function is for finding an already queued work item in the
  8301. * given que hashtable. Code using this function must be able
  8302. * to handle NULL as a return which implies there is no matching work.
  8303. * The calling function must lock access to the que if it is required.
  8304. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  8305. struct work *__find_work_bymidstate(struct work *que, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  8306. {
  8307. struct work *work, *tmp, *ret = NULL;
  8308. HASH_ITER(hh, que, work, tmp) {
  8309. if (memcmp(work->midstate, midstate, midstatelen) == 0 &&
  8310. memcmp(work->data + offset, data, datalen) == 0) {
  8311. ret = work;
  8312. break;
  8313. }
  8314. }
  8315. return ret;
  8316. }
  8317. /* This function is for finding an already queued work item in the
  8318. * device's queued_work hashtable. Code using this function must be able
  8319. * to handle NULL as a return which implies there is no matching work.
  8320. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  8321. struct work *find_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  8322. {
  8323. struct work *ret;
  8324. rd_lock(&cgpu->qlock);
  8325. ret = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  8326. rd_unlock(&cgpu->qlock);
  8327. return ret;
  8328. }
  8329. struct work *clone_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  8330. {
  8331. struct work *work, *ret = NULL;
  8332. rd_lock(&cgpu->qlock);
  8333. work = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  8334. if (work)
  8335. ret = copy_work(work);
  8336. rd_unlock(&cgpu->qlock);
  8337. return ret;
  8338. }
  8339. void __work_completed(struct cgpu_info *cgpu, struct work *work)
  8340. {
  8341. cgpu->queued_count--;
  8342. HASH_DEL(cgpu->queued_work, work);
  8343. }
  8344. /* This function should be used by queued device drivers when they're sure
  8345. * the work struct is no longer in use. */
  8346. void work_completed(struct cgpu_info *cgpu, struct work *work)
  8347. {
  8348. wr_lock(&cgpu->qlock);
  8349. __work_completed(cgpu, work);
  8350. wr_unlock(&cgpu->qlock);
  8351. free_work(work);
  8352. }
  8353. /* Combines find_queued_work_bymidstate and work_completed in one function
  8354. * withOUT destroying the work so the driver must free it. */
  8355. struct work *take_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  8356. {
  8357. struct work *work;
  8358. wr_lock(&cgpu->qlock);
  8359. work = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  8360. if (work)
  8361. __work_completed(cgpu, work);
  8362. wr_unlock(&cgpu->qlock);
  8363. return work;
  8364. }
  8365. static void flush_queue(struct cgpu_info *cgpu)
  8366. {
  8367. struct work *work = NULL;
  8368. wr_lock(&cgpu->qlock);
  8369. work = cgpu->unqueued_work;
  8370. cgpu->unqueued_work = NULL;
  8371. wr_unlock(&cgpu->qlock);
  8372. if (work) {
  8373. free_work(work);
  8374. applog(LOG_DEBUG, "Discarded queued work item");
  8375. }
  8376. }
  8377. /* This version of hash work is for devices that are fast enough to always
  8378. * perform a full nonce range and need a queue to maintain the device busy.
  8379. * Work creation and destruction is not done from within this function
  8380. * directly. */
  8381. void hash_queued_work(struct thr_info *mythr)
  8382. {
  8383. const long cycle = opt_log_interval / 5 ? : 1;
  8384. struct timeval tv_start = {0, 0}, tv_end;
  8385. struct cgpu_info *cgpu = mythr->cgpu;
  8386. struct device_drv *drv = cgpu->drv;
  8387. const int thr_id = mythr->id;
  8388. int64_t hashes_done = 0;
  8389. if (unlikely(cgpu->deven != DEV_ENABLED))
  8390. mt_disable(mythr);
  8391. while (likely(!cgpu->shutdown)) {
  8392. struct timeval diff;
  8393. int64_t hashes;
  8394. fill_queue(mythr, cgpu, drv, thr_id);
  8395. thread_reportin(mythr);
  8396. hashes = drv->scanwork(mythr);
  8397. /* Reset the bool here in case the driver looks for it
  8398. * synchronously in the scanwork loop. */
  8399. mythr->work_restart = false;
  8400. if (unlikely(hashes == -1 )) {
  8401. applog(LOG_ERR, "%s %d failure, disabling!", drv->name, cgpu->device_id);
  8402. cgpu->deven = DEV_DISABLED;
  8403. dev_error(cgpu, REASON_THREAD_ZERO_HASH);
  8404. mt_disable(mythr);
  8405. }
  8406. hashes_done += hashes;
  8407. cgtime(&tv_end);
  8408. timersub(&tv_end, &tv_start, &diff);
  8409. if (diff.tv_sec >= cycle) {
  8410. hashmeter(thr_id, &diff, hashes_done);
  8411. hashes_done = 0;
  8412. copy_time(&tv_start, &tv_end);
  8413. }
  8414. if (unlikely(mythr->pause || cgpu->deven != DEV_ENABLED))
  8415. mt_disable(mythr);
  8416. if (unlikely(mythr->work_restart)) {
  8417. flush_queue(cgpu);
  8418. if (drv->flush_work)
  8419. drv->flush_work(cgpu);
  8420. }
  8421. }
  8422. // cgpu->deven = DEV_DISABLED; set in miner_thread
  8423. }
  8424. // Called by minerloop, when it is re-enabling a processor
  8425. void mt_disable_finish(struct thr_info *mythr)
  8426. {
  8427. struct device_drv *drv = mythr->cgpu->drv;
  8428. thread_reportin(mythr);
  8429. __thr_being_msg(LOG_WARNING, mythr, "being re-enabled");
  8430. if (drv->thread_enable)
  8431. drv->thread_enable(mythr);
  8432. mythr->_mt_disable_called = false;
  8433. }
  8434. // Called by synchronous minerloops, when they find their processor should be disabled
  8435. // Calls mt_disable_start, waits until it's re-enabled, then calls mt_disable_finish
  8436. void mt_disable(struct thr_info *mythr)
  8437. {
  8438. const struct cgpu_info * const cgpu = mythr->cgpu;
  8439. mt_disable_start(mythr);
  8440. applog(LOG_DEBUG, "Waiting for wakeup notification in miner thread");
  8441. do {
  8442. notifier_read(mythr->notifier);
  8443. } while (mythr->pause || cgpu->deven != DEV_ENABLED);
  8444. mt_disable_finish(mythr);
  8445. }
  8446. enum {
  8447. STAT_SLEEP_INTERVAL = 1,
  8448. STAT_CTR_INTERVAL = 10000000,
  8449. FAILURE_INTERVAL = 30,
  8450. };
  8451. /* Stage another work item from the work returned in a longpoll */
  8452. 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)
  8453. {
  8454. bool rc;
  8455. work->rolltime = rolltime;
  8456. rc = work_decode(pool, work, val);
  8457. if (unlikely(!rc)) {
  8458. applog(LOG_ERR, "Could not convert longpoll data to work");
  8459. free_work(work);
  8460. return;
  8461. }
  8462. total_getworks++;
  8463. pool->getwork_requested++;
  8464. work->pool = pool;
  8465. copy_time(&work->tv_getwork, tv_lp);
  8466. copy_time(&work->tv_getwork_reply, tv_lp_reply);
  8467. calc_diff(work, 0);
  8468. if (pool->enabled == POOL_REJECTING)
  8469. work->mandatory = true;
  8470. work->longpoll = true;
  8471. work->getwork_mode = GETWORK_MODE_LP;
  8472. update_last_work(work);
  8473. /* We'll be checking this work item twice, but we already know it's
  8474. * from a new block so explicitly force the new block detection now
  8475. * rather than waiting for it to hit the stage thread. This also
  8476. * allows testwork to know whether LP discovered the block or not. */
  8477. test_work_current(work);
  8478. /* Don't use backup LPs as work if we have failover-only enabled. Use
  8479. * the longpoll work from a pool that has been rejecting shares as a
  8480. * way to detect when the pool has recovered.
  8481. */
  8482. if (pool != current_pool() && opt_fail_only && pool->enabled != POOL_REJECTING) {
  8483. free_work(work);
  8484. return;
  8485. }
  8486. work = clone_work(work);
  8487. applog(LOG_DEBUG, "Pushing converted work to stage thread");
  8488. stage_work(work);
  8489. applog(LOG_DEBUG, "Converted longpoll data to work");
  8490. }
  8491. /* If we want longpoll, enable it for the chosen default pool, or, if
  8492. * the pool does not support longpoll, find the first one that does
  8493. * and use its longpoll support */
  8494. static struct pool *select_longpoll_pool(struct pool *cp)
  8495. {
  8496. int i;
  8497. if (cp->lp_url)
  8498. return cp;
  8499. for (i = 0; i < total_pools; i++) {
  8500. struct pool *pool = pools[i];
  8501. if (pool->has_stratum || pool->lp_url)
  8502. return pool;
  8503. }
  8504. return NULL;
  8505. }
  8506. /* This will make the longpoll thread wait till it's the current pool, or it
  8507. * has been flagged as rejecting, before attempting to open any connections.
  8508. */
  8509. static void wait_lpcurrent(struct pool *pool)
  8510. {
  8511. while (!cnx_needed(pool))
  8512. {
  8513. mutex_lock(&lp_lock);
  8514. pthread_cond_wait(&lp_cond, &lp_lock);
  8515. mutex_unlock(&lp_lock);
  8516. }
  8517. }
  8518. static curl_socket_t save_curl_socket(void *vpool, __maybe_unused curlsocktype purpose, struct curl_sockaddr *addr) {
  8519. struct pool *pool = vpool;
  8520. curl_socket_t sock = socket(addr->family, addr->socktype, addr->protocol);
  8521. pool->lp_socket = sock;
  8522. return sock;
  8523. }
  8524. static void *longpoll_thread(void *userdata)
  8525. {
  8526. struct pool *cp = (struct pool *)userdata;
  8527. /* This *pool is the source of the actual longpoll, not the pool we've
  8528. * tied it to */
  8529. struct timeval start, reply, end;
  8530. struct pool *pool = NULL;
  8531. char threadname[20];
  8532. CURL *curl = NULL;
  8533. int failures = 0;
  8534. char *lp_url;
  8535. int rolltime;
  8536. #ifndef HAVE_PTHREAD_CANCEL
  8537. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  8538. #endif
  8539. snprintf(threadname, 20, "longpoll%u", cp->pool_no);
  8540. RenameThread(threadname);
  8541. curl = curl_easy_init();
  8542. if (unlikely(!curl)) {
  8543. applog(LOG_ERR, "CURL initialisation failed");
  8544. return NULL;
  8545. }
  8546. retry_pool:
  8547. pool = select_longpoll_pool(cp);
  8548. if (!pool) {
  8549. applog(LOG_WARNING, "No suitable long-poll found for %s", cp->rpc_url);
  8550. while (!pool) {
  8551. cgsleep_ms(60000);
  8552. pool = select_longpoll_pool(cp);
  8553. }
  8554. }
  8555. if (pool->has_stratum) {
  8556. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  8557. cp->rpc_url, pool->rpc_url);
  8558. goto out;
  8559. }
  8560. /* Any longpoll from any pool is enough for this to be true */
  8561. have_longpoll = true;
  8562. wait_lpcurrent(cp);
  8563. {
  8564. lp_url = pool->lp_url;
  8565. if (cp == pool)
  8566. applog(LOG_WARNING, "Long-polling activated for %s (%s)", lp_url, pool_protocol_name(pool->lp_proto));
  8567. else
  8568. applog(LOG_WARNING, "Long-polling activated for %s via %s (%s)", cp->rpc_url, lp_url, pool_protocol_name(pool->lp_proto));
  8569. }
  8570. while (42) {
  8571. json_t *val, *soval;
  8572. struct work *work = make_work();
  8573. char *lpreq;
  8574. lpreq = prepare_rpc_req(work, pool->lp_proto, pool->lp_id);
  8575. work->pool = pool;
  8576. if (!lpreq)
  8577. {
  8578. free_work(work);
  8579. goto lpfail;
  8580. }
  8581. wait_lpcurrent(cp);
  8582. cgtime(&start);
  8583. /* Longpoll connections can be persistent for a very long time
  8584. * and any number of issues could have come up in the meantime
  8585. * so always establish a fresh connection instead of relying on
  8586. * a persistent one. */
  8587. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  8588. curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, save_curl_socket);
  8589. curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, pool);
  8590. val = json_rpc_call(curl, lp_url, pool->rpc_userpass,
  8591. lpreq, false, true, &rolltime, pool, false);
  8592. pool->lp_socket = CURL_SOCKET_BAD;
  8593. cgtime(&reply);
  8594. free(lpreq);
  8595. if (likely(val)) {
  8596. soval = json_object_get(json_object_get(val, "result"), "submitold");
  8597. if (soval)
  8598. pool->submit_old = json_is_true(soval);
  8599. else
  8600. pool->submit_old = false;
  8601. convert_to_work(val, rolltime, pool, work, &start, &reply);
  8602. failures = 0;
  8603. json_decref(val);
  8604. } else {
  8605. /* Some pools regularly drop the longpoll request so
  8606. * only see this as longpoll failure if it happens
  8607. * immediately and just restart it the rest of the
  8608. * time. */
  8609. cgtime(&end);
  8610. free_work(work);
  8611. if (end.tv_sec - start.tv_sec > 30)
  8612. continue;
  8613. if (failures == 1)
  8614. applog(LOG_WARNING, "longpoll failed for %s, retrying every 30s", lp_url);
  8615. lpfail:
  8616. cgsleep_ms(30000);
  8617. }
  8618. if (pool != cp) {
  8619. pool = select_longpoll_pool(cp);
  8620. if (pool->has_stratum) {
  8621. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  8622. cp->rpc_url, pool->rpc_url);
  8623. break;
  8624. }
  8625. if (unlikely(!pool))
  8626. goto retry_pool;
  8627. }
  8628. if (unlikely(pool->removed))
  8629. break;
  8630. }
  8631. out:
  8632. curl_easy_cleanup(curl);
  8633. return NULL;
  8634. }
  8635. static void stop_longpoll(void)
  8636. {
  8637. int i;
  8638. want_longpoll = false;
  8639. for (i = 0; i < total_pools; ++i)
  8640. {
  8641. struct pool *pool = pools[i];
  8642. if (unlikely(!pool->lp_started))
  8643. continue;
  8644. pool->lp_started = false;
  8645. pthread_cancel(pool->longpoll_thread);
  8646. }
  8647. have_longpoll = false;
  8648. }
  8649. static void start_longpoll(void)
  8650. {
  8651. int i;
  8652. want_longpoll = true;
  8653. for (i = 0; i < total_pools; ++i)
  8654. {
  8655. struct pool *pool = pools[i];
  8656. if (unlikely(pool->removed || pool->lp_started || !pool->lp_url))
  8657. continue;
  8658. pool->lp_started = true;
  8659. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  8660. quit(1, "Failed to create pool longpoll thread");
  8661. }
  8662. }
  8663. void reinit_device(struct cgpu_info *cgpu)
  8664. {
  8665. if (cgpu->drv->reinit_device)
  8666. cgpu->drv->reinit_device(cgpu);
  8667. }
  8668. static struct timeval rotate_tv;
  8669. /* We reap curls if they are unused for over a minute */
  8670. static void reap_curl(struct pool *pool)
  8671. {
  8672. struct curl_ent *ent, *iter;
  8673. struct timeval now;
  8674. int reaped = 0;
  8675. cgtime(&now);
  8676. mutex_lock(&pool->pool_lock);
  8677. LL_FOREACH_SAFE(pool->curllist, ent, iter) {
  8678. if (pool->curls < 2)
  8679. break;
  8680. if (now.tv_sec - ent->tv.tv_sec > 300) {
  8681. reaped++;
  8682. pool->curls--;
  8683. LL_DELETE(pool->curllist, ent);
  8684. curl_easy_cleanup(ent->curl);
  8685. free(ent);
  8686. }
  8687. }
  8688. mutex_unlock(&pool->pool_lock);
  8689. if (reaped)
  8690. applog(LOG_DEBUG, "Reaped %d curl%s from pool %d", reaped, reaped > 1 ? "s" : "", pool->pool_no);
  8691. }
  8692. static void *watchpool_thread(void __maybe_unused *userdata)
  8693. {
  8694. int intervals = 0;
  8695. #ifndef HAVE_PTHREAD_CANCEL
  8696. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  8697. #endif
  8698. RenameThread("watchpool");
  8699. while (42) {
  8700. struct timeval now;
  8701. int i;
  8702. if (++intervals > 20)
  8703. intervals = 0;
  8704. cgtime(&now);
  8705. for (i = 0; i < total_pools; i++) {
  8706. struct pool *pool = pools[i];
  8707. if (!opt_benchmark)
  8708. reap_curl(pool);
  8709. /* Get a rolling utility per pool over 10 mins */
  8710. if (intervals > 19) {
  8711. int shares = pool->diff1 - pool->last_shares;
  8712. pool->last_shares = pool->diff1;
  8713. pool->utility = (pool->utility + (double)shares * 0.63) / 1.63;
  8714. pool->shares = pool->utility;
  8715. }
  8716. if (pool->enabled == POOL_DISABLED)
  8717. continue;
  8718. /* Don't start testing any pools if the test threads
  8719. * from startup are still doing their first attempt. */
  8720. if (unlikely(pool->testing)) {
  8721. pthread_join(pool->test_thread, NULL);
  8722. }
  8723. /* Test pool is idle once every minute */
  8724. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 30) {
  8725. cgtime(&pool->tv_idle);
  8726. if (pool_active(pool, true) && pool_tclear(pool, &pool->idle))
  8727. pool_resus(pool);
  8728. }
  8729. /* Only switch pools if the failback pool has been
  8730. * alive for more than 5 minutes (default) to prevent
  8731. * intermittently failing pools from being used. */
  8732. if (!pool->idle && pool_strategy == POOL_FAILOVER && pool->prio < cp_prio() &&
  8733. now.tv_sec - pool->tv_idle.tv_sec > opt_fail_switch_delay) {
  8734. if (opt_fail_switch_delay % 60)
  8735. applog(LOG_WARNING, "Pool %d %s stable for %d second%s",
  8736. pool->pool_no, pool->rpc_url,
  8737. opt_fail_switch_delay,
  8738. (opt_fail_switch_delay == 1 ? "" : "s"));
  8739. else
  8740. applog(LOG_WARNING, "Pool %d %s stable for %d minute%s",
  8741. pool->pool_no, pool->rpc_url,
  8742. opt_fail_switch_delay / 60,
  8743. (opt_fail_switch_delay == 60 ? "" : "s"));
  8744. switch_pools(NULL);
  8745. }
  8746. }
  8747. if (current_pool()->idle)
  8748. switch_pools(NULL);
  8749. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  8750. cgtime(&rotate_tv);
  8751. switch_pools(NULL);
  8752. }
  8753. cgsleep_ms(30000);
  8754. }
  8755. return NULL;
  8756. }
  8757. void mt_enable(struct thr_info *thr)
  8758. {
  8759. applog(LOG_DEBUG, "Waking up thread %d", thr->id);
  8760. notifier_wake(thr->notifier);
  8761. }
  8762. void proc_enable(struct cgpu_info *cgpu)
  8763. {
  8764. int j;
  8765. cgpu->deven = DEV_ENABLED;
  8766. for (j = cgpu->threads ?: 1; j--; )
  8767. mt_enable(cgpu->thr[j]);
  8768. }
  8769. #define device_recovered(cgpu) proc_enable(cgpu)
  8770. void cgpu_set_defaults(struct cgpu_info * const cgpu)
  8771. {
  8772. struct string_elist *setstr_elist;
  8773. const char *p, *p2;
  8774. char replybuf[0x2000];
  8775. size_t L;
  8776. DL_FOREACH(opt_set_device_list, setstr_elist)
  8777. {
  8778. const char * const setstr = setstr_elist->string;
  8779. p = strchr(setstr, ':');
  8780. if (!p)
  8781. p = setstr;
  8782. {
  8783. L = p - setstr;
  8784. char pattern[L + 1];
  8785. if (L)
  8786. memcpy(pattern, setstr, L);
  8787. pattern[L] = '\0';
  8788. if (!cgpu_match(pattern, cgpu))
  8789. continue;
  8790. }
  8791. applog(LOG_DEBUG, "%"PRIpreprv": %s: Matched with set default: %s",
  8792. cgpu->proc_repr, __func__, setstr);
  8793. if (p[0] == ':')
  8794. ++p;
  8795. p2 = strchr(p, '=');
  8796. if (!p2)
  8797. {
  8798. L = strlen(p);
  8799. p2 = "";
  8800. }
  8801. else
  8802. {
  8803. L = p2 - p;
  8804. ++p2;
  8805. }
  8806. char opt[L + 1];
  8807. if (L)
  8808. memcpy(opt, p, L);
  8809. opt[L] = '\0';
  8810. L = strlen(p2);
  8811. char setval[L + 1];
  8812. if (L)
  8813. memcpy(setval, p2, L);
  8814. setval[L] = '\0';
  8815. enum bfg_set_device_replytype success;
  8816. p = proc_set_device(cgpu, opt, setval, replybuf, &success);
  8817. switch (success)
  8818. {
  8819. case SDR_OK:
  8820. applog(LOG_DEBUG, "%"PRIpreprv": Applied rule %s%s%s",
  8821. cgpu->proc_repr, setstr,
  8822. p ? ": " : "", p ?: "");
  8823. break;
  8824. case SDR_ERR:
  8825. case SDR_HELP:
  8826. case SDR_UNKNOWN:
  8827. applog(LOG_DEBUG, "%"PRIpreprv": Applying rule %s: %s",
  8828. cgpu->proc_repr, setstr, p);
  8829. break;
  8830. case SDR_AUTO:
  8831. case SDR_NOSUPP:
  8832. applog(LOG_WARNING, "%"PRIpreprv": set_device is not implemented (trying to apply rule: %s)",
  8833. cgpu->proc_repr, setstr);
  8834. }
  8835. }
  8836. cgpu->already_set_defaults = true;
  8837. }
  8838. void drv_set_defaults(const struct device_drv * const drv, const void *datap, void *userp, const char * const devpath, const char * const serial, const int mode)
  8839. {
  8840. struct device_drv dummy_drv = *drv;
  8841. struct cgpu_info dummy_cgpu = {
  8842. .drv = &dummy_drv,
  8843. .device = &dummy_cgpu,
  8844. .device_id = -1,
  8845. .proc_id = -1,
  8846. .device_data = userp,
  8847. .device_path = devpath,
  8848. .dev_serial = serial,
  8849. };
  8850. strcpy(dummy_cgpu.proc_repr, drv->name);
  8851. switch (mode)
  8852. {
  8853. case 0:
  8854. dummy_drv.set_device = datap;
  8855. break;
  8856. case 1:
  8857. dummy_drv.set_device = NULL;
  8858. dummy_cgpu.set_device_funcs = datap;
  8859. break;
  8860. }
  8861. cgpu_set_defaults(&dummy_cgpu);
  8862. }
  8863. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  8864. * the screen at regular intervals, and restarts threads if they appear to have
  8865. * died. */
  8866. #define WATCHDOG_SICK_TIME 60
  8867. #define WATCHDOG_DEAD_TIME 600
  8868. #define WATCHDOG_SICK_COUNT (WATCHDOG_SICK_TIME/WATCHDOG_INTERVAL)
  8869. #define WATCHDOG_DEAD_COUNT (WATCHDOG_DEAD_TIME/WATCHDOG_INTERVAL)
  8870. static void *watchdog_thread(void __maybe_unused *userdata)
  8871. {
  8872. const unsigned int interval = WATCHDOG_INTERVAL;
  8873. struct timeval zero_tv;
  8874. #ifndef HAVE_PTHREAD_CANCEL
  8875. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  8876. #endif
  8877. RenameThread("watchdog");
  8878. memset(&zero_tv, 0, sizeof(struct timeval));
  8879. cgtime(&rotate_tv);
  8880. while (1) {
  8881. int i;
  8882. struct timeval now;
  8883. sleep(interval);
  8884. discard_stale();
  8885. hashmeter(-1, &zero_tv, 0);
  8886. #ifdef HAVE_CURSES
  8887. const int ts = total_staged();
  8888. if (curses_active_locked()) {
  8889. change_logwinsize();
  8890. curses_print_status(ts);
  8891. _refresh_devstatus(true);
  8892. touchwin(logwin);
  8893. wrefresh(logwin);
  8894. unlock_curses();
  8895. }
  8896. #endif
  8897. cgtime(&now);
  8898. if (!sched_paused && !should_run()) {
  8899. applog(LOG_WARNING, "Pausing execution as per stop time %02d:%02d scheduled",
  8900. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  8901. if (!schedstart.enable) {
  8902. quit(0, "Terminating execution as planned");
  8903. break;
  8904. }
  8905. applog(LOG_WARNING, "Will restart execution as scheduled at %02d:%02d",
  8906. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  8907. sched_paused = true;
  8908. rd_lock(&mining_thr_lock);
  8909. for (i = 0; i < mining_threads; i++)
  8910. mining_thr[i]->pause = true;
  8911. rd_unlock(&mining_thr_lock);
  8912. } else if (sched_paused && should_run()) {
  8913. applog(LOG_WARNING, "Restarting execution as per start time %02d:%02d scheduled",
  8914. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  8915. if (schedstop.enable)
  8916. applog(LOG_WARNING, "Will pause execution as scheduled at %02d:%02d",
  8917. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  8918. sched_paused = false;
  8919. for (i = 0; i < mining_threads; i++) {
  8920. struct thr_info *thr;
  8921. thr = get_thread(i);
  8922. thr->pause = false;
  8923. }
  8924. for (i = 0; i < total_devices; ++i)
  8925. {
  8926. struct cgpu_info *cgpu = get_devices(i);
  8927. /* Don't touch disabled devices */
  8928. if (cgpu->deven == DEV_DISABLED)
  8929. continue;
  8930. proc_enable(cgpu);
  8931. }
  8932. }
  8933. for (i = 0; i < total_devices; ++i) {
  8934. struct cgpu_info *cgpu = get_devices(i);
  8935. if (!cgpu->disable_watchdog)
  8936. bfg_watchdog(cgpu, &now);
  8937. }
  8938. }
  8939. return NULL;
  8940. }
  8941. void bfg_watchdog(struct cgpu_info * const cgpu, struct timeval * const tvp_now)
  8942. {
  8943. struct thr_info *thr = cgpu->thr[0];
  8944. enum dev_enable *denable;
  8945. char *dev_str = cgpu->proc_repr;
  8946. if (likely(drv_ready(cgpu)))
  8947. {
  8948. if (unlikely(!cgpu->already_set_defaults))
  8949. cgpu_set_defaults(cgpu);
  8950. if (cgpu->drv->get_stats)
  8951. cgpu->drv->get_stats(cgpu);
  8952. }
  8953. denable = &cgpu->deven;
  8954. if (cgpu->drv->watchdog)
  8955. cgpu->drv->watchdog(cgpu, tvp_now);
  8956. /* Thread is disabled */
  8957. if (*denable == DEV_DISABLED)
  8958. return;
  8959. else
  8960. if (*denable == DEV_RECOVER_ERR) {
  8961. if (opt_restart && timer_elapsed(&cgpu->tv_device_last_not_well, NULL) > cgpu->reinit_backoff) {
  8962. applog(LOG_NOTICE, "Attempting to reinitialize %s",
  8963. dev_str);
  8964. if (cgpu->reinit_backoff < 300)
  8965. cgpu->reinit_backoff *= 2;
  8966. device_recovered(cgpu);
  8967. }
  8968. return;
  8969. }
  8970. else
  8971. if (*denable == DEV_RECOVER) {
  8972. if (opt_restart && cgpu->temp < cgpu->targettemp) {
  8973. applog(LOG_NOTICE, "%s recovered to temperature below target, re-enabling",
  8974. dev_str);
  8975. device_recovered(cgpu);
  8976. }
  8977. dev_error_update(cgpu, REASON_DEV_THERMAL_CUTOFF);
  8978. return;
  8979. }
  8980. else
  8981. if (cgpu->temp > cgpu->cutofftemp)
  8982. {
  8983. applog(LOG_WARNING, "%s hit thermal cutoff limit at %dC, disabling!",
  8984. dev_str, (int)cgpu->temp);
  8985. *denable = DEV_RECOVER;
  8986. dev_error(cgpu, REASON_DEV_THERMAL_CUTOFF);
  8987. run_cmd(cmd_idle);
  8988. }
  8989. if (thr->getwork) {
  8990. if (cgpu->status == LIFE_WELL && thr->getwork < tvp_now->tv_sec - opt_log_interval) {
  8991. int thrid;
  8992. bool cgpu_idle = true;
  8993. thr->rolling = 0;
  8994. for (thrid = 0; thrid < cgpu->threads; ++thrid)
  8995. if (!cgpu->thr[thrid]->getwork)
  8996. cgpu_idle = false;
  8997. if (cgpu_idle) {
  8998. cgpu->rolling = 0;
  8999. cgpu->status = LIFE_WAIT;
  9000. }
  9001. }
  9002. return;
  9003. }
  9004. else if (cgpu->status == LIFE_WAIT)
  9005. cgpu->status = LIFE_WELL;
  9006. #ifdef WANT_CPUMINE
  9007. if (!strcmp(cgpu->drv->dname, "cpu"))
  9008. return;
  9009. #endif
  9010. if (cgpu->status != LIFE_WELL && (tvp_now->tv_sec - thr->last.tv_sec < WATCHDOG_SICK_TIME)) {
  9011. if (likely(cgpu->status != LIFE_INIT && cgpu->status != LIFE_INIT2))
  9012. applog(LOG_ERR, "%s: Recovered, declaring WELL!", dev_str);
  9013. cgpu->status = LIFE_WELL;
  9014. cgpu->device_last_well = time(NULL);
  9015. } else if (cgpu->status == LIFE_WELL && (tvp_now->tv_sec - thr->last.tv_sec > WATCHDOG_SICK_TIME)) {
  9016. thr->rolling = cgpu->rolling = 0;
  9017. cgpu->status = LIFE_SICK;
  9018. applog(LOG_ERR, "%s: Idle for more than 60 seconds, declaring SICK!", dev_str);
  9019. cgtime(&thr->sick);
  9020. dev_error(cgpu, REASON_DEV_SICK_IDLE_60);
  9021. run_cmd(cmd_sick);
  9022. if (opt_restart && cgpu->drv->reinit_device) {
  9023. applog(LOG_ERR, "%s: Attempting to restart", dev_str);
  9024. reinit_device(cgpu);
  9025. }
  9026. } else if (cgpu->status == LIFE_SICK && (tvp_now->tv_sec - thr->last.tv_sec > WATCHDOG_DEAD_TIME)) {
  9027. cgpu->status = LIFE_DEAD;
  9028. applog(LOG_ERR, "%s: Not responded for more than 10 minutes, declaring DEAD!", dev_str);
  9029. cgtime(&thr->sick);
  9030. dev_error(cgpu, REASON_DEV_DEAD_IDLE_600);
  9031. run_cmd(cmd_dead);
  9032. } else if (tvp_now->tv_sec - thr->sick.tv_sec > 60 &&
  9033. (cgpu->status == LIFE_SICK || cgpu->status == LIFE_DEAD)) {
  9034. /* Attempt to restart a GPU that's sick or dead once every minute */
  9035. cgtime(&thr->sick);
  9036. if (opt_restart)
  9037. reinit_device(cgpu);
  9038. }
  9039. }
  9040. static void log_print_status(struct cgpu_info *cgpu)
  9041. {
  9042. char logline[255];
  9043. get_statline(logline, sizeof(logline), cgpu);
  9044. applog(LOG_WARNING, "%s", logline);
  9045. }
  9046. void print_summary(void)
  9047. {
  9048. struct timeval diff;
  9049. int hours, mins, secs, i;
  9050. double utility, efficiency = 0.0;
  9051. char xfer[(ALLOC_H2B_SPACED*2)+4+1], bw[(ALLOC_H2B_SPACED*2)+6+1];
  9052. int pool_secs;
  9053. timersub(&total_tv_end, &total_tv_start, &diff);
  9054. hours = diff.tv_sec / 3600;
  9055. mins = (diff.tv_sec % 3600) / 60;
  9056. secs = diff.tv_sec % 60;
  9057. utility = total_accepted / total_secs * 60;
  9058. efficiency = total_bytes_xfer ? total_diff_accepted * 2048. / total_bytes_xfer : 0.0;
  9059. applog(LOG_WARNING, "\nSummary of runtime statistics:\n");
  9060. applog(LOG_WARNING, "Started at %s", datestamp);
  9061. if (total_pools == 1)
  9062. applog(LOG_WARNING, "Pool: %s", pools[0]->rpc_url);
  9063. #ifdef WANT_CPUMINE
  9064. if (opt_n_threads > 0)
  9065. applog(LOG_WARNING, "CPU hasher algorithm used: %s", algo_names[opt_algo]);
  9066. #endif
  9067. applog(LOG_WARNING, "Runtime: %d hrs : %d mins : %d secs", hours, mins, secs);
  9068. applog(LOG_WARNING, "Average hashrate: %.1f Megahash/s", total_mhashes_done / total_secs);
  9069. applog(LOG_WARNING, "Solved blocks: %d", found_blocks);
  9070. applog(LOG_WARNING, "Best share difficulty: %s", best_share);
  9071. applog(LOG_WARNING, "Share submissions: %d", total_accepted + total_rejected);
  9072. applog(LOG_WARNING, "Accepted shares: %d", total_accepted);
  9073. applog(LOG_WARNING, "Rejected shares: %d + %d stale (%.2f%%)",
  9074. total_rejected, total_stale,
  9075. (float)(total_rejected + total_stale) / (float)(total_rejected + total_stale + total_accepted)
  9076. );
  9077. applog(LOG_WARNING, "Accepted difficulty shares: %1.f", total_diff_accepted);
  9078. applog(LOG_WARNING, "Rejected difficulty shares: %1.f", total_diff_rejected);
  9079. applog(LOG_WARNING, "Hardware errors: %d", hw_errors);
  9080. applog(LOG_WARNING, "Network transfer: %s (%s)",
  9081. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  9082. (float)total_bytes_rcvd,
  9083. (float)total_bytes_sent),
  9084. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  9085. (float)(total_bytes_rcvd / total_secs),
  9086. (float)(total_bytes_sent / total_secs)));
  9087. applog(LOG_WARNING, "Efficiency (accepted shares * difficulty / 2 KB): %.2f", efficiency);
  9088. applog(LOG_WARNING, "Utility (accepted shares / min): %.2f/min\n", utility);
  9089. applog(LOG_WARNING, "Unable to get work from server occasions: %d", total_go);
  9090. applog(LOG_WARNING, "Work items generated locally: %d", local_work);
  9091. applog(LOG_WARNING, "Submitting work remotely delay occasions: %d", total_ro);
  9092. applog(LOG_WARNING, "New blocks detected on network: %d\n", new_blocks);
  9093. if (total_pools > 1) {
  9094. for (i = 0; i < total_pools; i++) {
  9095. struct pool *pool = pools[i];
  9096. applog(LOG_WARNING, "Pool: %s", pool->rpc_url);
  9097. if (pool->solved)
  9098. applog(LOG_WARNING, "SOLVED %d BLOCK%s!", pool->solved, pool->solved > 1 ? "S" : "");
  9099. applog(LOG_WARNING, " Share submissions: %d", pool->accepted + pool->rejected);
  9100. applog(LOG_WARNING, " Accepted shares: %d", pool->accepted);
  9101. applog(LOG_WARNING, " Rejected shares: %d + %d stale (%.2f%%)",
  9102. pool->rejected, pool->stale_shares,
  9103. (float)(pool->rejected + pool->stale_shares) / (float)(pool->rejected + pool->stale_shares + pool->accepted)
  9104. );
  9105. applog(LOG_WARNING, " Accepted difficulty shares: %1.f", pool->diff_accepted);
  9106. applog(LOG_WARNING, " Rejected difficulty shares: %1.f", pool->diff_rejected);
  9107. pool_secs = timer_elapsed(&pool->cgminer_stats.start_tv, NULL);
  9108. applog(LOG_WARNING, " Network transfer: %s (%s)",
  9109. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  9110. (float)pool->cgminer_pool_stats.net_bytes_received,
  9111. (float)pool->cgminer_pool_stats.net_bytes_sent),
  9112. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  9113. (float)(pool->cgminer_pool_stats.net_bytes_received / pool_secs),
  9114. (float)(pool->cgminer_pool_stats.net_bytes_sent / pool_secs)));
  9115. uint64_t pool_bytes_xfer = pool->cgminer_pool_stats.net_bytes_received + pool->cgminer_pool_stats.net_bytes_sent;
  9116. efficiency = pool_bytes_xfer ? pool->diff_accepted * 2048. / pool_bytes_xfer : 0.0;
  9117. applog(LOG_WARNING, " Efficiency (accepted * difficulty / 2 KB): %.2f", efficiency);
  9118. applog(LOG_WARNING, " Items worked on: %d", pool->works);
  9119. applog(LOG_WARNING, " Unable to get work from server occasions: %d", pool->getfail_occasions);
  9120. applog(LOG_WARNING, " Submitting work remotely delay occasions: %d\n", pool->remotefail_occasions);
  9121. }
  9122. }
  9123. if (opt_quit_summary != BQS_NONE)
  9124. {
  9125. if (opt_quit_summary == BQS_DETAILED)
  9126. include_serial_in_statline = true;
  9127. applog(LOG_WARNING, "Summary of per device statistics:\n");
  9128. for (i = 0; i < total_devices; ++i) {
  9129. struct cgpu_info *cgpu = get_devices(i);
  9130. if (!cgpu->proc_id)
  9131. {
  9132. // Device summary line
  9133. opt_show_procs = false;
  9134. log_print_status(cgpu);
  9135. opt_show_procs = true;
  9136. }
  9137. if ((opt_quit_summary == BQS_PROCS || opt_quit_summary == BQS_DETAILED) && cgpu->procs > 1)
  9138. log_print_status(cgpu);
  9139. }
  9140. }
  9141. if (opt_shares) {
  9142. applog(LOG_WARNING, "Mined %g accepted shares of %g requested\n", total_diff_accepted, opt_shares);
  9143. if (opt_shares > total_diff_accepted)
  9144. applog(LOG_WARNING, "WARNING - Mined only %g shares of %g requested.", total_diff_accepted, opt_shares);
  9145. }
  9146. applog(LOG_WARNING, " ");
  9147. fflush(stderr);
  9148. fflush(stdout);
  9149. }
  9150. void _bfg_clean_up(bool restarting)
  9151. {
  9152. #ifdef HAVE_OPENCL
  9153. clear_adl(nDevs);
  9154. #endif
  9155. #ifdef HAVE_LIBUSB
  9156. if (likely(have_libusb))
  9157. libusb_exit(NULL);
  9158. #endif
  9159. cgtime(&total_tv_end);
  9160. #ifdef WIN32
  9161. timeEndPeriod(1);
  9162. #endif
  9163. if (!restarting) {
  9164. /* Attempting to disable curses or print a summary during a
  9165. * restart can lead to a deadlock. */
  9166. #ifdef HAVE_CURSES
  9167. disable_curses();
  9168. #endif
  9169. if (!opt_realquiet && successful_connect)
  9170. print_summary();
  9171. }
  9172. if (opt_n_threads > 0)
  9173. free(cpus);
  9174. curl_global_cleanup();
  9175. #ifdef WIN32
  9176. WSACleanup();
  9177. #endif
  9178. }
  9179. void _quit(int status)
  9180. {
  9181. if (status) {
  9182. const char *ev = getenv("__BFGMINER_SEGFAULT_ERRQUIT");
  9183. if (unlikely(ev && ev[0] && ev[0] != '0')) {
  9184. int *p = NULL;
  9185. // NOTE debugger can bypass with: p = &p
  9186. *p = status; // Segfault, hopefully dumping core
  9187. }
  9188. }
  9189. #if defined(unix) || defined(__APPLE__)
  9190. if (forkpid > 0) {
  9191. kill(forkpid, SIGTERM);
  9192. forkpid = 0;
  9193. }
  9194. #endif
  9195. exit(status);
  9196. }
  9197. #ifdef HAVE_CURSES
  9198. char *curses_input(const char *query)
  9199. {
  9200. char *input;
  9201. echo();
  9202. input = malloc(255);
  9203. if (!input)
  9204. quit(1, "Failed to malloc input");
  9205. leaveok(logwin, false);
  9206. wlogprint("%s:\n", query);
  9207. wgetnstr(logwin, input, 255);
  9208. if (!strlen(input))
  9209. {
  9210. free(input);
  9211. input = NULL;
  9212. }
  9213. leaveok(logwin, true);
  9214. noecho();
  9215. return input;
  9216. }
  9217. #endif
  9218. static bool pools_active = false;
  9219. static void *test_pool_thread(void *arg)
  9220. {
  9221. struct pool *pool = (struct pool *)arg;
  9222. if (pool_active(pool, false)) {
  9223. pool_tset(pool, &pool->lagging);
  9224. pool_tclear(pool, &pool->idle);
  9225. bool first_pool = false;
  9226. cg_wlock(&control_lock);
  9227. if (!pools_active) {
  9228. currentpool = pool;
  9229. if (pool->pool_no != 0)
  9230. first_pool = true;
  9231. pools_active = true;
  9232. }
  9233. cg_wunlock(&control_lock);
  9234. if (unlikely(first_pool))
  9235. applog(LOG_NOTICE, "Switching to pool %d %s - first alive pool", pool->pool_no, pool->rpc_url);
  9236. else
  9237. applog(LOG_NOTICE, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  9238. switch_pools(NULL);
  9239. } else
  9240. pool_died(pool);
  9241. pool->testing = false;
  9242. return NULL;
  9243. }
  9244. /* Always returns true that the pool details were added unless we are not
  9245. * live, implying this is the only pool being added, so if no pools are
  9246. * active it returns false. */
  9247. bool add_pool_details(struct pool *pool, bool live, char *url, char *user, char *pass)
  9248. {
  9249. size_t siz;
  9250. pool->rpc_url = url;
  9251. pool->rpc_user = user;
  9252. pool->rpc_pass = pass;
  9253. siz = strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2;
  9254. pool->rpc_userpass = malloc(siz);
  9255. if (!pool->rpc_userpass)
  9256. quit(1, "Failed to malloc userpass");
  9257. snprintf(pool->rpc_userpass, siz, "%s:%s", pool->rpc_user, pool->rpc_pass);
  9258. pool->testing = true;
  9259. pool->idle = true;
  9260. enable_pool(pool);
  9261. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  9262. if (!live) {
  9263. pthread_join(pool->test_thread, NULL);
  9264. return pools_active;
  9265. }
  9266. return true;
  9267. }
  9268. #ifdef HAVE_CURSES
  9269. static bool input_pool(bool live)
  9270. {
  9271. char *url = NULL, *user = NULL, *pass = NULL;
  9272. struct pool *pool;
  9273. bool ret = false;
  9274. immedok(logwin, true);
  9275. wlogprint("Input server details.\n");
  9276. url = curses_input("URL");
  9277. if (!url)
  9278. goto out;
  9279. user = curses_input("Username");
  9280. if (!user)
  9281. goto out;
  9282. pass = curses_input("Password");
  9283. if (!pass)
  9284. pass = calloc(1, 1);
  9285. pool = add_pool();
  9286. if (!detect_stratum(pool, url) && strncmp(url, "http://", 7) &&
  9287. strncmp(url, "https://", 8)) {
  9288. char *httpinput;
  9289. httpinput = malloc(256);
  9290. if (!httpinput)
  9291. quit(1, "Failed to malloc httpinput");
  9292. strcpy(httpinput, "http://");
  9293. strncat(httpinput, url, 248);
  9294. free(url);
  9295. url = httpinput;
  9296. }
  9297. ret = add_pool_details(pool, live, url, user, pass);
  9298. out:
  9299. immedok(logwin, false);
  9300. if (!ret) {
  9301. if (url)
  9302. free(url);
  9303. if (user)
  9304. free(user);
  9305. if (pass)
  9306. free(pass);
  9307. }
  9308. return ret;
  9309. }
  9310. #endif
  9311. #if defined(unix) || defined(__APPLE__)
  9312. static void fork_monitor()
  9313. {
  9314. // Make a pipe: [readFD, writeFD]
  9315. int pfd[2];
  9316. int r = pipe(pfd);
  9317. if (r < 0) {
  9318. perror("pipe - failed to create pipe for --monitor");
  9319. exit(1);
  9320. }
  9321. // Make stderr write end of pipe
  9322. fflush(stderr);
  9323. r = dup2(pfd[1], 2);
  9324. if (r < 0) {
  9325. perror("dup2 - failed to alias stderr to write end of pipe for --monitor");
  9326. exit(1);
  9327. }
  9328. r = close(pfd[1]);
  9329. if (r < 0) {
  9330. perror("close - failed to close write end of pipe for --monitor");
  9331. exit(1);
  9332. }
  9333. // Don't allow a dying monitor to kill the main process
  9334. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  9335. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  9336. if (SIG_ERR == sr0 || SIG_ERR == sr1) {
  9337. perror("signal - failed to edit signal mask for --monitor");
  9338. exit(1);
  9339. }
  9340. // Fork a child process
  9341. forkpid = fork();
  9342. if (forkpid < 0) {
  9343. perror("fork - failed to fork child process for --monitor");
  9344. exit(1);
  9345. }
  9346. // Child: launch monitor command
  9347. if (0 == forkpid) {
  9348. // Make stdin read end of pipe
  9349. r = dup2(pfd[0], 0);
  9350. if (r < 0) {
  9351. perror("dup2 - in child, failed to alias read end of pipe to stdin for --monitor");
  9352. exit(1);
  9353. }
  9354. close(pfd[0]);
  9355. if (r < 0) {
  9356. perror("close - in child, failed to close read end of pipe for --monitor");
  9357. exit(1);
  9358. }
  9359. // Launch user specified command
  9360. execl("/bin/bash", "/bin/bash", "-c", opt_stderr_cmd, (char*)NULL);
  9361. perror("execl - in child failed to exec user specified command for --monitor");
  9362. exit(1);
  9363. }
  9364. // Parent: clean up unused fds and bail
  9365. r = close(pfd[0]);
  9366. if (r < 0) {
  9367. perror("close - failed to close read end of pipe for --monitor");
  9368. exit(1);
  9369. }
  9370. }
  9371. #endif // defined(unix)
  9372. #ifdef HAVE_CURSES
  9373. #ifdef USE_UNICODE
  9374. static
  9375. wchar_t select_unicode_char(const wchar_t *opt)
  9376. {
  9377. for ( ; *opt; ++opt)
  9378. if (iswprint(*opt))
  9379. return *opt;
  9380. return '?';
  9381. }
  9382. #endif
  9383. void enable_curses(void) {
  9384. int x;
  9385. __maybe_unused int y;
  9386. lock_curses();
  9387. if (curses_active) {
  9388. unlock_curses();
  9389. return;
  9390. }
  9391. #ifdef USE_UNICODE
  9392. if (use_unicode)
  9393. {
  9394. setlocale(LC_CTYPE, "");
  9395. if (iswprint(0xb0))
  9396. have_unicode_degrees = true;
  9397. unicode_micro = select_unicode_char(L"\xb5\u03bcu");
  9398. }
  9399. #endif
  9400. mainwin = initscr();
  9401. start_color();
  9402. #if defined(PDCURSES) || defined(NCURSES_VERSION)
  9403. if (ERR != use_default_colors())
  9404. default_bgcolor = -1;
  9405. #endif
  9406. if (has_colors() && ERR != init_pair(1, COLOR_WHITE, COLOR_BLUE))
  9407. {
  9408. menu_attr = COLOR_PAIR(1);
  9409. if (ERR != init_pair(2, COLOR_RED, default_bgcolor))
  9410. attr_bad |= COLOR_PAIR(2);
  9411. }
  9412. keypad(mainwin, true);
  9413. getmaxyx(mainwin, y, x);
  9414. statuswin = newwin(logstart, x, 0, 0);
  9415. leaveok(statuswin, true);
  9416. // For whatever reason, PDCurses crashes if the logwin is initialized to height y-logcursor
  9417. // We resize the window later anyway, so just start it off at 1 :)
  9418. logwin = newwin(1, 0, logcursor, 0);
  9419. idlok(logwin, true);
  9420. scrollok(logwin, true);
  9421. leaveok(logwin, true);
  9422. cbreak();
  9423. noecho();
  9424. nonl();
  9425. curses_active = true;
  9426. statusy = logstart;
  9427. unlock_curses();
  9428. }
  9429. #endif
  9430. /* TODO: fix need a dummy CPU device_drv even if no support for CPU mining */
  9431. #ifndef WANT_CPUMINE
  9432. struct device_drv cpu_drv;
  9433. struct device_drv cpu_drv = {
  9434. .name = "CPU",
  9435. };
  9436. #endif
  9437. static int cgminer_id_count = 0;
  9438. static int device_line_id_count;
  9439. void register_device(struct cgpu_info *cgpu)
  9440. {
  9441. cgpu->deven = DEV_ENABLED;
  9442. wr_lock(&devices_lock);
  9443. devices[cgpu->cgminer_id = cgminer_id_count++] = cgpu;
  9444. wr_unlock(&devices_lock);
  9445. if (!cgpu->proc_id)
  9446. cgpu->device_line_id = device_line_id_count++;
  9447. mining_threads += cgpu->threads ?: 1;
  9448. #ifdef HAVE_CURSES
  9449. adj_width(mining_threads, &dev_width);
  9450. #endif
  9451. rwlock_init(&cgpu->qlock);
  9452. cgpu->queued_work = NULL;
  9453. }
  9454. struct _cgpu_devid_counter {
  9455. char name[4];
  9456. int lastid;
  9457. UT_hash_handle hh;
  9458. };
  9459. void renumber_cgpu(struct cgpu_info *cgpu)
  9460. {
  9461. static struct _cgpu_devid_counter *devids = NULL;
  9462. struct _cgpu_devid_counter *d;
  9463. HASH_FIND_STR(devids, cgpu->drv->name, d);
  9464. if (d)
  9465. cgpu->device_id = ++d->lastid;
  9466. else {
  9467. d = malloc(sizeof(*d));
  9468. memcpy(d->name, cgpu->drv->name, sizeof(d->name));
  9469. cgpu->device_id = d->lastid = 0;
  9470. HASH_ADD_STR(devids, name, d);
  9471. }
  9472. // Build repr strings
  9473. sprintf(cgpu->dev_repr, "%s%2u", cgpu->drv->name, cgpu->device_id % 100);
  9474. sprintf(cgpu->dev_repr_ns, "%s%u", cgpu->drv->name, cgpu->device_id % 100);
  9475. strcpy(cgpu->proc_repr, cgpu->dev_repr);
  9476. sprintf(cgpu->proc_repr_ns, "%s%u", cgpu->drv->name, cgpu->device_id);
  9477. const int lpcount = cgpu->procs;
  9478. if (lpcount > 1)
  9479. {
  9480. int ns;
  9481. struct cgpu_info *slave;
  9482. int lpdigits = 1;
  9483. for (int i = lpcount; i > 26 && lpdigits < 3; i /= 26)
  9484. ++lpdigits;
  9485. memset(&cgpu->proc_repr[5], 'a', lpdigits);
  9486. cgpu->proc_repr[5 + lpdigits] = '\0';
  9487. ns = strlen(cgpu->proc_repr_ns);
  9488. strcpy(&cgpu->proc_repr_ns[ns], &cgpu->proc_repr[5]);
  9489. slave = cgpu;
  9490. for (int i = 1; i < lpcount; ++i)
  9491. {
  9492. slave = slave->next_proc;
  9493. strcpy(slave->proc_repr, cgpu->proc_repr);
  9494. strcpy(slave->proc_repr_ns, cgpu->proc_repr_ns);
  9495. for (int x = i, y = lpdigits; --y, x; x /= 26)
  9496. {
  9497. slave->proc_repr_ns[ns + y] =
  9498. slave->proc_repr[5 + y] += (x % 26);
  9499. }
  9500. }
  9501. }
  9502. }
  9503. static bool my_blkmaker_sha256_callback(void *digest, const void *buffer, size_t length)
  9504. {
  9505. sha256(buffer, length, digest);
  9506. return true;
  9507. }
  9508. static
  9509. int drv_algo_check(const struct device_drv * const drv)
  9510. {
  9511. const int algomatch = opt_scrypt ? POW_SCRYPT : POW_SHA256D;
  9512. const supported_algos_t algos = drv->supported_algos ?: POW_SHA256D;
  9513. return (algos & algomatch);
  9514. }
  9515. #ifndef HAVE_PTHREAD_CANCEL
  9516. extern void setup_pthread_cancel_workaround();
  9517. extern struct sigaction pcwm_orig_term_handler;
  9518. #endif
  9519. bool bfg_need_detect_rescan;
  9520. extern void probe_device(struct lowlevel_device_info *);
  9521. static void schedule_rescan(const struct timeval *);
  9522. static
  9523. void drv_detect_all()
  9524. {
  9525. bool rescanning = false;
  9526. rescan:
  9527. bfg_need_detect_rescan = false;
  9528. #ifdef HAVE_BFG_LOWLEVEL
  9529. struct lowlevel_device_info * const infolist = lowlevel_scan(), *info, *infotmp;
  9530. LL_FOREACH_SAFE(infolist, info, infotmp)
  9531. probe_device(info);
  9532. LL_FOREACH_SAFE(infolist, info, infotmp)
  9533. pthread_join(info->probe_pth, NULL);
  9534. #endif
  9535. struct driver_registration *reg, *tmp;
  9536. BFG_FOREACH_DRIVER_BY_PRIORITY(reg, tmp)
  9537. {
  9538. const struct device_drv * const drv = reg->drv;
  9539. if (!(drv_algo_check(drv) && drv->drv_detect))
  9540. continue;
  9541. drv->drv_detect();
  9542. }
  9543. #ifdef HAVE_BFG_LOWLEVEL
  9544. lowlevel_scan_free();
  9545. #endif
  9546. if (bfg_need_detect_rescan)
  9547. {
  9548. if (rescanning)
  9549. {
  9550. applog(LOG_DEBUG, "Device rescan requested a second time, delaying");
  9551. struct timeval tv_when;
  9552. timer_set_delay_from_now(&tv_when, rescan_delay_ms * 1000);
  9553. schedule_rescan(&tv_when);
  9554. }
  9555. else
  9556. {
  9557. rescanning = true;
  9558. applog(LOG_DEBUG, "Device rescan requested");
  9559. goto rescan;
  9560. }
  9561. }
  9562. }
  9563. static
  9564. void allocate_cgpu(struct cgpu_info *cgpu, unsigned int *kp)
  9565. {
  9566. struct thr_info *thr;
  9567. int j;
  9568. struct device_drv *api = cgpu->drv;
  9569. cgpu->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  9570. int threadobj = cgpu->threads;
  9571. if (!threadobj)
  9572. // Create a fake thread object to handle hashmeter etc
  9573. threadobj = 1;
  9574. cgpu->thr = calloc(threadobj + 1, sizeof(*cgpu->thr));
  9575. cgpu->thr[threadobj] = NULL;
  9576. cgpu->status = LIFE_INIT;
  9577. if (opt_devices_enabled_list)
  9578. {
  9579. struct string_elist *enablestr_elist;
  9580. cgpu->deven = DEV_DISABLED;
  9581. DL_FOREACH(opt_devices_enabled_list, enablestr_elist)
  9582. {
  9583. const char * const enablestr = enablestr_elist->string;
  9584. if (cgpu_match(enablestr, cgpu))
  9585. {
  9586. cgpu->deven = DEV_ENABLED;
  9587. break;
  9588. }
  9589. }
  9590. }
  9591. cgpu->max_hashes = 0;
  9592. BFGINIT(cgpu->min_nonce_diff, 1);
  9593. BFGINIT(cgpu->cutofftemp, opt_cutofftemp);
  9594. BFGINIT(cgpu->targettemp, cgpu->cutofftemp - 6);
  9595. // Setup thread structs before starting any of the threads, in case they try to interact
  9596. for (j = 0; j < threadobj; ++j, ++*kp) {
  9597. thr = get_thread(*kp);
  9598. thr->id = *kp;
  9599. thr->cgpu = cgpu;
  9600. thr->device_thread = j;
  9601. thr->work_restart_notifier[1] = INVSOCK;
  9602. thr->mutex_request[1] = INVSOCK;
  9603. thr->_job_transition_in_progress = true;
  9604. timerclear(&thr->tv_morework);
  9605. thr->scanhash_working = true;
  9606. thr->hashes_done = 0;
  9607. timerclear(&thr->tv_hashes_done);
  9608. cgtime(&thr->tv_lastupdate);
  9609. thr->tv_poll.tv_sec = -1;
  9610. thr->_max_nonce = api->can_limit_work ? api->can_limit_work(thr) : 0xffffffff;
  9611. cgpu->thr[j] = thr;
  9612. }
  9613. if (!cgpu->device->threads)
  9614. notifier_init_invalid(cgpu->thr[0]->notifier);
  9615. else
  9616. if (!cgpu->threads)
  9617. memcpy(&cgpu->thr[0]->notifier, &cgpu->device->thr[0]->notifier, sizeof(cgpu->thr[0]->notifier));
  9618. else
  9619. for (j = 0; j < cgpu->threads; ++j)
  9620. {
  9621. thr = cgpu->thr[j];
  9622. notifier_init(thr->notifier);
  9623. }
  9624. }
  9625. static
  9626. void start_cgpu(struct cgpu_info *cgpu)
  9627. {
  9628. struct thr_info *thr;
  9629. int j;
  9630. for (j = 0; j < cgpu->threads; ++j) {
  9631. thr = cgpu->thr[j];
  9632. /* Enable threads for devices set not to mine but disable
  9633. * their queue in case we wish to enable them later */
  9634. if (cgpu->drv->thread_prepare && !cgpu->drv->thread_prepare(thr))
  9635. continue;
  9636. thread_reportout(thr);
  9637. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  9638. quit(1, "thread %d create failed", thr->id);
  9639. notifier_wake(thr->notifier);
  9640. }
  9641. if (cgpu->deven == DEV_ENABLED)
  9642. proc_enable(cgpu);
  9643. }
  9644. static
  9645. void _scan_serial(void *p)
  9646. {
  9647. const char *s = p;
  9648. struct string_elist *iter, *tmp;
  9649. struct string_elist *orig_scan_devices = scan_devices;
  9650. if (s)
  9651. {
  9652. // Make temporary scan_devices list
  9653. scan_devices = NULL;
  9654. string_elist_add("noauto", &scan_devices);
  9655. add_serial(s);
  9656. }
  9657. drv_detect_all();
  9658. if (s)
  9659. {
  9660. DL_FOREACH_SAFE(scan_devices, iter, tmp)
  9661. {
  9662. string_elist_del(&scan_devices, iter);
  9663. }
  9664. scan_devices = orig_scan_devices;
  9665. }
  9666. }
  9667. #ifdef HAVE_BFG_LOWLEVEL
  9668. static
  9669. bool _probe_device_match(const struct lowlevel_device_info * const info, const char * const ser)
  9670. {
  9671. if (!(false
  9672. || (info->serial && !strcasecmp(ser, info->serial))
  9673. || (info->path && !strcasecmp(ser, info->path ))
  9674. || (info->devid && !strcasecmp(ser, info->devid ))
  9675. ))
  9676. {
  9677. char *devid = devpath_to_devid(ser);
  9678. if (!devid)
  9679. return false;
  9680. const bool different = strcmp(info->devid, devid);
  9681. free(devid);
  9682. if (different)
  9683. return false;
  9684. }
  9685. return true;
  9686. }
  9687. static
  9688. const struct device_drv *_probe_device_find_drv(const char * const _dname, const size_t dnamelen)
  9689. {
  9690. struct driver_registration *dreg;
  9691. char dname[dnamelen];
  9692. int i;
  9693. for (i = 0; i < dnamelen; ++i)
  9694. dname[i] = tolower(_dname[i]);
  9695. BFG_FIND_DRV_BY_DNAME(dreg, dname, dnamelen);
  9696. if (!dreg)
  9697. {
  9698. for (i = 0; i < dnamelen; ++i)
  9699. dname[i] = toupper(_dname[i]);
  9700. BFG_FIND_DRV_BY_NAME(dreg, dname, dnamelen);
  9701. if (!dreg)
  9702. return NULL;
  9703. }
  9704. if (!drv_algo_check(dreg->drv))
  9705. return NULL;
  9706. return dreg->drv;
  9707. }
  9708. static
  9709. void *probe_device_thread(void *p)
  9710. {
  9711. struct lowlevel_device_info * const infolist = p;
  9712. struct lowlevel_device_info *info = infolist;
  9713. bool request_rescan = false;
  9714. {
  9715. char threadname[5 + strlen(info->devid) + 1];
  9716. sprintf(threadname, "probe_%s", info->devid);
  9717. RenameThread(threadname);
  9718. }
  9719. // If already in use, ignore
  9720. if (bfg_claim_any(NULL, NULL, info->devid))
  9721. applogr(NULL, LOG_DEBUG, "%s: \"%s\" already in use",
  9722. __func__, info->product);
  9723. // if lowlevel device matches specific user assignment, probe requested driver(s)
  9724. struct string_elist *sd_iter, *sd_tmp;
  9725. struct driver_registration *dreg, *dreg_tmp;
  9726. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  9727. {
  9728. const char * const dname = sd_iter->string;
  9729. const char * const colon = strpbrk(dname, ":@");
  9730. if (!(colon && colon != dname))
  9731. continue;
  9732. const char * const ser = &colon[1];
  9733. LL_FOREACH2(infolist, info, same_devid_next)
  9734. {
  9735. if (!_probe_device_match(info, ser))
  9736. continue;
  9737. const size_t dnamelen = (colon - dname);
  9738. const struct device_drv * const drv = _probe_device_find_drv(dname, dnamelen);
  9739. if (!(drv && drv->lowl_probe && drv_algo_check(drv)))
  9740. continue;
  9741. if (drv->lowl_probe(info))
  9742. return NULL;
  9743. else
  9744. if (opt_hotplug)
  9745. request_rescan = true;
  9746. }
  9747. }
  9748. // probe driver(s) with auto enabled and matching VID/PID/Product/etc of device
  9749. BFG_FOREACH_DRIVER_BY_PRIORITY(dreg, dreg_tmp)
  9750. {
  9751. const struct device_drv * const drv = dreg->drv;
  9752. if (!drv_algo_check(drv))
  9753. continue;
  9754. // Check for "noauto" flag
  9755. // NOTE: driver-specific configuration overrides general
  9756. bool doauto = true;
  9757. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  9758. {
  9759. const char * const dname = sd_iter->string;
  9760. // NOTE: Only checking flags here, NOT path/serial, so @ is unacceptable
  9761. const char *colon = strchr(dname, ':');
  9762. if (!colon)
  9763. colon = &dname[-1];
  9764. if (strcasecmp("noauto", &colon[1]) && strcasecmp("auto", &colon[1]))
  9765. continue;
  9766. const ssize_t dnamelen = (colon - dname);
  9767. if (dnamelen >= 0 && _probe_device_find_drv(dname, dnamelen) != drv)
  9768. continue;
  9769. doauto = (tolower(colon[1]) == 'a');
  9770. if (dnamelen != -1)
  9771. break;
  9772. }
  9773. if (doauto && drv->lowl_match)
  9774. {
  9775. LL_FOREACH2(infolist, info, same_devid_next)
  9776. {
  9777. if (!drv->lowl_match(info))
  9778. continue;
  9779. if (drv->lowl_probe(info))
  9780. return NULL;
  9781. else
  9782. if (opt_hotplug)
  9783. bfg_need_detect_rescan = true;
  9784. }
  9785. }
  9786. }
  9787. // probe driver(s) with 'all' enabled
  9788. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  9789. {
  9790. const char * const dname = sd_iter->string;
  9791. // NOTE: Only checking flags here, NOT path/serial, so @ is unacceptable
  9792. const char * const colon = strchr(dname, ':');
  9793. if (!colon)
  9794. {
  9795. LL_FOREACH2(infolist, info, same_devid_next)
  9796. {
  9797. if (
  9798. #ifdef NEED_BFG_LOWL_VCOM
  9799. (info->lowl == &lowl_vcom && !strcasecmp(dname, "all")) ||
  9800. #endif
  9801. _probe_device_match(info, (dname[0] == '@') ? &dname[1] : dname))
  9802. {
  9803. BFG_FOREACH_DRIVER_BY_PRIORITY(dreg, dreg_tmp)
  9804. {
  9805. const struct device_drv * const drv = dreg->drv;
  9806. if (!drv_algo_check(drv))
  9807. continue;
  9808. if (drv->lowl_probe_by_name_only)
  9809. continue;
  9810. if (!drv->lowl_probe)
  9811. continue;
  9812. if (drv->lowl_probe(info))
  9813. return NULL;
  9814. }
  9815. if (opt_hotplug)
  9816. request_rescan = true;
  9817. break;
  9818. }
  9819. }
  9820. continue;
  9821. }
  9822. if (strcasecmp(&colon[1], "all"))
  9823. continue;
  9824. const size_t dnamelen = (colon - dname);
  9825. LL_FOREACH2(infolist, info, same_devid_next)
  9826. {
  9827. const struct device_drv * const drv = _probe_device_find_drv(dname, dnamelen);
  9828. if (!(drv && drv->lowl_probe && drv_algo_check(drv)))
  9829. continue;
  9830. if (drv->lowl_probe(info))
  9831. return NULL;
  9832. }
  9833. }
  9834. // Only actually request a rescan if we never found any cgpu
  9835. if (request_rescan)
  9836. bfg_need_detect_rescan = true;
  9837. return NULL;
  9838. }
  9839. void probe_device(struct lowlevel_device_info * const info)
  9840. {
  9841. pthread_create(&info->probe_pth, NULL, probe_device_thread, info);
  9842. }
  9843. #endif
  9844. int create_new_cgpus(void (*addfunc)(void*), void *arg)
  9845. {
  9846. static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  9847. int devcount, i, mining_threads_new = 0;
  9848. unsigned int k;
  9849. struct cgpu_info *cgpu;
  9850. struct thr_info *thr;
  9851. void *p;
  9852. mutex_lock(&mutex);
  9853. devcount = total_devices;
  9854. addfunc(arg);
  9855. if (!total_devices_new)
  9856. goto out;
  9857. wr_lock(&devices_lock);
  9858. p = realloc(devices, sizeof(struct cgpu_info *) * (total_devices + total_devices_new + 1));
  9859. if (unlikely(!p))
  9860. {
  9861. wr_unlock(&devices_lock);
  9862. applog(LOG_ERR, "scan_serial: realloc failed trying to grow devices array");
  9863. goto out;
  9864. }
  9865. devices = p;
  9866. wr_unlock(&devices_lock);
  9867. for (i = 0; i < total_devices_new; ++i)
  9868. {
  9869. cgpu = devices_new[i];
  9870. mining_threads_new += cgpu->threads ?: 1;
  9871. }
  9872. wr_lock(&mining_thr_lock);
  9873. mining_threads_new += mining_threads;
  9874. p = realloc(mining_thr, sizeof(struct thr_info *) * mining_threads_new);
  9875. if (unlikely(!p))
  9876. {
  9877. wr_unlock(&mining_thr_lock);
  9878. applog(LOG_ERR, "scan_serial: realloc failed trying to grow mining_thr");
  9879. goto out;
  9880. }
  9881. mining_thr = p;
  9882. wr_unlock(&mining_thr_lock);
  9883. for (i = mining_threads; i < mining_threads_new; ++i) {
  9884. mining_thr[i] = calloc(1, sizeof(*thr));
  9885. if (!mining_thr[i])
  9886. {
  9887. applog(LOG_ERR, "scan_serial: Failed to calloc mining_thr[%d]", i);
  9888. for ( ; --i >= mining_threads; )
  9889. free(mining_thr[i]);
  9890. goto out;
  9891. }
  9892. }
  9893. k = mining_threads;
  9894. for (i = 0; i < total_devices_new; ++i)
  9895. {
  9896. cgpu = devices_new[i];
  9897. allocate_cgpu(cgpu, &k);
  9898. }
  9899. for (i = 0; i < total_devices_new; ++i)
  9900. {
  9901. cgpu = devices_new[i];
  9902. start_cgpu(cgpu);
  9903. register_device(cgpu);
  9904. ++total_devices;
  9905. }
  9906. #ifdef HAVE_CURSES
  9907. switch_logsize();
  9908. #endif
  9909. out:
  9910. total_devices_new = 0;
  9911. devcount = total_devices - devcount;
  9912. mutex_unlock(&mutex);
  9913. return devcount;
  9914. }
  9915. int scan_serial(const char *s)
  9916. {
  9917. return create_new_cgpus(_scan_serial, (void*)s);
  9918. }
  9919. static pthread_mutex_t rescan_mutex = PTHREAD_MUTEX_INITIALIZER;
  9920. static bool rescan_active;
  9921. static struct timeval tv_rescan;
  9922. static notifier_t rescan_notifier;
  9923. static
  9924. void *rescan_thread(__maybe_unused void *p)
  9925. {
  9926. pthread_detach(pthread_self());
  9927. RenameThread("rescan");
  9928. struct timeval tv_timeout, tv_now;
  9929. fd_set rfds;
  9930. while (true)
  9931. {
  9932. mutex_lock(&rescan_mutex);
  9933. tv_timeout = tv_rescan;
  9934. if (!timer_isset(&tv_timeout))
  9935. {
  9936. rescan_active = false;
  9937. mutex_unlock(&rescan_mutex);
  9938. break;
  9939. }
  9940. mutex_unlock(&rescan_mutex);
  9941. FD_ZERO(&rfds);
  9942. FD_SET(rescan_notifier[0], &rfds);
  9943. const int maxfd = rescan_notifier[0];
  9944. timer_set_now(&tv_now);
  9945. if (select(maxfd+1, &rfds, NULL, NULL, select_timeout(&tv_timeout, &tv_now)) > 0)
  9946. notifier_read(rescan_notifier);
  9947. mutex_lock(&rescan_mutex);
  9948. if (timer_passed(&tv_rescan, NULL))
  9949. {
  9950. timer_unset(&tv_rescan);
  9951. mutex_unlock(&rescan_mutex);
  9952. applog(LOG_DEBUG, "Rescan timer expired, triggering");
  9953. scan_serial(NULL);
  9954. }
  9955. else
  9956. mutex_unlock(&rescan_mutex);
  9957. }
  9958. return NULL;
  9959. }
  9960. static
  9961. void _schedule_rescan(const struct timeval * const tvp_when)
  9962. {
  9963. if (rescan_active)
  9964. {
  9965. if (timercmp(tvp_when, &tv_rescan, <))
  9966. applog(LOG_DEBUG, "schedule_rescan: New schedule is before current, waiting it out");
  9967. else
  9968. {
  9969. applog(LOG_DEBUG, "schedule_rescan: New schedule is after current, delaying rescan");
  9970. tv_rescan = *tvp_when;
  9971. }
  9972. return;
  9973. }
  9974. applog(LOG_DEBUG, "schedule_rescan: Scheduling rescan (no rescans currently pending)");
  9975. tv_rescan = *tvp_when;
  9976. rescan_active = true;
  9977. static pthread_t pth;
  9978. if (unlikely(pthread_create(&pth, NULL, rescan_thread, NULL)))
  9979. applog(LOG_ERR, "Failed to start rescan thread");
  9980. }
  9981. static
  9982. void schedule_rescan(const struct timeval * const tvp_when)
  9983. {
  9984. mutex_lock(&rescan_mutex);
  9985. _schedule_rescan(tvp_when);
  9986. mutex_unlock(&rescan_mutex);
  9987. }
  9988. #ifdef HAVE_BFG_HOTPLUG
  9989. static
  9990. void hotplug_trigger()
  9991. {
  9992. applog(LOG_DEBUG, "%s: Scheduling rescan immediately", __func__);
  9993. struct timeval tv_now;
  9994. timer_set_now(&tv_now);
  9995. schedule_rescan(&tv_now);
  9996. }
  9997. #endif
  9998. #if defined(HAVE_LIBUDEV) && defined(HAVE_SYS_EPOLL_H)
  9999. static
  10000. void *hotplug_thread(__maybe_unused void *p)
  10001. {
  10002. pthread_detach(pthread_self());
  10003. RenameThread("hotplug");
  10004. struct udev * const udev = udev_new();
  10005. if (unlikely(!udev))
  10006. applogfailr(NULL, LOG_ERR, "udev_new");
  10007. struct udev_monitor * const mon = udev_monitor_new_from_netlink(udev, "udev");
  10008. if (unlikely(!mon))
  10009. applogfailr(NULL, LOG_ERR, "udev_monitor_new_from_netlink");
  10010. if (unlikely(udev_monitor_enable_receiving(mon)))
  10011. applogfailr(NULL, LOG_ERR, "udev_monitor_enable_receiving");
  10012. const int epfd = epoll_create(1);
  10013. if (unlikely(epfd == -1))
  10014. applogfailr(NULL, LOG_ERR, "epoll_create");
  10015. {
  10016. const int fd = udev_monitor_get_fd(mon);
  10017. struct epoll_event ev = {
  10018. .events = EPOLLIN | EPOLLPRI,
  10019. .data.fd = fd,
  10020. };
  10021. if (epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev))
  10022. applogfailr(NULL, LOG_ERR, "epoll_ctl");
  10023. }
  10024. struct epoll_event ev;
  10025. int rv;
  10026. bool pending = false;
  10027. while (true)
  10028. {
  10029. rv = epoll_wait(epfd, &ev, 1, pending ? hotplug_delay_ms : -1);
  10030. if (rv == -1)
  10031. {
  10032. if (errno == EAGAIN || errno == EINTR)
  10033. continue;
  10034. break;
  10035. }
  10036. if (!rv)
  10037. {
  10038. hotplug_trigger();
  10039. pending = false;
  10040. continue;
  10041. }
  10042. struct udev_device * const device = udev_monitor_receive_device(mon);
  10043. if (!device)
  10044. continue;
  10045. const char * const action = udev_device_get_action(device);
  10046. applog(LOG_DEBUG, "%s: Received %s event", __func__, action);
  10047. if (!strcmp(action, "add"))
  10048. pending = true;
  10049. udev_device_unref(device);
  10050. }
  10051. applogfailr(NULL, LOG_ERR, "epoll_wait");
  10052. }
  10053. #elif defined(WIN32)
  10054. static UINT_PTR _hotplug_wintimer_id;
  10055. VOID CALLBACK hotplug_win_timer(HWND hwnd, UINT msg, UINT_PTR idEvent, DWORD dwTime)
  10056. {
  10057. KillTimer(NULL, _hotplug_wintimer_id);
  10058. _hotplug_wintimer_id = 0;
  10059. hotplug_trigger();
  10060. }
  10061. LRESULT CALLBACK hotplug_win_callback(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
  10062. {
  10063. if (msg == WM_DEVICECHANGE && wParam == DBT_DEVNODES_CHANGED)
  10064. {
  10065. applog(LOG_DEBUG, "%s: Received DBT_DEVNODES_CHANGED event", __func__);
  10066. _hotplug_wintimer_id = SetTimer(NULL, _hotplug_wintimer_id, hotplug_delay_ms, hotplug_win_timer);
  10067. }
  10068. return DefWindowProc(hwnd, msg, wParam, lParam);
  10069. }
  10070. static
  10071. void *hotplug_thread(__maybe_unused void *p)
  10072. {
  10073. pthread_detach(pthread_self());
  10074. WNDCLASS DummyWinCls = {
  10075. .lpszClassName = "BFGDummyWinCls",
  10076. .lpfnWndProc = hotplug_win_callback,
  10077. };
  10078. ATOM a = RegisterClass(&DummyWinCls);
  10079. if (unlikely(!a))
  10080. applogfailinfor(NULL, LOG_ERR, "RegisterClass", "%d", (int)GetLastError());
  10081. HWND hwnd = CreateWindow((void*)(intptr_t)a, NULL, WS_OVERLAPPED, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, NULL, NULL);
  10082. if (unlikely(!hwnd))
  10083. applogfailinfor(NULL, LOG_ERR, "CreateWindow", "%d", (int)GetLastError());
  10084. MSG msg;
  10085. while (GetMessage(&msg, NULL, 0, 0))
  10086. {
  10087. TranslateMessage(&msg);
  10088. DispatchMessage(&msg);
  10089. }
  10090. quit(0, "WM_QUIT received");
  10091. return NULL;
  10092. }
  10093. #endif
  10094. #ifdef HAVE_BFG_HOTPLUG
  10095. static
  10096. void hotplug_start()
  10097. {
  10098. pthread_t pth;
  10099. if (unlikely(pthread_create(&pth, NULL, hotplug_thread, NULL)))
  10100. applog(LOG_ERR, "Failed to start hotplug thread");
  10101. }
  10102. #endif
  10103. static void probe_pools(void)
  10104. {
  10105. int i;
  10106. for (i = 0; i < total_pools; i++) {
  10107. struct pool *pool = pools[i];
  10108. pool->testing = true;
  10109. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  10110. }
  10111. }
  10112. static void raise_fd_limits(void)
  10113. {
  10114. #ifdef HAVE_SETRLIMIT
  10115. struct rlimit fdlimit;
  10116. rlim_t old_soft_limit;
  10117. char frombuf[0x10] = "unlimited";
  10118. char hardbuf[0x10] = "unlimited";
  10119. if (getrlimit(RLIMIT_NOFILE, &fdlimit))
  10120. applogr(, LOG_DEBUG, "setrlimit: Failed to getrlimit(RLIMIT_NOFILE)");
  10121. old_soft_limit = fdlimit.rlim_cur;
  10122. if (fdlimit.rlim_max > FD_SETSIZE || fdlimit.rlim_max == RLIM_INFINITY)
  10123. fdlimit.rlim_cur = FD_SETSIZE;
  10124. else
  10125. fdlimit.rlim_cur = fdlimit.rlim_max;
  10126. if (fdlimit.rlim_max != RLIM_INFINITY)
  10127. snprintf(hardbuf, sizeof(hardbuf), "%lu", (unsigned long)fdlimit.rlim_max);
  10128. if (old_soft_limit != RLIM_INFINITY)
  10129. snprintf(frombuf, sizeof(frombuf), "%lu", (unsigned long)old_soft_limit);
  10130. if (fdlimit.rlim_cur == old_soft_limit)
  10131. applogr(, LOG_DEBUG, "setrlimit: Soft fd limit not being changed from %lu (FD_SETSIZE=%lu; hard limit=%s)",
  10132. (unsigned long)old_soft_limit, (unsigned long)FD_SETSIZE, hardbuf);
  10133. if (setrlimit(RLIMIT_NOFILE, &fdlimit))
  10134. applogr(, LOG_DEBUG, "setrlimit: Failed to change soft fd limit from %s to %lu (FD_SETSIZE=%lu; hard limit=%s)",
  10135. frombuf, (unsigned long)fdlimit.rlim_cur, (unsigned long)FD_SETSIZE, hardbuf);
  10136. applog(LOG_DEBUG, "setrlimit: Changed soft fd limit from %s to %lu (FD_SETSIZE=%lu; hard limit=%s)",
  10137. frombuf, (unsigned long)fdlimit.rlim_cur, (unsigned long)FD_SETSIZE, hardbuf);
  10138. #else
  10139. applog(LOG_DEBUG, "setrlimit: Not supported by platform");
  10140. #endif
  10141. }
  10142. extern void bfg_init_threadlocal();
  10143. extern void stratumsrv_start();
  10144. int main(int argc, char *argv[])
  10145. {
  10146. struct sigaction handler;
  10147. struct thr_info *thr;
  10148. struct block *block;
  10149. unsigned int k;
  10150. int i;
  10151. int rearrange_pools = 0;
  10152. char *s;
  10153. #ifdef WIN32
  10154. LoadLibrary("backtrace.dll");
  10155. #endif
  10156. blkmk_sha256_impl = my_blkmaker_sha256_callback;
  10157. bfg_init_threadlocal();
  10158. #ifndef HAVE_PTHREAD_CANCEL
  10159. setup_pthread_cancel_workaround();
  10160. #endif
  10161. bfg_init_checksums();
  10162. #ifdef WIN32
  10163. {
  10164. WSADATA wsa;
  10165. i = WSAStartup(MAKEWORD(2, 2), &wsa);
  10166. if (i)
  10167. quit(1, "Failed to initialise Winsock: %s", bfg_strerror(i, BST_SOCKET));
  10168. }
  10169. #endif
  10170. /* This dangerous functions tramples random dynamically allocated
  10171. * variables so do it before anything at all */
  10172. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  10173. quit(1, "Failed to curl_global_init");
  10174. initial_args = malloc(sizeof(char *) * (argc + 1));
  10175. for (i = 0; i < argc; i++)
  10176. initial_args[i] = strdup(argv[i]);
  10177. initial_args[argc] = NULL;
  10178. mutex_init(&hash_lock);
  10179. mutex_init(&console_lock);
  10180. cglock_init(&control_lock);
  10181. mutex_init(&stats_lock);
  10182. mutex_init(&sharelog_lock);
  10183. cglock_init(&ch_lock);
  10184. mutex_init(&sshare_lock);
  10185. rwlock_init(&blk_lock);
  10186. rwlock_init(&netacc_lock);
  10187. rwlock_init(&mining_thr_lock);
  10188. rwlock_init(&devices_lock);
  10189. mutex_init(&lp_lock);
  10190. if (unlikely(pthread_cond_init(&lp_cond, NULL)))
  10191. quit(1, "Failed to pthread_cond_init lp_cond");
  10192. if (unlikely(pthread_cond_init(&gws_cond, NULL)))
  10193. quit(1, "Failed to pthread_cond_init gws_cond");
  10194. notifier_init(submit_waiting_notifier);
  10195. timer_unset(&tv_rescan);
  10196. notifier_init(rescan_notifier);
  10197. /* Create a unique get work queue */
  10198. getq = tq_new();
  10199. if (!getq)
  10200. quit(1, "Failed to create getq");
  10201. /* We use the getq mutex as the staged lock */
  10202. stgd_lock = &getq->mutex;
  10203. snprintf(packagename, sizeof(packagename), "%s %s", PACKAGE, VERSION);
  10204. #ifdef WANT_CPUMINE
  10205. init_max_name_len();
  10206. #endif
  10207. handler.sa_handler = &sighandler;
  10208. handler.sa_flags = 0;
  10209. sigemptyset(&handler.sa_mask);
  10210. #ifdef HAVE_PTHREAD_CANCEL
  10211. sigaction(SIGTERM, &handler, &termhandler);
  10212. #else
  10213. // Need to let pthread_cancel emulation handle SIGTERM first
  10214. termhandler = pcwm_orig_term_handler;
  10215. pcwm_orig_term_handler = handler;
  10216. #endif
  10217. sigaction(SIGINT, &handler, &inthandler);
  10218. #ifndef WIN32
  10219. signal(SIGPIPE, SIG_IGN);
  10220. #else
  10221. timeBeginPeriod(1);
  10222. #endif
  10223. opt_kernel_path = CGMINER_PREFIX;
  10224. cgminer_path = alloca(PATH_MAX);
  10225. s = strdup(argv[0]);
  10226. strcpy(cgminer_path, dirname(s));
  10227. free(s);
  10228. strcat(cgminer_path, "/");
  10229. #if defined(WANT_CPUMINE) && defined(WIN32)
  10230. {
  10231. char buf[32];
  10232. int gev = GetEnvironmentVariable("BFGMINER_BENCH_ALGO", buf, sizeof(buf));
  10233. if (gev > 0 && gev < sizeof(buf))
  10234. {
  10235. setup_benchmark_pool();
  10236. double rate = bench_algo_stage3(atoi(buf));
  10237. // Write result to shared memory for parent
  10238. char unique_name[64];
  10239. if (GetEnvironmentVariable("BFGMINER_SHARED_MEM", unique_name, 32))
  10240. {
  10241. HANDLE map_handle = CreateFileMapping(
  10242. INVALID_HANDLE_VALUE, // use paging file
  10243. NULL, // default security attributes
  10244. PAGE_READWRITE, // read/write access
  10245. 0, // size: high 32-bits
  10246. 4096, // size: low 32-bits
  10247. unique_name // name of map object
  10248. );
  10249. if (NULL != map_handle) {
  10250. void *shared_mem = MapViewOfFile(
  10251. map_handle, // object to map view of
  10252. FILE_MAP_WRITE, // read/write access
  10253. 0, // high offset: map from
  10254. 0, // low offset: beginning
  10255. 0 // default: map entire file
  10256. );
  10257. if (NULL != shared_mem)
  10258. CopyMemory(shared_mem, &rate, sizeof(rate));
  10259. (void)UnmapViewOfFile(shared_mem);
  10260. }
  10261. (void)CloseHandle(map_handle);
  10262. }
  10263. exit(0);
  10264. }
  10265. }
  10266. #endif
  10267. devcursor = 8;
  10268. logstart = devcursor;
  10269. logcursor = logstart;
  10270. block = calloc(sizeof(struct block), 1);
  10271. if (unlikely(!block))
  10272. quit (1, "main OOM");
  10273. for (i = 0; i < 36; i++)
  10274. strcat(block->hash, "0");
  10275. HASH_ADD_STR(blocks, hash, block);
  10276. strcpy(current_block, block->hash);
  10277. mutex_init(&submitting_lock);
  10278. #ifdef HAVE_OPENCL
  10279. opencl_early_init();
  10280. #endif
  10281. schedstart.tm.tm_sec = 1;
  10282. schedstop .tm.tm_sec = 1;
  10283. opt_register_table(opt_early_table, NULL);
  10284. opt_register_table(opt_config_table, NULL);
  10285. opt_register_table(opt_cmdline_table, NULL);
  10286. opt_early_parse(argc, argv, applog_and_exit);
  10287. if (!config_loaded)
  10288. {
  10289. load_default_config();
  10290. rearrange_pools = total_pools;
  10291. }
  10292. opt_free_table();
  10293. /* parse command line */
  10294. opt_register_table(opt_config_table,
  10295. "Options for both config file and command line");
  10296. opt_register_table(opt_cmdline_table,
  10297. "Options for command line only");
  10298. opt_parse(&argc, argv, applog_and_exit);
  10299. if (argc != 1)
  10300. quit(1, "Unexpected extra commandline arguments");
  10301. if (rearrange_pools && rearrange_pools < total_pools)
  10302. {
  10303. // Prioritise commandline pools before default-config pools
  10304. for (i = 0; i < rearrange_pools; ++i)
  10305. pools[i]->prio += rearrange_pools;
  10306. for ( ; i < total_pools; ++i)
  10307. pools[i]->prio -= rearrange_pools;
  10308. }
  10309. #ifndef HAVE_PTHREAD_CANCEL
  10310. // Can't do this any earlier, or config isn't loaded
  10311. applog(LOG_DEBUG, "pthread_cancel workaround in use");
  10312. #endif
  10313. #ifdef HAVE_PWD_H
  10314. struct passwd *user_info = NULL;
  10315. if (opt_setuid != NULL) {
  10316. if ((user_info = getpwnam(opt_setuid)) == NULL) {
  10317. quit(1, "Unable to find setuid user information");
  10318. }
  10319. }
  10320. #endif
  10321. #ifdef HAVE_CHROOT
  10322. if (chroot_dir != NULL) {
  10323. #ifdef HAVE_PWD_H
  10324. if (user_info == NULL && getuid() == 0) {
  10325. applog(LOG_WARNING, "Running as root inside chroot");
  10326. }
  10327. #endif
  10328. if (chroot(chroot_dir) != 0) {
  10329. quit(1, "Unable to chroot");
  10330. }
  10331. if (chdir("/"))
  10332. quit(1, "Unable to chdir to chroot");
  10333. }
  10334. #endif
  10335. #ifdef HAVE_PWD_H
  10336. if (user_info != NULL) {
  10337. if (setgid((*user_info).pw_gid) != 0)
  10338. quit(1, "Unable to setgid");
  10339. if (setuid((*user_info).pw_uid) != 0)
  10340. quit(1, "Unable to setuid");
  10341. }
  10342. #endif
  10343. raise_fd_limits();
  10344. if (opt_benchmark) {
  10345. while (total_pools)
  10346. remove_pool(pools[0]);
  10347. setup_benchmark_pool();
  10348. }
  10349. if (opt_unittest) {
  10350. test_cgpu_match();
  10351. test_intrange();
  10352. test_decimal_width();
  10353. test_domain_funcs();
  10354. test_target();
  10355. utf8_test();
  10356. }
  10357. #ifdef HAVE_CURSES
  10358. if (opt_realquiet || opt_display_devs)
  10359. use_curses = false;
  10360. setlocale(LC_ALL, "C");
  10361. if (use_curses)
  10362. enable_curses();
  10363. #endif
  10364. #ifdef HAVE_LIBUSB
  10365. int err = libusb_init(NULL);
  10366. if (err)
  10367. applog(LOG_WARNING, "libusb_init() failed err %d", err);
  10368. else
  10369. have_libusb = true;
  10370. #endif
  10371. applog(LOG_WARNING, "Started %s", packagename);
  10372. if (cnfbuf) {
  10373. applog(LOG_NOTICE, "Loaded configuration file %s", cnfbuf);
  10374. switch (fileconf_load) {
  10375. case 0:
  10376. applog(LOG_WARNING, "Fatal JSON error in configuration file.");
  10377. applog(LOG_WARNING, "Configuration file could not be used.");
  10378. break;
  10379. case -1:
  10380. applog(LOG_WARNING, "Error in configuration file, partially loaded.");
  10381. if (use_curses)
  10382. applog(LOG_WARNING, "Start BFGMiner with -T to see what failed to load.");
  10383. break;
  10384. default:
  10385. break;
  10386. }
  10387. free(cnfbuf);
  10388. cnfbuf = NULL;
  10389. }
  10390. i = strlen(opt_kernel_path) + 2;
  10391. char __kernel_path[i];
  10392. snprintf(__kernel_path, i, "%s/", opt_kernel_path);
  10393. opt_kernel_path = __kernel_path;
  10394. if (want_per_device_stats)
  10395. opt_log_output = true;
  10396. #ifdef WANT_CPUMINE
  10397. #ifdef USE_SCRYPT
  10398. if (opt_scrypt)
  10399. set_scrypt_algo(&opt_algo);
  10400. #endif
  10401. #endif
  10402. bfg_devapi_init();
  10403. drv_detect_all();
  10404. total_devices = total_devices_new;
  10405. devices = devices_new;
  10406. total_devices_new = 0;
  10407. devices_new = NULL;
  10408. if (opt_display_devs) {
  10409. int devcount = 0;
  10410. applog(LOG_ERR, "Devices detected:");
  10411. for (i = 0; i < total_devices; ++i) {
  10412. struct cgpu_info *cgpu = devices[i];
  10413. char buf[0x100];
  10414. if (cgpu->device != cgpu)
  10415. continue;
  10416. if (cgpu->name)
  10417. snprintf(buf, sizeof(buf), " %s", cgpu->name);
  10418. else
  10419. if (cgpu->dev_manufacturer)
  10420. snprintf(buf, sizeof(buf), " %s by %s", (cgpu->dev_product ?: "Device"), cgpu->dev_manufacturer);
  10421. else
  10422. if (cgpu->dev_product)
  10423. snprintf(buf, sizeof(buf), " %s", cgpu->dev_product);
  10424. else
  10425. strcpy(buf, " Device");
  10426. tailsprintf(buf, sizeof(buf), " (driver=%s; procs=%d", cgpu->drv->dname, cgpu->procs);
  10427. if (cgpu->dev_serial)
  10428. tailsprintf(buf, sizeof(buf), "; serial=%s", cgpu->dev_serial);
  10429. if (cgpu->device_path)
  10430. tailsprintf(buf, sizeof(buf), "; path=%s", cgpu->device_path);
  10431. tailsprintf(buf, sizeof(buf), ")");
  10432. _applog(LOG_NOTICE, buf);
  10433. ++devcount;
  10434. }
  10435. quit(0, "%d devices listed", devcount);
  10436. }
  10437. mining_threads = 0;
  10438. for (i = 0; i < total_devices; ++i)
  10439. register_device(devices[i]);
  10440. if (!total_devices) {
  10441. applog(LOG_WARNING, "No devices detected!");
  10442. if (use_curses)
  10443. applog(LOG_WARNING, "Waiting for devices; press 'M+' to add, or 'Q' to quit");
  10444. else
  10445. applog(LOG_WARNING, "Waiting for devices");
  10446. }
  10447. if (opt_quit_summary == BQS_DEFAULT)
  10448. {
  10449. if (total_devices < 25)
  10450. opt_quit_summary = BQS_PROCS;
  10451. else
  10452. opt_quit_summary = BQS_DEVS;
  10453. }
  10454. #ifdef HAVE_CURSES
  10455. switch_logsize();
  10456. #endif
  10457. if (!total_pools) {
  10458. applog(LOG_WARNING, "Need to specify at least one pool server.");
  10459. #ifdef HAVE_CURSES
  10460. if (!use_curses || !input_pool(false))
  10461. #endif
  10462. quit(1, "Pool setup failed");
  10463. }
  10464. for (i = 0; i < total_pools; i++) {
  10465. struct pool *pool = pools[i];
  10466. size_t siz;
  10467. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  10468. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  10469. if (!pool->rpc_url)
  10470. quit(1, "No URI supplied for pool %u", i);
  10471. if (!pool->rpc_userpass) {
  10472. if (!pool->rpc_user || !pool->rpc_pass)
  10473. quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  10474. siz = strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2;
  10475. pool->rpc_userpass = malloc(siz);
  10476. if (!pool->rpc_userpass)
  10477. quit(1, "Failed to malloc userpass");
  10478. snprintf(pool->rpc_userpass, siz, "%s:%s", pool->rpc_user, pool->rpc_pass);
  10479. }
  10480. }
  10481. /* Set the currentpool to pool with priority 0 */
  10482. validate_pool_priorities();
  10483. for (i = 0; i < total_pools; i++) {
  10484. struct pool *pool = pools[i];
  10485. if (!pool->prio)
  10486. currentpool = pool;
  10487. }
  10488. #ifdef HAVE_SYSLOG_H
  10489. if (use_syslog)
  10490. openlog(PACKAGE, LOG_PID, LOG_USER);
  10491. #endif
  10492. #if defined(unix) || defined(__APPLE__)
  10493. if (opt_stderr_cmd)
  10494. fork_monitor();
  10495. #endif // defined(unix)
  10496. mining_thr = calloc(mining_threads, sizeof(thr));
  10497. if (!mining_thr)
  10498. quit(1, "Failed to calloc mining_thr");
  10499. for (i = 0; i < mining_threads; i++) {
  10500. mining_thr[i] = calloc(1, sizeof(*thr));
  10501. if (!mining_thr[i])
  10502. quit(1, "Failed to calloc mining_thr[%d]", i);
  10503. }
  10504. total_control_threads = 6;
  10505. control_thr = calloc(total_control_threads, sizeof(*thr));
  10506. if (!control_thr)
  10507. quit(1, "Failed to calloc control_thr");
  10508. if (opt_benchmark)
  10509. goto begin_bench;
  10510. for (i = 0; i < total_pools; i++) {
  10511. struct pool *pool = pools[i];
  10512. enable_pool(pool);
  10513. pool->idle = true;
  10514. }
  10515. applog(LOG_NOTICE, "Probing for an alive pool");
  10516. do {
  10517. bool still_testing;
  10518. int i;
  10519. /* Look for at least one active pool before starting */
  10520. probe_pools();
  10521. do {
  10522. sleep(1);
  10523. if (pools_active)
  10524. break;
  10525. still_testing = false;
  10526. for (int i = 0; i < total_pools; ++i)
  10527. if (pools[i]->testing)
  10528. still_testing = true;
  10529. } while (still_testing);
  10530. if (!pools_active) {
  10531. applog(LOG_ERR, "No servers were found that could be used to get work from.");
  10532. applog(LOG_ERR, "Please check the details from the list below of the servers you have input");
  10533. applog(LOG_ERR, "Most likely you have input the wrong URL, forgotten to add a port, or have not set up workers");
  10534. for (i = 0; i < total_pools; i++) {
  10535. struct pool *pool;
  10536. pool = pools[i];
  10537. applog(LOG_WARNING, "Pool: %d URL: %s User: %s Password: %s",
  10538. i, pool->rpc_url, pool->rpc_user, pool->rpc_pass);
  10539. }
  10540. #ifdef HAVE_CURSES
  10541. if (use_curses) {
  10542. halfdelay(150);
  10543. applog(LOG_ERR, "Press any key to exit, or BFGMiner will try again in 15s.");
  10544. if (getch() != ERR)
  10545. quit(0, "No servers could be used! Exiting.");
  10546. cbreak();
  10547. } else
  10548. #endif
  10549. quit(0, "No servers could be used! Exiting.");
  10550. }
  10551. } while (!pools_active);
  10552. #ifdef USE_SCRYPT
  10553. if (detect_algo == 1 && !opt_scrypt) {
  10554. applog(LOG_NOTICE, "Detected scrypt algorithm");
  10555. opt_scrypt = true;
  10556. }
  10557. #endif
  10558. detect_algo = 0;
  10559. begin_bench:
  10560. total_mhashes_done = 0;
  10561. for (i = 0; i < total_devices; i++) {
  10562. struct cgpu_info *cgpu = devices[i];
  10563. cgpu->rolling = cgpu->total_mhashes = 0;
  10564. }
  10565. cgtime(&total_tv_start);
  10566. cgtime(&total_tv_end);
  10567. miner_started = total_tv_start;
  10568. time_t miner_start_ts = time(NULL);
  10569. if (schedstart.tm.tm_sec)
  10570. localtime_r(&miner_start_ts, &schedstart.tm);
  10571. if (schedstop.tm.tm_sec)
  10572. localtime_r(&miner_start_ts, &schedstop .tm);
  10573. get_datestamp(datestamp, sizeof(datestamp), miner_start_ts);
  10574. // Initialise processors and threads
  10575. k = 0;
  10576. for (i = 0; i < total_devices; ++i) {
  10577. struct cgpu_info *cgpu = devices[i];
  10578. allocate_cgpu(cgpu, &k);
  10579. }
  10580. // Start threads
  10581. for (i = 0; i < total_devices; ++i) {
  10582. struct cgpu_info *cgpu = devices[i];
  10583. start_cgpu(cgpu);
  10584. }
  10585. #ifdef HAVE_OPENCL
  10586. for (i = 0; i < nDevs; i++)
  10587. pause_dynamic_threads(i);
  10588. #endif
  10589. #ifdef WANT_CPUMINE
  10590. if (opt_n_threads > 0)
  10591. applog(LOG_INFO, "%d cpu miner threads started, using '%s' algorithm.",
  10592. opt_n_threads, algo_names[opt_algo]);
  10593. #endif
  10594. cgtime(&total_tv_start);
  10595. cgtime(&total_tv_end);
  10596. if (!opt_benchmark)
  10597. {
  10598. pthread_t submit_thread;
  10599. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, NULL)))
  10600. quit(1, "submit_work thread create failed");
  10601. }
  10602. watchpool_thr_id = 1;
  10603. thr = &control_thr[watchpool_thr_id];
  10604. /* start watchpool thread */
  10605. if (thr_info_create(thr, NULL, watchpool_thread, NULL))
  10606. quit(1, "watchpool thread create failed");
  10607. pthread_detach(thr->pth);
  10608. watchdog_thr_id = 2;
  10609. thr = &control_thr[watchdog_thr_id];
  10610. /* start watchdog thread */
  10611. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  10612. quit(1, "watchdog thread create failed");
  10613. pthread_detach(thr->pth);
  10614. #ifdef HAVE_OPENCL
  10615. /* Create reinit gpu thread */
  10616. gpur_thr_id = 3;
  10617. thr = &control_thr[gpur_thr_id];
  10618. thr->q = tq_new();
  10619. if (!thr->q)
  10620. quit(1, "tq_new failed for gpur_thr_id");
  10621. if (thr_info_create(thr, NULL, reinit_gpu, thr))
  10622. quit(1, "reinit_gpu thread create failed");
  10623. #endif
  10624. /* Create API socket thread */
  10625. api_thr_id = 4;
  10626. thr = &control_thr[api_thr_id];
  10627. if (thr_info_create(thr, NULL, api_thread, thr))
  10628. quit(1, "API thread create failed");
  10629. #ifdef USE_LIBMICROHTTPD
  10630. if (httpsrv_port != -1)
  10631. httpsrv_start(httpsrv_port);
  10632. #endif
  10633. #ifdef USE_LIBEVENT
  10634. if (stratumsrv_port != -1)
  10635. stratumsrv_start();
  10636. #endif
  10637. #ifdef HAVE_BFG_HOTPLUG
  10638. if (opt_hotplug && !opt_scrypt)
  10639. hotplug_start();
  10640. #endif
  10641. #ifdef HAVE_CURSES
  10642. /* Create curses input thread for keyboard input. Create this last so
  10643. * that we know all threads are created since this can call kill_work
  10644. * to try and shut down ll previous threads. */
  10645. input_thr_id = 5;
  10646. thr = &control_thr[input_thr_id];
  10647. if (thr_info_create(thr, NULL, input_thread, thr))
  10648. quit(1, "input thread create failed");
  10649. pthread_detach(thr->pth);
  10650. #endif
  10651. /* Just to be sure */
  10652. if (total_control_threads != 6)
  10653. quit(1, "incorrect total_control_threads (%d) should be 7", total_control_threads);
  10654. /* Once everything is set up, main() becomes the getwork scheduler */
  10655. while (42) {
  10656. int ts, max_staged = opt_queue;
  10657. struct pool *pool, *cp;
  10658. bool lagging = false;
  10659. struct curl_ent *ce;
  10660. struct work *work;
  10661. cp = current_pool();
  10662. // Generally, each processor needs a new work, and all at once during work restarts
  10663. max_staged += mining_threads;
  10664. mutex_lock(stgd_lock);
  10665. ts = __total_staged();
  10666. if (!pool_localgen(cp) && !ts && !opt_fail_only)
  10667. lagging = true;
  10668. /* Wait until hash_pop tells us we need to create more work */
  10669. if (ts > max_staged) {
  10670. staged_full = true;
  10671. pthread_cond_wait(&gws_cond, stgd_lock);
  10672. ts = __total_staged();
  10673. }
  10674. mutex_unlock(stgd_lock);
  10675. if (ts > max_staged)
  10676. continue;
  10677. work = make_work();
  10678. if (lagging && !pool_tset(cp, &cp->lagging)) {
  10679. applog(LOG_WARNING, "Pool %d not providing work fast enough", cp->pool_no);
  10680. cp->getfail_occasions++;
  10681. total_go++;
  10682. }
  10683. pool = select_pool(lagging);
  10684. retry:
  10685. if (pool->has_stratum) {
  10686. while (!pool->stratum_active || !pool->stratum_notify) {
  10687. struct pool *altpool = select_pool(true);
  10688. if (altpool == pool && pool->has_stratum)
  10689. cgsleep_ms(5000);
  10690. pool = altpool;
  10691. goto retry;
  10692. }
  10693. gen_stratum_work(pool, work);
  10694. applog(LOG_DEBUG, "Generated stratum work");
  10695. stage_work(work);
  10696. continue;
  10697. }
  10698. if (pool->last_work_copy) {
  10699. mutex_lock(&pool->last_work_lock);
  10700. struct work *last_work = pool->last_work_copy;
  10701. if (!last_work)
  10702. {}
  10703. else
  10704. if (can_roll(last_work) && should_roll(last_work)) {
  10705. struct timeval tv_now;
  10706. cgtime(&tv_now);
  10707. free_work(work);
  10708. work = make_clone(pool->last_work_copy);
  10709. mutex_unlock(&pool->last_work_lock);
  10710. roll_work(work);
  10711. applog(LOG_DEBUG, "Generated work from latest GBT job in get_work_thread with %d seconds left", (int)blkmk_time_left(work->tr->tmpl, tv_now.tv_sec));
  10712. stage_work(work);
  10713. continue;
  10714. } else if (last_work->tr && pool->proto == PLP_GETBLOCKTEMPLATE && blkmk_work_left(last_work->tr->tmpl) > (unsigned long)mining_threads) {
  10715. // Don't free last_work_copy, since it is used to detect upstream provides plenty of work per template
  10716. } else {
  10717. free_work(last_work);
  10718. pool->last_work_copy = NULL;
  10719. }
  10720. mutex_unlock(&pool->last_work_lock);
  10721. }
  10722. if (clone_available()) {
  10723. applog(LOG_DEBUG, "Cloned getwork work");
  10724. free_work(work);
  10725. continue;
  10726. }
  10727. if (opt_benchmark) {
  10728. get_benchmark_work(work);
  10729. applog(LOG_DEBUG, "Generated benchmark work");
  10730. stage_work(work);
  10731. continue;
  10732. }
  10733. work->pool = pool;
  10734. ce = pop_curl_entry3(pool, 2);
  10735. /* obtain new work from bitcoin via JSON-RPC */
  10736. if (!get_upstream_work(work, ce->curl)) {
  10737. struct pool *next_pool;
  10738. /* Make sure the pool just hasn't stopped serving
  10739. * requests but is up as we'll keep hammering it */
  10740. push_curl_entry(ce, pool);
  10741. ++pool->seq_getfails;
  10742. pool_died(pool);
  10743. next_pool = select_pool(!opt_fail_only);
  10744. if (pool == next_pool) {
  10745. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, retrying in 5s", pool->pool_no);
  10746. cgsleep_ms(5000);
  10747. } else {
  10748. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, failover activated", pool->pool_no);
  10749. pool = next_pool;
  10750. }
  10751. goto retry;
  10752. }
  10753. if (ts >= max_staged)
  10754. pool_tclear(pool, &pool->lagging);
  10755. if (pool_tclear(pool, &pool->idle))
  10756. pool_resus(pool);
  10757. applog(LOG_DEBUG, "Generated getwork work");
  10758. stage_work(work);
  10759. push_curl_entry(ce, pool);
  10760. }
  10761. return 0;
  10762. }