pax_global_header00006660000000000000000000000064150160346510014513gustar00rootroot0000000000000052 comment=f9520b6bab4075e514291a1f7e3839e88eab35bc ethtool-0.6.1/000077500000000000000000000000001501603465100131755ustar00rootroot00000000000000ethtool-0.6.1/.github/000077500000000000000000000000001501603465100145355ustar00rootroot00000000000000ethtool-0.6.1/.github/dependabot.yml000066400000000000000000000006521501603465100173700ustar00rootroot00000000000000# To get started with Dependabot version updates, you'll need to specify which # package ecosystems to update and where the package manifests are located. # Please see the documentation for all configuration options: # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates version: 2 updates: - package-ecosystem: gomod directory: / schedule: interval: weekly ethtool-0.6.1/.github/workflows/000077500000000000000000000000001501603465100165725ustar00rootroot00000000000000ethtool-0.6.1/.github/workflows/golangci-lint.yml000066400000000000000000000007121501603465100220440ustar00rootroot00000000000000name: golangci-lint on: push: branches: - main - master pull_request: branches: - main - master permissions: contents: read jobs: golangci: name: lint runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-go@v5 with: go-version: stable - name: golangci-lint uses: golangci/golangci-lint-action@v7 with: version: v2.0 ethtool-0.6.1/.github/workflows/unittests.yml000066400000000000000000000007511501603465100213620ustar00rootroot00000000000000name: "Unit tests" run-name: ${{ github.actor }} is testing ethtool 🚀 on: [push, pull_request] jobs: unittests: runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v4 - name: Setup Go uses: actions/setup-go@v5 with: go-version: '1.24.2' - uses: ibiqlik/action-yamllint@v3 with: format: auto - name: Run unit tests run: | go test -v -test.short ./... ethtool-0.6.1/.gitignore000066400000000000000000000005001501603465100151600ustar00rootroot00000000000000# 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 ethtool-0.6.1/.golangci.yml000066400000000000000000000011021501603465100155530ustar00rootroot00000000000000version: "2" linters: enable: - gocritic - misspell - staticcheck - errcheck exclusions: generated: lax presets: - comments - common-false-positives - legacy - std-error-handling paths: - third_party$ - builtin$ - examples$ formatters: enable: - gci - gofmt - goimports settings: gci: sections: - standard - default - prefix(github.com/safchain/ethtool) exclusions: generated: lax paths: - third_party$ - builtin$ - examples$ ethtool-0.6.1/.yamllint000066400000000000000000000001271501603465100150270ustar00rootroot00000000000000--- extends: default rules: document-start: disable truthy: check-keys: false ethtool-0.6.1/LICENSE000066400000000000000000000261321501603465100142060ustar00rootroot00000000000000 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 (c) 2015 The Ethtool Authors 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. ethtool-0.6.1/Makefile000066400000000000000000000001641501603465100146360ustar00rootroot00000000000000all: build build: CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build ethtool-0.6.1/README.md000066400000000000000000000031511501603465100144540ustar00rootroot00000000000000# 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. ethtool-0.6.1/ethtool.go000066400000000000000000001113211501603465100152010ustar00rootroot00000000000000/* * * 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" "sync" "time" "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_PRIV_FLAGS = 2 ETH_SS_FEATURES = 4 // CMD supported ETHTOOL_GSET = 0x00000001 /* Get settings. */ ETHTOOL_SSET = 0x00000002 /* Set settings. */ ETHTOOL_GWOL = 0x00000005 /* Get wake-on-lan options. */ ETHTOOL_SWOL = 0x00000006 /* Set wake-on-lan options. */ ETHTOOL_GDRVINFO = 0x00000003 /* Get driver info. */ ETHTOOL_GMSGLVL = 0x00000007 /* Get driver message level */ ETHTOOL_SMSGLVL = 0x00000008 /* Set driver msg level. */ ETHTOOL_GLINKSETTINGS = unix.ETHTOOL_GLINKSETTINGS // 0x4c ETHTOOL_SLINKSETTINGS = unix.ETHTOOL_SLINKSETTINGS // 0x4d // 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_GCOALESCE = 0x0000000e /* Get coalesce config */ ETHTOOL_SCOALESCE = 0x0000000f /* Set coalesce config */ ETHTOOL_GRINGPARAM = 0x00000010 /* Get ring parameters */ ETHTOOL_SRINGPARAM = 0x00000011 /* Set ring parameters. */ ETHTOOL_GPAUSEPARAM = 0x00000012 /* Get pause parameters */ ETHTOOL_SPAUSEPARAM = 0x00000013 /* Set pause parameters. */ ETHTOOL_GSTRINGS = 0x0000001b /* Get specified string set */ ETHTOOL_PHYS_ID = 0x0000001c /* Identify the NIC */ ETHTOOL_GSTATS = 0x0000001d /* Get NIC-specific statistics */ ETHTOOL_GPERMADDR = 0x00000020 /* Get permanent hardware address */ ETHTOOL_GFLAGS = 0x00000025 /* Get flags bitmap(ethtool_value) */ ETHTOOL_GPFLAGS = 0x00000027 /* Get driver-private flags bitmap */ ETHTOOL_SPFLAGS = 0x00000028 /* Set driver-private flags bitmap */ ETHTOOL_GSSET_INFO = 0x00000037 /* Get string set info */ ETHTOOL_GFEATURES = 0x0000003a /* Get device offload settings */ ETHTOOL_SFEATURES = 0x0000003b /* Change device offload settings */ ETHTOOL_GCHANNELS = 0x0000003c /* Get no of channels */ ETHTOOL_SCHANNELS = 0x0000003d /* Set no of channels */ ETHTOOL_GET_TS_INFO = 0x00000041 /* Get time stamping and PHC info */ ETHTOOL_GMODULEINFO = 0x00000042 /* Get plug-in module information */ ETHTOOL_GMODULEEEPROM = 0x00000043 /* Get plug-in module eeprom */ ETHTOOL_GRXFHINDIR = 0x00000038 /* Get RX flow hash indir'n table */ ETHTOOL_SRXFHINDIR = 0x00000039 /* Set RX flow hash indir'n table */ ETH_RXFH_INDIR_NO_CHANGE = 0xFFFFFFFF // Speed and Duplex unknowns/constants (Manually defined based on ) SPEED_UNKNOWN = 0xffffffff // ((__u32)-1) SPEED_UNKNOWN DUPLEX_HALF = 0x00 // DUPLEX_HALF DUPLEX_FULL = 0x01 // DUPLEX_FULL DUPLEX_UNKNOWN = 0xff // DUPLEX_UNKNOWN // Port types (Manually defined based on ) PORT_TP = 0x00 // PORT_TP PORT_AUI = 0x01 // PORT_AUI PORT_MII = 0x02 // PORT_MII PORT_FIBRE = 0x03 // PORT_FIBRE PORT_BNC = 0x04 // PORT_BNC PORT_DA = 0x05 // PORT_DA PORT_NONE = 0xef // PORT_NONE PORT_OTHER = 0xff // PORT_OTHER // Autoneg settings (Manually defined based on ) AUTONEG_DISABLE = 0x00 // AUTONEG_DISABLE AUTONEG_ENABLE = 0x01 // AUTONEG_ENABLE // MDIX states (Manually defined based on ) ETH_TP_MDI_INVALID = 0x00 // ETH_TP_MDI_INVALID ETH_TP_MDI = 0x01 // ETH_TP_MDI ETH_TP_MDI_X = 0x02 // ETH_TP_MDI_X ETH_TP_MDI_AUTO = 0x03 // Control value ETH_TP_MDI_AUTO // Link mode mask bits count (Manually defined based on ethtool.h) ETHTOOL_LINK_MODE_MASK_NBITS = 92 // __ETHTOOL_LINK_MODE_MASK_NBITS // Calculate max nwords based on NBITS using the manually defined constant MAX_LINK_MODE_MASK_NWORDS = (ETHTOOL_LINK_MODE_MASK_NBITS + 31) / 32 // = 3 ) // 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 ) // ethtool sset_info related constants const ( MAX_SSET_INFO = 64 ) const ( DEFAULT_BLINK_DURATION = 60 * time.Second ) var ( gstringsPool = sync.Pool{ New: func() interface{} { // new() will allocate and zero-initialize the struct. // The large data array within ethtoolGStrings will be zeroed. return new(EthtoolGStrings) }, } statsPool = sync.Pool{ New: func() interface{} { // new() will allocate and zero-initialize the struct. // The large data array within ethtoolStats will be zeroed. return new(EthtoolStats) }, } ) 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 uint64 data [MAX_SSET_INFO]uint32 } 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 } // IdentityConf is an identity config for an interface type IdentityConf struct { Cmd uint32 Duration uint32 } // WoL options const ( WAKE_PHY = 1 << 0 WAKE_UCAST = 1 << 1 WAKE_MCAST = 1 << 2 WAKE_BCAST = 1 << 3 WAKE_ARP = 1 << 4 WAKE_MAGIC = 1 << 5 WAKE_MAGICSECURE = 1 << 6 // only meaningful if WAKE_MAGIC ) var WoLMap = map[uint32]string{ WAKE_PHY: "p", // Wake on PHY activity WAKE_UCAST: "u", // Wake on unicast messages WAKE_MCAST: "m", // Wake on multicast messages WAKE_BCAST: "b", // Wake on broadcast messages WAKE_ARP: "a", // Wake on ARP WAKE_MAGIC: "g", // Wake on MagicPacket™ WAKE_MAGICSECURE: "s", // Enable SecureOn™ password for MagicPacket™ // f Wake on filter(s) // d Disable (wake on nothing). This option clears all previous options. } // WakeOnLan contains WoL config for an interface type WakeOnLan struct { Cmd uint32 // ETHTOOL_GWOL or ETHTOOL_SWOL Supported uint32 // r/o bitmask of WAKE_* flags for supported WoL modes Opts uint32 // Bitmask of WAKE_* flags for enabled WoL modes } // Timestamping options // see: https://www.kernel.org/doc/Documentation/networking/timestamping.txt const ( SOF_TIMESTAMPING_TX_HARDWARE = (1 << 0) /* Request tx timestamps generated by the network adapter. */ SOF_TIMESTAMPING_TX_SOFTWARE = (1 << 1) /* Request tx timestamps when data leaves the kernel. */ SOF_TIMESTAMPING_RX_HARDWARE = (1 << 2) /* Request rx timestamps generated by the network adapter. */ SOF_TIMESTAMPING_RX_SOFTWARE = (1 << 3) /* Request rx timestamps when data enters the kernel. */ SOF_TIMESTAMPING_SOFTWARE = (1 << 4) /* Report any software timestamps when available. */ SOF_TIMESTAMPING_SYS_HARDWARE = (1 << 5) /* This option is deprecated and ignored. */ SOF_TIMESTAMPING_RAW_HARDWARE = (1 << 6) /* Report hardware timestamps. */ SOF_TIMESTAMPING_OPT_ID = (1 << 7) /* Generate a unique identifier along with each packet. */ SOF_TIMESTAMPING_TX_SCHED = (1 << 8) /* Request tx timestamps prior to entering the packet scheduler. */ SOF_TIMESTAMPING_TX_ACK = (1 << 9) /* Request tx timestamps when all data in the send buffer has been acknowledged. */ SOF_TIMESTAMPING_OPT_CMSG = (1 << 10) /* Support recv() cmsg for all timestamped packets. */ SOF_TIMESTAMPING_OPT_TSONLY = (1 << 11) /* Applies to transmit timestamps only. */ SOF_TIMESTAMPING_OPT_STATS = (1 << 12) /* Optional stats that are obtained along with the transmit timestamps. */ SOF_TIMESTAMPING_OPT_PKTINFO = (1 << 13) /* Enable the SCM_TIMESTAMPING_PKTINFO control message for incoming packets with hardware timestamps. */ SOF_TIMESTAMPING_OPT_TX_SWHW = (1 << 14) /* Request both hardware and software timestamps for outgoing packets when SOF_TIMESTAMPING_TX_HARDWARE and SOF_TIMESTAMPING_TX_SOFTWARE are enabled at the same time. */ SOF_TIMESTAMPING_BIND_PHC = (1 << 15) /* Bind the socket to a specific PTP Hardware Clock. */ ) 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 */ ) // TimestampingInformation contains PTP timetstapming information 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 } // Ring is a ring config for an interface type Ring struct { Cmd uint32 RxMaxPending uint32 RxMiniMaxPending uint32 RxJumboMaxPending uint32 TxMaxPending uint32 RxPending uint32 RxMiniPending uint32 RxJumboPending uint32 TxPending uint32 } // Pause is a pause config for an interface type Pause struct { Cmd uint32 Autoneg uint32 RxPause uint32 TxPause uint32 } // Ethtool is a struct that contains the file descriptor for the ethtool type Ethtool struct { fd int } // max values for my setup dont know how to make this dynamic const MAX_INDIR_SIZE = 256 const MAX_CORES = 32 type Indir struct { Cmd uint32 Size uint32 RingIndex [MAX_INDIR_SIZE]uint32 // statically definded otherwise crash } type SetIndir struct { Equal uint8 // used to set number of cores Weight []uint32 // used to select cores } // 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 } // ModuleEepromHex returns Eeprom information as hexadecimal string 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 } // GetIndir retrieves the indirection table of the given interface name. func (e *Ethtool) GetIndir(intf string) (Indir, error) { indir, err := e.getIndir(intf) if err != nil { return Indir{}, err } return indir, nil } // SetIndir sets the indirection table of the given interface from the SetIndir struct func (e *Ethtool) SetIndir(intf string, setIndir SetIndir) (Indir, error) { if setIndir.Equal != 0 && setIndir.Weight != nil { return Indir{}, fmt.Errorf("equal and weight options are mutually exclusive") } indir, err := e.GetIndir(intf) if err != nil { return Indir{}, err } newindir, err := e.setIndir(intf, indir, setIndir) if err != nil { return Indir{}, err } return newindir, 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 } // SetCoalesce sets the coalesce config for the given interface name. func (e *Ethtool) SetCoalesce(intf string, coalesce Coalesce) (Coalesce, error) { coalesce, err := e.setCoalesce(intf, coalesce) 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 } // GetWakeOnLan returns the WoL config for the given interface name. func (e *Ethtool) GetWakeOnLan(intf string) (WakeOnLan, error) { wol := WakeOnLan{ Cmd: ETHTOOL_GWOL, } if err := e.ioctl(intf, uintptr(unsafe.Pointer(&wol))); err != nil { return WakeOnLan{}, err } return wol, nil } // SetWakeOnLan sets the WoL config for the given interface name and // returns the new WoL config. func (e *Ethtool) SetWakeOnLan(intf string, wol WakeOnLan) (WakeOnLan, error) { wol.Cmd = ETHTOOL_SWOL if err := e.ioctl(intf, uintptr(unsafe.Pointer(&wol))); err != nil { return WakeOnLan{}, err } return wol, 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 } // parsing of do_grxfhindir from ethtool.c func (e *Ethtool) getIndir(intf string) (Indir, error) { indir_head := Indir{ Cmd: ETHTOOL_GRXFHINDIR, Size: 0, } if err := e.ioctl(intf, uintptr(unsafe.Pointer(&indir_head))); err != nil { return Indir{}, err } indir := Indir{ Cmd: ETHTOOL_GRXFHINDIR, Size: indir_head.Size, } if err := e.ioctl(intf, uintptr(unsafe.Pointer(&indir))); err != nil { return Indir{}, err } return indir, nil } // parsing of do_srxfhindir from ethtool.c func (e *Ethtool) setIndir(intf string, indir Indir, setIndir SetIndir) (Indir, error) { err := fillIndirTable(&indir.Size, indir.RingIndex[:], 0, 0, int(setIndir.Equal), setIndir.Weight, uint32(len(setIndir.Weight))) if err != nil { return Indir{}, err } if indir.Size == ETH_RXFH_INDIR_NO_CHANGE { indir.Size = MAX_INDIR_SIZE return indir, nil } indir.Cmd = ETHTOOL_SRXFHINDIR if err := e.ioctl(intf, uintptr(unsafe.Pointer(&indir))); err != nil { return Indir{}, err } return indir, nil } func fillIndirTable(indirSize *uint32, indir []uint32, rxfhindirDefault int, rxfhindirStart int, rxfhindirEqual int, rxfhindirWeight []uint32, numWeights uint32) error { switch { case rxfhindirEqual != 0: for i := uint32(0); i < *indirSize; i++ { indir[i] = uint32(rxfhindirStart) + (i % uint32(rxfhindirEqual)) } case rxfhindirWeight != nil: var sum, partial uint32 = 0, 0 var j, weight uint32 for j = range numWeights { weight = rxfhindirWeight[j] sum += weight } if sum == 0 { return fmt.Errorf("at least one weight must be non-zero") } if sum > *indirSize { return fmt.Errorf("total weight exceeds the size of the indirection table") } j = ^uint32(0) // equivalent to -1 for unsigned for i := uint32(0); i < *indirSize; i++ { for i >= (*indirSize*partial)/sum { j++ weight = rxfhindirWeight[j] partial += weight } indir[i] = uint32(rxfhindirStart) + j } case rxfhindirDefault != 0: *indirSize = 0 default: *indirSize = ETH_RXFH_INDIR_NO_CHANGE } return 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) setCoalesce(intf string, coalesce Coalesce) (Coalesce, error) { coalesce.Cmd = ETHTOOL_SCOALESCE 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 } // GetRing retrieves ring parameters of the given interface name. func (e *Ethtool) GetRing(intf string) (Ring, error) { ring := Ring{ Cmd: ETHTOOL_GRINGPARAM, } if err := e.ioctl(intf, uintptr(unsafe.Pointer(&ring))); err != nil { return Ring{}, err } return ring, nil } // SetRing sets ring parameters of the given interface name. func (e *Ethtool) SetRing(intf string, ring Ring) (Ring, error) { ring.Cmd = ETHTOOL_SRINGPARAM if err := e.ioctl(intf, uintptr(unsafe.Pointer(&ring))); err != nil { return Ring{}, err } return ring, nil } // GetPause retrieves pause parameters of the given interface name. func (e *Ethtool) GetPause(intf string) (Pause, error) { pause := Pause{ Cmd: ETHTOOL_GPAUSEPARAM, } if err := e.ioctl(intf, uintptr(unsafe.Pointer(&pause))); err != nil { return Pause{}, err } return pause, nil } // SetPause sets pause parameters of the given interface name. func (e *Ethtool) SetPause(intf string, pause Pause) (Pause, error) { pause.Cmd = ETHTOOL_SPAUSEPARAM if err := e.ioctl(intf, uintptr(unsafe.Pointer(&pause))); err != nil { return Pause{}, err } return pause, nil } func isFeatureBitSet(blocks [MAX_FEATURE_BLOCKS]ethtoolGetFeaturesBlock, index uint) bool { return (blocks)[index/32].active&(1<<(index%32)) != 0 } // FeatureState contains the state of a feature. type FeatureState struct { Available bool Requested bool Active bool NeverChanged bool } func getFeatureStateBits(blocks [MAX_FEATURE_BLOCKS]ethtoolGetFeaturesBlock, index uint) FeatureState { return FeatureState{ Available: (blocks)[index/32].available&(1<<(index%32)) != 0, Requested: (blocks)[index/32].requested&(1<<(index%32)) != 0, Active: (blocks)[index/32].active&(1<<(index%32)) != 0, NeverChanged: (blocks)[index/32].never_changed&(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) } } func (e *Ethtool) getNames(intf string, mask int) (map[string]uint, error) { ssetInfo := ethtoolSsetInfo{ cmd: ETHTOOL_GSSET_INFO, sset_mask: 1 << mask, data: [MAX_SSET_INFO]uint32{}, } if err := e.ioctl(intf, uintptr(unsafe.Pointer(&ssetInfo))); err != nil { return nil, err } /* we only read data on first index because single bit was set in sset_mask(0x10) */ length := ssetInfo.data[0] 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: uint32(mask), len: length, data: [MAX_GSTRINGS * ETH_GSTRING_LEN]byte{}, } if err := e.ioctl(intf, uintptr(unsafe.Pointer(&gstrings))); err != nil { return nil, err } 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 } // FeatureNames shows supported features by their name. func (e *Ethtool) FeatureNames(intf string) (map[string]uint, error) { return e.getNames(intf, ETH_SS_FEATURES) } // 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 } result := make(map[string]bool, length) for key, index := range names { result[key] = isFeatureBitSet(features.blocks, index) } return result, nil } // FeaturesWithState retrieves features of the given interface name, // with extra flags to explain if they can be enabled func (e *Ethtool) FeaturesWithState(intf string) (map[string]FeatureState, error) { names, err := e.FeatureNames(intf) if err != nil { return nil, err } length := uint32(len(names)) if length == 0 { return map[string]FeatureState{}, 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]FeatureState, length) for key, index := range names { result[key] = getFeatureStateBits(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))) } // PrivFlagsNames shows supported private flags by their name. func (e *Ethtool) PrivFlagsNames(intf string) (map[string]uint, error) { return e.getNames(intf, ETH_SS_PRIV_FLAGS) } // PrivFlags retrieves private flags of the given interface name. func (e *Ethtool) PrivFlags(intf string) (map[string]bool, error) { names, err := e.PrivFlagsNames(intf) if err != nil { return nil, err } length := uint32(len(names)) if length == 0 { return map[string]bool{}, nil } var val ethtoolLink val.cmd = ETHTOOL_GPFLAGS if err := e.ioctl(intf, uintptr(unsafe.Pointer(&val))); err != nil { return nil, err } result := make(map[string]bool, length) for name, mask := range names { result[name] = val.data&(1< MAX_GSTRINGS { return nil, fmt.Errorf("ethtool currently doesn't support more than %d entries, received %d", MAX_GSTRINGS, drvinfo.n_stats) } gstringsPtr.cmd = ETHTOOL_GSTRINGS gstringsPtr.string_set = ETH_SS_STATS gstringsPtr.len = drvinfo.n_stats if err := e.ioctl(intf, uintptr(unsafe.Pointer(gstringsPtr))); err != nil { return nil, err } statsPtr.cmd = ETHTOOL_GSTATS statsPtr.n_stats = drvinfo.n_stats if err := e.ioctl(intf, uintptr(unsafe.Pointer(statsPtr))); err != nil { return nil, err } result := make(map[string]uint64, drvinfo.n_stats) for i := 0; i != int(drvinfo.n_stats); i++ { b := gstringsPtr.data[i*ETH_GSTRING_LEN : (i+1)*ETH_GSTRING_LEN] strEnd := bytes.IndexByte(b, 0) if strEnd == -1 { strEnd = ETH_GSTRING_LEN } key := string(b[:strEnd]) if len(key) != 0 { result[key] = statsPtr.data[i] } } return result, nil } // Close closes the ethool handler func (e *Ethtool) Close() { unix.Close(e.fd) } // Identity the nic with blink duration, if not specify blink for 60 seconds func (e *Ethtool) Identity(intf string, duration *time.Duration) error { dur := uint32(DEFAULT_BLINK_DURATION.Seconds()) if duration != nil { dur = uint32(duration.Seconds()) } return e.identity(intf, IdentityConf{Duration: dur}) } func (e *Ethtool) identity(intf string, identity IdentityConf) error { identity.Cmd = ETHTOOL_PHYS_ID return e.ioctl(intf, uintptr(unsafe.Pointer(&identity))) } // NewEthtool returns a new ethtool handler func NewEthtool() (*Ethtool, error) { fd, err := unix.Socket(unix.AF_INET, unix.SOCK_DGRAM|unix.SOCK_CLOEXEC, 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) } // Identity the nic with blink duration, if not specify blink infinity func Identity(intf string, duration *time.Duration) error { e, err := NewEthtool() if err != nil { return err } defer e.Close() return e.Identity(intf, duration) } func supportedSpeeds(mask uint64) (ret []struct { name string mask uint64 speed uint64 }) { for _, mode := range supportedCapabilities { if mode.speed > 0 && ((1< ret { ret = mode.speed } } return ret } ethtool-0.6.1/ethtool_cmd.go000066400000000000000000000116271501603465100160340ustar00rootroot00000000000000/* * * 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" ) // EthtoolCmd is the Go version of the Linux kerne ethtool_cmd struct // see ethtool.c type EthtoolCmd struct { 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() switch tt := t.(type) { case uint32: retv[typeField.Name] = uint64(tt) case uint16: retv[typeField.Name] = uint64(tt) case uint8: retv[typeField.Name] = uint64(tt) case int32: retv[typeField.Name] = uint64(tt) case int16: retv[typeField.Name] = uint64(tt) case int8: retv[typeField.Name] = uint64(tt) default: retv[typeField.Name+"_unknown_type"] = 0 } } } // 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(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(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 } result := make(map[string]uint64) // ref https://gist.github.com/drewolson/4771479 // Golang Reflection Example ecmd.reflect(result) var speedval = (uint32(ecmd.Speed_hi) << 16) | (uint32(ecmd.Speed) & 0xffff) result["speed"] = uint64(speedval) return result, nil } // CmdGetMapped returns the interface settings in a map func CmdGetMapped(intf string) (map[string]uint64, error) { e, err := NewEthtool() if err != nil { return nil, err } defer e.Close() return e.CmdGetMapped(intf) } ethtool-0.6.1/ethtool_cmd_test.go000066400000000000000000000031251501603465100170650ustar00rootroot00000000000000/* * * 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 import ( "net" "testing" ) func TestCmdGet(t *testing.T) { intfs, err := net.Interfaces() if err != nil { t.Fatal(err) } // we expected to have at least one success success := false for _, intf := range intfs { var ecmd EthtoolCmd _, err := ecmd.CmdGet(intf.Name) if err == nil { success = true } } if !success { t.Fatal("Unable to get settings from any interface of this system.") } } func TestCmdGetMapped(t *testing.T) { intfs, err := net.Interfaces() if err != nil { t.Fatal(err) } // we expected to have at least one success success := false for _, intf := range intfs { _, err := CmdGetMapped(intf.Name) if err == nil { success = true } } if !success { t.Fatal("Unable to get settings map from any interface of this system.") } } ethtool-0.6.1/ethtool_darwin.go000066400000000000000000000016751501603465100165570ustar00rootroot00000000000000/* * * 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 var supportedCapabilities = []struct { name string mask uint64 speed uint64 }{ // no supported capabilities on darwin } ethtool-0.6.1/ethtool_link_settings.go000066400000000000000000000273671501603465100201560ustar00rootroot00000000000000package ethtool import ( "errors" "fmt" "math" "strings" "syscall" "unsafe" "golang.org/x/sys/unix" ) type LinkSettingSource string // Constants defining the source of the LinkSettings data const ( SourceGLinkSettings LinkSettingSource = "GLINKSETTINGS" SourceGSet LinkSettingSource = "GSET" ) // EthtoolLinkSettingsFixed corresponds to struct ethtool_link_settings fixed part type EthtoolLinkSettingsFixed struct { Cmd uint32 Speed uint32 Duplex uint8 Port uint8 PhyAddress uint8 Autoneg uint8 MdixSupport uint8 // Renamed from mdio_support EthTpMdix uint8 EthTpMdixCtrl uint8 LinkModeMasksNwords int8 Transceiver uint8 MasterSlaveCfg uint8 MasterSlaveState uint8 Reserved1 [1]byte Reserved [7]uint32 // Flexible array member link_mode_masks[0] starts here implicitly } // ethtoolLinkSettingsRequest includes space for the flexible array members type ethtoolLinkSettingsRequest struct { Settings EthtoolLinkSettingsFixed Masks [3 * MAX_LINK_MODE_MASK_NWORDS]uint32 // Uses MAX_LINK_MODE_MASK_NWORDS constant from ethtool.go } // LinkSettings is the user-friendly representation returned by GetLinkSettings type LinkSettings struct { Speed uint32 Duplex uint8 Port uint8 PhyAddress uint8 Autoneg uint8 MdixSupport uint8 EthTpMdix uint8 EthTpMdixCtrl uint8 Transceiver uint8 MasterSlaveCfg uint8 MasterSlaveState uint8 SupportedLinkModes []string AdvertisingLinkModes []string LpAdvertisingModes []string Source LinkSettingSource // "GSET" or "GLINKSETTINGS" } // GetLinkSettings retrieves link settings, preferring ETHTOOL_GLINKSETTINGS and falling back to ETHTOOL_GSET. // Uses a single ioctl call with the maximum expected buffer size. func (e *Ethtool) GetLinkSettings(intf string) (*LinkSettings, error) { // 1. Attempt ETHTOOL_GLINKSETTINGS with max buffer size var req ethtoolLinkSettingsRequest req.Settings.Cmd = ETHTOOL_GLINKSETTINGS // Provide the maximum expected nwords based on our constant req.Settings.LinkModeMasksNwords = int8(MAX_LINK_MODE_MASK_NWORDS) err := e.ioctl(intf, uintptr(unsafe.Pointer(&req))) fallbackReason := "" var errno syscall.Errno switch { case errors.As(err, &errno) && errors.Is(errno, unix.EOPNOTSUPP): // Condition 1: ioctl returned EOPNOTSUPP fallbackReason = "EOPNOTSUPP" case err == nil: // Condition 2: ioctl succeeded, but nwords might be invalid or buffer too small nwords := int(req.Settings.LinkModeMasksNwords) switch { case nwords <= 0 || nwords > MAX_LINK_MODE_MASK_NWORDS: // Sub-case 2a: Invalid nwords -> fallback fmt.Printf("Warning: GLINKSETTINGS succeeded but returned invalid nwords (%d), attempting fallback to GSET\n", nwords) fallbackReason = "invalid nwords from GLINKSETTINGS" case 3*nwords > len(req.Masks): // Sub-case 2b: Buffer too small -> error return nil, fmt.Errorf("kernel requires %d words for GLINKSETTINGS, buffer only has space for %d (max %d)", nwords, len(req.Masks)/3, MAX_LINK_MODE_MASK_NWORDS) default: // Sub-case 2c: Success (nwords valid and buffer sufficient) results := &LinkSettings{ Speed: req.Settings.Speed, Duplex: req.Settings.Duplex, Port: req.Settings.Port, PhyAddress: req.Settings.PhyAddress, Autoneg: req.Settings.Autoneg, MdixSupport: req.Settings.MdixSupport, EthTpMdix: req.Settings.EthTpMdix, EthTpMdixCtrl: req.Settings.EthTpMdixCtrl, Transceiver: req.Settings.Transceiver, MasterSlaveCfg: req.Settings.MasterSlaveCfg, MasterSlaveState: req.Settings.MasterSlaveState, SupportedLinkModes: parseLinkModeMasks(req.Masks[0*nwords : 1*nwords]), AdvertisingLinkModes: parseLinkModeMasks(req.Masks[1*nwords : 2*nwords]), LpAdvertisingModes: parseLinkModeMasks(req.Masks[2*nwords : 3*nwords]), Source: SourceGLinkSettings, } return results, nil } default: // Condition 3: ioctl failed with an error other than EOPNOTSUPP // No fallback in this case. return nil, fmt.Errorf("ETHTOOL_GLINKSETTINGS ioctl failed: %w", err) } // Fallback to ETHTOOL_GSET using e.CmdGet var cmd EthtoolCmd _, errGet := e.CmdGet(&cmd, intf) if errGet != nil { return nil, fmt.Errorf("ETHTOOL_GLINKSETTINGS failed (%s), fallback ETHTOOL_GSET (CmdGet) also failed: %w", fallbackReason, errGet) } results := convertCmdToLinkSettings(&cmd) results.Source = SourceGSet return results, nil } // SetLinkSettings applies link settings, determining whether to use ETHTOOL_SLINKSETTINGS or ETHTOOL_SSET. func (e *Ethtool) SetLinkSettings(intf string, settings *LinkSettings) error { var checkReq ethtoolLinkSettingsRequest checkReq.Settings.Cmd = ETHTOOL_GLINKSETTINGS checkReq.Settings.LinkModeMasksNwords = int8(MAX_LINK_MODE_MASK_NWORDS) errGLinkSettings := e.ioctl(intf, uintptr(unsafe.Pointer(&checkReq))) canUseGLinkSettings := false nwords := 0 if errGLinkSettings == nil { nwords = int(checkReq.Settings.LinkModeMasksNwords) if nwords <= 0 || nwords > MAX_LINK_MODE_MASK_NWORDS { return fmt.Errorf("ETHTOOL_GLINKSETTINGS check succeeded but returned invalid nwords: %d", nwords) } canUseGLinkSettings = true } else { var errno syscall.Errno if !errors.As(errGLinkSettings, &errno) || !errors.Is(errno, unix.EOPNOTSUPP) { return fmt.Errorf("checking support via ETHTOOL_GLINKSETTINGS failed: %w", errGLinkSettings) } } if canUseGLinkSettings { var setReq ethtoolLinkSettingsRequest if 3*nwords > len(setReq.Masks) { return fmt.Errorf("internal error: required nwords (%d) exceeds allocated buffer (%d)", nwords, MAX_LINK_MODE_MASK_NWORDS) } setReq.Settings.Cmd = ETHTOOL_SLINKSETTINGS setReq.Settings.Speed = settings.Speed setReq.Settings.Duplex = settings.Duplex setReq.Settings.Port = settings.Port setReq.Settings.PhyAddress = settings.PhyAddress setReq.Settings.Autoneg = settings.Autoneg setReq.Settings.EthTpMdixCtrl = settings.EthTpMdixCtrl setReq.Settings.MasterSlaveCfg = settings.MasterSlaveCfg setReq.Settings.LinkModeMasksNwords = int8(nwords) advertisingMask := buildLinkModeMask(settings.AdvertisingLinkModes, nwords) if len(advertisingMask) != nwords { return fmt.Errorf("failed to build advertising mask with correct size (%d != %d)", len(advertisingMask), nwords) } copy(setReq.Masks[nwords:2*nwords], advertisingMask) zeroMaskSupported := make([]uint32, nwords) zeroMaskLp := make([]uint32, nwords) copy(setReq.Masks[0*nwords:1*nwords], zeroMaskSupported) copy(setReq.Masks[2*nwords:3*nwords], zeroMaskLp) if err := e.ioctl(intf, uintptr(unsafe.Pointer(&setReq))); err != nil { return fmt.Errorf("ETHTOOL_SLINKSETTINGS ioctl failed: %w", err) } return nil } // Check if trying to set high bits when only SSET is available advertisingMaskCheck := buildLinkModeMask(settings.AdvertisingLinkModes, MAX_LINK_MODE_MASK_NWORDS) for i := 1; i < len(advertisingMaskCheck); i++ { if advertisingMaskCheck[i] != 0 { return fmt.Errorf("cannot set link modes beyond 32 bits using legacy ETHTOOL_SSET; device does not support ETHTOOL_SLINKSETTINGS") } } // Fallback to SSET cmd := convertLinkSettingsToCmd(settings) _, errSet := e.CmdSet(cmd, intf) if errSet != nil { return fmt.Errorf("ETHTOOL_SLINKSETTINGS not supported, fallback ETHTOOL_SSET (CmdSet) failed: %w", errSet) } return nil } // parseLinkModeMasks converts a slice of uint32 bitmasks to a list of mode names. // It filters out non-speed/duplex modes (like TP, Autoneg, Pause). func parseLinkModeMasks(mask []uint32) []string { modes := make([]string, 0, 8) for _, capability := range supportedCapabilities { // Only include capabilities that represent a speed/duplex mode if capability.speed > 0 { bitIndex := int(capability.mask) wordIndex := bitIndex / 32 bitInWord := uint(bitIndex % 32) if wordIndex < len(mask) && (mask[wordIndex]>>(bitInWord))&1 != 0 { modes = append(modes, capability.name) } } } return modes } // buildLinkModeMask converts a list of mode names back into a uint32 bitmask slice. // It filters out non-speed/duplex modes. func buildLinkModeMask(modes []string, nwords int) []uint32 { if nwords <= 0 || nwords > MAX_LINK_MODE_MASK_NWORDS { return make([]uint32, 0) } mask := make([]uint32, nwords) modeMap := make(map[string]struct { bitIndex int speed uint64 }) for _, capability := range supportedCapabilities { // Only consider capabilities that represent a speed/duplex mode if capability.speed > 0 { modeMap[capability.name] = struct { bitIndex int speed uint64 }{bitIndex: int(capability.mask), speed: capability.speed} } } for _, modeName := range modes { if info, ok := modeMap[strings.TrimSpace(modeName)]; ok { wordIndex := info.bitIndex / 32 bitInWord := uint(info.bitIndex % 32) if wordIndex < nwords { mask[wordIndex] |= 1 << bitInWord } else { fmt.Printf("Warning: Link mode '%s' (bit %d) exceeds device's mask size (%d words)\n", modeName, info.bitIndex, nwords) } } else { // Check if the user provided a non-speed mode name - ignore it for the mask, maybe warn? isKnownNonSpeed := false for _, capability := range supportedCapabilities { if capability.speed == 0 && capability.name == strings.TrimSpace(modeName) { isKnownNonSpeed = true break } } if !isKnownNonSpeed { fmt.Printf("Warning: Unknown link mode '%s' specified for mask building\n", modeName) } // Silently ignore known non-speed modes like Autoneg, TP, Pause for the mask } } return mask } // convertCmdToLinkSettings converts data from the legacy EthtoolCmd to the new LinkSettings format. func convertCmdToLinkSettings(cmd *EthtoolCmd) *LinkSettings { ls := &LinkSettings{ Speed: (uint32(cmd.Speed_hi) << 16) | uint32(cmd.Speed), Duplex: cmd.Duplex, Port: cmd.Port, PhyAddress: cmd.Phy_address, Autoneg: cmd.Autoneg, MdixSupport: cmd.Mdio_support, EthTpMdix: cmd.Eth_tp_mdix, EthTpMdixCtrl: ETH_TP_MDI_INVALID, Transceiver: cmd.Transceiver, MasterSlaveCfg: 0, // No equivalent in EthtoolCmd MasterSlaveState: 0, // No equivalent in EthtoolCmd SupportedLinkModes: parseLegacyLinkModeMask(cmd.Supported), AdvertisingLinkModes: parseLegacyLinkModeMask(cmd.Advertising), LpAdvertisingModes: parseLegacyLinkModeMask(cmd.Lp_advertising), } if cmd.Speed == math.MaxUint16 && cmd.Speed_hi == math.MaxUint16 { ls.Speed = SPEED_UNKNOWN // GSET uses 0xFFFF/0xFFFF for unknown/auto } return ls } // parseLegacyLinkModeMask helper for converting single uint32 mask. func parseLegacyLinkModeMask(mask uint32) []string { return parseLinkModeMasks([]uint32{mask}) } // convertLinkSettingsToCmd converts new LinkSettings data back to the legacy EthtoolCmd format for SSET fallback. func convertLinkSettingsToCmd(ls *LinkSettings) *EthtoolCmd { cmd := &EthtoolCmd{} if ls.Speed == 0 || ls.Speed == SPEED_UNKNOWN { cmd.Speed = math.MaxUint16 cmd.Speed_hi = math.MaxUint16 } else { cmd.Speed = uint16(ls.Speed & 0xFFFF) cmd.Speed_hi = uint16((ls.Speed >> 16) & 0xFFFF) } cmd.Duplex = ls.Duplex cmd.Port = ls.Port cmd.Phy_address = ls.PhyAddress cmd.Autoneg = ls.Autoneg // Cannot set EthTpMdixCtrl via EthtoolCmd cmd.Transceiver = ls.Transceiver cmd.Advertising = buildLegacyLinkModeMask(ls.AdvertisingLinkModes) return cmd } // buildLegacyLinkModeMask helper for building single uint32 mask from names. func buildLegacyLinkModeMask(modes []string) uint32 { maskSlice := buildLinkModeMask(modes, 1) if len(maskSlice) > 0 { return maskSlice[0] } return 0 } ethtool-0.6.1/ethtool_link_settings_test.go000066400000000000000000000071001501603465100211740ustar00rootroot00000000000000package ethtool import ( "errors" "net" "reflect" "sort" "syscall" "testing" "golang.org/x/sys/unix" ) // TestGetLinkSettings attempts to get link settings for all non-loopback interfaces. // This serves as a basic integration test to ensure the function handles // real ioctl calls, including potential fallbacks, without crashing. // Asserting specific values is difficult as capabilities vary widely between interfaces and drivers. func TestGetLinkSettings(t *testing.T) { intfs, err := net.Interfaces() if err != nil { t.Fatal(err) } for _, intf := range intfs { intfName := intf.Name if intfName == "lo" { continue } e, err := NewEthtool() // Assumes NewEthtool() correctly gets a socket fd if err != nil { // Log error for this interface but continue testing others t.Errorf("Failed to create Ethtool instance for interface %s: %v", intfName, err) continue } defer e.Close() settings, err := e.GetLinkSettings(intfName) // We expect either success (returning some data, possibly indicating 'unknown') // or a specific error like EOPNOTSUPP if the interface/driver // doesn't support either GLINKSETTINGS or GSET. if err != nil { var errno syscall.Errno if errors.As(err, &errno) { if errors.Is(errno, unix.EOPNOTSUPP) { // This is an expected outcome for some interfaces/drivers t.Logf("GetLinkSettings for '%s' returned EOPNOTSUPP (expected for some devices)", intfName) } else { // Report other unexpected errors t.Errorf("GetLinkSettings for '%s' failed with unexpected error: %v", intfName, err) } } else { // Non-syscall error t.Errorf("GetLinkSettings for '%s' failed with non-syscall error: %v", intfName, err) } } else { // If successful, check that the settings struct is not nil and Source is set if settings == nil { t.Errorf("GetLinkSettings for '%s' succeeded but returned nil settings", intfName) // Cannot continue checks if settings is nil continue } if settings.Source != SourceGLinkSettings && settings.Source != SourceGSet { t.Errorf("GetLinkSettings for '%s' succeeded but Source ('%s') is invalid", intfName, settings.Source) } t.Logf("GetLinkSettings for '%s' succeeded (Source: %s). Settings: %+v", intfName, settings.Source, settings) // Check SupportedLinkModes if settings.SupportedLinkModes == nil { t.Errorf("GetLinkSettings for '%s' succeeded but SupportedLinkModes is nil", intfName) } else { t.Logf("Interface '%s' supported modes: %v", intfName, settings.SupportedLinkModes) } // If source was GSET, verify the conversion logic if settings.Source == SourceGSet { var cmd EthtoolCmd _, errGet := e.CmdGet(&cmd, intfName) if errGet != nil { t.Errorf("Failed to re-run CmdGet for '%s' to verify GSET conversion: %v", intfName, errGet) } else { expectedModes := parseLegacyLinkModeMask(cmd.Supported) // Sort both slices for reliable comparison sort.Strings(expectedModes) actualModes := make([]string, len(settings.SupportedLinkModes)) copy(actualModes, settings.SupportedLinkModes) sort.Strings(actualModes) if !reflect.DeepEqual(actualModes, expectedModes) { t.Errorf("SupportedLinkModes mismatch for '%s' (Source: GSET). Got %v, expected %v (from raw CmdGet)", intfName, actualModes, expectedModes) } } } // Basic sanity checks if it succeeded (values might be 0 or unknown) if settings.Speed == SPEED_UNKNOWN { // SPEED_UNKNOWN defined in ethtool.go t.Logf("Interface '%s' reported speed as SPEED_UNKNOWN (0x%x)", intfName, SPEED_UNKNOWN) } } } } ethtool-0.6.1/ethtool_linux.go000066400000000000000000000263331501603465100164300ustar00rootroot00000000000000/* * * 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 import ( "golang.org/x/sys/unix" ) // Updated supportedCapabilities including modes from ethtool.h enum ethtool_link_mode_bit_indices var supportedCapabilities = []struct { name string mask uint64 // Use uint64 to accommodate indices > 31 speed uint64 // Speed in bps, 0 for non-speed modes }{ // Existing entries (reordered slightly by bit index for clarity) {"10baseT_Half", unix.ETHTOOL_LINK_MODE_10baseT_Half_BIT, 10_000_000}, // 0 {"10baseT_Full", unix.ETHTOOL_LINK_MODE_10baseT_Full_BIT, 10_000_000}, // 1 {"100baseT_Half", unix.ETHTOOL_LINK_MODE_100baseT_Half_BIT, 100_000_000}, // 2 {"100baseT_Full", unix.ETHTOOL_LINK_MODE_100baseT_Full_BIT, 100_000_000}, // 3 {"1000baseT_Half", unix.ETHTOOL_LINK_MODE_1000baseT_Half_BIT, 1_000_000_000}, // 4 {"1000baseT_Full", unix.ETHTOOL_LINK_MODE_1000baseT_Full_BIT, 1_000_000_000}, // 5 // Newly added or re-confirmed based on full enum {"Autoneg", unix.ETHTOOL_LINK_MODE_Autoneg_BIT, 0}, // 6 {"TP", unix.ETHTOOL_LINK_MODE_TP_BIT, 0}, // 7 (Twisted Pair port) {"AUI", unix.ETHTOOL_LINK_MODE_AUI_BIT, 0}, // 8 (AUI port) {"MII", unix.ETHTOOL_LINK_MODE_MII_BIT, 0}, // 9 (MII port) {"FIBRE", unix.ETHTOOL_LINK_MODE_FIBRE_BIT, 0}, // 10 (FIBRE port) {"BNC", unix.ETHTOOL_LINK_MODE_BNC_BIT, 0}, // 11 (BNC port) {"10000baseT_Full", unix.ETHTOOL_LINK_MODE_10000baseT_Full_BIT, 10_000_000_000}, // 12 {"Pause", unix.ETHTOOL_LINK_MODE_Pause_BIT, 0}, // 13 {"Asym_Pause", unix.ETHTOOL_LINK_MODE_Asym_Pause_BIT, 0}, // 14 {"2500baseX_Full", unix.ETHTOOL_LINK_MODE_2500baseX_Full_BIT, 2_500_000_000}, // 15 {"Backplane", unix.ETHTOOL_LINK_MODE_Backplane_BIT, 0}, // 16 (Backplane port) {"1000baseKX_Full", unix.ETHTOOL_LINK_MODE_1000baseKX_Full_BIT, 1_000_000_000}, // 17 {"10000baseKX4_Full", unix.ETHTOOL_LINK_MODE_10000baseKX4_Full_BIT, 10_000_000_000}, // 18 {"10000baseKR_Full", unix.ETHTOOL_LINK_MODE_10000baseKR_Full_BIT, 10_000_000_000}, // 19 {"10000baseR_FEC", unix.ETHTOOL_LINK_MODE_10000baseR_FEC_BIT, 10_000_000_000}, // 20 {"20000baseMLD2_Full", unix.ETHTOOL_LINK_MODE_20000baseMLD2_Full_BIT, 20_000_000_000}, // 21 {"20000baseKR2_Full", unix.ETHTOOL_LINK_MODE_20000baseKR2_Full_BIT, 20_000_000_000}, // 22 {"40000baseKR4_Full", unix.ETHTOOL_LINK_MODE_40000baseKR4_Full_BIT, 40_000_000_000}, // 23 {"40000baseCR4_Full", unix.ETHTOOL_LINK_MODE_40000baseCR4_Full_BIT, 40_000_000_000}, // 24 {"40000baseSR4_Full", unix.ETHTOOL_LINK_MODE_40000baseSR4_Full_BIT, 40_000_000_000}, // 25 {"40000baseLR4_Full", unix.ETHTOOL_LINK_MODE_40000baseLR4_Full_BIT, 40_000_000_000}, // 26 {"56000baseKR4_Full", unix.ETHTOOL_LINK_MODE_56000baseKR4_Full_BIT, 56_000_000_000}, // 27 {"56000baseCR4_Full", unix.ETHTOOL_LINK_MODE_56000baseCR4_Full_BIT, 56_000_000_000}, // 28 {"56000baseSR4_Full", unix.ETHTOOL_LINK_MODE_56000baseSR4_Full_BIT, 56_000_000_000}, // 29 {"56000baseLR4_Full", unix.ETHTOOL_LINK_MODE_56000baseLR4_Full_BIT, 56_000_000_000}, // 30 {"25000baseCR_Full", unix.ETHTOOL_LINK_MODE_25000baseCR_Full_BIT, 25_000_000_000}, // 31 // Modes beyond bit 31 (require GLINKSETTINGS) {"25000baseKR_Full", unix.ETHTOOL_LINK_MODE_25000baseKR_Full_BIT, 25_000_000_000}, // 32 {"25000baseSR_Full", unix.ETHTOOL_LINK_MODE_25000baseSR_Full_BIT, 25_000_000_000}, // 33 {"50000baseCR2_Full", unix.ETHTOOL_LINK_MODE_50000baseCR2_Full_BIT, 50_000_000_000}, // 34 {"50000baseKR2_Full", unix.ETHTOOL_LINK_MODE_50000baseKR2_Full_BIT, 50_000_000_000}, // 35 {"100000baseKR4_Full", unix.ETHTOOL_LINK_MODE_100000baseKR4_Full_BIT, 100_000_000_000}, // 36 {"100000baseSR4_Full", unix.ETHTOOL_LINK_MODE_100000baseSR4_Full_BIT, 100_000_000_000}, // 37 {"100000baseCR4_Full", unix.ETHTOOL_LINK_MODE_100000baseCR4_Full_BIT, 100_000_000_000}, // 38 {"100000baseLR4_ER4_Full", unix.ETHTOOL_LINK_MODE_100000baseLR4_ER4_Full_BIT, 100_000_000_000}, // 39 {"50000baseSR2_Full", unix.ETHTOOL_LINK_MODE_50000baseSR2_Full_BIT, 50_000_000_000}, // 40 {"1000baseX_Full", unix.ETHTOOL_LINK_MODE_1000baseX_Full_BIT, 1_000_000_000}, // 41 {"10000baseCR_Full", unix.ETHTOOL_LINK_MODE_10000baseCR_Full_BIT, 10_000_000_000}, // 42 {"10000baseSR_Full", unix.ETHTOOL_LINK_MODE_10000baseSR_Full_BIT, 10_000_000_000}, // 43 {"10000baseLR_Full", unix.ETHTOOL_LINK_MODE_10000baseLR_Full_BIT, 10_000_000_000}, // 44 {"10000baseLRM_Full", unix.ETHTOOL_LINK_MODE_10000baseLRM_Full_BIT, 10_000_000_000}, // 45 {"10000baseER_Full", unix.ETHTOOL_LINK_MODE_10000baseER_Full_BIT, 10_000_000_000}, // 46 {"2500baseT_Full", unix.ETHTOOL_LINK_MODE_2500baseT_Full_BIT, 2_500_000_000}, // 47 (already present but reconfirmed) {"5000baseT_Full", unix.ETHTOOL_LINK_MODE_5000baseT_Full_BIT, 5_000_000_000}, // 48 {"FEC_NONE", unix.ETHTOOL_LINK_MODE_FEC_NONE_BIT, 0}, // 49 {"FEC_RS", unix.ETHTOOL_LINK_MODE_FEC_RS_BIT, 0}, // 50 (Reed-Solomon FEC) {"FEC_BASER", unix.ETHTOOL_LINK_MODE_FEC_BASER_BIT, 0}, // 51 (BaseR FEC) {"50000baseKR_Full", unix.ETHTOOL_LINK_MODE_50000baseKR_Full_BIT, 50_000_000_000}, // 52 {"50000baseSR_Full", unix.ETHTOOL_LINK_MODE_50000baseSR_Full_BIT, 50_000_000_000}, // 53 {"50000baseCR_Full", unix.ETHTOOL_LINK_MODE_50000baseCR_Full_BIT, 50_000_000_000}, // 54 {"50000baseLR_ER_FR_Full", unix.ETHTOOL_LINK_MODE_50000baseLR_ER_FR_Full_BIT, 50_000_000_000}, // 55 {"50000baseDR_Full", unix.ETHTOOL_LINK_MODE_50000baseDR_Full_BIT, 50_000_000_000}, // 56 {"100000baseKR2_Full", unix.ETHTOOL_LINK_MODE_100000baseKR2_Full_BIT, 100_000_000_000}, // 57 {"100000baseSR2_Full", unix.ETHTOOL_LINK_MODE_100000baseSR2_Full_BIT, 100_000_000_000}, // 58 {"100000baseCR2_Full", unix.ETHTOOL_LINK_MODE_100000baseCR2_Full_BIT, 100_000_000_000}, // 59 {"100000baseLR2_ER2_FR2_Full", unix.ETHTOOL_LINK_MODE_100000baseLR2_ER2_FR2_Full_BIT, 100_000_000_000}, // 60 {"100000baseDR2_Full", unix.ETHTOOL_LINK_MODE_100000baseDR2_Full_BIT, 100_000_000_000}, // 61 {"200000baseKR4_Full", unix.ETHTOOL_LINK_MODE_200000baseKR4_Full_BIT, 200_000_000_000}, // 62 {"200000baseSR4_Full", unix.ETHTOOL_LINK_MODE_200000baseSR4_Full_BIT, 200_000_000_000}, // 63 {"200000baseLR4_ER4_FR4_Full", unix.ETHTOOL_LINK_MODE_200000baseLR4_ER4_FR4_Full_BIT, 200_000_000_000}, // 64 {"200000baseDR4_Full", unix.ETHTOOL_LINK_MODE_200000baseDR4_Full_BIT, 200_000_000_000}, // 65 {"200000baseCR4_Full", unix.ETHTOOL_LINK_MODE_200000baseCR4_Full_BIT, 200_000_000_000}, // 66 {"100baseT1_Full", unix.ETHTOOL_LINK_MODE_100baseT1_Full_BIT, 100_000_000}, // 67 (Automotive/SPE) {"1000baseT1_Full", unix.ETHTOOL_LINK_MODE_1000baseT1_Full_BIT, 1_000_000_000}, // 68 (Automotive/SPE) {"400000baseKR8_Full", unix.ETHTOOL_LINK_MODE_400000baseKR8_Full_BIT, 400_000_000_000}, // 69 {"400000baseSR8_Full", unix.ETHTOOL_LINK_MODE_400000baseSR8_Full_BIT, 400_000_000_000}, // 70 {"400000baseLR8_ER8_FR8_Full", unix.ETHTOOL_LINK_MODE_400000baseLR8_ER8_FR8_Full_BIT, 400_000_000_000}, // 71 {"400000baseDR8_Full", unix.ETHTOOL_LINK_MODE_400000baseDR8_Full_BIT, 400_000_000_000}, // 72 {"400000baseCR8_Full", unix.ETHTOOL_LINK_MODE_400000baseCR8_Full_BIT, 400_000_000_000}, // 73 {"FEC_LLRS", unix.ETHTOOL_LINK_MODE_FEC_LLRS_BIT, 0}, // 74 (Low Latency Reed-Solomon FEC) // PAM4 modes start here? Often indicated by lack of KR/CR/SR/LR or different naming {"100000baseKR_Full", unix.ETHTOOL_LINK_MODE_100000baseKR_Full_BIT, 100_000_000_000}, // 75 (Likely 100GBASE-KR1) {"100000baseSR_Full", unix.ETHTOOL_LINK_MODE_100000baseSR_Full_BIT, 100_000_000_000}, // 76 (Likely 100GBASE-SR1) {"100000baseLR_ER_FR_Full", unix.ETHTOOL_LINK_MODE_100000baseLR_ER_FR_Full_BIT, 100_000_000_000}, // 77 (Likely 100GBASE-LR1/ER1/FR1) {"100000baseCR_Full", unix.ETHTOOL_LINK_MODE_100000baseCR_Full_BIT, 100_000_000_000}, // 78 (Likely 100GBASE-CR1) {"100000baseDR_Full", unix.ETHTOOL_LINK_MODE_100000baseDR_Full_BIT, 100_000_000_000}, // 79 {"200000baseKR2_Full", unix.ETHTOOL_LINK_MODE_200000baseKR2_Full_BIT, 200_000_000_000}, // 80 (Likely 200GBASE-KR2) {"200000baseSR2_Full", unix.ETHTOOL_LINK_MODE_200000baseSR2_Full_BIT, 200_000_000_000}, // 81 (Likely 200GBASE-SR2) {"200000baseLR2_ER2_FR2_Full", unix.ETHTOOL_LINK_MODE_200000baseLR2_ER2_FR2_Full_BIT, 200_000_000_000}, // 82 (Likely 200GBASE-LR2/etc) {"200000baseDR2_Full", unix.ETHTOOL_LINK_MODE_200000baseDR2_Full_BIT, 200_000_000_000}, // 83 {"200000baseCR2_Full", unix.ETHTOOL_LINK_MODE_200000baseCR2_Full_BIT, 200_000_000_000}, // 84 (Likely 200GBASE-CR2) {"400000baseKR4_Full", unix.ETHTOOL_LINK_MODE_400000baseKR4_Full_BIT, 400_000_000_000}, // 85 (Likely 400GBASE-KR4) {"400000baseSR4_Full", unix.ETHTOOL_LINK_MODE_400000baseSR4_Full_BIT, 400_000_000_000}, // 86 (Likely 400GBASE-SR4) {"400000baseLR4_ER4_FR4_Full", unix.ETHTOOL_LINK_MODE_400000baseLR4_ER4_FR4_Full_BIT, 400_000_000_000}, // 87 (Likely 400GBASE-LR4/etc) {"400000baseDR4_Full", unix.ETHTOOL_LINK_MODE_400000baseDR4_Full_BIT, 400_000_000_000}, // 88 {"400000baseCR4_Full", unix.ETHTOOL_LINK_MODE_400000baseCR4_Full_BIT, 400_000_000_000}, // 89 (Likely 400GBASE-CR4) {"100baseFX_Half", unix.ETHTOOL_LINK_MODE_100baseFX_Half_BIT, 100_000_000}, // 90 {"100baseFX_Full", unix.ETHTOOL_LINK_MODE_100baseFX_Full_BIT, 100_000_000}, // 91 } ethtool-0.6.1/ethtool_msglvl.go000066400000000000000000000055421501603465100165740ustar00rootroot00000000000000/* * * 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) } ethtool-0.6.1/ethtool_msglvl_test.go000066400000000000000000000026551501603465100176350ustar00rootroot00000000000000/* * * 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 import ( "fmt" "net" "os" "testing" ) func TestMsglvlGet(t *testing.T) { intfs, err := net.Interfaces() if err != nil { t.Fatal(err) } // we expected to have at least one success success := false for _, intf := range intfs { _, err := MsglvlGet(intf.Name) if err != nil { continue } success = true } // fake success if run on travis if os.Getenv("TRAVIS") == "true" { fmt.Println("testing on travis.") if !success { fmt.Println("testing msglvl force success on travis.") success = true } } if !success { t.Fatal("Unable to get msglvl from any interface of this system.") } } ethtool-0.6.1/ethtool_test.go000066400000000000000000000106201501603465100162400ustar00rootroot00000000000000/* * * 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 import ( "net" "reflect" "testing" ) func TestGoString(t *testing.T) { testcases := map[string][]byte{ "": {}, "0.5-4": {48, 46, 53, 45, 52, 0, 0, 0}, "1.6": {49, 46, 54, 0, 46, 48, 45, 50, 50, 45, 103, 101, 110, 101, 114, 105, 99}, } for want, s := range testcases { got := goString(s) if got != want { t.Errorf("String conversion failed, got: %s, want: %s.", got, want) } } } func TestStats(t *testing.T) { intfs, err := net.Interfaces() if err != nil { t.Fatal(err) } // we expected to have at least one success empty := true for _, intf := range intfs { stats, err := Stats(intf.Name) if err != nil { continue } for range stats { empty = false break } } if empty { t.Fatal("Unable to retrieve stats from any interface of this system.") } } func TestDriverName(t *testing.T) { intfs, err := net.Interfaces() if err != nil { t.Fatal(err) } // we expected to have at least one success success := false for _, intf := range intfs { _, err := DriverName(intf.Name) if err == nil { success = true } } if !success { t.Fatal("Unable to retrieve driver from any interface of this system.") } } func TestBusInfo(t *testing.T) { intfs, err := net.Interfaces() if err != nil { t.Fatal(err) } // we expected to have at least one success success := false for _, intf := range intfs { _, err := BusInfo(intf.Name) if err == nil { success = true } } if !success { t.Fatal("Unable to retrieve bus info from any interface of this system.") } } func TestSupportedLinkModes(t *testing.T) { var cases = []struct { inputMask uint64 expected []string }{ {0b01100010_11101111, []string{"10baseT_Half", "10baseT_Full", "100baseT_Half", "100baseT_Full", "1000baseT_Full"}}, } for _, testcase := range cases { actual := SupportedLinkModes(testcase.inputMask) if !reflect.DeepEqual(actual, testcase.expected) { t.Error("Expected ", testcase.expected, " got ", actual) } } } func TestFeatures(t *testing.T) { et, err := NewEthtool() if err != nil { t.Fatal(err) } defer et.Close() feats, err := et.Features("lo") if err != nil { t.Fatal(err) } if len(feats) == 0 { // TOD0: do we have a sane subset of features we should check? t.Fatalf("expected features for loopback interface") } featsWithState, err := et.FeaturesWithState("lo") if err != nil { t.Fatal(err) } if len(feats) != len(featsWithState) { t.Fatalf("features mismatch: %d with state %d", len(feats), len(featsWithState)) } fixed := 0 for key, val := range feats { state, ok := featsWithState[key] if !ok || val != state.Active { t.Errorf("inconsistent feature: %q reported %v active %v", key, val, state.Active) } if !state.Available { fixed++ } } if fixed == 0 { // the lo interface MUST have some non-available features, by design t.Fatalf("loopback interface reported all features available") } } func TestIdentity(t *testing.T) { if testing.Short() { return } intfs, err := net.Interfaces() if err != nil { t.Fatal(err) } // we expected to have at least one success empty := true for _, intf := range intfs { err := Identity(intf.Name, nil) if err != nil { continue } empty = false } if empty { t.Fatal("Unable to identity any interface of this system.") } } func BenchmarkStats(b *testing.B) { intfs, err := net.Interfaces() if err != nil { b.Fatal(err) } for _, intf := range intfs { if intf.Name == "lo" { continue } b.Run(intf.Name, func(b *testing.B) { for i := 0; i < b.N; i++ { _, err := Stats(intf.Name) if err != nil { b.Fatal(err) } } }) } } ethtool-0.6.1/example/000077500000000000000000000000001501603465100146305ustar00rootroot00000000000000ethtool-0.6.1/example/Makefile000066400000000000000000000001031501603465100162620ustar00rootroot00000000000000all: build build: CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build ethtool-0.6.1/example/main.go000066400000000000000000000033231501603465100161040ustar00rootroot00000000000000package main import ( "flag" "fmt" "log" "github.com/safchain/ethtool" ) func main() { name := flag.String("interface", "", "Interface name") flag.Parse() if *name == "" { log.Fatal("interface is not specified") } e, err := ethtool.NewEthtool() if err != nil { panic(err.Error()) } defer e.Close() features, err := e.Features(*name) if err != nil { panic(err.Error()) } fmt.Printf("features: %+v\n", features) stats, err := e.Stats(*name) if err != nil { panic(err.Error()) } fmt.Printf("stats: %+v\n", stats) busInfo, err := e.BusInfo(*name) if err != nil { panic(err.Error()) } fmt.Printf("bus info: %+v\n", busInfo) drvr, err := e.DriverName(*name) if err != nil { panic(err.Error()) } fmt.Printf("driver name: %+v\n", drvr) cmdGet, err := e.CmdGetMapped(*name) if err != nil { panic(err.Error()) } fmt.Printf("cmd get: %+v\n", cmdGet) fmt.Printf("max capacity: %+v\n", ethtool.SupportedSpeed(cmdGet["Supported"])) msgLvlGet, err := e.MsglvlGet(*name) if err != nil { panic(err.Error()) } fmt.Printf("msg lvl get: %+v\n", msgLvlGet) drvInfo, err := e.DriverInfo(*name) if err != nil { panic(err.Error()) } fmt.Printf("drvrinfo: %+v\n", drvInfo) permAddr, err := e.PermAddr(*name) if err != nil { panic(err.Error()) } fmt.Printf("permaddr: %+v\n", permAddr) ts, err := e.GetTimestampingInformation(*name) if err != nil { panic(err.Error()) } fmt.Printf("timestamping information: %+v\n", ts) eeprom, err := e.ModuleEepromHex(*name) if err != nil { panic(err.Error()) } fmt.Printf("module eeprom: %+v\n", eeprom) linkSettings, err := e.GetLinkSettings(*name) if err != nil { panic(err.Error()) } fmt.Printf("link settings: %+v\n", linkSettings) } ethtool-0.6.1/go.mod000066400000000000000000000001201501603465100142740ustar00rootroot00000000000000module github.com/safchain/ethtool go 1.24.2 require golang.org/x/sys v0.33.0 ethtool-0.6.1/go.sum000066400000000000000000000002311501603465100143240ustar00rootroot00000000000000golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw= golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=