diff --git a/go.mod b/go.mod index 51633e802..1e9fd3814 100644 --- a/go.mod +++ b/go.mod @@ -22,6 +22,7 @@ require ( github.com/openshift/client-go v0.0.0-20220831193253-4950ae70c8ea github.com/openshift/machine-config-operator v0.0.1-0.20230118083703-fc27a2bdaa85 github.com/pkg/errors v0.9.1 + github.com/safchain/ethtool v0.3.0 github.com/spf13/cobra v1.7.0 github.com/stretchr/testify v1.8.4 github.com/vishvananda/netlink v1.2.1-beta.2.0.20240221172127-ec7bcb248e94 diff --git a/go.sum b/go.sum index 5393c333c..1b09ab724 100644 --- a/go.sum +++ b/go.sum @@ -389,6 +389,8 @@ github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjR github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/safchain/ethtool v0.3.0 h1:gimQJpsI6sc1yIqP/y8GYgiXn/NjgvpM0RNoWLVVmP0= +github.com/safchain/ethtool v0.3.0/go.mod h1:SA9BwrgyAqNo7M+uaL6IYbxpm5wk3L7Mm6ocLW+CJUs= github.com/sergi/go-diff v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0= github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= github.com/shopspring/decimal v1.2.0 h1:abSATXmQEYyShuxI4/vyW3tV1MrKAJzCZ/0zLUXYbsQ= @@ -625,6 +627,7 @@ golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.17.0 h1:25cE3gD+tdBA7lp7QfhuV+rJiE9YXTcS3VG1SqssI/Y= golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= diff --git a/pkg/helper/mock/mock_helper.go b/pkg/helper/mock/mock_helper.go index 2b967572d..b48523a59 100644 --- a/pkg/helper/mock/mock_helper.go +++ b/pkg/helper/mock/mock_helper.go @@ -239,6 +239,20 @@ func (mr *MockHostHelpersInterfaceMockRecorder) DiscoverVDPAType(pciAddr interfa return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DiscoverVDPAType", reflect.TypeOf((*MockHostHelpersInterface)(nil).DiscoverVDPAType), pciAddr) } +// EnableHwTcOffload mocks base method. +func (m *MockHostHelpersInterface) EnableHwTcOffload(ifaceName string) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "EnableHwTcOffload", ifaceName) + ret0, _ := ret[0].(error) + return ret0 +} + +// EnableHwTcOffload indicates an expected call of EnableHwTcOffload. +func (mr *MockHostHelpersInterfaceMockRecorder) EnableHwTcOffload(ifaceName interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EnableHwTcOffload", reflect.TypeOf((*MockHostHelpersInterface)(nil).EnableHwTcOffload), ifaceName) +} + // EnableRDMA mocks base method. func (m *MockHostHelpersInterface) EnableRDMA(conditionFilePath, serviceName, packageManager string) (bool, error) { m.ctrl.T.Helper() diff --git a/pkg/host/internal/lib/ethtool/ethtool.go b/pkg/host/internal/lib/ethtool/ethtool.go new file mode 100644 index 000000000..89fa8ddd1 --- /dev/null +++ b/pkg/host/internal/lib/ethtool/ethtool.go @@ -0,0 +1,51 @@ +package ethtool + +import ( + "github.com/safchain/ethtool" +) + +func New() EthtoolLib { + return &libWrapper{} +} + +//go:generate ../../../../../bin/mockgen -destination mock/mock_ethtool.go -source ethtool.go +type EthtoolLib interface { + // Features retrieves features of the given interface name. + Features(ifaceName string) (map[string]bool, error) + // FeatureNames shows supported features by their name. + FeatureNames(ifaceName string) (map[string]uint, error) + // Change requests a change in the given device's features. + Change(ifaceName string, config map[string]bool) error +} + +type libWrapper struct{} + +// Features retrieves features of the given interface name. +func (w *libWrapper) Features(ifaceName string) (map[string]bool, error) { + e, err := ethtool.NewEthtool() + if err != nil { + return nil, err + } + defer e.Close() + return e.Features(ifaceName) +} + +// FeatureNames shows supported features by their name. +func (w *libWrapper) FeatureNames(ifaceName string) (map[string]uint, error) { + e, err := ethtool.NewEthtool() + if err != nil { + return nil, err + } + defer e.Close() + return e.FeatureNames(ifaceName) +} + +// Change requests a change in the given device's features. +func (w *libWrapper) Change(ifaceName string, config map[string]bool) error { + e, err := ethtool.NewEthtool() + if err != nil { + return err + } + defer e.Close() + return e.Change(ifaceName, config) +} diff --git a/pkg/host/internal/lib/ethtool/mock/mock_ethtool.go b/pkg/host/internal/lib/ethtool/mock/mock_ethtool.go new file mode 100644 index 000000000..b838bc868 --- /dev/null +++ b/pkg/host/internal/lib/ethtool/mock/mock_ethtool.go @@ -0,0 +1,78 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: ethtool.go + +// Package mock_ethtool is a generated GoMock package. +package mock_ethtool + +import ( + reflect "reflect" + + gomock "github.com/golang/mock/gomock" +) + +// MockEthtoolLib is a mock of EthtoolLib interface. +type MockEthtoolLib struct { + ctrl *gomock.Controller + recorder *MockEthtoolLibMockRecorder +} + +// MockEthtoolLibMockRecorder is the mock recorder for MockEthtoolLib. +type MockEthtoolLibMockRecorder struct { + mock *MockEthtoolLib +} + +// NewMockEthtoolLib creates a new mock instance. +func NewMockEthtoolLib(ctrl *gomock.Controller) *MockEthtoolLib { + mock := &MockEthtoolLib{ctrl: ctrl} + mock.recorder = &MockEthtoolLibMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockEthtoolLib) EXPECT() *MockEthtoolLibMockRecorder { + return m.recorder +} + +// Change mocks base method. +func (m *MockEthtoolLib) Change(ifaceName string, config map[string]bool) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Change", ifaceName, config) + ret0, _ := ret[0].(error) + return ret0 +} + +// Change indicates an expected call of Change. +func (mr *MockEthtoolLibMockRecorder) Change(ifaceName, config interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Change", reflect.TypeOf((*MockEthtoolLib)(nil).Change), ifaceName, config) +} + +// FeatureNames mocks base method. +func (m *MockEthtoolLib) FeatureNames(ifaceName string) (map[string]uint, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "FeatureNames", ifaceName) + ret0, _ := ret[0].(map[string]uint) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// FeatureNames indicates an expected call of FeatureNames. +func (mr *MockEthtoolLibMockRecorder) FeatureNames(ifaceName interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FeatureNames", reflect.TypeOf((*MockEthtoolLib)(nil).FeatureNames), ifaceName) +} + +// Features mocks base method. +func (m *MockEthtoolLib) Features(ifaceName string) (map[string]bool, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Features", ifaceName) + ret0, _ := ret[0].(map[string]bool) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Features indicates an expected call of Features. +func (mr *MockEthtoolLibMockRecorder) Features(ifaceName interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Features", reflect.TypeOf((*MockEthtoolLib)(nil).Features), ifaceName) +} diff --git a/pkg/host/internal/network/network.go b/pkg/host/internal/network/network.go index b4a2a16ad..3973d0fa4 100644 --- a/pkg/host/internal/network/network.go +++ b/pkg/host/internal/network/network.go @@ -14,6 +14,7 @@ import ( "github.com/k8snetworkplumbingwg/sriov-network-operator/pkg/consts" dputilsPkg "github.com/k8snetworkplumbingwg/sriov-network-operator/pkg/host/internal/lib/dputils" + ethtoolPkg "github.com/k8snetworkplumbingwg/sriov-network-operator/pkg/host/internal/lib/ethtool" netlinkPkg "github.com/k8snetworkplumbingwg/sriov-network-operator/pkg/host/internal/lib/netlink" "github.com/k8snetworkplumbingwg/sriov-network-operator/pkg/host/types" "github.com/k8snetworkplumbingwg/sriov-network-operator/pkg/utils" @@ -24,13 +25,15 @@ type network struct { utilsHelper utils.CmdInterface dputilsLib dputilsPkg.DPUtilsLib netlinkLib netlinkPkg.NetlinkLib + ethtoolLib ethtoolPkg.EthtoolLib } -func New(utilsHelper utils.CmdInterface, dputilsLib dputilsPkg.DPUtilsLib, netlinkLib netlinkPkg.NetlinkLib) types.NetworkInterface { +func New(utilsHelper utils.CmdInterface, dputilsLib dputilsPkg.DPUtilsLib, netlinkLib netlinkPkg.NetlinkLib, ethtoolLib ethtoolPkg.EthtoolLib) types.NetworkInterface { return &network{ utilsHelper: utilsHelper, dputilsLib: dputilsLib, netlinkLib: netlinkLib, + ethtoolLib: ethtoolLib, } } @@ -286,3 +289,43 @@ func (n *network) SetDevlinkDeviceParam(pciAddr, paramName, value string) error } return nil } + +// EnableHwTcOffload makes sure that hw-tc-offload feature is enabled if device supports it +func (n *network) EnableHwTcOffload(ifaceName string) error { + log.Log.V(2).Info("EnableHwTcOffload(): enable offloading", "device", ifaceName) + hwTcOffloadFeatureName := "hw-tc-offload" + + knownFeatures, err := n.ethtoolLib.FeatureNames(ifaceName) + if err != nil { + log.Log.Error(err, "EnableHwTcOffload(): can't list supported features", "device", ifaceName) + return err + } + if _, isKnown := knownFeatures[hwTcOffloadFeatureName]; !isKnown { + log.Log.V(0).Info("EnableHwTcOffload(): can't enable feature, feature is not supported", "device", ifaceName) + return nil + } + currentFeaturesState, err := n.ethtoolLib.Features(ifaceName) + if err != nil { + log.Log.Error(err, "EnableHwTcOffload(): can't read features state for device", "device", ifaceName) + return err + } + if currentFeaturesState[hwTcOffloadFeatureName] { + log.Log.V(2).Info("EnableHwTcOffload(): already enabled", "device", ifaceName) + return nil + } + if err := n.ethtoolLib.Change(ifaceName, map[string]bool{hwTcOffloadFeatureName: true}); err != nil { + log.Log.Error(err, "EnableHwTcOffload(): can't set feature for device", "device", ifaceName) + return err + } + updatedFeaturesState, err := n.ethtoolLib.Features(ifaceName) + if err != nil { + log.Log.Error(err, "EnableHwTcOffload(): can't read features state for device", "device", ifaceName) + return err + } + if updatedFeaturesState[hwTcOffloadFeatureName] { + log.Log.V(2).Info("EnableHwTcOffload(): feature enabled", "device", ifaceName) + return nil + } + log.Log.V(0).Info("EnableHwTcOffload(): feature is still disabled, not supported by device", "device", ifaceName) + return nil +} diff --git a/pkg/host/internal/network/network_test.go b/pkg/host/internal/network/network_test.go index cd604aeae..cd4dbaedc 100644 --- a/pkg/host/internal/network/network_test.go +++ b/pkg/host/internal/network/network_test.go @@ -12,6 +12,7 @@ import ( hostMockPkg "github.com/k8snetworkplumbingwg/sriov-network-operator/pkg/helper/mock" dputilsMockPkg "github.com/k8snetworkplumbingwg/sriov-network-operator/pkg/host/internal/lib/dputils/mock" + ethtoolMockPkg "github.com/k8snetworkplumbingwg/sriov-network-operator/pkg/host/internal/lib/ethtool/mock" netlinkMockPkg "github.com/k8snetworkplumbingwg/sriov-network-operator/pkg/host/internal/lib/netlink/mock" "github.com/k8snetworkplumbingwg/sriov-network-operator/pkg/host/types" ) @@ -29,6 +30,7 @@ var _ = Describe("Network", func() { var ( n types.NetworkInterface netlinkLibMock *netlinkMockPkg.MockNetlinkLib + ethtoolLibMock *ethtoolMockPkg.MockEthtoolLib dputilsLibMock *dputilsMockPkg.MockDPUtilsLib hostMock *hostMockPkg.MockHostHelpersInterface @@ -38,10 +40,11 @@ var _ = Describe("Network", func() { BeforeEach(func() { testCtrl = gomock.NewController(GinkgoT()) netlinkLibMock = netlinkMockPkg.NewMockNetlinkLib(testCtrl) + ethtoolLibMock = ethtoolMockPkg.NewMockEthtoolLib(testCtrl) dputilsLibMock = dputilsMockPkg.NewMockDPUtilsLib(testCtrl) hostMock = hostMockPkg.NewMockHostHelpersInterface(testCtrl) - n = New(hostMock, dputilsLibMock, netlinkLibMock) + n = New(hostMock, dputilsLibMock, netlinkLibMock, ethtoolLibMock) }) AfterEach(func() { @@ -152,4 +155,51 @@ var _ = Describe("Network", func() { Expect(err).To(HaveOccurred()) }) }) + Context("EnableHwTcOffload", func() { + It("Enabled", func() { + ethtoolLibMock.EXPECT().FeatureNames("enp216s0f0np0").Return(map[string]uint{"hw-tc-offload": 42}, nil) + ethtoolLibMock.EXPECT().Features("enp216s0f0np0").Return(map[string]bool{"hw-tc-offload": false}, nil) + ethtoolLibMock.EXPECT().Change("enp216s0f0np0", map[string]bool{"hw-tc-offload": true}).Return(nil) + ethtoolLibMock.EXPECT().Features("enp216s0f0np0").Return(map[string]bool{"hw-tc-offload": true}, nil) + Expect(n.EnableHwTcOffload("enp216s0f0np0")).NotTo(HaveOccurred()) + }) + It("Feature unknown", func() { + ethtoolLibMock.EXPECT().FeatureNames("enp216s0f0np0").Return(map[string]uint{}, nil) + Expect(n.EnableHwTcOffload("enp216s0f0np0")).NotTo(HaveOccurred()) + }) + It("Already enabled", func() { + ethtoolLibMock.EXPECT().FeatureNames("enp216s0f0np0").Return(map[string]uint{"hw-tc-offload": 42}, nil) + ethtoolLibMock.EXPECT().Features("enp216s0f0np0").Return(map[string]bool{"hw-tc-offload": true}, nil) + Expect(n.EnableHwTcOffload("enp216s0f0np0")).NotTo(HaveOccurred()) + }) + It("not supported", func() { + ethtoolLibMock.EXPECT().FeatureNames("enp216s0f0np0").Return(map[string]uint{"hw-tc-offload": 42}, nil) + ethtoolLibMock.EXPECT().Features("enp216s0f0np0").Return(map[string]bool{"hw-tc-offload": false}, nil) + ethtoolLibMock.EXPECT().Change("enp216s0f0np0", map[string]bool{"hw-tc-offload": true}).Return(nil) + ethtoolLibMock.EXPECT().Features("enp216s0f0np0").Return(map[string]bool{"hw-tc-offload": false}, nil) + Expect(n.EnableHwTcOffload("enp216s0f0np0")).NotTo(HaveOccurred()) + }) + It("fail - can't list supported", func() { + ethtoolLibMock.EXPECT().FeatureNames("enp216s0f0np0").Return(nil, testErr) + Expect(n.EnableHwTcOffload("enp216s0f0np0")).To(MatchError(testErr)) + }) + It("fail - can't get features", func() { + ethtoolLibMock.EXPECT().FeatureNames("enp216s0f0np0").Return(map[string]uint{"hw-tc-offload": 42}, nil) + ethtoolLibMock.EXPECT().Features("enp216s0f0np0").Return(nil, testErr) + Expect(n.EnableHwTcOffload("enp216s0f0np0")).To(MatchError(testErr)) + }) + It("fail - can't change features", func() { + ethtoolLibMock.EXPECT().FeatureNames("enp216s0f0np0").Return(map[string]uint{"hw-tc-offload": 42}, nil) + ethtoolLibMock.EXPECT().Features("enp216s0f0np0").Return(map[string]bool{"hw-tc-offload": false}, nil) + ethtoolLibMock.EXPECT().Change("enp216s0f0np0", map[string]bool{"hw-tc-offload": true}).Return(testErr) + Expect(n.EnableHwTcOffload("enp216s0f0np0")).To(MatchError(testErr)) + }) + It("fail - can't reread features", func() { + ethtoolLibMock.EXPECT().FeatureNames("enp216s0f0np0").Return(map[string]uint{"hw-tc-offload": 42}, nil) + ethtoolLibMock.EXPECT().Features("enp216s0f0np0").Return(map[string]bool{"hw-tc-offload": false}, nil) + ethtoolLibMock.EXPECT().Change("enp216s0f0np0", map[string]bool{"hw-tc-offload": true}).Return(nil) + ethtoolLibMock.EXPECT().Features("enp216s0f0np0").Return(nil, testErr) + Expect(n.EnableHwTcOffload("enp216s0f0np0")).To(MatchError(testErr)) + }) + }) }) diff --git a/pkg/host/manager.go b/pkg/host/manager.go index 7e5a92001..9dd4b7152 100644 --- a/pkg/host/manager.go +++ b/pkg/host/manager.go @@ -3,6 +3,7 @@ package host import ( "github.com/k8snetworkplumbingwg/sriov-network-operator/pkg/host/internal/kernel" "github.com/k8snetworkplumbingwg/sriov-network-operator/pkg/host/internal/lib/dputils" + "github.com/k8snetworkplumbingwg/sriov-network-operator/pkg/host/internal/lib/ethtool" "github.com/k8snetworkplumbingwg/sriov-network-operator/pkg/host/internal/lib/netlink" "github.com/k8snetworkplumbingwg/sriov-network-operator/pkg/host/internal/network" "github.com/k8snetworkplumbingwg/sriov-network-operator/pkg/host/internal/service" @@ -38,8 +39,9 @@ type hostManager struct { func NewHostManager(utilsInterface utils.CmdInterface) HostManagerInterface { dpUtils := dputils.New() netlinkLib := netlink.New() + ethtoolLib := ethtool.New() k := kernel.New(utilsInterface) - n := network.New(utilsInterface, dpUtils, netlinkLib) + n := network.New(utilsInterface, dpUtils, netlinkLib, ethtoolLib) sv := service.New(utilsInterface) u := udev.New(utilsInterface) sr := sriov.New(utilsInterface, k, n, u, netlinkLib, dpUtils) diff --git a/pkg/host/mock/mock_host.go b/pkg/host/mock/mock_host.go index 992a813b9..8e0a56d6e 100644 --- a/pkg/host/mock/mock_host.go +++ b/pkg/host/mock/mock_host.go @@ -209,6 +209,20 @@ func (mr *MockHostManagerInterfaceMockRecorder) DiscoverVDPAType(pciAddr interfa return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DiscoverVDPAType", reflect.TypeOf((*MockHostManagerInterface)(nil).DiscoverVDPAType), pciAddr) } +// EnableHwTcOffload mocks base method. +func (m *MockHostManagerInterface) EnableHwTcOffload(ifaceName string) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "EnableHwTcOffload", ifaceName) + ret0, _ := ret[0].(error) + return ret0 +} + +// EnableHwTcOffload indicates an expected call of EnableHwTcOffload. +func (mr *MockHostManagerInterfaceMockRecorder) EnableHwTcOffload(ifaceName interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EnableHwTcOffload", reflect.TypeOf((*MockHostManagerInterface)(nil).EnableHwTcOffload), ifaceName) +} + // EnableRDMA mocks base method. func (m *MockHostManagerInterface) EnableRDMA(conditionFilePath, serviceName, packageManager string) (bool, error) { m.ctrl.T.Helper() diff --git a/pkg/host/types/interfaces.go b/pkg/host/types/interfaces.go index 06a9aedac..e267c83fb 100644 --- a/pkg/host/types/interfaces.go +++ b/pkg/host/types/interfaces.go @@ -104,6 +104,8 @@ type NetworkInterface interface { // as a string. Automatically set CMODE for the parameter and converts the value to the right // type before submitting it. SetDevlinkDeviceParam(pciAddr, paramName, value string) error + // EnableHwTcOffload make sure that hw-tc-offload feature is enabled if device supports it + EnableHwTcOffload(ifaceName string) error } type ServiceInterface interface { diff --git a/vendor/github.com/safchain/ethtool/.gitignore b/vendor/github.com/safchain/ethtool/.gitignore new file mode 100644 index 000000000..db6cadffd --- /dev/null +++ b/vendor/github.com/safchain/ethtool/.gitignore @@ -0,0 +1,27 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe +*.test +*.prof + +# Skip compiled example binary file +/example/example diff --git a/vendor/github.com/safchain/ethtool/.golangci.yml b/vendor/github.com/safchain/ethtool/.golangci.yml new file mode 100644 index 000000000..77ccf927e --- /dev/null +++ b/vendor/github.com/safchain/ethtool/.golangci.yml @@ -0,0 +1,14 @@ +linters: + disable: + - gosimple + - unused + enable: + - gci + - gofmt + - misspell +linters-settings: + gci: + sections: + - standard + - default + - prefix(github.com/safchain/ethtool) diff --git a/vendor/github.com/safchain/ethtool/LICENSE b/vendor/github.com/safchain/ethtool/LICENSE new file mode 100644 index 000000000..8f71f43fe --- /dev/null +++ b/vendor/github.com/safchain/ethtool/LICENSE @@ -0,0 +1,202 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + diff --git a/vendor/github.com/safchain/ethtool/Makefile b/vendor/github.com/safchain/ethtool/Makefile new file mode 100644 index 000000000..67d2da395 --- /dev/null +++ b/vendor/github.com/safchain/ethtool/Makefile @@ -0,0 +1,4 @@ +all: build + +build: + CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build diff --git a/vendor/github.com/safchain/ethtool/README.md b/vendor/github.com/safchain/ethtool/README.md new file mode 100644 index 000000000..e44367582 --- /dev/null +++ b/vendor/github.com/safchain/ethtool/README.md @@ -0,0 +1,55 @@ +# ethtool go package # + +![Build Status](https://github.com/safchain/ethtool/actions/workflows/unittests.yml/badge.svg) +[![GoDoc](https://godoc.org/github.com/safchain/ethtool?status.svg)](https://godoc.org/github.com/safchain/ethtool) + + +The ethtool package aims to provide a library that provides easy access to the Linux SIOCETHTOOL ioctl operations. It can be used to retrieve information from a network device such as statistics, driver related information or even the peer of a VETH interface. + +# Installation + +```shell +go get github.com/safchain/ethtool +``` + +# How to use + +```go +package main + +import ( + "fmt" + + "github.com/safchain/ethtool" +) + +func main() { + ethHandle, err := ethtool.NewEthtool() + if err != nil { + panic(err.Error()) + } + defer ethHandle.Close() + + // Retrieve tx from eth0 + stats, err := ethHandle.Stats("eth0") + if err != nil { + panic(err.Error()) + } + fmt.Printf("TX: %d\n", stats["tx_bytes"]) + + // Retrieve peer index of a veth interface + stats, err = ethHandle.Stats("veth0") + if err != nil { + panic(err.Error()) + } + fmt.Printf("Peer Index: %d\n", stats["peer_ifindex"]) +} +``` + +## LICENSE ## + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. diff --git a/vendor/github.com/safchain/ethtool/ethtool.go b/vendor/github.com/safchain/ethtool/ethtool.go new file mode 100644 index 000000000..4d8dec69a --- /dev/null +++ b/vendor/github.com/safchain/ethtool/ethtool.go @@ -0,0 +1,800 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +// The ethtool package aims to provide a library that provides easy access +// to the Linux SIOCETHTOOL ioctl operations. It can be used to retrieve information +// from a network device such as statistics, driver related information or even +// the peer of a VETH interface. +package ethtool + +import ( + "bytes" + "encoding/hex" + "fmt" + "strings" + "unsafe" + + "golang.org/x/sys/unix" +) + +// Maximum size of an interface name +const ( + IFNAMSIZ = 16 +) + +// ioctl ethtool request +const ( + SIOCETHTOOL = 0x8946 +) + +// ethtool stats related constants. +const ( + ETH_GSTRING_LEN = 32 + ETH_SS_STATS = 1 + ETH_SS_FEATURES = 4 + + // CMD supported + ETHTOOL_GDRVINFO = 0x00000003 /* Get driver info. */ + ETHTOOL_GSTRINGS = 0x0000001b /* get specified string set */ + ETHTOOL_GSTATS = 0x0000001d /* get NIC-specific statistics */ + // other CMDs from ethtool-copy.h of ethtool-3.5 package + ETHTOOL_GSET = 0x00000001 /* Get settings. */ + ETHTOOL_SSET = 0x00000002 /* Set settings. */ + ETHTOOL_GMSGLVL = 0x00000007 /* Get driver message level */ + ETHTOOL_SMSGLVL = 0x00000008 /* Set driver msg level. */ + ETHTOOL_GCHANNELS = 0x0000003c /* Get no of channels */ + ETHTOOL_SCHANNELS = 0x0000003d /* Set no of channels */ + ETHTOOL_GCOALESCE = 0x0000000e /* Get coalesce config */ + /* Get link status for host, i.e. whether the interface *and* the + * physical port (if there is one) are up (ethtool_value). */ + ETHTOOL_GLINK = 0x0000000a + ETHTOOL_GMODULEINFO = 0x00000042 /* Get plug-in module information */ + ETHTOOL_GMODULEEEPROM = 0x00000043 /* Get plug-in module eeprom */ + ETHTOOL_GPERMADDR = 0x00000020 /* Get permanent hardware address */ + ETHTOOL_GFEATURES = 0x0000003a /* Get device offload settings */ + ETHTOOL_SFEATURES = 0x0000003b /* Change device offload settings */ + ETHTOOL_GFLAGS = 0x00000025 /* Get flags bitmap(ethtool_value) */ + ETHTOOL_GSSET_INFO = 0x00000037 /* Get string set info */ + ETHTOOL_GET_TS_INFO = 0x00000041 /* Get time stamping and PHC info */ +) + +// MAX_GSTRINGS maximum number of stats entries that ethtool can +// retrieve currently. +const ( + MAX_GSTRINGS = 32768 + MAX_FEATURE_BLOCKS = (MAX_GSTRINGS + 32 - 1) / 32 + EEPROM_LEN = 640 + PERMADDR_LEN = 32 +) + +type ifreq struct { + ifr_name [IFNAMSIZ]byte + ifr_data uintptr +} + +// following structures comes from uapi/linux/ethtool.h +type ethtoolSsetInfo struct { + cmd uint32 + reserved uint32 + sset_mask uint32 + data uintptr +} + +type ethtoolGetFeaturesBlock struct { + available uint32 + requested uint32 + active uint32 + never_changed uint32 +} + +type ethtoolGfeatures struct { + cmd uint32 + size uint32 + blocks [MAX_FEATURE_BLOCKS]ethtoolGetFeaturesBlock +} + +type ethtoolSetFeaturesBlock struct { + valid uint32 + requested uint32 +} + +type ethtoolSfeatures struct { + cmd uint32 + size uint32 + blocks [MAX_FEATURE_BLOCKS]ethtoolSetFeaturesBlock +} + +type ethtoolDrvInfo struct { + cmd uint32 + driver [32]byte + version [32]byte + fw_version [32]byte + bus_info [32]byte + erom_version [32]byte + reserved2 [12]byte + n_priv_flags uint32 + n_stats uint32 + testinfo_len uint32 + eedump_len uint32 + regdump_len uint32 +} + +// DrvInfo contains driver information +// ethtool.h v3.5: struct ethtool_drvinfo +type DrvInfo struct { + Cmd uint32 + Driver string + Version string + FwVersion string + BusInfo string + EromVersion string + Reserved2 string + NPrivFlags uint32 + NStats uint32 + TestInfoLen uint32 + EedumpLen uint32 + RegdumpLen uint32 +} + +// Channels contains the number of channels for a given interface. +type Channels struct { + Cmd uint32 + MaxRx uint32 + MaxTx uint32 + MaxOther uint32 + MaxCombined uint32 + RxCount uint32 + TxCount uint32 + OtherCount uint32 + CombinedCount uint32 +} + +// Coalesce is a coalesce config for an interface +type Coalesce struct { + Cmd uint32 + RxCoalesceUsecs uint32 + RxMaxCoalescedFrames uint32 + RxCoalesceUsecsIrq uint32 + RxMaxCoalescedFramesIrq uint32 + TxCoalesceUsecs uint32 + TxMaxCoalescedFrames uint32 + TxCoalesceUsecsIrq uint32 + TxMaxCoalescedFramesIrq uint32 + StatsBlockCoalesceUsecs uint32 + UseAdaptiveRxCoalesce uint32 + UseAdaptiveTxCoalesce uint32 + PktRateLow uint32 + RxCoalesceUsecsLow uint32 + RxMaxCoalescedFramesLow uint32 + TxCoalesceUsecsLow uint32 + TxMaxCoalescedFramesLow uint32 + PktRateHigh uint32 + RxCoalesceUsecsHigh uint32 + RxMaxCoalescedFramesHigh uint32 + TxCoalesceUsecsHigh uint32 + TxMaxCoalescedFramesHigh uint32 + RateSampleInterval uint32 +} + +const ( + SOF_TIMESTAMPING_TX_HARDWARE = (1 << 0) + SOF_TIMESTAMPING_TX_SOFTWARE = (1 << 1) + SOF_TIMESTAMPING_RX_HARDWARE = (1 << 2) + SOF_TIMESTAMPING_RX_SOFTWARE = (1 << 3) + SOF_TIMESTAMPING_SOFTWARE = (1 << 4) + SOF_TIMESTAMPING_SYS_HARDWARE = (1 << 5) + SOF_TIMESTAMPING_RAW_HARDWARE = (1 << 6) + SOF_TIMESTAMPING_OPT_ID = (1 << 7) + SOF_TIMESTAMPING_TX_SCHED = (1 << 8) + SOF_TIMESTAMPING_TX_ACK = (1 << 9) + SOF_TIMESTAMPING_OPT_CMSG = (1 << 10) + SOF_TIMESTAMPING_OPT_TSONLY = (1 << 11) + SOF_TIMESTAMPING_OPT_STATS = (1 << 12) + SOF_TIMESTAMPING_OPT_PKTINFO = (1 << 13) + SOF_TIMESTAMPING_OPT_TX_SWHW = (1 << 14) + SOF_TIMESTAMPING_BIND_PHC = (1 << 15) +) + +const ( + /* + * No outgoing packet will need hardware time stamping; + * should a packet arrive which asks for it, no hardware + * time stamping will be done. + */ + HWTSTAMP_TX_OFF = iota + + /* + * Enables hardware time stamping for outgoing packets; + * the sender of the packet decides which are to be + * time stamped by setting %SOF_TIMESTAMPING_TX_SOFTWARE + * before sending the packet. + */ + HWTSTAMP_TX_ON + + /* + * Enables time stamping for outgoing packets just as + * HWTSTAMP_TX_ON does, but also enables time stamp insertion + * directly into Sync packets. In this case, transmitted Sync + * packets will not received a time stamp via the socket error + * queue. + */ + HWTSTAMP_TX_ONESTEP_SYNC + + /* + * Same as HWTSTAMP_TX_ONESTEP_SYNC, but also enables time + * stamp insertion directly into PDelay_Resp packets. In this + * case, neither transmitted Sync nor PDelay_Resp packets will + * receive a time stamp via the socket error queue. + */ + HWTSTAMP_TX_ONESTEP_P2P +) + +const ( + HWTSTAMP_FILTER_NONE = iota /* time stamp no incoming packet at all */ + HWTSTAMP_FILTER_ALL /* time stamp any incoming packet */ + HWTSTAMP_FILTER_SOME /* return value: time stamp all packets requested plus some others */ + HWTSTAMP_FILTER_PTP_V1_L4_EVENT /* PTP v1, UDP, any kind of event packet */ + HWTSTAMP_FILTER_PTP_V1_L4_SYNC /* PTP v1, UDP, Sync packet */ + HWTSTAMP_FILTER_PTP_V1_L4_DELAY_REQ /* PTP v1, UDP, Delay_req packet */ + HWTSTAMP_FILTER_PTP_V2_L4_EVENT /* PTP v2, UDP, any kind of event packet */ + HWTSTAMP_FILTER_PTP_V2_L4_SYNC /* PTP v2, UDP, Sync packet */ + HWTSTAMP_FILTER_PTP_V2_L4_DELAY_REQ /* PTP v2, UDP, Delay_req packet */ + HWTSTAMP_FILTER_PTP_V2_L2_EVENT /* 802.AS1, Ethernet, any kind of event packet */ + HWTSTAMP_FILTER_PTP_V2_L2_SYNC /* 802.AS1, Ethernet, Sync packet */ + HWTSTAMP_FILTER_PTP_V2_L2_DELAY_REQ /* 802.AS1, Ethernet, Delay_req packet */ + HWTSTAMP_FILTER_PTP_V2_EVENT /* PTP v2/802.AS1, any layer, any kind of event packet */ + HWTSTAMP_FILTER_PTP_V2_SYNC /* PTP v2/802.AS1, any layer, Sync packet */ + HWTSTAMP_FILTER_PTP_V2_DELAY_REQ /* PTP v2/802.AS1, any layer, Delay_req packet */ + HWTSTAMP_FILTER_NTP_ALL /* NTP, UDP, all versions and packet modes */ +) + +type TimestampingInformation struct { + Cmd uint32 + SoTimestamping uint32 /* SOF_TIMESTAMPING_* bitmask */ + PhcIndex int32 + TxTypes uint32 /* HWTSTAMP_TX_* */ + txReserved [3]uint32 + RxFilters uint32 /* HWTSTAMP_FILTER_ */ + rxReserved [3]uint32 +} + +type ethtoolGStrings struct { + cmd uint32 + string_set uint32 + len uint32 + data [MAX_GSTRINGS * ETH_GSTRING_LEN]byte +} + +type ethtoolStats struct { + cmd uint32 + n_stats uint32 + data [MAX_GSTRINGS]uint64 +} + +type ethtoolEeprom struct { + cmd uint32 + magic uint32 + offset uint32 + len uint32 + data [EEPROM_LEN]byte +} + +type ethtoolModInfo struct { + cmd uint32 + tpe uint32 + eeprom_len uint32 + reserved [8]uint32 +} + +type ethtoolLink struct { + cmd uint32 + data uint32 +} + +type ethtoolPermAddr struct { + cmd uint32 + size uint32 + data [PERMADDR_LEN]byte +} + +type Ethtool struct { + fd int +} + +// Convert zero-terminated array of chars (string in C) to a Go string. +func goString(s []byte) string { + strEnd := bytes.IndexByte(s, 0) + if strEnd == -1 { + return string(s[:]) + } + return string(s[:strEnd]) +} + +// DriverName returns the driver name of the given interface name. +func (e *Ethtool) DriverName(intf string) (string, error) { + info, err := e.getDriverInfo(intf) + if err != nil { + return "", err + } + return goString(info.driver[:]), nil +} + +// BusInfo returns the bus information of the given interface name. +func (e *Ethtool) BusInfo(intf string) (string, error) { + info, err := e.getDriverInfo(intf) + if err != nil { + return "", err + } + return goString(info.bus_info[:]), nil +} + +// ModuleEeprom returns Eeprom information of the given interface name. +func (e *Ethtool) ModuleEeprom(intf string) ([]byte, error) { + eeprom, _, err := e.getModuleEeprom(intf) + if err != nil { + return nil, err + } + + return eeprom.data[:eeprom.len], nil +} + +// ModuleEeprom returns Eeprom information of the given interface name. +func (e *Ethtool) ModuleEepromHex(intf string) (string, error) { + eeprom, _, err := e.getModuleEeprom(intf) + if err != nil { + return "", err + } + + return hex.EncodeToString(eeprom.data[:eeprom.len]), nil +} + +// DriverInfo returns driver information of the given interface name. +func (e *Ethtool) DriverInfo(intf string) (DrvInfo, error) { + i, err := e.getDriverInfo(intf) + if err != nil { + return DrvInfo{}, err + } + + drvInfo := DrvInfo{ + Cmd: i.cmd, + Driver: goString(i.driver[:]), + Version: goString(i.version[:]), + FwVersion: goString(i.fw_version[:]), + BusInfo: goString(i.bus_info[:]), + EromVersion: goString(i.erom_version[:]), + Reserved2: goString(i.reserved2[:]), + NPrivFlags: i.n_priv_flags, + NStats: i.n_stats, + TestInfoLen: i.testinfo_len, + EedumpLen: i.eedump_len, + RegdumpLen: i.regdump_len, + } + + return drvInfo, nil +} + +// GetChannels returns the number of channels for the given interface name. +func (e *Ethtool) GetChannels(intf string) (Channels, error) { + channels, err := e.getChannels(intf) + if err != nil { + return Channels{}, err + } + + return channels, nil +} + +// SetChannels sets the number of channels for the given interface name and +// returns the new number of channels. +func (e *Ethtool) SetChannels(intf string, channels Channels) (Channels, error) { + channels, err := e.setChannels(intf, channels) + if err != nil { + return Channels{}, err + } + + return channels, nil +} + +// GetCoalesce returns the coalesce config for the given interface name. +func (e *Ethtool) GetCoalesce(intf string) (Coalesce, error) { + coalesce, err := e.getCoalesce(intf) + if err != nil { + return Coalesce{}, err + } + return coalesce, nil +} + +// GetTimestampingInformation returns the PTP timestamping information for the given interface name. +func (e *Ethtool) GetTimestampingInformation(intf string) (TimestampingInformation, error) { + ts, err := e.getTimestampingInformation(intf) + if err != nil { + return TimestampingInformation{}, err + } + return ts, nil +} + +// PermAddr returns permanent address of the given interface name. +func (e *Ethtool) PermAddr(intf string) (string, error) { + permAddr, err := e.getPermAddr(intf) + if err != nil { + return "", err + } + + if permAddr.data[0] == 0 && permAddr.data[1] == 0 && + permAddr.data[2] == 0 && permAddr.data[3] == 0 && + permAddr.data[4] == 0 && permAddr.data[5] == 0 { + return "", nil + } + + return fmt.Sprintf("%x:%x:%x:%x:%x:%x", + permAddr.data[0:1], + permAddr.data[1:2], + permAddr.data[2:3], + permAddr.data[3:4], + permAddr.data[4:5], + permAddr.data[5:6], + ), nil +} + +func (e *Ethtool) ioctl(intf string, data uintptr) error { + var name [IFNAMSIZ]byte + copy(name[:], []byte(intf)) + + ifr := ifreq{ + ifr_name: name, + ifr_data: data, + } + + _, _, ep := unix.Syscall(unix.SYS_IOCTL, uintptr(e.fd), SIOCETHTOOL, uintptr(unsafe.Pointer(&ifr))) + if ep != 0 { + return ep + } + + return nil +} + +func (e *Ethtool) getDriverInfo(intf string) (ethtoolDrvInfo, error) { + drvinfo := ethtoolDrvInfo{ + cmd: ETHTOOL_GDRVINFO, + } + + if err := e.ioctl(intf, uintptr(unsafe.Pointer(&drvinfo))); err != nil { + return ethtoolDrvInfo{}, err + } + + return drvinfo, nil +} + +func (e *Ethtool) getChannels(intf string) (Channels, error) { + channels := Channels{ + Cmd: ETHTOOL_GCHANNELS, + } + + if err := e.ioctl(intf, uintptr(unsafe.Pointer(&channels))); err != nil { + return Channels{}, err + } + + return channels, nil +} + +func (e *Ethtool) setChannels(intf string, channels Channels) (Channels, error) { + channels.Cmd = ETHTOOL_SCHANNELS + + if err := e.ioctl(intf, uintptr(unsafe.Pointer(&channels))); err != nil { + return Channels{}, err + } + + return channels, nil +} + +func (e *Ethtool) getCoalesce(intf string) (Coalesce, error) { + coalesce := Coalesce{ + Cmd: ETHTOOL_GCOALESCE, + } + + if err := e.ioctl(intf, uintptr(unsafe.Pointer(&coalesce))); err != nil { + return Coalesce{}, err + } + + return coalesce, nil +} + +func (e *Ethtool) getTimestampingInformation(intf string) (TimestampingInformation, error) { + ts := TimestampingInformation{ + Cmd: ETHTOOL_GET_TS_INFO, + } + + if err := e.ioctl(intf, uintptr(unsafe.Pointer(&ts))); err != nil { + return TimestampingInformation{}, err + } + + return ts, nil +} + +func (e *Ethtool) getPermAddr(intf string) (ethtoolPermAddr, error) { + permAddr := ethtoolPermAddr{ + cmd: ETHTOOL_GPERMADDR, + size: PERMADDR_LEN, + } + + if err := e.ioctl(intf, uintptr(unsafe.Pointer(&permAddr))); err != nil { + return ethtoolPermAddr{}, err + } + + return permAddr, nil +} + +func (e *Ethtool) getModuleEeprom(intf string) (ethtoolEeprom, ethtoolModInfo, error) { + modInfo := ethtoolModInfo{ + cmd: ETHTOOL_GMODULEINFO, + } + + if err := e.ioctl(intf, uintptr(unsafe.Pointer(&modInfo))); err != nil { + return ethtoolEeprom{}, ethtoolModInfo{}, err + } + + eeprom := ethtoolEeprom{ + cmd: ETHTOOL_GMODULEEEPROM, + len: modInfo.eeprom_len, + offset: 0, + } + + if modInfo.eeprom_len > EEPROM_LEN { + return ethtoolEeprom{}, ethtoolModInfo{}, fmt.Errorf("eeprom size: %d is larger than buffer size: %d", modInfo.eeprom_len, EEPROM_LEN) + } + + if err := e.ioctl(intf, uintptr(unsafe.Pointer(&eeprom))); err != nil { + return ethtoolEeprom{}, ethtoolModInfo{}, err + } + + return eeprom, modInfo, nil +} + +func isFeatureBitSet(blocks [MAX_FEATURE_BLOCKS]ethtoolGetFeaturesBlock, index uint) bool { + return (blocks)[index/32].active&(1<<(index%32)) != 0 +} + +func setFeatureBit(blocks *[MAX_FEATURE_BLOCKS]ethtoolSetFeaturesBlock, index uint, value bool) { + blockIndex, bitIndex := index/32, index%32 + + blocks[blockIndex].valid |= 1 << bitIndex + + if value { + blocks[blockIndex].requested |= 1 << bitIndex + } else { + blocks[blockIndex].requested &= ^(1 << bitIndex) + } +} + +// FeatureNames shows supported features by their name. +func (e *Ethtool) FeatureNames(intf string) (map[string]uint, error) { + ssetInfo := ethtoolSsetInfo{ + cmd: ETHTOOL_GSSET_INFO, + sset_mask: 1 << ETH_SS_FEATURES, + } + + if err := e.ioctl(intf, uintptr(unsafe.Pointer(&ssetInfo))); err != nil { + return nil, err + } + + length := uint32(ssetInfo.data) + if length == 0 { + return map[string]uint{}, nil + } else if length > MAX_GSTRINGS { + return nil, fmt.Errorf("ethtool currently doesn't support more than %d entries, received %d", MAX_GSTRINGS, length) + } + + gstrings := ethtoolGStrings{ + cmd: ETHTOOL_GSTRINGS, + string_set: ETH_SS_FEATURES, + len: length, + data: [MAX_GSTRINGS * ETH_GSTRING_LEN]byte{}, + } + + if err := e.ioctl(intf, uintptr(unsafe.Pointer(&gstrings))); err != nil { + return nil, err + } + + var result = make(map[string]uint) + for i := 0; i != int(length); i++ { + b := gstrings.data[i*ETH_GSTRING_LEN : i*ETH_GSTRING_LEN+ETH_GSTRING_LEN] + key := goString(b) + if key != "" { + result[key] = uint(i) + } + } + + return result, nil +} + +// Features retrieves features of the given interface name. +func (e *Ethtool) Features(intf string) (map[string]bool, error) { + names, err := e.FeatureNames(intf) + if err != nil { + return nil, err + } + + length := uint32(len(names)) + if length == 0 { + return map[string]bool{}, nil + } + + features := ethtoolGfeatures{ + cmd: ETHTOOL_GFEATURES, + size: (length + 32 - 1) / 32, + } + + if err := e.ioctl(intf, uintptr(unsafe.Pointer(&features))); err != nil { + return nil, err + } + + var result = make(map[string]bool, length) + for key, index := range names { + result[key] = isFeatureBitSet(features.blocks, index) + } + + return result, nil +} + +// Change requests a change in the given device's features. +func (e *Ethtool) Change(intf string, config map[string]bool) error { + names, err := e.FeatureNames(intf) + if err != nil { + return err + } + + length := uint32(len(names)) + + features := ethtoolSfeatures{ + cmd: ETHTOOL_SFEATURES, + size: (length + 32 - 1) / 32, + } + + for key, value := range config { + if index, ok := names[key]; ok { + setFeatureBit(&features.blocks, index, value) + } else { + return fmt.Errorf("unsupported feature %q", key) + } + } + + return e.ioctl(intf, uintptr(unsafe.Pointer(&features))) +} + +// Get state of a link. +func (e *Ethtool) LinkState(intf string) (uint32, error) { + x := ethtoolLink{ + cmd: ETHTOOL_GLINK, + } + + if err := e.ioctl(intf, uintptr(unsafe.Pointer(&x))); err != nil { + return 0, err + } + + return x.data, nil +} + +// Stats retrieves stats of the given interface name. +func (e *Ethtool) Stats(intf string) (map[string]uint64, error) { + drvinfo := ethtoolDrvInfo{ + cmd: ETHTOOL_GDRVINFO, + } + + if err := e.ioctl(intf, uintptr(unsafe.Pointer(&drvinfo))); err != nil { + return nil, err + } + + if drvinfo.n_stats*ETH_GSTRING_LEN > MAX_GSTRINGS*ETH_GSTRING_LEN { + return nil, fmt.Errorf("ethtool currently doesn't support more than %d entries, received %d", MAX_GSTRINGS, drvinfo.n_stats) + } + + gstrings := ethtoolGStrings{ + cmd: ETHTOOL_GSTRINGS, + string_set: ETH_SS_STATS, + len: drvinfo.n_stats, + data: [MAX_GSTRINGS * ETH_GSTRING_LEN]byte{}, + } + + if err := e.ioctl(intf, uintptr(unsafe.Pointer(&gstrings))); err != nil { + return nil, err + } + + stats := ethtoolStats{ + cmd: ETHTOOL_GSTATS, + n_stats: drvinfo.n_stats, + data: [MAX_GSTRINGS]uint64{}, + } + + if err := e.ioctl(intf, uintptr(unsafe.Pointer(&stats))); err != nil { + return nil, err + } + + var result = make(map[string]uint64) + for i := 0; i != int(drvinfo.n_stats); i++ { + b := gstrings.data[i*ETH_GSTRING_LEN : i*ETH_GSTRING_LEN+ETH_GSTRING_LEN] + strEnd := strings.Index(string(b), "\x00") + if strEnd == -1 { + strEnd = ETH_GSTRING_LEN + } + key := string(b[:strEnd]) + if len(key) != 0 { + result[key] = stats.data[i] + } + } + + return result, nil +} + +// Close closes the ethool handler +func (e *Ethtool) Close() { + unix.Close(e.fd) +} + +// NewEthtool returns a new ethtool handler +func NewEthtool() (*Ethtool, error) { + fd, err := unix.Socket(unix.AF_INET, unix.SOCK_DGRAM, unix.IPPROTO_IP) + if err != nil { + return nil, err + } + + return &Ethtool{ + fd: int(fd), + }, nil +} + +// BusInfo returns bus information of the given interface name. +func BusInfo(intf string) (string, error) { + e, err := NewEthtool() + if err != nil { + return "", err + } + defer e.Close() + return e.BusInfo(intf) +} + +// DriverName returns the driver name of the given interface name. +func DriverName(intf string) (string, error) { + e, err := NewEthtool() + if err != nil { + return "", err + } + defer e.Close() + return e.DriverName(intf) +} + +// Stats retrieves stats of the given interface name. +func Stats(intf string) (map[string]uint64, error) { + e, err := NewEthtool() + if err != nil { + return nil, err + } + defer e.Close() + return e.Stats(intf) +} + +// PermAddr returns permanent address of the given interface name. +func PermAddr(intf string) (string, error) { + e, err := NewEthtool() + if err != nil { + return "", err + } + defer e.Close() + return e.PermAddr(intf) +} diff --git a/vendor/github.com/safchain/ethtool/ethtool_cmd.go b/vendor/github.com/safchain/ethtool/ethtool_cmd.go new file mode 100644 index 000000000..ee52cd8f8 --- /dev/null +++ b/vendor/github.com/safchain/ethtool/ethtool_cmd.go @@ -0,0 +1,208 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +// Package ethtool aims to provide a library giving a simple access to the +// Linux SIOCETHTOOL ioctl operations. It can be used to retrieve informations +// from a network device like statistics, driver related informations or +// even the peer of a VETH interface. +package ethtool + +import ( + "math" + "reflect" + "unsafe" + + "golang.org/x/sys/unix" +) + +type EthtoolCmd struct { /* ethtool.c: struct ethtool_cmd */ + Cmd uint32 + Supported uint32 + Advertising uint32 + Speed uint16 + Duplex uint8 + Port uint8 + Phy_address uint8 + Transceiver uint8 + Autoneg uint8 + Mdio_support uint8 + Maxtxpkt uint32 + Maxrxpkt uint32 + Speed_hi uint16 + Eth_tp_mdix uint8 + Reserved2 uint8 + Lp_advertising uint32 + Reserved [2]uint32 +} + +// CmdGet returns the interface settings in the receiver struct +// and returns speed +func (ecmd *EthtoolCmd) CmdGet(intf string) (uint32, error) { + e, err := NewEthtool() + if err != nil { + return 0, err + } + defer e.Close() + return e.CmdGet(ecmd, intf) +} + +// CmdSet sets and returns the settings in the receiver struct +// and returns speed +func (ecmd *EthtoolCmd) CmdSet(intf string) (uint32, error) { + e, err := NewEthtool() + if err != nil { + return 0, err + } + defer e.Close() + return e.CmdSet(ecmd, intf) +} + +func (f *EthtoolCmd) reflect(retv *map[string]uint64) { + val := reflect.ValueOf(f).Elem() + + for i := 0; i < val.NumField(); i++ { + valueField := val.Field(i) + typeField := val.Type().Field(i) + + t := valueField.Interface() + //tt := reflect.TypeOf(t) + //fmt.Printf(" t %T %v tt %T %v\n", t, t, tt, tt) + switch t.(type) { + case uint32: + //fmt.Printf(" t is uint32\n") + (*retv)[typeField.Name] = uint64(t.(uint32)) + case uint16: + (*retv)[typeField.Name] = uint64(t.(uint16)) + case uint8: + (*retv)[typeField.Name] = uint64(t.(uint8)) + case int32: + (*retv)[typeField.Name] = uint64(t.(int32)) + case int16: + (*retv)[typeField.Name] = uint64(t.(int16)) + case int8: + (*retv)[typeField.Name] = uint64(t.(int8)) + default: + (*retv)[typeField.Name+"_unknown_type"] = 0 + } + + //tag := typeField.Tag + //fmt.Printf("Field Name: %s,\t Field Value: %v,\t Tag Value: %s\n", + // typeField.Name, valueField.Interface(), tag.Get("tag_name")) + } +} + +// CmdGet returns the interface settings in the receiver struct +// and returns speed +func (e *Ethtool) CmdGet(ecmd *EthtoolCmd, intf string) (uint32, error) { + ecmd.Cmd = ETHTOOL_GSET + + var name [IFNAMSIZ]byte + copy(name[:], []byte(intf)) + + ifr := ifreq{ + ifr_name: name, + ifr_data: uintptr(unsafe.Pointer(ecmd)), + } + + _, _, ep := unix.Syscall(unix.SYS_IOCTL, uintptr(e.fd), + SIOCETHTOOL, uintptr(unsafe.Pointer(&ifr))) + if ep != 0 { + return 0, ep + } + + var speedval uint32 = (uint32(ecmd.Speed_hi) << 16) | + (uint32(ecmd.Speed) & 0xffff) + if speedval == math.MaxUint16 { + speedval = math.MaxUint32 + } + + return speedval, nil +} + +// CmdSet sets and returns the settings in the receiver struct +// and returns speed +func (e *Ethtool) CmdSet(ecmd *EthtoolCmd, intf string) (uint32, error) { + ecmd.Cmd = ETHTOOL_SSET + + var name [IFNAMSIZ]byte + copy(name[:], []byte(intf)) + + ifr := ifreq{ + ifr_name: name, + ifr_data: uintptr(unsafe.Pointer(ecmd)), + } + + _, _, ep := unix.Syscall(unix.SYS_IOCTL, uintptr(e.fd), + SIOCETHTOOL, uintptr(unsafe.Pointer(&ifr))) + if ep != 0 { + return 0, unix.Errno(ep) + } + + var speedval uint32 = (uint32(ecmd.Speed_hi) << 16) | + (uint32(ecmd.Speed) & 0xffff) + if speedval == math.MaxUint16 { + speedval = math.MaxUint32 + } + + return speedval, nil +} + +// CmdGetMapped returns the interface settings in a map +func (e *Ethtool) CmdGetMapped(intf string) (map[string]uint64, error) { + ecmd := EthtoolCmd{ + Cmd: ETHTOOL_GSET, + } + + var name [IFNAMSIZ]byte + copy(name[:], []byte(intf)) + + ifr := ifreq{ + ifr_name: name, + ifr_data: uintptr(unsafe.Pointer(&ecmd)), + } + + _, _, ep := unix.Syscall(unix.SYS_IOCTL, uintptr(e.fd), + SIOCETHTOOL, uintptr(unsafe.Pointer(&ifr))) + if ep != 0 { + return nil, ep + } + + var result = make(map[string]uint64) + + // ref https://gist.github.com/drewolson/4771479 + // Golang Reflection Example + ecmd.reflect(&result) + + var speedval uint32 = (uint32(ecmd.Speed_hi) << 16) | + (uint32(ecmd.Speed) & 0xffff) + result["speed"] = uint64(speedval) + + return result, nil +} + +func CmdGetMapped(intf string) (map[string]uint64, error) { + e, err := NewEthtool() + if err != nil { + return nil, err + } + defer e.Close() + return e.CmdGetMapped(intf) +} diff --git a/vendor/github.com/safchain/ethtool/ethtool_msglvl.go b/vendor/github.com/safchain/ethtool/ethtool_msglvl.go new file mode 100644 index 000000000..1f6e338cf --- /dev/null +++ b/vendor/github.com/safchain/ethtool/ethtool_msglvl.go @@ -0,0 +1,114 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +// Package ethtool aims to provide a library giving a simple access to the +// Linux SIOCETHTOOL ioctl operations. It can be used to retrieve informations +// from a network device like statistics, driver related informations or +// even the peer of a VETH interface. +package ethtool + +import ( + "unsafe" + + "golang.org/x/sys/unix" +) + +type ethtoolValue struct { /* ethtool.c: struct ethtool_value */ + cmd uint32 + data uint32 +} + +// MsglvlGet returns the msglvl of the given interface. +func (e *Ethtool) MsglvlGet(intf string) (uint32, error) { + edata := ethtoolValue{ + cmd: ETHTOOL_GMSGLVL, + } + + var name [IFNAMSIZ]byte + copy(name[:], []byte(intf)) + + ifr := ifreq{ + ifr_name: name, + ifr_data: uintptr(unsafe.Pointer(&edata)), + } + + _, _, ep := unix.Syscall(unix.SYS_IOCTL, uintptr(e.fd), + SIOCETHTOOL, uintptr(unsafe.Pointer(&ifr))) + if ep != 0 { + return 0, ep + } + + return edata.data, nil +} + +// MsglvlSet returns the read-msglvl, post-set-msglvl of the given interface. +func (e *Ethtool) MsglvlSet(intf string, valset uint32) (uint32, uint32, error) { + edata := ethtoolValue{ + cmd: ETHTOOL_GMSGLVL, + } + + var name [IFNAMSIZ]byte + copy(name[:], []byte(intf)) + + ifr := ifreq{ + ifr_name: name, + ifr_data: uintptr(unsafe.Pointer(&edata)), + } + + _, _, ep := unix.Syscall(unix.SYS_IOCTL, uintptr(e.fd), + SIOCETHTOOL, uintptr(unsafe.Pointer(&ifr))) + if ep != 0 { + return 0, 0, ep + } + + readval := edata.data + + edata.cmd = ETHTOOL_SMSGLVL + edata.data = valset + + _, _, ep = unix.Syscall(unix.SYS_IOCTL, uintptr(e.fd), + SIOCETHTOOL, uintptr(unsafe.Pointer(&ifr))) + if ep != 0 { + return 0, 0, ep + } + + return readval, edata.data, nil +} + +// MsglvlGet returns the msglvl of the given interface. +func MsglvlGet(intf string) (uint32, error) { + e, err := NewEthtool() + if err != nil { + return 0, err + } + defer e.Close() + return e.MsglvlGet(intf) +} + +// MsglvlSet returns the read-msglvl, post-set-msglvl of the given interface. +func MsglvlSet(intf string, valset uint32) (uint32, uint32, error) { + e, err := NewEthtool() + if err != nil { + return 0, 0, err + } + defer e.Close() + return e.MsglvlSet(intf, valset) +} diff --git a/vendor/modules.txt b/vendor/modules.txt index 6148479a9..575527cb0 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -439,6 +439,9 @@ github.com/prometheus/procfs/internal/util # github.com/russross/blackfriday/v2 v2.1.0 ## explicit github.com/russross/blackfriday/v2 +# github.com/safchain/ethtool v0.3.0 +## explicit; go 1.16 +github.com/safchain/ethtool # github.com/shopspring/decimal v1.2.0 ## explicit; go 1.13 github.com/shopspring/decimal